diff --git a/tools/tree.go b/tools/tree.go index b474baa..4de5e99 100644 --- a/tools/tree.go +++ b/tools/tree.go @@ -135,6 +135,30 @@ func (t *Tree) set(value interface{}, i int, segments []string, node *node) { t.set(value, i+1, segments, child) } +// Get gets the values from the topic that exactly matches the supplied topics. +func (t *Tree) Get(topic string) []interface{} { + t.mutex.Lock() + defer t.mutex.Unlock() + + return t.get(0, strings.Split(topic, t.Separator), t.root) +} + +func (t *Tree) get(i int, segments []string, node *node) []interface{} { + // set value on leaf + if i == len(segments) { + return node.values + } + + // get next segment + segment := segments[i] + child, ok := node.children[segment] + if !ok { + return nil + } + + return t.get(i+1, segments, child) +} + // Remove un-registers the value from the supplied topic. This function will // automatically shrink the tree. func (t *Tree) Remove(topic string, value interface{}) { diff --git a/tools/tree_test.go b/tools/tree_test.go index 3d35145..b39cbfc 100644 --- a/tools/tree_test.go +++ b/tools/tree_test.go @@ -41,6 +41,14 @@ func TestTreeSetReplace(t *testing.T) { assert.Equal(t, 2, tree.root.children["foo"].children["bar"].values[0]) } +func TestTreeGet(t *testing.T) { + tree := NewTree() + + tree.Set("foo/#", 1) + + assert.Equal(t, 1, tree.Get("foo/#")[0]) +} + func TestTreeRemove(t *testing.T) { tree := NewTree() @@ -119,6 +127,14 @@ func TestTreeMatchWildcard4(t *testing.T) { assert.Equal(t, 1, tree.Match("foo/bar")[0]) } +func TestTreeMatchWildcard5(t *testing.T) { + tree := NewTree() + + tree.Add("foo/#", 1) + + assert.Equal(t, 1, tree.Match("foo/bar/#")[0]) +} + func TestTreeMatchMultiple(t *testing.T) { tree := NewTree() @@ -195,6 +211,14 @@ func TestTreeSearchWildcard4(t *testing.T) { assert.Equal(t, 1, tree.Search("foo/bar/#")[0]) } +func TestTreeSearchWildcard5(t *testing.T) { + tree := NewTree() + + tree.Add("foo/bar/#", 1) + + assert.Equal(t, 1, tree.Search("foo/#")[0]) +} + func TestTreeSearchMultiple(t *testing.T) { tree := NewTree()