xxhash_unsafe.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // +build !appengine
  2. // This file encapsulates usage of unsafe.
  3. // xxhash_safe.go contains the safe implementations.
  4. package xxhash
  5. import (
  6. "unsafe"
  7. )
  8. // In the future it's possible that compiler optimizations will make these
  9. // XxxString functions unnecessary by realizing that calls such as
  10. // Sum64([]byte(s)) don't need to copy s. See https://golang.org/issue/2205.
  11. // If that happens, even if we keep these functions they can be replaced with
  12. // the trivial safe code.
  13. // NOTE: The usual way of doing an unsafe string-to-[]byte conversion is:
  14. //
  15. // var b []byte
  16. // bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  17. // bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
  18. // bh.Len = len(s)
  19. // bh.Cap = len(s)
  20. //
  21. // Unfortunately, as of Go 1.15.3 the inliner's cost model assigns a high enough
  22. // weight to this sequence of expressions that any function that uses it will
  23. // not be inlined. Instead, the functions below use a different unsafe
  24. // conversion designed to minimize the inliner weight and allow both to be
  25. // inlined. There is also a test (TestInlining) which verifies that these are
  26. // inlined.
  27. //
  28. // See https://github.com/golang/go/issues/42739 for discussion.
  29. // Sum64String computes the 64-bit xxHash digest of s.
  30. // It may be faster than Sum64([]byte(s)) by avoiding a copy.
  31. func Sum64String(s string) uint64 {
  32. b := *(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)}))
  33. return Sum64(b)
  34. }
  35. // WriteString adds more data to d. It always returns len(s), nil.
  36. // It may be faster than Write([]byte(s)) by avoiding a copy.
  37. func (d *Digest) WriteString(s string) (n int, err error) {
  38. d.Write(*(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)})))
  39. // d.Write always returns len(s), nil.
  40. // Ignoring the return output and returning these fixed values buys a
  41. // savings of 6 in the inliner's cost model.
  42. return len(s), nil
  43. }
  44. // sliceHeader is similar to reflect.SliceHeader, but it assumes that the layout
  45. // of the first two words is the same as the layout of a string.
  46. type sliceHeader struct {
  47. s string
  48. cap int
  49. }