github.com/nicocha30/gvisor-ligolo@v0.0.0-20230726075806-989fa2c0a413/pkg/tcpip/hash/jenkins/jenkins.go (about) 1 // Copyright 2018 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package jenkins implements Jenkins's one_at_a_time, non-cryptographic hash 16 // functions created by by Bob Jenkins. 17 // 18 // See https://en.wikipedia.org/wiki/Jenkins_hash_function#cite_note-dobbsx-1 19 package jenkins 20 21 import ( 22 "hash" 23 ) 24 25 // Sum32 represents Jenkins's one_at_a_time hash. 26 // 27 // Use the Sum32 type directly (as opposed to New32 below) 28 // to avoid allocations. 29 type Sum32 uint32 30 31 // New32 returns a new 32-bit Jenkins's one_at_a_time hash.Hash. 32 // 33 // Its Sum method will lay the value out in big-endian byte order. 34 func New32() hash.Hash32 { 35 var s Sum32 36 return &s 37 } 38 39 // Reset resets the hash to its initial state. 40 func (s *Sum32) Reset() { *s = 0 } 41 42 // Sum32 returns the hash value 43 func (s *Sum32) Sum32() uint32 { 44 sCopy := *s 45 46 sCopy += sCopy << 3 47 sCopy ^= sCopy >> 11 48 sCopy += sCopy << 15 49 50 return uint32(sCopy) 51 } 52 53 // Write adds more data to the running hash. 54 // 55 // It never returns an error. 56 func (s *Sum32) Write(data []byte) (int, error) { 57 sCopy := *s 58 for _, b := range data { 59 sCopy += Sum32(b) 60 sCopy += sCopy << 10 61 sCopy ^= sCopy >> 6 62 } 63 *s = sCopy 64 return len(data), nil 65 } 66 67 // Size returns the number of bytes Sum will return. 68 func (s *Sum32) Size() int { return 4 } 69 70 // BlockSize returns the hash's underlying block size. 71 func (s *Sum32) BlockSize() int { return 1 } 72 73 // Sum appends the current hash to in and returns the resulting slice. 74 // 75 // It does not change the underlying hash state. 76 func (s *Sum32) Sum(in []byte) []byte { 77 v := s.Sum32() 78 return append(in, byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) 79 }