github.com/flowerwrong/netstack@v0.0.0-20191009141956-e5848263af28/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 // 20 package jenkins 21 22 import ( 23 "hash" 24 ) 25 26 // Sum32 represents Jenkins's one_at_a_time hash. 27 // 28 // Use the Sum32 type directly (as opposed to New32 below) 29 // to avoid allocations. 30 type Sum32 uint32 31 32 // New32 returns a new 32-bit Jenkins's one_at_a_time hash.Hash. 33 // 34 // Its Sum method will lay the value out in big-endian byte order. 35 func New32() hash.Hash32 { 36 var s Sum32 37 return &s 38 } 39 40 // Reset resets the hash to its initial state. 41 func (s *Sum32) Reset() { *s = 0 } 42 43 // Sum32 returns the hash value 44 func (s *Sum32) Sum32() uint32 { 45 hash := *s 46 47 hash += (hash << 3) 48 hash ^= hash >> 11 49 hash += hash << 15 50 51 return uint32(hash) 52 } 53 54 // Write adds more data to the running hash. 55 // 56 // It never returns an error. 57 func (s *Sum32) Write(data []byte) (int, error) { 58 hash := *s 59 for _, b := range data { 60 hash += Sum32(b) 61 hash += hash << 10 62 hash ^= hash >> 6 63 } 64 *s = hash 65 return len(data), nil 66 } 67 68 // Size returns the number of bytes Sum will return. 69 func (s *Sum32) Size() int { return 4 } 70 71 // BlockSize returns the hash's underlying block size. 72 func (s *Sum32) BlockSize() int { return 1 } 73 74 // Sum appends the current hash to in and returns the resulting slice. 75 // 76 // It does not change the underlying hash state. 77 func (s *Sum32) Sum(in []byte) []byte { 78 v := s.Sum32() 79 return append(in, byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) 80 }