use alloc::vec::Vec;
use cfg_if::cfg_if;
use core::cmp::Ordering;
use core::fmt::{self, Debug};
use core::hash::{Hash, Hasher};
use core::iter::{FromIterator, FusedIterator};
use core::marker::PhantomData;
use core::mem::{self, ManuallyDrop};
use core::ops::{Index, RangeBounds};
use core::ptr;
use crate::{
default::{OrdStoredKey, OrdTotalOrder},
polyfill::*,
SortableBy, TotalOrder,
};
use super::borrow::DormantMutRef;
use super::dedup_sorted_iter::DedupSortedIter;
use super::navigate::{LazyLeafRange, LeafRange};
use super::node::{self, marker, ForceResult::*, Handle, NodeRef, Root};
use super::search::SearchResult::*;
use super::set_val::SetValZST;
mod entry;
#[cfg(feature = "map_try_insert")]
pub use entry::OccupiedError;
pub use entry::{Entry, OccupiedEntry, VacantEntry};
use Entry::*;
pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
#[cfg_attr(feature = "rustc_attrs", rustc_insignificant_dtor)]
pub struct BTreeMap<
K,
V,
O = OrdTotalOrder<<K as OrdStoredKey>::OrdKeyType>,
A: Allocator + Clone = Global,
> {
root: Option<Root<K, V>>,
length: usize,
pub(super) order: O,
pub(super) alloc: ManuallyDrop<A>,
_marker: PhantomData<alloc::boxed::Box<(K, V)>>,
}
cfg_if! {
if #[cfg(feature = "dropck_eyepatch")] {
unsafe impl<#[may_dangle] K, #[may_dangle] V, O, A: Allocator + Clone> Drop
for BTreeMap<K, V, O, A>
{
fn drop(&mut self) {
drop(unsafe { ptr::read(self) }.into_iter())
}
}
} else {
impl<K, V, O, A: Allocator + Clone> Drop for BTreeMap<K, V, O, A> {
fn drop(&mut self) {
drop(unsafe { ptr::read(self) }.into_iter())
}
}
}
}
impl<K, V, O, A: Allocator + Clone> core::panic::UnwindSafe for BTreeMap<K, V, O, A>
where
A: core::panic::UnwindSafe,
K: core::panic::RefUnwindSafe,
V: core::panic::RefUnwindSafe,
{
}
impl<K: Clone, V: Clone, O: Clone, A: Allocator + Clone> Clone for BTreeMap<K, V, O, A> {
fn clone(&self) -> BTreeMap<K, V, O, A> {
fn clone_subtree<'a, K: Clone, V: Clone, O: Clone, A: Allocator + Clone>(
node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
order: &O,
alloc: A,
) -> BTreeMap<K, V, O, A>
where
K: 'a,
V: 'a,
{
match node.force() {
Leaf(leaf) => {
let mut out_tree = BTreeMap {
root: Some(Root::new(alloc.clone())),
length: 0,
order: order.clone(),
alloc: ManuallyDrop::new(alloc),
_marker: PhantomData,
};
{
let root = out_tree.root.as_mut().unwrap(); let mut out_node = match root.borrow_mut().force() {
Leaf(leaf) => leaf,
Internal(_) => unreachable!(),
};
let mut in_edge = leaf.first_edge();
while let Ok(kv) = in_edge.right_kv() {
let (k, v) = kv.into_kv();
in_edge = kv.right_edge();
out_node.push(k.clone(), v.clone());
out_tree.length += 1;
}
}
out_tree
}
Internal(internal) => {
let mut out_tree =
clone_subtree(internal.first_edge().descend(), order, alloc.clone());
{
let out_root = out_tree.root.as_mut().unwrap();
let mut out_node = out_root.push_internal_level(alloc.clone());
let mut in_edge = internal.first_edge();
while let Ok(kv) = in_edge.right_kv() {
let (k, v) = kv.into_kv();
in_edge = kv.right_edge();
let k = (*k).clone();
let v = (*v).clone();
let subtree = clone_subtree(in_edge.descend(), order, alloc.clone());
let (subroot, sublength) = unsafe {
let subtree = ManuallyDrop::new(subtree);
let root = ptr::read(&subtree.root);
let length = subtree.length;
(root, length)
};
out_node.push(
k,
v,
subroot.unwrap_or_else(|| Root::new(alloc.clone())),
);
out_tree.length += 1 + sublength;
}
}
out_tree
}
}
}
if self.is_empty() {
BTreeMap::new_in(self.order.clone(), (*self.alloc).clone())
} else {
clone_subtree(
self.root.as_ref().unwrap().reborrow(),
&self.order,
(*self.alloc).clone(),
) }
}
}
impl<K, Q: ?Sized, O, A: Allocator + Clone> super::Recover<Q> for BTreeMap<K, SetValZST, O, A>
where
K: SortableBy<O>,
Q: SortableBy<O>,
O: TotalOrder,
{
type Key = K;
fn get(&self, key: &Q) -> Option<&K> {
let root_node = self.root.as_ref()?.reborrow();
match root_node.search_tree(key, &self.order) {
Found(handle) => Some(handle.into_kv().0),
GoDown(_) => None,
}
}
fn take(&mut self, key: &Q) -> Option<K> {
let (map, dormant_map) = DormantMutRef::new(self);
let root_node = map.root.as_mut()?.borrow_mut();
match root_node.search_tree(key, &map.order) {
Found(handle) => Some(
OccupiedEntry {
handle,
dormant_map,
alloc: (*map.alloc).clone(),
_marker: PhantomData,
}
.remove_kv()
.0,
),
GoDown(_) => None,
}
}
fn replace(&mut self, key: K) -> Option<K> {
let (map, dormant_map) = DormantMutRef::new(self);
let root_node =
map.root.get_or_insert_with(|| Root::new((*map.alloc).clone())).borrow_mut();
match root_node.search_tree(&key, &map.order) {
Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
GoDown(handle) => {
VacantEntry {
key,
handle: Some(handle),
dormant_map,
alloc: (*map.alloc).clone(),
_marker: PhantomData,
}
.insert(SetValZST::default());
None
}
}
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Iter<'a, K: 'a, V: 'a> {
range: LazyLeafRange<marker::Immut<'a>, K, V>,
length: usize,
}
impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
pub struct IterMut<'a, K: 'a, V: 'a> {
range: LazyLeafRange<marker::ValMut<'a>, K, V>,
length: usize,
_marker: PhantomData<&'a mut (K, V)>,
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IterMut<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let range = Iter { range: self.range.reborrow(), length: self.length };
f.debug_list().entries(range).finish()
}
}
#[cfg_attr(feature = "rustc_attrs", rustc_insignificant_dtor)]
pub struct IntoIter<K, V, A: Allocator + Clone = Global> {
range: LazyLeafRange<marker::Dying, K, V>,
length: usize,
alloc: A,
}
impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
#[inline]
pub(super) fn iter(&self) -> Iter<'_, K, V> {
Iter { range: self.range.reborrow(), length: self.length }
}
}
impl<K: Debug, V: Debug, A: Allocator + Clone> Debug for IntoIter<K, V, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Keys<'a, K, V> {
inner: Iter<'a, K, V>,
}
impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Values<'a, K, V> {
inner: Iter<'a, K, V>,
}
impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct ValuesMut<'a, K, V> {
inner: IterMut<'a, K, V>,
}
impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct IntoKeys<K, V, A: Allocator + Clone = Global> {
inner: IntoIter<K, V, A>,
}
impl<K: fmt::Debug, V, A: Allocator + Clone> fmt::Debug for IntoKeys<K, V, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct IntoValues<K, V, A: Allocator + Clone = Global> {
inner: IntoIter<K, V, A>,
}
impl<K, V: fmt::Debug, A: Allocator + Clone> fmt::Debug for IntoValues<K, V, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Range<'a, K: 'a, V: 'a> {
inner: LeafRange<marker::Immut<'a>, K, V>,
}
impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct RangeMut<'a, K: 'a, V: 'a> {
inner: LeafRange<marker::ValMut<'a>, K, V>,
_marker: PhantomData<&'a mut (K, V)>,
}
impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let range = Range { inner: self.inner.reborrow() };
f.debug_list().entries(range).finish()
}
}
impl<K, V, O> BTreeMap<K, V, O> {
#[must_use]
pub const fn new(order: O) -> BTreeMap<K, V, O> {
BTreeMap {
root: None,
length: 0,
order,
alloc: ManuallyDrop::new(Global),
_marker: PhantomData,
}
}
}
impl<K, V, O, A: Allocator + Clone> BTreeMap<K, V, O, A> {
pub fn clear(&mut self)
where
O: Clone,
{
mem::drop(BTreeMap {
root: mem::replace(&mut self.root, None),
length: mem::replace(&mut self.length, 0),
order: self.order.clone(),
alloc: self.alloc.clone(),
_marker: PhantomData,
});
}
decorate_if! {
if #[cfg(feature = "btreemap_alloc")] {
pub
}
fn new_in(order: O, alloc: A) -> BTreeMap<K, V, O, A> {
BTreeMap {
root: None,
length: 0,
order,
alloc: ManuallyDrop::new(alloc),
_marker: PhantomData,
}
}
}
}
impl<K, V, O, A: Allocator + Clone> BTreeMap<K, V, O, A> {
pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
where
K: SortableBy<O>,
Q: SortableBy<O>,
O: TotalOrder,
{
let root_node = self.root.as_ref()?.reborrow();
match root_node.search_tree(key, &self.order) {
Found(handle) => Some(handle.into_kv().1),
GoDown(_) => None,
}
}
pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
where
K: SortableBy<O>,
Q: SortableBy<O>,
O: TotalOrder,
{
let root_node = self.root.as_ref()?.reborrow();
match root_node.search_tree(k, &self.order) {
Found(handle) => Some(handle.into_kv()),
GoDown(_) => None,
}
}
pub fn first_key_value(&self) -> Option<(&K, &V)>
where
K: SortableBy<O>,
O: TotalOrder,
{
let root_node = self.root.as_ref()?.reborrow();
root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
}
pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, O, A>>
where
K: SortableBy<O>,
O: TotalOrder,
{
let (map, dormant_map) = DormantMutRef::new(self);
let root_node = map.root.as_mut()?.borrow_mut();
let kv = root_node.first_leaf_edge().right_kv().ok()?;
Some(OccupiedEntry {
handle: kv.forget_node_type(),
dormant_map,
alloc: (*map.alloc).clone(),
_marker: PhantomData,
})
}
pub fn pop_first(&mut self) -> Option<(K, V)>
where
K: SortableBy<O>,
O: TotalOrder,
{
self.first_entry().map(|entry| entry.remove_entry())
}
pub fn last_key_value(&self) -> Option<(&K, &V)>
where
K: SortableBy<O>,
O: TotalOrder,
{
let root_node = self.root.as_ref()?.reborrow();
root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
}
pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, O, A>>
where
K: SortableBy<O>,
O: TotalOrder,
{
let (map, dormant_map) = DormantMutRef::new(self);
let root_node = map.root.as_mut()?.borrow_mut();
let kv = root_node.last_leaf_edge().left_kv().ok()?;
Some(OccupiedEntry {
handle: kv.forget_node_type(),
dormant_map,
alloc: (*map.alloc).clone(),
_marker: PhantomData,
})
}
pub fn pop_last(&mut self) -> Option<(K, V)>
where
K: SortableBy<O>,
O: TotalOrder,
{
self.last_entry().map(|entry| entry.remove_entry())
}
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where
K: SortableBy<O>,
Q: SortableBy<O>,
O: TotalOrder,
{
self.get(key).is_some()
}
pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
where
K: SortableBy<O>,
Q: SortableBy<O>,
O: TotalOrder,
{
let root_node = self.root.as_mut()?.borrow_mut();
match root_node.search_tree(key, &self.order) {
Found(handle) => Some(handle.into_val_mut()),
GoDown(_) => None,
}
}
pub fn insert(&mut self, key: K, value: V) -> Option<V>
where
K: SortableBy<O>,
O: TotalOrder,
{
match self.entry(key) {
Occupied(mut entry) => Some(entry.insert(value)),
Vacant(entry) => {
entry.insert(value);
None
}
}
}
#[cfg(feature = "map_try_insert")]
pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, O, A>>
where
K: SortableBy<O>,
O: TotalOrder,
{
match self.entry(key) {
Occupied(entry) => Err(OccupiedError { entry, value }),
Vacant(entry) => Ok(entry.insert(value)),
}
}
pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
where
K: SortableBy<O>,
Q: SortableBy<O>,
O: TotalOrder,
{
self.remove_entry(key).map(|(_, v)| v)
}
pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
where
K: SortableBy<O>,
Q: SortableBy<O>,
O: TotalOrder,
{
let (map, dormant_map) = DormantMutRef::new(self);
let root_node = map.root.as_mut()?.borrow_mut();
match root_node.search_tree(key, &map.order) {
Found(handle) => Some(
OccupiedEntry {
handle,
dormant_map,
alloc: (*map.alloc).clone(),
_marker: PhantomData,
}
.remove_entry(),
),
GoDown(_) => None,
}
}
#[inline]
pub fn retain<F>(&mut self, mut f: F)
where
K: SortableBy<O>,
O: TotalOrder,
F: FnMut(&K, &mut V) -> bool,
{
self.drain_filter(|k, v| !f(k, v));
}
pub fn append(&mut self, other: &mut Self)
where
K: SortableBy<O>,
O: Clone + TotalOrder,
A: Clone,
{
if other.is_empty() {
return;
}
if self.is_empty() {
mem::swap(self, other);
return;
}
let self_iter =
mem::replace(self, Self::new_in(self.order.clone(), (*self.alloc).clone())).into_iter();
let other_iter =
mem::replace(other, Self::new_in(self.order.clone(), (*self.alloc).clone()))
.into_iter();
let root = self.root.get_or_insert_with(|| Root::new((*self.alloc).clone()));
root.append_from_sorted_iters(
self_iter,
other_iter,
&mut self.length,
|a: &(K, V), b: &(K, V)| self.order.cmp_any(&a.0, &b.0),
(*self.alloc).clone(),
)
}
pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
where
T: SortableBy<O>,
K: SortableBy<O>,
O: TotalOrder,
R: RangeBounds<T>,
{
if let Some(root) = &self.root {
Range { inner: root.reborrow().range_search(&self.order, range) }
} else {
Range { inner: LeafRange::none() }
}
}
pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
where
T: SortableBy<O>,
K: SortableBy<O>,
O: TotalOrder,
R: RangeBounds<T>,
{
if let Some(root) = &mut self.root {
RangeMut {
inner: root.borrow_valmut().range_search(&self.order, range),
_marker: PhantomData,
}
} else {
RangeMut { inner: LeafRange::none(), _marker: PhantomData }
}
}
pub fn entry(&mut self, key: K) -> Entry<'_, K, V, O, A>
where
K: SortableBy<O>,
O: TotalOrder,
{
let (map, dormant_map) = DormantMutRef::new(self);
match map.root {
None => Vacant(VacantEntry {
key,
handle: None,
dormant_map,
alloc: (*map.alloc).clone(),
_marker: PhantomData,
}),
Some(ref mut root) => match root.borrow_mut().search_tree(&key, &map.order) {
Found(handle) => Occupied(OccupiedEntry {
handle,
dormant_map,
alloc: (*map.alloc).clone(),
_marker: PhantomData,
}),
GoDown(handle) => Vacant(VacantEntry {
key,
handle: Some(handle),
dormant_map,
alloc: (*map.alloc).clone(),
_marker: PhantomData,
}),
},
}
}
pub fn split_off<Q: ?Sized>(&mut self, key: &Q) -> Self
where
K: SortableBy<O>,
Q: SortableBy<O>,
O: Clone + TotalOrder,
A: Clone,
{
if self.is_empty() {
return Self::new_in(self.order.clone(), (*self.alloc).clone());
}
let total_num = self.len();
let left_root = self.root.as_mut().unwrap();
let right_root = left_root.split_off(key, &self.order, (*self.alloc).clone());
let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
self.length = new_left_len;
BTreeMap {
root: Some(right_root),
length: right_len,
order: self.order.clone(),
alloc: self.alloc.clone(),
_marker: PhantomData,
}
}
decorate_if! {
if #[cfg(feature = "btree_drain_filter")] {
pub
}
fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F, A>
where
K: SortableBy<O>,
O: TotalOrder,
F: FnMut(&K, &mut V) -> bool,
{
let (inner, alloc) = self.drain_filter_inner();
DrainFilter { pred, inner, alloc }
}
}
pub(super) fn drain_filter_inner(&mut self) -> (DrainFilterInner<'_, K, V>, A)
where
K: SortableBy<O>,
O: TotalOrder,
{
if let Some(root) = self.root.as_mut() {
let (root, dormant_root) = DormantMutRef::new(root);
let front = root.borrow_mut().first_leaf_edge();
(
DrainFilterInner {
length: &mut self.length,
dormant_root: Some(dormant_root),
cur_leaf_edge: Some(front),
},
(*self.alloc).clone(),
)
} else {
(
DrainFilterInner {
length: &mut self.length,
dormant_root: None,
cur_leaf_edge: None,
},
(*self.alloc).clone(),
)
}
}
#[inline]
pub fn into_keys(self) -> IntoKeys<K, V, A> {
IntoKeys { inner: self.into_iter() }
}
#[inline]
pub fn into_values(self) -> IntoValues<K, V, A> {
IntoValues { inner: self.into_iter() }
}
pub(crate) fn bulk_build_from_sorted_iter<I>(
iter: I,
order: O,
alloc: A,
) -> BTreeMap<K, V, O, A>
where
K: SortableBy<O>,
O: TotalOrder,
I: IntoIterator<Item = (K, V)>,
{
let mut root = Root::new(alloc.clone());
let mut length = 0;
root.bulk_push(DedupSortedIter::new(iter.into_iter(), &order), &mut length, alloc.clone());
BTreeMap {
root: Some(root),
length,
order,
alloc: ManuallyDrop::new(alloc),
_marker: PhantomData,
}
}
}
impl<'a, K, V, O, A: Allocator + Clone> IntoIterator for &'a BTreeMap<K, V, O, A> {
type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>;
fn into_iter(self) -> Iter<'a, K, V> {
self.iter()
}
}
impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<(&'a K, &'a V)> {
if self.length == 0 {
None
} else {
self.length -= 1;
Some(unsafe { self.range.next_unchecked() })
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.length, Some(self.length))
}
fn last(mut self) -> Option<(&'a K, &'a V)> {
self.next_back()
}
fn min(mut self) -> Option<(&'a K, &'a V)> {
self.next()
}
fn max(mut self) -> Option<(&'a K, &'a V)> {
self.next_back()
}
}
impl<K, V> FusedIterator for Iter<'_, K, V> {}
impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
if self.length == 0 {
None
} else {
self.length -= 1;
Some(unsafe { self.range.next_back_unchecked() })
}
}
}
impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
fn len(&self) -> usize {
self.length
}
}
impl<K, V> Clone for Iter<'_, K, V> {
fn clone(&self) -> Self {
Iter { range: self.range.clone(), length: self.length }
}
}
impl<'a, K, V, O, A: Allocator + Clone> IntoIterator for &'a mut BTreeMap<K, V, O, A> {
type Item = (&'a K, &'a mut V);
type IntoIter = IterMut<'a, K, V>;
fn into_iter(self) -> IterMut<'a, K, V> {
self.iter_mut()
}
}
impl<'a, K, V> Iterator for IterMut<'a, K, V> {
type Item = (&'a K, &'a mut V);
fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
if self.length == 0 {
None
} else {
self.length -= 1;
Some(unsafe { self.range.next_unchecked() })
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.length, Some(self.length))
}
fn last(mut self) -> Option<(&'a K, &'a mut V)> {
self.next_back()
}
fn min(mut self) -> Option<(&'a K, &'a mut V)> {
self.next()
}
fn max(mut self) -> Option<(&'a K, &'a mut V)> {
self.next_back()
}
}
impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
if self.length == 0 {
None
} else {
self.length -= 1;
Some(unsafe { self.range.next_back_unchecked() })
}
}
}
impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
fn len(&self) -> usize {
self.length
}
}
impl<K, V> FusedIterator for IterMut<'_, K, V> {}
impl<'a, K, V> IterMut<'a, K, V> {
#[inline]
pub(super) fn iter(&self) -> Iter<'_, K, V> {
Iter { range: self.range.reborrow(), length: self.length }
}
}
impl<K, V, O, A: Allocator + Clone> IntoIterator for BTreeMap<K, V, O, A> {
type Item = (K, V);
type IntoIter = IntoIter<K, V, A>;
fn into_iter(self) -> IntoIter<K, V, A> {
let mut me = ManuallyDrop::new(self);
if let Some(root) = me.root.take() {
let full_range = root.into_dying().full_range();
IntoIter {
range: full_range,
length: me.length,
alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
}
} else {
IntoIter {
range: LazyLeafRange::none(),
length: 0,
alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
}
}
}
}
impl<K, V, A: Allocator + Clone> Drop for IntoIter<K, V, A> {
fn drop(&mut self) {
struct DropGuard<'a, K, V, A: Allocator + Clone>(&'a mut IntoIter<K, V, A>);
impl<'a, K, V, A: Allocator + Clone> Drop for DropGuard<'a, K, V, A> {
fn drop(&mut self) {
while let Some(kv) = self.0.dying_next() {
unsafe { kv.drop_key_val() };
}
}
}
while let Some(kv) = self.dying_next() {
let guard = DropGuard(self);
unsafe { kv.drop_key_val() };
mem::forget(guard);
}
}
}
impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
fn dying_next(
&mut self,
) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
if self.length == 0 {
self.range.deallocating_end(self.alloc.clone());
None
} else {
self.length -= 1;
Some(unsafe { self.range.deallocating_next_unchecked(self.alloc.clone()) })
}
}
fn dying_next_back(
&mut self,
) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
if self.length == 0 {
self.range.deallocating_end(self.alloc.clone());
None
} else {
self.length -= 1;
Some(unsafe { self.range.deallocating_next_back_unchecked(self.alloc.clone()) })
}
}
}
impl<K, V, A: Allocator + Clone> Iterator for IntoIter<K, V, A> {
type Item = (K, V);
fn next(&mut self) -> Option<(K, V)> {
self.dying_next().map(unsafe { |kv| kv.into_key_val() })
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.length, Some(self.length))
}
}
impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoIter<K, V, A> {
fn next_back(&mut self) -> Option<(K, V)> {
self.dying_next_back().map(unsafe { |kv| kv.into_key_val() })
}
}
impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoIter<K, V, A> {
fn len(&self) -> usize {
self.length
}
}
impl<K, V, A: Allocator + Clone> FusedIterator for IntoIter<K, V, A> {}
impl<'a, K, V> Iterator for Keys<'a, K, V> {
type Item = &'a K;
fn next(&mut self) -> Option<&'a K> {
self.inner.next().map(|(k, _)| k)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
fn last(mut self) -> Option<&'a K> {
self.next_back()
}
fn min(mut self) -> Option<&'a K> {
self.next()
}
fn max(mut self) -> Option<&'a K> {
self.next_back()
}
}
impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
fn next_back(&mut self) -> Option<&'a K> {
self.inner.next_back().map(|(k, _)| k)
}
}
impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K, V> FusedIterator for Keys<'_, K, V> {}
impl<K, V> Clone for Keys<'_, K, V> {
fn clone(&self) -> Self {
Keys { inner: self.inner.clone() }
}
}
impl<'a, K, V> Iterator for Values<'a, K, V> {
type Item = &'a V;
fn next(&mut self) -> Option<&'a V> {
self.inner.next().map(|(_, v)| v)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
fn last(mut self) -> Option<&'a V> {
self.next_back()
}
}
impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
fn next_back(&mut self) -> Option<&'a V> {
self.inner.next_back().map(|(_, v)| v)
}
}
impl<K, V> ExactSizeIterator for Values<'_, K, V> {
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K, V> FusedIterator for Values<'_, K, V> {}
impl<K, V> Clone for Values<'_, K, V> {
fn clone(&self) -> Self {
Values { inner: self.inner.clone() }
}
}
decorate_if! {
if #[cfg(feature = "btree_drain_filter")] { pub }
struct DrainFilter<'a, K, V, F, A: Allocator + Clone = Global>
where
F: 'a + FnMut(&K, &mut V) -> bool,
{
pred: F,
inner: DrainFilterInner<'a, K, V>,
alloc: A,
}
}
pub(super) struct DrainFilterInner<'a, K, V> {
length: &'a mut usize,
dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
}
impl<K, V, F, A: Allocator + Clone> Drop for DrainFilter<'_, K, V, F, A>
where
F: FnMut(&K, &mut V) -> bool,
{
fn drop(&mut self) {
self.for_each(drop);
}
}
impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
where
K: fmt::Debug,
V: fmt::Debug,
F: FnMut(&K, &mut V) -> bool,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
}
}
impl<K, V, F, A: Allocator + Clone> Iterator for DrainFilter<'_, K, V, F, A>
where
F: FnMut(&K, &mut V) -> bool,
{
type Item = (K, V);
fn next(&mut self) -> Option<(K, V)> {
self.inner.next(&mut self.pred, self.alloc.clone())
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<'a, K, V> DrainFilterInner<'a, K, V> {
pub(super) fn peek(&self) -> Option<(&K, &V)> {
let edge = self.cur_leaf_edge.as_ref()?;
edge.reborrow().next_kv().ok().map(Handle::into_kv)
}
pub(super) fn next<F, A: Allocator + Clone>(&mut self, pred: &mut F, alloc: A) -> Option<(K, V)>
where
F: FnMut(&K, &mut V) -> bool,
{
while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
let (k, v) = kv.kv_mut();
if pred(k, v) {
*self.length -= 1;
let (kv, pos) = kv.remove_kv_tracking(
|| {
let root = unsafe { self.dormant_root.take().unwrap().awaken() };
root.pop_internal_level(alloc.clone());
self.dormant_root = Some(DormantMutRef::new(root).1);
},
alloc.clone(),
);
self.cur_leaf_edge = Some(pos);
return Some(kv);
}
self.cur_leaf_edge = Some(kv.next_leaf_edge());
}
None
}
pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(*self.length))
}
}
impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
impl<'a, K, V> Iterator for Range<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<(&'a K, &'a V)> {
self.inner.next_checked()
}
fn last(mut self) -> Option<(&'a K, &'a V)> {
self.next_back()
}
fn min(mut self) -> Option<(&'a K, &'a V)> {
self.next()
}
fn max(mut self) -> Option<(&'a K, &'a V)> {
self.next_back()
}
}
impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
type Item = &'a mut V;
fn next(&mut self) -> Option<&'a mut V> {
self.inner.next().map(|(_, v)| v)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
fn last(mut self) -> Option<&'a mut V> {
self.next_back()
}
}
impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
fn next_back(&mut self) -> Option<&'a mut V> {
self.inner.next_back().map(|(_, v)| v)
}
}
impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
impl<K, V, A: Allocator + Clone> Iterator for IntoKeys<K, V, A> {
type Item = K;
fn next(&mut self) -> Option<K> {
self.inner.next().map(|(k, _)| k)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
fn last(mut self) -> Option<K> {
self.next_back()
}
fn min(mut self) -> Option<K> {
self.next()
}
fn max(mut self) -> Option<K> {
self.next_back()
}
}
impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoKeys<K, V, A> {
fn next_back(&mut self) -> Option<K> {
self.inner.next_back().map(|(k, _)| k)
}
}
impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoKeys<K, V, A> {
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K, V, A: Allocator + Clone> FusedIterator for IntoKeys<K, V, A> {}
impl<K, V, A: Allocator + Clone> Iterator for IntoValues<K, V, A> {
type Item = V;
fn next(&mut self) -> Option<V> {
self.inner.next().map(|(_, v)| v)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
fn last(mut self) -> Option<V> {
self.next_back()
}
}
impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoValues<K, V, A> {
fn next_back(&mut self) -> Option<V> {
self.inner.next_back().map(|(_, v)| v)
}
}
impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoValues<K, V, A> {
fn len(&self) -> usize {
self.inner.len()
}
}
impl<K, V, A: Allocator + Clone> FusedIterator for IntoValues<K, V, A> {}
impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
self.inner.next_back_checked()
}
}
impl<K, V> FusedIterator for Range<'_, K, V> {}
impl<K, V> Clone for Range<'_, K, V> {
fn clone(&self) -> Self {
Range { inner: self.inner.clone() }
}
}
impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
type Item = (&'a K, &'a mut V);
fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
self.inner.next_checked()
}
fn last(mut self) -> Option<(&'a K, &'a mut V)> {
self.next_back()
}
fn min(mut self) -> Option<(&'a K, &'a mut V)> {
self.next()
}
fn max(mut self) -> Option<(&'a K, &'a mut V)> {
self.next_back()
}
}
impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
self.inner.next_back_checked()
}
}
impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
impl<K: SortableBy<O>, V, O: TotalOrder + Default> FromIterator<(K, V)> for BTreeMap<K, V, O> {
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V, O> {
let mut inputs: Vec<_> = iter.into_iter().collect();
if inputs.is_empty() {
return BTreeMap::new(O::default());
}
let order = O::default();
inputs.sort_by(|a, b| order.cmp_any(&a.0, &b.0));
BTreeMap::bulk_build_from_sorted_iter(inputs, order, Global)
}
}
impl<K: SortableBy<O>, V, O: TotalOrder, A: Allocator + Clone> Extend<(K, V)>
for BTreeMap<K, V, O, A>
{
#[inline]
fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
iter.into_iter().for_each(move |(k, v)| {
self.insert(k, v);
});
}
#[inline]
#[cfg(feature = "extend_one")]
fn extend_one(&mut self, (k, v): (K, V)) {
self.insert(k, v);
}
}
impl<'a, K: SortableBy<O> + Copy, V: Copy, O: TotalOrder, A: Allocator + Clone>
Extend<(&'a K, &'a V)> for BTreeMap<K, V, O, A>
{
fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
}
#[inline]
#[cfg(feature = "extend_one")]
fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
self.insert(k, v);
}
}
impl<K: Hash, V: Hash, O, A: Allocator + Clone> Hash for BTreeMap<K, V, O, A> {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_length_prefix(self.len());
for elt in self {
elt.hash(state);
}
}
}
impl<K, V, O: TotalOrder + Default> Default for BTreeMap<K, V, O> {
fn default() -> BTreeMap<K, V, O> {
BTreeMap::new(O::default())
}
}
impl<K: PartialEq, V: PartialEq, O, A: Allocator + Clone> PartialEq for BTreeMap<K, V, O, A> {
fn eq(&self, other: &BTreeMap<K, V, O, A>) -> bool {
self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
}
}
impl<K: Eq, V: Eq, O, A: Allocator + Clone> Eq for BTreeMap<K, V, O, A> {}
impl<K: PartialOrd, V: PartialOrd, O, A: Allocator + Clone> PartialOrd for BTreeMap<K, V, O, A> {
#[inline]
fn partial_cmp(&self, other: &BTreeMap<K, V, O, A>) -> Option<Ordering> {
self.iter().partial_cmp(other.iter())
}
}
impl<K: Ord, V: Ord, O, A: Allocator + Clone> Ord for BTreeMap<K, V, O, A> {
#[inline]
fn cmp(&self, other: &BTreeMap<K, V, O, A>) -> Ordering {
self.iter().cmp(other.iter())
}
}
impl<K: Debug, V: Debug, O, A: Allocator + Clone> Debug for BTreeMap<K, V, O, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
impl<K, Q: ?Sized, V, O, A: Allocator + Clone> Index<&Q> for BTreeMap<K, V, O, A>
where
K: SortableBy<O>,
Q: SortableBy<O>,
O: TotalOrder,
{
type Output = V;
#[inline]
fn index(&self, key: &Q) -> &V {
self.get(key).expect("no entry found for key")
}
}
impl<K: SortableBy<O>, V, O: TotalOrder + Default, const N: usize> From<[(K, V); N]>
for BTreeMap<K, V, O>
{
fn from(mut arr: [(K, V); N]) -> Self {
if N == 0 {
return BTreeMap::new(O::default());
}
let order = O::default();
arr.sort_by(|a, b| order.cmp_any(&a.0, &b.0));
BTreeMap::bulk_build_from_sorted_iter(arr, order, Global)
}
}
impl<K, V, O, A: Allocator + Clone> BTreeMap<K, V, O, A> {
pub fn iter(&self) -> Iter<'_, K, V> {
if let Some(root) = &self.root {
let full_range = root.reborrow().full_range();
Iter { range: full_range, length: self.length }
} else {
Iter { range: LazyLeafRange::none(), length: 0 }
}
}
pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
if let Some(root) = &mut self.root {
let full_range = root.borrow_valmut().full_range();
IterMut { range: full_range, length: self.length, _marker: PhantomData }
} else {
IterMut { range: LazyLeafRange::none(), length: 0, _marker: PhantomData }
}
}
pub fn keys(&self) -> Keys<'_, K, V> {
Keys { inner: self.iter() }
}
pub fn values(&self) -> Values<'_, K, V> {
Values { inner: self.iter() }
}
pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
ValuesMut { inner: self.iter_mut() }
}
decorate_if! {
#[must_use]
pub
if #[cfg(feature = "const_btree_len")] { const }
fn len(&self) -> usize {
self.length
}
}
decorate_if! {
#[must_use]
pub
if #[cfg(feature = "const_btree_len")] { const }
fn is_empty(&self) -> bool {
self.len() == 0
}
}
}
#[cfg(test)]
mod tests;