github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/runtime/memhash_fnv.go (about)

     1  //go:build (!wasip1 && !runtime_memhash_tsip && !runtime_memhash_leveldb) || (wasip1 && runtime_memhash_fnv)
     2  
     3  // This is the default for all targets except WASI, unless a more specific build
     4  // tag is set.
     5  
     6  package runtime
     7  
     8  import "unsafe"
     9  
    10  // Get FNV-1a hash of the given memory buffer.
    11  //
    12  // https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#FNV-1a_hash
    13  func hash32(ptr unsafe.Pointer, n, seed uintptr) uint32 {
    14  	var result uint32 = 2166136261 // FNV offset basis
    15  	result *= uint32(seed)
    16  	for i := uintptr(0); i < n; i++ {
    17  		c := *(*uint8)(unsafe.Add(ptr, i))
    18  		result ^= uint32(c) // XOR with byte
    19  		result *= 16777619  // FNV prime
    20  	}
    21  	return result
    22  }
    23  
    24  // Also a FNV-1a hash.
    25  func hash64(ptr unsafe.Pointer, n, seed uintptr) uint64 {
    26  	var result uint64 = 14695981039346656037 // FNV offset basis
    27  	result *= uint64(seed)
    28  	for i := uintptr(0); i < n; i++ {
    29  		c := *(*uint8)(unsafe.Add(ptr, i))
    30  		result ^= uint64(c)     // XOR with byte
    31  		result *= 1099511628211 // FNV prime
    32  	}
    33  	return result
    34  }