| 1 |
use core::borrow::Borrow; |
| 2 |
|
| 3 |
use core::cmp::Ordering; |
| 4 |
|
| 5 |
use super::node::{marker, ForceResult::*, Handle, NodeRef}; |
| 6 |
|
| 7 |
use SearchResult::*; |
| 8 |
|
| 9 |
pub enum SearchResult<BorrowType, K, V, FoundType, GoDownType> { |
| 10 |
Found(Handle<NodeRef<BorrowType, K, V, FoundType>, marker::KV>), |
| 11 |
GoDown(Handle<NodeRef<BorrowType, K, V, GoDownType>, marker::Edge>), |
| 12 |
} |
| 13 |
|
| 14 |
pub fn search_tree<BorrowType, K, V, Q: ?Sized>( |
| 15 |
mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>, |
| 16 |
key: &Q, |
| 17 |
) -> SearchResult<BorrowType, K, V, marker::LeafOrInternal, marker::Leaf> |
| 18 |
where |
| 19 |
Q: Ord, |
| 20 |
K: Borrow<Q>, |
| 21 |
{ |
| 22 |
loop { |
| 23 |
match search_node(node, key) { |
| 24 |
Found(handle) => return Found(handle), |
| 25 |
GoDown(handle) => match handle.force() { |
| 26 |
Leaf(leaf) => return GoDown(leaf), |
| 27 |
Internal(internal) => { |
| 28 |
node = internal.descend(); |
| 29 |
continue; |
| 30 |
} |
| 31 |
}, |
| 32 |
} |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
pub fn search_node<BorrowType, K, V, Type, Q: ?Sized>( |
| 37 |
node: NodeRef<BorrowType, K, V, Type>, |
| 38 |
key: &Q, |
| 39 |
) -> SearchResult<BorrowType, K, V, Type, Type> |
| 40 |
where |
| 41 |
Q: Ord, |
| 42 |
K: Borrow<Q>, |
| 43 |
{ |
| 44 |
match search_linear(&node, key) { |
| 45 |
(idx, true) => Found(Handle::new_kv(node, idx)), |
| 46 |
(idx, false) => SearchResult::GoDown(Handle::new_edge(node, idx)), |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
pub fn search_linear<BorrowType, K, V, Type, Q: ?Sized>( |
| 51 |
node: &NodeRef<BorrowType, K, V, Type>, |
| 52 |
key: &Q, |
| 53 |
) -> (usize, bool) |
| 54 |
where |
| 55 |
Q: Ord, |
| 56 |
K: Borrow<Q>, |
| 57 |
{ |
| 58 |
for (i, k) in node.keys().iter().enumerate() { |
| 59 |
match key.cmp(k.borrow()) { |
| 60 |
Ordering::Greater => {} |
| 61 |
Ordering::Equal => return (i, true), |
| 62 |
Ordering::Less => return (i, false), |
| 63 |
} |
| 64 |
} |
| 65 |
(node.keys().len(), false) |
| 66 |
} |