From f58991ce59b10c49d76a840916bb1c6b89d19407 Mon Sep 17 00:00:00 2001 From: Derek Collison Date: Tue, 16 Jul 2024 13:39:19 -0500 Subject: [PATCH] More protection against stree being nil Signed-off-by: Derek Collison --- server/stree/stree.go | 14 +++++++++++++- server/stree/stree_test.go | 11 +++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/server/stree/stree.go b/server/stree/stree.go index fd72b3bac0..d0835bf5d1 100644 --- a/server/stree/stree.go +++ b/server/stree/stree.go @@ -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++ @@ -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() { @@ -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-- @@ -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 '>'. diff --git a/server/stree/stree_test.go b/server/stree/stree_test.go index 7ce59e287e..7177cd6d94 100644 --- a/server/stree/stree_test.go +++ b/server/stree/stree_test.go @@ -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) +}