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