|
| 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 | +) |
| 15 | + |
| 16 | +// String writes the given string to the hash. |
| 17 | +func String[T ~string](h hash.Hash, data T) { |
| 18 | + Num64(h, len(data)) |
| 19 | + _, _ = h.Write([]byte(data)) |
| 20 | +} |
| 21 | + |
| 22 | +// Num64 writes the given 64-bit number to the hash. |
| 23 | +func Num64[T ~int64 | ~uint64 | ~int | ~uint](h hash.Hash, data T) { |
| 24 | + var buffer [8]byte |
| 25 | + d := uint64(data) |
| 26 | + buffer[0] = byte(d) |
| 27 | + buffer[1] = byte(d >> 8) |
| 28 | + buffer[2] = byte(d >> 16) |
| 29 | + buffer[3] = byte(d >> 24) |
| 30 | + buffer[4] = byte(d >> 32) |
| 31 | + buffer[5] = byte(d >> 40) |
| 32 | + buffer[6] = byte(d >> 48) |
| 33 | + buffer[7] = byte(d >> 56) |
| 34 | + _, _ = h.Write(buffer[:]) |
| 35 | +} |
| 36 | + |
| 37 | +// Num32 writes the given 32-bit number to the hash. |
| 38 | +func Num32[T ~int32 | ~uint32](h hash.Hash, data T) { |
| 39 | + var buffer [4]byte |
| 40 | + d := uint32(data) |
| 41 | + buffer[0] = byte(d) |
| 42 | + buffer[1] = byte(d >> 8) |
| 43 | + buffer[2] = byte(d >> 16) |
| 44 | + buffer[3] = byte(d >> 24) |
| 45 | + _, _ = h.Write(buffer[:]) |
| 46 | +} |
| 47 | + |
| 48 | +// Num16 writes the given 16-bit number to the hash. |
| 49 | +func Num16[T ~int16 | ~uint16](h hash.Hash, data T) { |
| 50 | + var buffer [2]byte |
| 51 | + d := uint16(data) |
| 52 | + buffer[0] = byte(d) |
| 53 | + buffer[1] = byte(d >> 8) |
| 54 | + _, _ = h.Write(buffer[:]) |
| 55 | +} |
| 56 | + |
| 57 | +// Num8 writes the given 8-bit number to the hash. |
| 58 | +func Num8[T ~uint8](h hash.Hash, data T) { |
| 59 | + _, _ = h.Write([]byte{byte(data)}) |
| 60 | +} |
| 61 | + |
| 62 | +// Bool writes the given boolean to the hash. |
| 63 | +func Bool[T ~bool](h hash.Hash, data T) { |
| 64 | + var b byte |
| 65 | + if data { |
| 66 | + b = 1 |
| 67 | + } |
| 68 | + _, _ = h.Write([]byte{b}) |
| 69 | +} |
0 commit comments