You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

59 lines
2.0 KiB

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