github.com/vugu/vugu@v0.3.6-0.20240430171613-3f6f402e014b/gen/comp-hasher.go (about)

     1  package gen
     2  
     3  import (
     4  	"encoding/binary"
     5  	"sync"
     6  
     7  	"github.com/vugu/xxhash"
     8  )
     9  
    10  var compHashCounts = make(map[string]int, 8)
    11  var compHashMU sync.Mutex
    12  
    13  // compHashCounted returns a hash value for the given string and
    14  // maintaining a count of the number of times that string was passed.
    15  // Each time a given s is provided a different hash will be returned,
    16  // but invocations from one program run to the next should return
    17  // the same series.  (This avoids unnecessary changes in generated files
    18  // when produced with the same input.)
    19  func compHashCounted(s string) uint64 {
    20  	compHashMU.Lock()
    21  	c := compHashCounts[s]
    22  	compHashCounts[s] = c + 1
    23  	compHashMU.Unlock()
    24  
    25  	h := xxhash.New()
    26  	_, err := h.WriteString(s)
    27  	if err != nil {
    28  		panic(err)
    29  	}
    30  	var b [8]byte
    31  	binary.BigEndian.PutUint64(b[:], uint64(c))
    32  	_, err = h.Write(b[:])
    33  	if err != nil {
    34  		panic(err)
    35  	}
    36  	return h.Sum64()
    37  }