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