intersect.go 1.1 KB
Newer Older
Petar Maymounkov's avatar
Petar Maymounkov committed
1 2 3 4 5
package trie

import (
	"github.com/libp2p/go-libp2p-xor/key"
)
Petar Maymounkov's avatar
Petar Maymounkov committed
6 7 8 9 10 11 12 13 14 15 16 17 18

// Intersect computes the intersection of the keys in p and q.
// p and q must be non-nil. The returned trie is never nil.
func Intersect(p, q *XorTrie) *XorTrie {
	return intersect(0, p, q)
}

func intersect(depth int, p, q *XorTrie) *XorTrie {
	switch {
	case p.isLeaf() && q.isLeaf():
		if p.isEmpty() || q.isEmpty() {
			return &XorTrie{} // empty set
		} else {
Petar Maymounkov's avatar
Petar Maymounkov committed
19
			if key.Equal(p.key, q.key) {
Petar Maymounkov's avatar
Petar Maymounkov committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
				return &XorTrie{key: p.key} // singleton
			} else {
				return &XorTrie{} // empty set
			}
		}
	case p.isLeaf() && !q.isLeaf():
		if p.isEmpty() {
			return &XorTrie{} // empty set
		} else {
			if _, found := q.find(depth, p.key); found {
				return &XorTrie{key: p.key}
			} else {
				return &XorTrie{} // empty set
			}
		}
	case !p.isLeaf() && q.isLeaf():
		return Intersect(q, p)
	case !p.isLeaf() && !q.isLeaf():
		disjointUnion := &XorTrie{
			branch: [2]*XorTrie{
				intersect(depth+1, p.branch[0], q.branch[0]),
				intersect(depth+1, p.branch[1], q.branch[1]),
			},
		}
		disjointUnion.shrink()
		return disjointUnion
	}
	panic("unreachable")
}