xxhash_unsafe.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // +build !appengine
  2. // This file encapsulates usage of unsafe.
  3. // xxhash_safe.go contains the safe implementations.
  4. package xxhash
  5. import (
  6. "reflect"
  7. "unsafe"
  8. )
  9. // Notes:
  10. //
  11. // See https://groups.google.com/d/msg/golang-nuts/dcjzJy-bSpw/tcZYBzQqAQAJ
  12. // for some discussion about these unsafe conversions.
  13. //
  14. // In the future it's possible that compiler optimizations will make these
  15. // unsafe operations unnecessary: https://golang.org/issue/2205.
  16. //
  17. // Both of these wrapper functions still incur function call overhead since they
  18. // will not be inlined. We could write Go/asm copies of Sum64 and Digest.Write
  19. // for strings to squeeze out a bit more speed. Mid-stack inlining should
  20. // eventually fix this.
  21. // Sum64String computes the 64-bit xxHash digest of s.
  22. // It may be faster than Sum64([]byte(s)) by avoiding a copy.
  23. func Sum64String(s string) uint64 {
  24. var b []byte
  25. bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  26. bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
  27. bh.Len = len(s)
  28. bh.Cap = len(s)
  29. return Sum64(b)
  30. }
  31. // WriteString adds more data to d. It always returns len(s), nil.
  32. // It may be faster than Write([]byte(s)) by avoiding a copy.
  33. func (d *Digest) WriteString(s string) (n int, err error) {
  34. var b []byte
  35. bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  36. bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
  37. bh.Len = len(s)
  38. bh.Cap = len(s)
  39. return d.Write(b)
  40. }