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