github.com/richardwilkes/toolbox@v1.121.0/xmath/hashhelper/hashhelper.go (about) 1 // Copyright (c) 2024 by Richard A. Wilkes. All rights reserved. 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, version 2.0. If a copy of the MPL was not distributed with 5 // this file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 // 7 // This Source Code Form is "Incompatible With Secondary Licenses", as 8 // defined by the Mozilla Public License, version 2.0. 9 10 package hashhelper 11 12 import ( 13 "hash" 14 "math" 15 ) 16 17 // String writes the given string to the hash. 18 func String[T ~string](h hash.Hash, data T) { 19 Num64(h, len(data)) 20 _, _ = h.Write([]byte(data)) 21 } 22 23 // Num64 writes the given 64-bit number to the hash. 24 func Num64[T ~int64 | ~uint64 | ~int | ~uint](h hash.Hash, data T) { 25 var buffer [8]byte 26 d := uint64(data) 27 buffer[0] = byte(d) 28 buffer[1] = byte(d >> 8) 29 buffer[2] = byte(d >> 16) 30 buffer[3] = byte(d >> 24) 31 buffer[4] = byte(d >> 32) 32 buffer[5] = byte(d >> 40) 33 buffer[6] = byte(d >> 48) 34 buffer[7] = byte(d >> 56) 35 _, _ = h.Write(buffer[:]) 36 } 37 38 // Num32 writes the given 32-bit number to the hash. 39 func Num32[T ~int32 | ~uint32](h hash.Hash, data T) { 40 var buffer [4]byte 41 d := uint32(data) 42 buffer[0] = byte(d) 43 buffer[1] = byte(d >> 8) 44 buffer[2] = byte(d >> 16) 45 buffer[3] = byte(d >> 24) 46 _, _ = h.Write(buffer[:]) 47 } 48 49 // Num16 writes the given 16-bit number to the hash. 50 func Num16[T ~int16 | ~uint16](h hash.Hash, data T) { 51 var buffer [2]byte 52 d := uint16(data) 53 buffer[0] = byte(d) 54 buffer[1] = byte(d >> 8) 55 _, _ = h.Write(buffer[:]) 56 } 57 58 // Num8 writes the given 8-bit number to the hash. 59 func Num8[T ~int8 | ~uint8](h hash.Hash, data T) { 60 _, _ = h.Write([]byte{byte(data)}) 61 } 62 63 // Bool writes the given boolean to the hash. 64 func Bool[T ~bool](h hash.Hash, data T) { 65 var b byte 66 if data { 67 b = 1 68 } 69 _, _ = h.Write([]byte{b}) 70 } 71 72 // Float64 writes the given 64-bit float to the hash. 73 func Float64[T ~float64](h hash.Hash, data T) { 74 Num64(h, math.Float64bits(float64(data))) 75 } 76 77 // Float32 writes the given 64-bit float to the hash. 78 func Float32[T ~float32](h hash.Hash, data T) { 79 Num32(h, math.Float32bits(float32(data))) 80 }