Skip to content

Commit

Permalink
More protection against stree being nil
Browse files Browse the repository at this point in the history
Signed-off-by: Derek Collison <[email protected]>
  • Loading branch information
derekcollison authored and wallyqs committed Jul 16, 2024
1 parent 5405206 commit f58991c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
14 changes: 13 additions & 1 deletion server/stree/stree.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ func (t *SubjectTree[T]) Empty() *SubjectTree[T] {

// Insert a value into the tree. Will return if the value was updated and if so the old value.
func (t *SubjectTree[T]) Insert(subject []byte, value T) (*T, bool) {
if t == nil {
return nil, false
}

old, updated := t.insert(&t.root, subject, value, 0)
if !updated {
t.size++
Expand All @@ -60,6 +64,10 @@ func (t *SubjectTree[T]) Insert(subject []byte, value T) (*T, bool) {

// Find will find the value and return it or false if it was not found.
func (t *SubjectTree[T]) Find(subject []byte) (*T, bool) {
if t == nil {
return nil, false
}

var si int
for n := t.root; n != nil; {
if n.isLeaf() {
Expand Down Expand Up @@ -88,6 +96,10 @@ func (t *SubjectTree[T]) Find(subject []byte) (*T, bool) {

// Delete will delete the item and return its value, or not found if it did not exist.
func (t *SubjectTree[T]) Delete(subject []byte) (*T, bool) {
if t == nil {
return nil, false
}

val, deleted := t.delete(&t.root, subject, 0)
if deleted {
t.size--
Expand All @@ -97,7 +109,7 @@ func (t *SubjectTree[T]) Delete(subject []byte) (*T, bool) {

// Match will match against a subject that can have wildcards and invoke the callback func for each matched value.
func (t *SubjectTree[T]) Match(filter []byte, cb func(subject []byte, val *T)) {
if len(filter) == 0 || cb == nil {
if t == nil || t.root == nil || len(filter) == 0 || cb == nil {
return
}
// We need to break this up into chunks based on wildcards, either pwc '*' or fwc '>'.
Expand Down
11 changes: 11 additions & 0 deletions server/stree/stree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -764,3 +764,14 @@ func TestSubjectTreeMatchNoCallbackDupe(t *testing.T) {
})
}
}

func TestSubjectTreeNilNoPanic(t *testing.T) {
var st *SubjectTree[int]
st.Match([]byte("foo"), func(_ []byte, _ *int) {})
_, found := st.Find([]byte("foo"))
require_False(t, found)
_, found = st.Delete([]byte("foo"))
require_False(t, found)
_, found = st.Insert([]byte("foo"), 22)
require_False(t, found)
}

0 comments on commit f58991c

Please sign in to comment.