Debian Codegraph @

attribute/internal/xxhash/xxhash.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package xxhash provides a wrapper around the xxhash library for attribute hashing.
5 package xxhash // import "go.opentelemetry.io/otel/attribute/internal/xxhash"
6
7 import (
8 "encoding/binary"
9 "math"
10
11 "github.com/cespare/xxhash/v2"
12 )
13
14 // Hash wraps xxhash.Digest to provide an API friendly for hashing attribute values.
15 type Hash struct {
16 d *xxhash.Digest
17 }
18
19 // New returns a new initialized xxHash64 hasher.
20 func New() Hash {
21 return Hash{d: xxhash.New()}
22 }
23
24 func (h Hash) Uint64(val uint64) Hash {
25 var buf [8]byte
26 binary.LittleEndian.PutUint64(buf[:], val)
27 // errors from Write are always nil for xxhash
28 // if it returns an err then panic
29 _, err := h.d.Write(buf[:])
30 if err != nil {
31 panic("xxhash write of uint64 failed: " + err.Error())
32 }
33 return h
34 }
35
36 func (h Hash) Bool(val bool) Hash { // nolint:revive // This is a hashing function.
37 if val {
38 return h.Uint64(1)
39 }
40 return h.Uint64(0)
41 }
42
43 func (h Hash) Float64(val float64) Hash {
44 return h.Uint64(math.Float64bits(val))
45 }
46
47 func (h Hash) Int64(val int64) Hash {
48 return h.Uint64(uint64(val)) // nolint:gosec // Overflow doesn't matter since we are hashing.
49 }
50
51 func (h Hash) String(val string) Hash {
52 // errors from WriteString are always nil for xxhash
53 // if it returns an err then panic
54 _, err := h.d.WriteString(val)
55 if err != nil {
56 panic("xxhash write of string failed: " + err.Error())
57 }
58 return h
59 }
60
61 // Sum64 returns the current hash value.
62 func (h Hash) Sum64() uint64 {
63 return h.d.Sum64()
64 }