github.com/mavryk-network/mvgo@v1.19.9/hash/fnv.go (about)

     1  // Copyright (c) 2018 - 2023 Blockwatch Data Inc.
     2  // Author: alex@blockwatch.cc
     3  
     4  package hash
     5  
     6  import (
     7  	"encoding/binary"
     8  )
     9  
    10  // Hash64 computes the FNV-1a hash of buf.
    11  func Hash64(buf []byte) uint64 {
    12  	hash := uint64(offset64)
    13  	for _, c := range buf {
    14  		hash ^= uint64(c)
    15  		hash *= prime64
    16  	}
    17  	return hash
    18  }
    19  
    20  // from stdlib hash/fnv/fnv.go
    21  const (
    22  	prime64  = 1099511628211
    23  	offset64 = 14695981039346656037
    24  )
    25  
    26  // InlineFNV64a is an alloc-free port of the standard library's fnv64a.
    27  // See https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
    28  type InlineFNV64a uint64
    29  
    30  // NewInlineFNV64a returns a new instance of InlineFNV64a.
    31  func NewInlineFNV64a() InlineFNV64a {
    32  	return offset64
    33  }
    34  
    35  // Write adds data to the running hash.
    36  func (s *InlineFNV64a) Write(data []byte) (int, error) {
    37  	hash := uint64(*s)
    38  	for _, c := range data {
    39  		hash ^= uint64(c)
    40  		hash *= prime64
    41  	}
    42  	*s = InlineFNV64a(hash)
    43  	return len(data), nil
    44  }
    45  
    46  // Write adds data to the running hash.
    47  func (s *InlineFNV64a) WriteString(data string) (int, error) {
    48  	return s.Write([]byte(data))
    49  }
    50  
    51  // Sum64 returns the uint64 of the current resulting hash.
    52  func (s *InlineFNV64a) Sum64() uint64 {
    53  	return uint64(*s)
    54  }
    55  
    56  func (s *InlineFNV64a) Sum() []byte {
    57  	var buf [8]byte
    58  	binary.BigEndian.PutUint64(buf[:], s.Sum64())
    59  	return buf[:]
    60  }
    61  
    62  func (s *InlineFNV64a) Reset() {
    63  	*s = offset64
    64  }