Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(key): add generic key CPL #9

Merged
merged 1 commit into from
Jul 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions kad/key/test/util_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package test

import (
"strings"
"testing"

"github.com/probe-lab/go-libdht/kad/key"
"github.com/probe-lab/go-libdht/kad/key/bit256"
"github.com/probe-lab/go-libdht/kad/key/bitstr"
"github.com/stretchr/testify/require"
)

func TestGenericCommonPrefixLength(t *testing.T) {
k0 := bit256.NewKey(make([]byte, 32)) // 0000...0000
k1 := bitstr.Key(strings.Repeat("0", 256)) // 0000...0000
k2 := bitstr.Key("01" + strings.Repeat("0", 254)) // 0100...0000
k3 := bitstr.Key("000") // 0001

require.Equal(t, 256, key.CommonPrefixLength(k0, k1)) // keys are identical
require.Equal(t, 1, key.CommonPrefixLength(k0, k2)) // only first bit is common
require.Equal(t, 3, key.CommonPrefixLength(k0, k3)) // no common bits
}
16 changes: 16 additions & 0 deletions kad/key/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,22 @@ func Equal[K kad.Key[K]](a, b K) bool {
return a.Compare(b) == 0
}

// CommonPrefixLength returns the length of the common prefix of two keys.
// Note that keys can be of different types, and different lengths.
func CommonPrefixLength[K0 kad.Key[K0], K1 kad.Key[K1]](a K0, b K1) int {
minLen := a.BitLen()
if b.BitLen() < minLen {
minLen = b.BitLen()
}

for i := 0; i < minLen; i++ {
if a.Bit(i) != b.Bit(i) {
return i
}
}
return minLen
}

// BitString returns a string containing the binary representation of a key.
func BitString[K kad.Key[K]](k K) string {
if bs, ok := any(k).(interface{ BitString() string }); ok {
Expand Down