Skip to content

Commit

Permalink
Fix unicode handling in trie
Browse files Browse the repository at this point in the history
Ref #34
  • Loading branch information
zyedidia committed Jan 9, 2023
1 parent b8c944d commit 254353f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 11 deletions.
10 changes: 5 additions & 5 deletions trie/trie.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ func (t *Trie[V]) LongestPrefix(query string) string {

// Keys returns all keys in the trie.
func (t *Trie[V]) Keys() (queue []string) {
return t.collect(t.root, "", queue)
return t.collect(t.root, nil, queue)
}

// KeysWithPrefix returns all keys with prefix 'prefix'.
Expand All @@ -149,17 +149,17 @@ func (t *Trie[V]) KeysWithPrefix(prefix string) (queue []string) {
if x.valid {
queue = []string{prefix}
}
return t.collect(x.mid, prefix, queue)
return t.collect(x.mid, []byte(prefix), queue)
}

func (t *Trie[V]) collect(x *node[V], prefix string, queue []string) []string {
func (t *Trie[V]) collect(x *node[V], prefix []byte, queue []string) []string {
if x == nil {
return queue
}
queue = t.collect(x.left, prefix, queue)
if x.valid {
queue = append(queue, prefix+string(x.c))
queue = append(queue, string(append(prefix, x.c)))
}
queue = t.collect(x.mid, prefix+string(x.c), queue)
queue = t.collect(x.mid, append(prefix, x.c), queue)
return t.collect(x.right, prefix, queue)
}
12 changes: 6 additions & 6 deletions trie/trie_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,15 +82,15 @@ func TestKeys(t *testing.T) {

func Example() {
tr := trie.New[int]()
tr.Put("foo", 1)
tr.Put("fo", 2)
tr.Put("f§oo", 1)
tr.Put("f§o", 2)
tr.Put("bar", 3)

fmt.Println(tr.Contains("f"))
fmt.Println(tr.Contains("§"))
fmt.Println(tr.KeysWithPrefix(""))
fmt.Println(tr.KeysWithPrefix("f"))
fmt.Println(tr.KeysWithPrefix("f§"))
// Output:
// false
// [bar fo foo]
// [fo foo]
// [bar f§o f§oo]
// [f§o f§oo]
}

0 comments on commit 254353f

Please sign in to comment.