xxhash.go 1.5 KB

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