github.com/grailbio/base@v0.0.11/writehash/writehash.go (about) 1 // Copyright 2019 GRAIL, Inc. All rights reserved. 2 // Use of this source code is governed by the Apache 2.0 3 // license that can be found in the LICENSE file. 4 5 // Package writehash provides a set of utility functions to hash 6 // common types into hashes. 7 package writehash 8 9 import ( 10 "encoding/binary" 11 "fmt" 12 "hash" 13 "io" 14 "math" 15 ) 16 17 func must(n int, err error) { 18 if err != nil { 19 panic(fmt.Sprintf("writehash: hash.Write returned unexpected error: %v", err)) 20 } 21 } 22 23 // String encodes the string s into writer w. 24 func String(h hash.Hash, s string) { 25 must(io.WriteString(h, s)) 26 } 27 28 // Int encodes the integer v into writer w. 29 func Int(h hash.Hash, v int) { 30 Uint64(h, uint64(v)) 31 } 32 33 // Int16 encodes the 16-bit integer v into writer w. 34 func Int16(h hash.Hash, v int) { 35 Uint16(h, uint16(v)) 36 } 37 38 // Int32 encodes the 32-bit integer v into writer w. 39 func Int32(h hash.Hash, v int32) { 40 Uint32(h, uint32(v)) 41 } 42 43 // Int64 encodes the 64-bit integer v into writer w. 44 func Int64(h hash.Hash, v int64) { 45 Uint64(h, uint64(v)) 46 } 47 48 // Uint encodes the unsigned integer v into writer w. 49 func Uint(h hash.Hash, v uint) { 50 Uint64(h, uint64(v)) 51 } 52 53 // Uint16 encodes the unsigned 16-bit integer v into writer w. 54 func Uint16(h hash.Hash, v uint16) { 55 var buf [2]byte 56 binary.LittleEndian.PutUint16(buf[:], v) 57 must(h.Write(buf[:])) 58 } 59 60 // Uint32 encodes the unsigned 32-bit integer v into writer w. 61 func Uint32(h hash.Hash, v uint32) { 62 var buf [4]byte 63 binary.LittleEndian.PutUint32(buf[:], v) 64 must(h.Write(buf[:])) 65 } 66 67 // Uint64 encodes the unsigned 64-bit integer v into writer w. 68 func Uint64(h hash.Hash, v uint64) { 69 var buf [8]byte 70 binary.LittleEndian.PutUint64(buf[:], v) 71 must(h.Write(buf[:])) 72 } 73 74 // Float32 encodes the 32-bit floating point number v into writer w. 75 func Float32(h hash.Hash, v float32) { 76 Uint32(h, math.Float32bits(v)) 77 } 78 79 // Float64 encodes the 64-bit floating point number v into writer w. 80 func Float64(h hash.Hash, v float64) { 81 Uint64(h, math.Float64bits(v)) 82 } 83 84 // Bool encodes the boolean v into writer w. 85 func Bool(h hash.Hash, v bool) { 86 if v { 87 Byte(h, 1) 88 } else { 89 Byte(h, 0) 90 } 91 } 92 93 // Byte writes the byte b into writer w. 94 func Byte(h hash.Hash, b byte) { 95 if w, ok := h.(io.ByteWriter); ok { 96 must(0, w.WriteByte(b)) 97 return 98 } 99 must(h.Write([]byte{b})) 100 } 101 102 // Run encodes the rune r into writer w. 103 func Rune(h hash.Hash, r rune) { 104 Int(h, int(r)) 105 }