Skip to content

Commit

Permalink
ctxlock: use safe implementation of keyify
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
BradLugo committed Jan 3, 2025
1 parent 6bbe356 commit de4d6bd
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 27 deletions.
11 changes: 1 addition & 10 deletions pkg/ctxlock/keyify.go
Original file line number Diff line number Diff line change
@@ -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)
}
17 changes: 0 additions & 17 deletions pkg/ctxlock/keyify_safe.go

This file was deleted.

0 comments on commit de4d6bd

Please sign in to comment.