From 154dc06169287f6e7bc56b5e2713f788111525eb Mon Sep 17 00:00:00 2001 From: Pavel Larkin Date: Wed, 7 Dec 2022 22:27:14 -0800 Subject: [PATCH] Fix null as a key (#27) Signed-off-by: plar --- node.go | 4 ++++ tree_test.go | 34 ++++++++++++++++++++++++++++++++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/node.go b/node.go index 88303d3..8f55bba 100644 --- a/node.go +++ b/node.go @@ -746,6 +746,10 @@ func (an *artNode) shrink() *artNode { // Leaf methods func (l *leaf) match(key Key) bool { + if len(key) == 0 && len(l.key) == 0 { + return true + } + if key == nil || len(l.key) != len(key) { return false } diff --git a/tree_test.go b/tree_test.go index 8b270aa..702019f 100644 --- a/tree_test.go +++ b/tree_test.go @@ -1076,9 +1076,7 @@ func TestTreeAPI(t *testing.T) { assert.True(t, found) } -// // Benchmarks -// func BenchmarkWordsTreeInsert(b *testing.B) { words := loadTestFile("test/assets/words.txt") b.ResetTimer() @@ -1495,3 +1493,35 @@ func TestTreeInsertAndSearchKeyWithUnicodeAccentChar(t *testing.T) { assert.True(t, found) assert.Equal(t, string(accent), v) } + +func TestTreeInsertNilKeyTwice(t *testing.T) { + tree := newTree() + + kk := Key("key") + kv := "kk-value" + old, updated := tree.Insert(kk, kv) + assert.Nil(t, old) + assert.False(t, updated) + v, found := tree.Search(kk) + assert.Equal(t, kv, v) + assert.True(t, found) + + knil := Key(nil) + knilv0 := "knil-value-0" + old, updated = tree.Insert(knil, knilv0) + assert.Nil(t, old) + assert.False(t, updated) + + v, found = tree.Search(knil) + assert.Equal(t, knilv0, v) + assert.True(t, found) + + knilv1 := "knil-value-1" + old, updated = tree.Insert(knil, knilv1) + assert.Equal(t, knilv0, old) + assert.True(t, updated) + + v, found = tree.Search(knil) + assert.Equal(t, knilv1, v) + assert.True(t, found) +}