murmur64.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package murmur3
  2. import (
  3. "hash"
  4. )
  5. // Make sure interfaces are correctly implemented.
  6. var (
  7. _ hash.Hash = new(digest64)
  8. _ hash.Hash64 = new(digest64)
  9. _ bmixer = new(digest64)
  10. )
  11. // digest64 is half a digest128.
  12. type digest64 digest128
  13. // New64 returns a 64-bit hasher
  14. func New64() hash.Hash64 { return New64WithSeed(0) }
  15. // New64WithSeed returns a 64-bit hasher set with explicit seed value
  16. func New64WithSeed(seed uint32) hash.Hash64 {
  17. d := (*digest64)(New128WithSeed(seed).(*digest128))
  18. return d
  19. }
  20. func (d *digest64) Sum(b []byte) []byte {
  21. h1 := d.Sum64()
  22. return append(b,
  23. byte(h1>>56), byte(h1>>48), byte(h1>>40), byte(h1>>32),
  24. byte(h1>>24), byte(h1>>16), byte(h1>>8), byte(h1))
  25. }
  26. func (d *digest64) Sum64() uint64 {
  27. h1, _ := (*digest128)(d).Sum128()
  28. return h1
  29. }
  30. // Sum64 returns the MurmurHash3 sum of data. It is equivalent to the
  31. // following sequence (without the extra burden and the extra allocation):
  32. // hasher := New64()
  33. // hasher.Write(data)
  34. // return hasher.Sum64()
  35. func Sum64(data []byte) uint64 { return Sum64WithSeed(data, 0) }
  36. // Sum64WithSeed returns the MurmurHash3 sum of data. It is equivalent to the
  37. // following sequence (without the extra burden and the extra allocation):
  38. // hasher := New64WithSeed(seed)
  39. // hasher.Write(data)
  40. // return hasher.Sum64()
  41. func Sum64WithSeed(data []byte, seed uint32) uint64 {
  42. d := &digest128{h1: uint64(seed), h2: uint64(seed)}
  43. d.seed = seed
  44. d.tail = d.bmix(data)
  45. d.clen = len(data)
  46. h1, _ := d.Sum128()
  47. return h1
  48. }