Skip to content

Commit

Permalink
radixdb: add longestCommonPrefix()
Browse files Browse the repository at this point in the history
  • Loading branch information
toru committed Oct 3, 2024
1 parent a01f9c8 commit 4f2a8a1
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
25 changes: 25 additions & 0 deletions radixdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,28 @@ func (rdb *RadixDB) Len() uint64 {

return rdb.numNodes
}

// longestCommonPrefix compares the two given byte slices, and returns the
// longest common prefix. It ensures memory-safety by establishing an index
// boundary based on the length of the shorter byte slice.
func longestCommonPrefix(a, b []byte) []byte {
minLen := len(a)

if len(b) < minLen {
minLen = len(b)
}

var i int

for i = 0; i < minLen; i++ {
if a[i] != b[i] {
break
}
}

if i == 0 {
return nil
}

return a[:i]
}
29 changes: 29 additions & 0 deletions radixdb_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package radixdb

import "testing"

func TestLongestCommonPrefix(t *testing.T) {
tests := []struct {
a, b []byte
expected []byte
}{
// Basic cases.
{[]byte("apple"), []byte("app"), []byte("app")},
{[]byte("banana"), []byte("band"), []byte("ban")},
{[]byte("cat"), []byte("candy"), []byte("ca")},
{[]byte("no"), []byte("match"), nil},
{[]byte("match"), []byte("match"), []byte("match")},

// Edge cases.
{[]byte(""), []byte(""), nil},
{nil, nil, nil},
}

for _, test := range tests {
subject := longestCommonPrefix(test.a, test.b)

if string(subject) != string(test.expected) {
t.Errorf("(%q,%q): got:%q, want:%q", test.a, test.b, subject, test.expected)
}
}
}

0 comments on commit 4f2a8a1

Please sign in to comment.