Skip to content

Commit

Permalink
Refs #4 - Remove original trie when no key removed
Browse files Browse the repository at this point in the history
  • Loading branch information
xprazak2 committed Jul 4, 2021
1 parent b93db3d commit 334493d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
12 changes: 10 additions & 2 deletions trie/remove.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,20 @@ func Remove(trie *Trie, q key.Key) (*Trie) {

func RemoveAtDepth(depth int, trie *Trie, q key.Key) (*Trie) {
switch {
case trie.IsEmptyLeaf() || trie.IsNonEmptyLeaf():
case trie.IsEmptyLeaf():
return trie
case trie.IsNonEmptyLeaf() && !key.Equal(trie.Key, q):
return trie
case trie.IsNonEmptyLeaf() && key.Equal(trie.Key, q):
return &Trie{}
default:
dir := q.BitAt(depth)
afterDelete := RemoveAtDepth(depth + 1, trie.Branch[dir], q)
if afterDelete == trie.Branch[dir] {
return trie
}
copy := &Trie{}
copy.Branch[dir] = RemoveAtDepth(depth + 1, trie.Branch[dir], q)
copy.Branch[dir] = afterDelete
copy.Branch[1 - dir] = trie.Branch[1 - dir]
copy.shrink()
return copy
Expand Down
10 changes: 10 additions & 0 deletions trie/remove_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package trie
import (
"testing"
"math/rand"
"github.com/libp2p/go-libp2p-xor/key"
)

func TestImmutableRemoveIsImmutable(t *testing.T) {
Expand Down Expand Up @@ -60,3 +61,12 @@ func TestRemoveIsOrderIndependent(t *testing.T) {
}
}
}

func TestRemoveReturnsOriginalWhenNoKeyRemoved(t *testing.T) {
trie := FromKeys(testAddSamples[0].Keys)

result := Remove(trie, key.ByteKey(2))
if trie != result {
t.Fatalf("Remove should return original trie when no key was removed")
}
}

0 comments on commit 334493d

Please sign in to comment.