From a5c452925bb15af7f252e2e589225bb3980045d3 Mon Sep 17 00:00:00 2001 From: Brad Lugo Date: Thu, 2 Jan 2025 12:46:44 -0800 Subject: [PATCH] ctxlock: use safe implementation of keyify The benchmarks for the unsafe implementation of keyify don't show a significant improvement over the safe implementation. These changes also fix a bug where keyify panics when an empty string input is received. Signed-off-by: Brad Lugo --- pkg/ctxlock/keyify.go | 11 +---------- pkg/ctxlock/keyify_safe.go | 17 ----------------- 2 files changed, 1 insertion(+), 27 deletions(-) delete mode 100644 pkg/ctxlock/keyify_safe.go diff --git a/pkg/ctxlock/keyify.go b/pkg/ctxlock/keyify.go index eabca0937..cb9d5ef0d 100644 --- a/pkg/ctxlock/keyify.go +++ b/pkg/ctxlock/keyify.go @@ -1,22 +1,13 @@ -//go:build !safe - package ctxlock import ( "hash/fnv" - "reflect" - "unsafe" ) // Keyify returns an int64 serialized into a []byte. func keyify(key string) []byte { - const maxsize = 0x7fff0000 - l := len(key) h := fnv.New64a() - // This is (obviously) unsafe -- it provides mutable access to "key". - // However, it doesn't outlive this Write call, and the implementation - // can be read to ensure it doesn't modify it. - h.Write((*[maxsize]byte)(unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data))[:l:l]) + h.Write([]byte(key)) b := make([]byte, 0, 8) return h.Sum(b) } diff --git a/pkg/ctxlock/keyify_safe.go b/pkg/ctxlock/keyify_safe.go deleted file mode 100644 index 2911dfdef..000000000 --- a/pkg/ctxlock/keyify_safe.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build safe - -package ctxlock - -import ( - "hash/fnv" -) - -// Keyify returns an int64 serialized into a []byte. -// -// This version avoids use of "unsafe" at the cost of extra allocations. -func keyify(key string) []byte { - h := fnv.New64a() - h.Write([]byte(key)) - b := make([]byte, 0, 8) - return h.Sum(b) -}