From eddb3b1467886d4642c2ffb94a58bb9417851f05 Mon Sep 17 00:00:00 2001 From: Soheil Hassas Yeganeh Date: Fri, 15 Jul 2016 08:07:12 -0700 Subject: [PATCH] Fix index out of range in patricia tree Bug #32 reported that there is an index out of range error. This issue was introduced in 703b087. Fix #32 and add a test to detect this issue --- patricia.go | 4 ++++ patricia_test.go | 9 ++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/patricia.go b/patricia.go index a38cae0..c3e3d85 100644 --- a/patricia.go +++ b/patricia.go @@ -161,6 +161,10 @@ func (n *ptNode) match(b []byte, prefix bool) bool { return true } + if l >= len(b) { + return false + } + nextN, ok := n.next[b[l]] if !ok { return false diff --git a/patricia_test.go b/patricia_test.go index f30992b..c13cbcf 100644 --- a/patricia_test.go +++ b/patricia_test.go @@ -33,6 +33,13 @@ func testPTree(t *testing.T, strs ...string) { if pt.match(strings.NewReader(s + s)) { t.Errorf("%s matches %s", s+s, s) } + + // The following tests are just to catch index out of + // range and off-by-one errors and not the functionality. + pt.matchPrefix(strings.NewReader(s[:len(s)-1])) + pt.match(strings.NewReader(s[:len(s)-1])) + pt.matchPrefix(strings.NewReader(s + "$")) + pt.match(strings.NewReader(s + "$")) } } @@ -45,5 +52,5 @@ func TestPatriciaNonOverlapping(t *testing.T) { } func TestPatriciaOverlapping(t *testing.T) { - testPTree(t, "foo", "far", "farther", "boo", "bar") + testPTree(t, "foo", "far", "farther", "boo", "ba", "bar") }