Skip to content

Commit

Permalink
Merge pull request #6 from adamdecaf/nil-fixes
Browse files Browse the repository at this point in the history
fix: don't let .Iterator() panic when empty
  • Loading branch information
sakeven authored Mar 11, 2024
2 parents 94e35f9 + af41d94 commit b3417fa
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
3 changes: 3 additions & 0 deletions rbtree.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ func (t *Tree[K, V]) Empty() bool {

// Iterator creates the rbtree's iterator that points to the minmum node.
func (t *Tree[K, V]) Iterator() *node[K, V] {
if t == nil || t.root == nil {
return nil
}
return minimum(t.root)
}

Expand Down
38 changes: 38 additions & 0 deletions rbtree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,20 @@ func TestFind(t *testing.T) {
if value != "jcd4" {
t.Error("Error value after modifyed other node")
}

t.Run("empty", func(t *testing.T) {
tree = NewTree[int, string]()

n := tree.FindIt(4)
if n != nil {
t.Fatalf("got %#v", n)
}

value := tree.Find(5)
if value != "" {
t.Fatalf("got %q", value)
}
})
}

func TestIterator(t *testing.T) {
Expand All @@ -97,6 +111,20 @@ func TestIterator(t *testing.T) {
it = it.Next()
}

t.Run("empty", func(t *testing.T) {
tree = NewTree[int, string]()

next := tree.Iterator()
t.Logf("tree.Iterator()=%#v", next)
if next != nil {
t.Fatalf(".Iterator() returned %#v", next)
}

size := tree.Size()
if size != 0 {
t.Fatalf("got size %d", size)
}
})
}

func TestDelete(t *testing.T) {
Expand All @@ -120,6 +148,16 @@ func TestDelete(t *testing.T) {
if tree.Find(1) != "" {
t.Error("Can't clear")
}

t.Run("empty", func(t *testing.T) {
tree = NewTree[int, string]()
tree.Delete(1)

size := tree.Size()
if size != 0 {
t.Fatalf("after size is %d", size)
}
})
}

func TestDelete2(t *testing.T) {
Expand Down

0 comments on commit b3417fa

Please sign in to comment.