Skip to content

Instantly share code, notes, and snippets.

@marcinwyszynski
Last active August 29, 2015 13:57
Show Gist options
  • Save marcinwyszynski/9821874 to your computer and use it in GitHub Desktop.
Save marcinwyszynski/9821874 to your computer and use it in GitHub Desktop.
Generic Trie for storing bytes
package trie
const (
// Number of possible values represented by a single byte.
byteValues = 1 << 8
)
type Trie struct {
culDeSac bool
children []*Trie
}
func NewTrie() *Trie {
return &Trie{
culDeSac: false,
children: make([]*Trie, byteValues),
}
}
func (t *Trie) Add(data []byte) {
t.children[data[0]] = NewTrie()
if len(data) == 1 {
t.children[data[0]].culDeSac = true
return
}
t.children[data[0]].Add(data[1:])
}
func (t *Trie) Contains(data []byte) bool {
next := t.children[data[0]]
if next == nil {
return false
}
if len(data) == 1 {
return next.culDeSac
}
return next.Contains(data[1:])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment