8 // WalkFn is used when walking the tree. Takes a
9 // key and value, returning if iteration should
11 type WalkFn func(s string, v interface{}) bool
13 // leafNode is used to represent a value
14 type leafNode struct {
19 // edge is used to represent an edge node
26 // leaf is used to store possible leaf
29 // prefix is the common prefix we ignore
32 // Edges should be stored in-order for iteration.
33 // We avoid a fully materialized slice to save memory,
34 // since in most cases we expect to be sparse
38 func (n *node) isLeaf() bool {
42 func (n *node) addEdge(e edge) {
43 n.edges = append(n.edges, e)
47 func (n *node) replaceEdge(e edge) {
49 idx := sort.Search(num, func(i int) bool {
50 return n.edges[i].label >= e.label
52 if idx < num && n.edges[idx].label == e.label {
53 n.edges[idx].node = e.node
56 panic("replacing missing edge")
59 func (n *node) getEdge(label byte) *node {
61 idx := sort.Search(num, func(i int) bool {
62 return n.edges[i].label >= label
64 if idx < num && n.edges[idx].label == label {
65 return n.edges[idx].node
70 func (n *node) delEdge(label byte) {
72 idx := sort.Search(num, func(i int) bool {
73 return n.edges[i].label >= label
75 if idx < num && n.edges[idx].label == label {
76 copy(n.edges[idx:], n.edges[idx+1:])
77 n.edges[len(n.edges)-1] = edge{}
78 n.edges = n.edges[:len(n.edges)-1]
84 func (e edges) Len() int {
88 func (e edges) Less(i, j int) bool {
89 return e[i].label < e[j].label
92 func (e edges) Swap(i, j int) {
93 e[i], e[j] = e[j], e[i]
96 func (e edges) Sort() {
100 // Tree implements a radix tree. This can be treated as a
101 // Dictionary abstract data type. The main advantage over
102 // a standard hash map is prefix-based lookups and
103 // ordered iteration,
109 // New returns an empty Tree
111 return NewFromMap(nil)
114 // NewFromMap returns a new tree containing the keys
115 // from an existing map
116 func NewFromMap(m map[string]interface{}) *Tree {
117 t := &Tree{root: &node{}}
118 for k, v := range m {
124 // Len is used to return the number of elements in the tree
125 func (t *Tree) Len() int {
129 // longestPrefix finds the length of the shared prefix
131 func longestPrefix(k1, k2 string) int {
133 if l := len(k2); l < max {
137 for i = 0; i < max; i++ {
145 // Insert is used to add a newentry or update
146 // an existing entry. Returns if updated.
147 func (t *Tree) Insert(s string, v interface{}) (interface{}, bool) {
152 // Handle key exhaution
153 if len(search) == 0 {
170 n = n.getEdge(search[0])
172 // No edge, create one
189 // Determine longest prefix of the search key on match
190 commonPrefix := longestPrefix(search, n.prefix)
191 if commonPrefix == len(n.prefix) {
192 search = search[commonPrefix:]
199 prefix: search[:commonPrefix],
201 parent.replaceEdge(edge{
206 // Restore the existing node
208 label: n.prefix[commonPrefix],
211 n.prefix = n.prefix[commonPrefix:]
213 // Create a new leaf node
219 // If the new key is a subset, add to to this node
220 search = search[commonPrefix:]
221 if len(search) == 0 {
226 // Create a new edge for the node
238 // Delete is used to delete a key, returning the previous
239 // value and if it was deleted
240 func (t *Tree) Delete(s string) (interface{}, bool) {
246 // Check for key exhaution
247 if len(search) == 0 {
262 // Consume the search prefix
263 if strings.HasPrefix(search, n.prefix) {
264 search = search[len(n.prefix):]
277 // Check if we should delete this node from the parent
278 if parent != nil && len(n.edges) == 0 {
279 parent.delEdge(label)
282 // Check if we should merge this node
283 if n != t.root && len(n.edges) == 1 {
287 // Check if we should merge the parent's other child
288 if parent != nil && parent != t.root && len(parent.edges) == 1 && !parent.isLeaf() {
292 return leaf.val, true
295 func (n *node) mergeChild() {
298 n.prefix = n.prefix + child.prefix
300 n.edges = child.edges
303 // Get is used to lookup a specific key, returning
304 // the value and if it was found
305 func (t *Tree) Get(s string) (interface{}, bool) {
309 // Check for key exhaution
310 if len(search) == 0 {
312 return n.leaf.val, true
318 n = n.getEdge(search[0])
323 // Consume the search prefix
324 if strings.HasPrefix(search, n.prefix) {
325 search = search[len(n.prefix):]
333 // LongestPrefix is like Get, but instead of an
334 // exact match, it will return the longest prefix match.
335 func (t *Tree) LongestPrefix(s string) (string, interface{}, bool) {
340 // Look for a leaf node
345 // Check for key exhaution
346 if len(search) == 0 {
351 n = n.getEdge(search[0])
356 // Consume the search prefix
357 if strings.HasPrefix(search, n.prefix) {
358 search = search[len(n.prefix):]
364 return last.key, last.val, true
366 return "", nil, false
369 // Minimum is used to return the minimum value in the tree
370 func (t *Tree) Minimum() (string, interface{}, bool) {
374 return n.leaf.key, n.leaf.val, true
376 if len(n.edges) > 0 {
382 return "", nil, false
385 // Maximum is used to return the maximum value in the tree
386 func (t *Tree) Maximum() (string, interface{}, bool) {
389 if num := len(n.edges); num > 0 {
390 n = n.edges[num-1].node
394 return n.leaf.key, n.leaf.val, true
398 return "", nil, false
401 // Walk is used to walk the tree
402 func (t *Tree) Walk(fn WalkFn) {
403 recursiveWalk(t.root, fn)
406 // WalkPrefix is used to walk the tree under a prefix
407 func (t *Tree) WalkPrefix(prefix string, fn WalkFn) {
411 // Check for key exhaution
412 if len(search) == 0 {
418 n = n.getEdge(search[0])
423 // Consume the search prefix
424 if strings.HasPrefix(search, n.prefix) {
425 search = search[len(n.prefix):]
427 } else if strings.HasPrefix(n.prefix, search) {
428 // Child may be under our search prefix
438 // WalkPath is used to walk the tree, but only visiting nodes
439 // from the root down to a given leaf. Where WalkPrefix walks
440 // all the entries *under* the given prefix, this walks the
441 // entries *above* the given prefix.
442 func (t *Tree) WalkPath(path string, fn WalkFn) {
446 // Visit the leaf values if any
447 if n.leaf != nil && fn(n.leaf.key, n.leaf.val) {
451 // Check for key exhaution
452 if len(search) == 0 {
457 n = n.getEdge(search[0])
462 // Consume the search prefix
463 if strings.HasPrefix(search, n.prefix) {
464 search = search[len(n.prefix):]
471 // recursiveWalk is used to do a pre-order walk of a node
472 // recursively. Returns true if the walk should be aborted
473 func recursiveWalk(n *node, fn WalkFn) bool {
474 // Visit the leaf values if any
475 if n.leaf != nil && fn(n.leaf.key, n.leaf.val) {
479 // Recurse on the children
480 for _, e := range n.edges {
481 if recursiveWalk(e.node, fn) {
488 // ToMap is used to walk the tree and convert it into a map
489 func (t *Tree) ToMap() map[string]interface{} {
490 out := make(map[string]interface{}, t.size)
491 t.Walk(func(k string, v interface{}) bool {