github.com/glide-im/glide@v1.6.0/pkg/hash/hash.go (about)

     1  package hash
     2  
     3  import (
     4  	"crypto/sha1"
     5  	"encoding/hex"
     6  	"math/bits"
     7  	"unsafe"
     8  )
     9  
    10  const (
    11  	c1_32 uint32 = 0xcc9e2d51
    12  	c2_32 uint32 = 0x1b873593
    13  )
    14  
    15  func SHA1(str string) string {
    16  	h := sha1.New()
    17  	_, _ = h.Write([]byte(str))
    18  	return hex.EncodeToString(h.Sum(nil))
    19  }
    20  
    21  func Hash(data []byte, seed uint32) uint32 {
    22  
    23  	h1 := seed
    24  
    25  	nblocks := len(data) / 4
    26  	var p uintptr
    27  	if len(data) > 0 {
    28  		p = uintptr(unsafe.Pointer(&data[0]))
    29  	}
    30  	p1 := p + uintptr(4*nblocks)
    31  	for ; p < p1; p += 4 {
    32  		k1 := *(*uint32)(unsafe.Pointer(p))
    33  
    34  		k1 *= c1_32
    35  		k1 = bits.RotateLeft32(k1, 15)
    36  		k1 *= c2_32
    37  
    38  		h1 ^= k1
    39  		h1 = bits.RotateLeft32(h1, 13)
    40  		h1 = h1*4 + h1 + 0xe6546b64
    41  	}
    42  
    43  	tail := data[nblocks*4:]
    44  
    45  	var k1 uint32
    46  	switch len(tail) & 3 {
    47  	case 3:
    48  		k1 ^= uint32(tail[2]) << 16
    49  		fallthrough
    50  	case 2:
    51  		k1 ^= uint32(tail[1]) << 8
    52  		fallthrough
    53  	case 1:
    54  		k1 ^= uint32(tail[0])
    55  		k1 *= c1_32
    56  		k1 = bits.RotateLeft32(k1, 15)
    57  		k1 *= c2_32
    58  		h1 ^= k1
    59  	}
    60  
    61  	h1 ^= uint32(len(data))
    62  
    63  	h1 ^= h1 >> 16
    64  	h1 *= 0x85ebca6b
    65  	h1 ^= h1 >> 13
    66  	h1 *= 0xc2b2ae35
    67  	h1 ^= h1 >> 16
    68  
    69  	return h1
    70  }