go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/murmur3/murmur64.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package murmur3
     9  
    10  import (
    11  	"hash"
    12  )
    13  
    14  // Make sure interfaces are correctly implemented.
    15  var (
    16  	_ hash.Hash   = new(digest64)
    17  	_ hash.Hash64 = new(digest64)
    18  	_ bmixer      = new(digest64)
    19  )
    20  
    21  // digest64 is half a digest128.
    22  type digest64 digest128
    23  
    24  // New64 returns a 64-bit hasher
    25  func New64() hash.Hash64 { return New64WithSeed(0) }
    26  
    27  // New64WithSeed returns a 64-bit hasher set with explicit seed value
    28  func New64WithSeed(seed uint32) hash.Hash64 {
    29  	d := (*digest64)(New128WithSeed(seed).(*digest128))
    30  	return d
    31  }
    32  
    33  func (d *digest64) Sum(b []byte) []byte {
    34  	h1 := d.Sum64()
    35  	return append(b,
    36  		byte(h1>>56), byte(h1>>48), byte(h1>>40), byte(h1>>32),
    37  		byte(h1>>24), byte(h1>>16), byte(h1>>8), byte(h1))
    38  }
    39  
    40  func (d *digest64) Sum64() uint64 {
    41  	h1, _ := (*digest128)(d).Sum128()
    42  	return h1
    43  }
    44  
    45  // Sum64 returns the MurmurHash3 sum of data. It is equivalent to the
    46  // following sequence (without the extra burden and the extra allocation):
    47  //
    48  //	hasher := New64()
    49  //	hasher.Write(data)
    50  //	return hasher.Sum64()
    51  func Sum64(data []byte) uint64 { return Sum64WithSeed(data, 0) }
    52  
    53  // Sum64WithSeed returns the MurmurHash3 sum of data. It is equivalent to the
    54  // following sequence (without the extra burden and the extra allocation):
    55  //
    56  //	hasher := New64WithSeed(seed)
    57  //	hasher.Write(data)
    58  //	return hasher.Sum64()
    59  func Sum64WithSeed(data []byte, seed uint32) uint64 {
    60  	d := digest128{h1: uint64(seed), h2: uint64(seed)}
    61  	d.seed = seed
    62  	d.tail = d.bmix(data)
    63  	d.clen = len(data)
    64  	h1, _ := d.Sum128()
    65  	return h1
    66  }