Skip to content

Commit

Permalink
feat(util): KeyWithUint64 and KeyWithUint32 helper functions for db keys
Browse files Browse the repository at this point in the history
  • Loading branch information
robert-zaremba committed Apr 16, 2024
1 parent 571d7c6 commit d6db781
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
18 changes: 18 additions & 0 deletions util/bytes.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,21 @@ func UintWithNullPrefix(n uint64) []byte {
binary.LittleEndian.PutUint64(bz[1:], n)
return bz
}

// KeyWithUint32 concatenates prefix big endian serialized n value.
// No zero byte is appended at the end.
func KeyWithUint32(prefix []byte, n uint32) []byte {
out := make([]byte, len(prefix)+4)
copy(out, prefix)
binary.BigEndian.PutUint32(out[len(prefix):], n)
return out
}

// KeyWithUint64 concatenates prefix big endian serialized n value.
// No zero byte is appended at the end.
func KeyWithUint64(prefix []byte, n uint64) []byte {
out := make([]byte, len(prefix)+8)
copy(out, prefix)
binary.BigEndian.PutUint64(out[len(prefix):], n)
return out
}
24 changes: 24 additions & 0 deletions util/bytes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,27 @@ func TestUintWithNullPrefix(t *testing.T) {
out := UintWithNullPrefix(math.MaxUint64)
assert.DeepEqual(t, expected, out)
}

func TestKeyWithUint(t *testing.T) {
prefix := []byte{1, 10}

out := KeyWithUint32(nil, 200)
assert.DeepEqual(t, out, []byte{0, 0, 0, 200})

out = KeyWithUint32(prefix, 200)
assert.DeepEqual(t, out, []byte{1, 10, 0, 0, 0, 200})

out = KeyWithUint32(prefix, 256)
assert.DeepEqual(t, out, []byte{1, 10, 0, 0, 1, 0})

// uint64 version

out = KeyWithUint64(nil, 200)
assert.DeepEqual(t, out, []byte{0, 0, 0, 0, 0, 0, 0, 200})

out = KeyWithUint64(prefix, 200)
assert.DeepEqual(t, out, []byte{1, 10, 0, 0, 0, 0, 0, 0, 0, 200})

out = KeyWithUint64(prefix, 256)
assert.DeepEqual(t, out, []byte{1, 10, 0, 0, 0, 0, 0, 0, 1, 0})
}

0 comments on commit d6db781

Please sign in to comment.