blob: 376e0ca2e49745ecb087871d2e27afb4ed2d987d [file] [log] [blame]
Naveen Sampath04696f72022-06-13 15:19:14 +05301// +build !appengine
2
3// This file encapsulates usage of unsafe.
4// xxhash_safe.go contains the safe implementations.
5
6package xxhash
7
8import (
9 "unsafe"
10)
11
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.
17
18// NOTE: The usual way of doing an unsafe string-to-[]byte conversion is:
19//
20// var b []byte
21// bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
22// bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
23// bh.Len = len(s)
24// bh.Cap = len(s)
25//
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
31// inlined.
32//
33// See https://github.com/golang/go/issues/42739 for discussion.
34
35// Sum64String computes the 64-bit xxHash digest of s.
36// It may be faster than Sum64([]byte(s)) by avoiding a copy.
37func Sum64String(s string) uint64 {
38 b := *(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)}))
39 return Sum64(b)
40}
41
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.
44func (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.
49 return len(s), nil
50}
51
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.
54type sliceHeader struct {
55 s string
56 cap int
57}