find.go 680 Bytes
Newer Older
1 2 3 4 5 6
package trie

import (
	"github.com/libp2p/go-libp2p-xor/key"
)

Petar Maymounkov's avatar
Petar Maymounkov committed
7 8 9
// Find looks for the key q in the trie.
// It returns the depth of the leaf reached along the path of q, regardless of whether q was found in that leaf.
// It also returns a boolean flag indicating whether the key was found.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
func (trie *Trie) Find(q key.Key) (reachedDepth int, found bool) {
	return trie.FindAtDepth(0, q)
}

func (trie *Trie) FindAtDepth(depth int, q key.Key) (reachedDepth int, found bool) {
	if qb := trie.Branch[q.BitAt(depth)]; qb != nil {
		return qb.FindAtDepth(depth+1, q)
	} else {
		if trie.Key == nil {
			return depth, false
		} else {
			return depth, key.Equal(trie.Key, q)
		}
	}
}