BTreeMap: convert search functions to methods

This commit is contained in:
Stein Somers 2020-11-30 12:15:25 +01:00
parent 93e0aedb07
commit de6e53a327
4 changed files with 85 additions and 85 deletions

View File

@ -10,7 +10,7 @@
use super::borrow::DormantMutRef; use super::borrow::DormantMutRef;
use super::node::{self, marker, ForceResult::*, Handle, NodeRef, Root}; use super::node::{self, marker, ForceResult::*, Handle, NodeRef, Root};
use super::search::{self, SearchResult::*}; use super::search::SearchResult::*;
use super::unwrap_unchecked; use super::unwrap_unchecked;
mod entry; mod entry;
@ -230,7 +230,7 @@ impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
fn get(&self, key: &Q) -> Option<&K> { fn get(&self, key: &Q) -> Option<&K> {
let root_node = self.root.as_ref()?.reborrow(); let root_node = self.root.as_ref()?.reborrow();
match search::search_tree(root_node, key) { match root_node.search_tree(key) {
Found(handle) => Some(handle.into_kv().0), Found(handle) => Some(handle.into_kv().0),
GoDown(_) => None, GoDown(_) => None,
} }
@ -239,7 +239,7 @@ fn get(&self, key: &Q) -> Option<&K> {
fn take(&mut self, key: &Q) -> Option<K> { fn take(&mut self, key: &Q) -> Option<K> {
let (map, dormant_map) = DormantMutRef::new(self); let (map, dormant_map) = DormantMutRef::new(self);
let root_node = map.root.as_mut()?.borrow_mut(); let root_node = map.root.as_mut()?.borrow_mut();
match search::search_tree(root_node, key) { match root_node.search_tree(key) {
Found(handle) => { Found(handle) => {
Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_kv().0) Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_kv().0)
} }
@ -250,7 +250,7 @@ fn take(&mut self, key: &Q) -> Option<K> {
fn replace(&mut self, key: K) -> Option<K> { fn replace(&mut self, key: K) -> Option<K> {
let (map, dormant_map) = DormantMutRef::new(self); let (map, dormant_map) = DormantMutRef::new(self);
let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut(); let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut();
match search::search_tree::<marker::Mut<'_>, K, (), K>(root_node, &key) { match root_node.search_tree::<K>(&key) {
Found(mut kv) => Some(mem::replace(kv.key_mut(), key)), Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
GoDown(handle) => { GoDown(handle) => {
VacantEntry { key, handle, dormant_map, _marker: PhantomData }.insert(()); VacantEntry { key, handle, dormant_map, _marker: PhantomData }.insert(());
@ -526,7 +526,7 @@ pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
Q: Ord, Q: Ord,
{ {
let root_node = self.root.as_ref()?.reborrow(); let root_node = self.root.as_ref()?.reborrow();
match search::search_tree(root_node, key) { match root_node.search_tree(key) {
Found(handle) => Some(handle.into_kv().1), Found(handle) => Some(handle.into_kv().1),
GoDown(_) => None, GoDown(_) => None,
} }
@ -554,7 +554,7 @@ pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
Q: Ord, Q: Ord,
{ {
let root_node = self.root.as_ref()?.reborrow(); let root_node = self.root.as_ref()?.reborrow();
match search::search_tree(root_node, k) { match root_node.search_tree(k) {
Found(handle) => Some(handle.into_kv()), Found(handle) => Some(handle.into_kv()),
GoDown(_) => None, GoDown(_) => None,
} }
@ -762,7 +762,7 @@ pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
Q: Ord, Q: Ord,
{ {
let root_node = self.root.as_mut()?.borrow_mut(); let root_node = self.root.as_mut()?.borrow_mut();
match search::search_tree(root_node, key) { match root_node.search_tree(key) {
Found(handle) => Some(handle.into_val_mut()), Found(handle) => Some(handle.into_val_mut()),
GoDown(_) => None, GoDown(_) => None,
} }
@ -858,7 +858,7 @@ pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
{ {
let (map, dormant_map) = DormantMutRef::new(self); let (map, dormant_map) = DormantMutRef::new(self);
let root_node = map.root.as_mut()?.borrow_mut(); let root_node = map.root.as_mut()?.borrow_mut();
match search::search_tree(root_node, key) { match root_node.search_tree(key) {
Found(handle) => { Found(handle) => {
Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry()) Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry())
} }
@ -1051,7 +1051,7 @@ pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
// FIXME(@porglezomp) Avoid allocating if we don't insert // FIXME(@porglezomp) Avoid allocating if we don't insert
let (map, dormant_map) = DormantMutRef::new(self); let (map, dormant_map) = DormantMutRef::new(self);
let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut(); let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut();
match search::search_tree(root_node, &key) { match root_node.search_tree(&key) {
Found(handle) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }), Found(handle) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }),
GoDown(handle) => { GoDown(handle) => {
Vacant(VacantEntry { key, handle, dormant_map, _marker: PhantomData }) Vacant(VacantEntry { key, handle, dormant_map, _marker: PhantomData })

View File

@ -5,7 +5,7 @@
use core::ptr; use core::ptr;
use super::node::{marker, ForceResult::*, Handle, NodeRef}; use super::node::{marker, ForceResult::*, Handle, NodeRef};
use super::search::{self, SearchResult}; use super::search::SearchResult;
use super::unwrap_unchecked; use super::unwrap_unchecked;
/// Finds the leaf edges delimiting a specified range in or underneath a node. /// Finds the leaf edges delimiting a specified range in or underneath a node.
@ -42,14 +42,14 @@ fn range_search<BorrowType, K, V, Q, R>(
loop { loop {
let front = match (min_found, range.start_bound()) { let front = match (min_found, range.start_bound()) {
(false, Included(key)) => match search::search_node(min_node, key) { (false, Included(key)) => match min_node.search_node(key) {
SearchResult::Found(kv) => { SearchResult::Found(kv) => {
min_found = true; min_found = true;
kv.left_edge() kv.left_edge()
} }
SearchResult::GoDown(edge) => edge, SearchResult::GoDown(edge) => edge,
}, },
(false, Excluded(key)) => match search::search_node(min_node, key) { (false, Excluded(key)) => match min_node.search_node(key) {
SearchResult::Found(kv) => { SearchResult::Found(kv) => {
min_found = true; min_found = true;
kv.right_edge() kv.right_edge()
@ -62,14 +62,14 @@ fn range_search<BorrowType, K, V, Q, R>(
}; };
let back = match (max_found, range.end_bound()) { let back = match (max_found, range.end_bound()) {
(false, Included(key)) => match search::search_node(max_node, key) { (false, Included(key)) => match max_node.search_node(key) {
SearchResult::Found(kv) => { SearchResult::Found(kv) => {
max_found = true; max_found = true;
kv.right_edge() kv.right_edge()
} }
SearchResult::GoDown(edge) => edge, SearchResult::GoDown(edge) => edge,
}, },
(false, Excluded(key)) => match search::search_node(max_node, key) { (false, Excluded(key)) => match max_node.search_node(key) {
SearchResult::Found(kv) => { SearchResult::Found(kv) => {
max_found = true; max_found = true;
kv.left_edge() kv.left_edge()

View File

@ -10,79 +10,79 @@ pub enum SearchResult<BorrowType, K, V, FoundType, GoDownType> {
GoDown(Handle<NodeRef<BorrowType, K, V, GoDownType>, marker::Edge>), GoDown(Handle<NodeRef<BorrowType, K, V, GoDownType>, marker::Edge>),
} }
/// Looks up a given key in a (sub)tree headed by the given node, recursively. pub enum IndexResult {
/// Returns a `Found` with the handle of the matching KV, if any. Otherwise, KV(usize),
/// returns a `GoDown` with the handle of the leaf edge where the key belongs. Edge(usize),
/// }
/// The result is meaningful only if the tree is ordered by key, like the tree
/// in a `BTreeMap` is. impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
pub fn search_tree<BorrowType, K, V, Q: ?Sized>( /// Looks up a given key in a (sub)tree headed by the node, recursively.
mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>, /// Returns a `Found` with the handle of the matching KV, if any. Otherwise,
key: &Q, /// returns a `GoDown` with the handle of the leaf edge where the key belongs.
) -> SearchResult<BorrowType, K, V, marker::LeafOrInternal, marker::Leaf> ///
where /// The result is meaningful only if the tree is ordered by key, like the tree
Q: Ord, /// in a `BTreeMap` is.
K: Borrow<Q>, pub fn search_tree<Q: ?Sized>(
{ mut self,
loop { key: &Q,
match search_node(node, key) { ) -> SearchResult<BorrowType, K, V, marker::LeafOrInternal, marker::Leaf>
Found(handle) => return Found(handle), where
GoDown(handle) => match handle.force() { Q: Ord,
Leaf(leaf) => return GoDown(leaf), K: Borrow<Q>,
Internal(internal) => { {
node = internal.descend(); loop {
continue; self = match self.search_node(key) {
} Found(handle) => return Found(handle),
}, GoDown(handle) => match handle.force() {
Leaf(leaf) => return GoDown(leaf),
Internal(internal) => internal.descend(),
},
}
} }
} }
} }
/// Looks up a given key in a given node, without recursion. impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
/// Returns a `Found` with the handle of the matching KV, if any. Otherwise, /// Looks up a given key in the node, without recursion.
/// returns a `GoDown` with the handle of the edge where the key might be found /// Returns a `Found` with the handle of the matching KV, if any. Otherwise,
/// (if the node is internal) or where the key can be inserted. /// returns a `GoDown` with the handle of the edge where the key might be found
/// /// (if the node is internal) or where the key can be inserted.
/// The result is meaningful only if the tree is ordered by key, like the tree ///
/// in a `BTreeMap` is. /// The result is meaningful only if the tree is ordered by key, like the tree
pub fn search_node<BorrowType, K, V, Type, Q: ?Sized>( /// in a `BTreeMap` is.
node: NodeRef<BorrowType, K, V, Type>, pub fn search_node<Q: ?Sized>(self, key: &Q) -> SearchResult<BorrowType, K, V, Type, Type>
key: &Q, where
) -> SearchResult<BorrowType, K, V, Type, Type> Q: Ord,
where K: Borrow<Q>,
Q: Ord, {
K: Borrow<Q>, match self.find_index(key) {
{ IndexResult::KV(idx) => Found(unsafe { Handle::new_kv(self, idx) }),
match search_linear(&node, key) { IndexResult::Edge(idx) => GoDown(unsafe { Handle::new_edge(self, idx) }),
(idx, true) => Found(unsafe { Handle::new_kv(node, idx) }),
(idx, false) => GoDown(unsafe { Handle::new_edge(node, idx) }),
}
}
/// Returns either the KV index in the node at which the key (or an equivalent)
/// exists and `true`, or the edge index where the key belongs and `false`.
///
/// The result is meaningful only if the tree is ordered by key, like the tree
/// in a `BTreeMap` is.
fn search_linear<BorrowType, K, V, Type, Q: ?Sized>(
node: &NodeRef<BorrowType, K, V, Type>,
key: &Q,
) -> (usize, bool)
where
Q: Ord,
K: Borrow<Q>,
{
// This function is defined over all borrow types (immutable, mutable, owned).
// Using `keys_at()` is fine here even if BorrowType is mutable, as all we return
// is an index -- not a reference.
let len = node.len();
for i in 0..len {
let k = unsafe { node.reborrow().key_at(i) };
match key.cmp(k.borrow()) {
Ordering::Greater => {}
Ordering::Equal => return (i, true),
Ordering::Less => return (i, false),
} }
} }
(len, false)
/// Returns either the KV index in the node at which the key (or an equivalent)
/// exists, or the edge index where the key belongs.
///
/// The result is meaningful only if the tree is ordered by key, like the tree
/// in a `BTreeMap` is.
fn find_index<Q: ?Sized>(&self, key: &Q) -> IndexResult
where
Q: Ord,
K: Borrow<Q>,
{
// This function is defined over all borrow types (immutable, mutable, owned).
// Using `keys_at()` is fine here even if BorrowType is mutable, as all we return
// is an index -- not a reference.
let len = self.len();
for i in 0..len {
let k = unsafe { self.reborrow().key_at(i) };
match key.cmp(k.borrow()) {
Ordering::Greater => {}
Ordering::Equal => return IndexResult::KV(i),
Ordering::Less => return IndexResult::Edge(i),
}
}
IndexResult::Edge(len)
}
} }

View File

@ -1,6 +1,6 @@
use super::map::MIN_LEN; use super::map::MIN_LEN;
use super::node::{ForceResult::*, Root}; use super::node::{ForceResult::*, Root};
use super::search::{search_node, SearchResult::*}; use super::search::SearchResult::*;
use core::borrow::Borrow; use core::borrow::Borrow;
impl<K, V> Root<K, V> { impl<K, V> Root<K, V> {
@ -21,7 +21,7 @@ pub fn split_off<Q: ?Sized + Ord>(&mut self, right_root: &mut Self, key: &Q)
let mut right_node = right_root.borrow_mut(); let mut right_node = right_root.borrow_mut();
loop { loop {
let mut split_edge = match search_node(left_node, key) { let mut split_edge = match left_node.search_node(key) {
// key is going to the right tree // key is going to the right tree
Found(kv) => kv.left_edge(), Found(kv) => kv.left_edge(),
GoDown(edge) => edge, GoDown(edge) => edge,