btree_slab/generic/
map.rs

1use crate::generic::node::{Address, Balance, Item, Node, WouldUnderflow};
2use cc_traits::{SimpleCollectionMut, SimpleCollectionRef, Slab, SlabMut};
3use std::{
4	borrow::Borrow,
5	cmp::Ordering,
6	hash::{Hash, Hasher},
7	iter::{DoubleEndedIterator, ExactSizeIterator, FromIterator, FusedIterator},
8	marker::PhantomData,
9	ops::{Bound, Index, RangeBounds},
10};
11
12mod entry;
13mod ext;
14
15pub use entry::*;
16pub use ext::*;
17
18/// Knuth order of the B-Trees.
19///
20/// Must be at least 4.
21pub const M: usize = 8;
22
23/// A map based on a B-Tree.
24///
25/// This offers an alternative over the standard implementation of B-Trees where nodes are
26/// allocated in a contiguous array of [`Node`]s, reducing the cost of tree nodes allocations.
27/// In addition the crate provides advanced functions to iterate through and update the map
28/// efficiently.
29///
30/// # Basic usage
31///
32/// Basic usage is similar to the map data structures offered by the standard library.
33/// ```
34/// use btree_slab::BTreeMap;
35///
36/// // type inference lets us omit an explicit type signature (which
37/// // would be `BTreeMap<&str, &str>` in this example).
38/// let mut movie_reviews = BTreeMap::new();
39///
40/// // review some movies.
41/// movie_reviews.insert("Office Space",       "Deals with real issues in the workplace.");
42/// movie_reviews.insert("Pulp Fiction",       "Masterpiece.");
43/// movie_reviews.insert("The Godfather",      "Very enjoyable.");
44/// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
45///
46/// // check for a specific one.
47/// if !movie_reviews.contains_key("Les Misérables") {
48///     println!("We've got {} reviews, but Les Misérables ain't one.",
49///              movie_reviews.len());
50/// }
51///
52/// // oops, this review has a lot of spelling mistakes, let's delete it.
53/// movie_reviews.remove("The Blues Brothers");
54///
55/// // look up the values associated with some keys.
56/// let to_find = ["Up!", "Office Space"];
57/// for movie in &to_find {
58///     match movie_reviews.get(movie) {
59///        Some(review) => println!("{}: {}", movie, review),
60///        None => println!("{} is unreviewed.", movie)
61///     }
62/// }
63///
64/// // Look up the value for a key (will panic if the key is not found).
65/// println!("Movie review: {}", movie_reviews["Office Space"]);
66///
67/// // iterate over everything.
68/// for (movie, review) in &movie_reviews {
69///     println!("{}: \"{}\"", movie, review);
70/// }
71/// ```
72///
73/// # Advanced usage
74///
75/// ## Entry API
76///
77/// This crate also reproduces the Entry API defined by the standard library,
78/// which allows for more complex methods of getting, setting, updating and removing keys and
79/// their values:
80/// ```
81/// use btree_slab::BTreeMap;
82///
83/// // type inference lets us omit an explicit type signature (which
84/// // would be `BTreeMap<&str, u8>` in this example).
85/// let mut player_stats: BTreeMap<&str, u8> = BTreeMap::new();
86///
87/// fn random_stat_buff() -> u8 {
88///     // could actually return some random value here - let's just return
89///     // some fixed value for now
90///     42
91/// }
92///
93/// // insert a key only if it doesn't already exist
94/// player_stats.entry("health").or_insert(100);
95///
96/// // insert a key using a function that provides a new value only if it
97/// // doesn't already exist
98/// player_stats.entry("defence").or_insert_with(random_stat_buff);
99///
100/// // update a key, guarding against the key possibly not being set
101/// let stat = player_stats.entry("attack").or_insert(100);
102/// *stat += random_stat_buff();
103/// ```
104///
105/// ## Mutable iterators
106///
107/// This type provides two iterators providing mutable references to the entries:
108///   - [`IterMut`] is a double-ended iterator following the standard
109///     [`std::collections::btree_map::IterMut`] implementation.
110///   - [`EntriesMut`] is a single-ended iterator that allows, in addition,
111///     insertion and deletion of entries at the current iterator's position in the map.
112///     An example is given below.
113///
114/// ```
115/// use btree_slab::BTreeMap;
116///
117/// let mut map = BTreeMap::new();
118/// map.insert("a", 1);
119/// map.insert("b", 2);
120/// map.insert("d", 4);
121///
122/// let mut entries = map.entries_mut();
123/// entries.next();
124/// entries.next();
125/// entries.insert("c", 3); // the inserted key must preserve the order of the map.
126///
127/// let entries: Vec<_> = map.into_iter().collect();
128/// assert_eq!(entries, vec![("a", 1), ("b", 2), ("c", 3), ("d", 4)]);
129/// ```
130///
131/// ## Custom allocation
132///
133/// This data structure is built on top of a slab data structure,
134/// but is agnostic of the actual slab implementation which is taken as parameter (`C`).
135/// If the `slab` feature is enabled,
136/// the [`slab::Slab`] implementation is used by default by reexporting
137/// `BTreeMap<K, V, slab::Slab<_>>` at the root of the crate.
138/// Any container implementing "slab-like" functionalities can be used.
139///
140/// ## Extended API
141///
142/// This crate provides the two traits [`BTreeExt`] and [`BTreeExtMut`] that can be imported to
143/// expose low-level operations on [`BTreeMap`].
144/// The extended API allows the caller to directly navigate and access the entries of the tree
145/// using their [`Address`].
146/// These functions are not intended to be directly called by the users,
147/// but can be used to extend the data structure with new functionalities.
148///
149/// # Correctness
150///
151/// It is a logic error for a key to be modified in such a way that the key's ordering relative
152/// to any other key, as determined by the [`Ord`] trait, changes while it is in the map.
153/// This is normally only possible through [`Cell`](`std::cell::Cell`),
154/// [`RefCell`](`std::cell::RefCell`), global state, I/O, or unsafe code.
155#[derive(Clone)]
156pub struct BTreeMap<K, V, C> {
157	/// Allocated and free nodes.
158	nodes: C,
159
160	/// Root node id.
161	root: Option<usize>,
162
163	/// Number of items in the tree.
164	len: usize,
165
166	k: PhantomData<K>,
167	v: PhantomData<V>,
168}
169
170impl<K, V, C> BTreeMap<K, V, C> {
171	/// Create a new empty B-tree.
172	#[inline]
173	pub fn new() -> BTreeMap<K, V, C>
174	where
175		C: Default,
176	{
177		BTreeMap {
178			nodes: Default::default(),
179			root: None,
180			len: 0,
181			k: PhantomData,
182			v: PhantomData,
183		}
184	}
185
186	/// Returns `true` if the map contains no elements.
187	///
188	/// # Example
189	///
190	/// ```
191	/// use btree_slab::BTreeMap;
192	///
193	/// let mut a = BTreeMap::new();
194	/// assert!(a.is_empty());
195	/// a.insert(1, "a");
196	/// assert!(!a.is_empty());
197	/// ```
198	#[inline]
199	pub fn is_empty(&self) -> bool {
200		self.root.is_none()
201	}
202
203	/// Returns the number of elements in the map.
204	///
205	/// # Example
206	///
207	/// ```
208	/// use btree_slab::BTreeMap;
209	///
210	/// let mut a = BTreeMap::new();
211	/// assert_eq!(a.len(), 0);
212	/// a.insert(1, "a");
213	/// assert_eq!(a.len(), 1);
214	/// ```
215	#[inline]
216	pub fn len(&self) -> usize {
217		self.len
218	}
219}
220
221impl<K, V, C: Slab<Node<K, V>>> BTreeMap<K, V, C>
222where
223	C: SimpleCollectionRef,
224{
225	/// Returns the key-value pair corresponding to the supplied key.
226	///
227	/// The supplied key may be any borrowed form of the map's key type, but the ordering
228	/// on the borrowed form *must* match the ordering on the key type.
229	///
230	/// # Example
231	///
232	/// ```
233	/// use btree_slab::BTreeMap;
234	///
235	/// let mut map: BTreeMap<i32, &str> = BTreeMap::new();
236	/// map.insert(1, "a");
237	/// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
238	/// assert_eq!(map.get_key_value(&2), None);
239	/// ```
240	#[inline]
241	pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
242	where
243		K: Borrow<Q>,
244		Q: Ord,
245	{
246		match self.root {
247			Some(id) => self.get_in(key, id),
248			None => None,
249		}
250	}
251
252	/// Returns the key-value pair corresponding to the supplied key.
253	///
254	/// The supplied key may be any borrowed form of the map's key type, but the ordering
255	/// on the borrowed form *must* match the ordering on the key type.
256	///
257	/// # Examples
258	///
259	/// ```
260	/// use btree_slab::BTreeMap;
261	///
262	/// let mut map = BTreeMap::new();
263	/// map.insert(1, "a");
264	/// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
265	/// assert_eq!(map.get_key_value(&2), None);
266	/// ```
267	#[inline]
268	pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
269	where
270		K: Borrow<Q>,
271		Q: Ord,
272	{
273		match self.address_of(k) {
274			Ok(addr) => {
275				let item = self.item(addr).unwrap();
276				Some((item.key(), item.value()))
277			}
278			Err(_) => None,
279		}
280	}
281
282	/// Returns the first key-value pair in the map.
283	/// The key in this pair is the minimum key in the map.
284	///
285	/// # Example
286	///
287	/// ```
288	/// use btree_slab::BTreeMap;
289	///
290	/// let mut map = BTreeMap::new();
291	/// assert_eq!(map.first_key_value(), None);
292	/// map.insert(1, "b");
293	/// map.insert(2, "a");
294	/// assert_eq!(map.first_key_value(), Some((&1, &"b")));
295	/// ```
296	#[inline]
297	pub fn first_key_value(&self) -> Option<(&K, &V)> {
298		match self.first_item_address() {
299			Some(addr) => {
300				let item = self.item(addr).unwrap();
301				Some((item.key(), item.value()))
302			}
303			None => None,
304		}
305	}
306
307	/// Returns the last key-value pair in the map.
308	/// The key in this pair is the maximum key in the map.
309	///
310	/// # Examples
311	///
312	/// Basic usage:
313	///
314	/// ```
315	/// use btree_slab::BTreeMap;
316	///
317	/// let mut map = BTreeMap::new();
318	/// map.insert(1, "b");
319	/// map.insert(2, "a");
320	/// assert_eq!(map.last_key_value(), Some((&2, &"a")));
321	/// ```
322	#[inline]
323	pub fn last_key_value(&self) -> Option<(&K, &V)> {
324		match self.last_item_address() {
325			Some(addr) => {
326				let item = self.item(addr).unwrap();
327				Some((item.key(), item.value()))
328			}
329			None => None,
330		}
331	}
332
333	/// Gets an iterator over the entries of the map, sorted by key.
334	///
335	/// # Example
336	///
337	/// ```
338	/// use btree_slab::BTreeMap;
339	///
340	/// let mut map = BTreeMap::new();
341	/// map.insert(3, "c");
342	/// map.insert(2, "b");
343	/// map.insert(1, "a");
344	///
345	/// for (key, value) in map.iter() {
346	///     println!("{}: {}", key, value);
347	/// }
348	///
349	/// let (first_key, first_value) = map.iter().next().unwrap();
350	/// assert_eq!((*first_key, *first_value), (1, "a"));
351	/// ```
352	#[inline]
353	pub fn iter(&self) -> Iter<K, V, C> {
354		Iter::new(self)
355	}
356
357	/// Gets an iterator over the keys of the map, in sorted order.
358	///
359	/// # Example
360	///
361	/// ```
362	/// use btree_slab::BTreeMap;
363	///
364	/// let mut a = BTreeMap::new();
365	/// a.insert(2, "b");
366	/// a.insert(1, "a");
367	///
368	/// let keys: Vec<_> = a.keys().cloned().collect();
369	/// assert_eq!(keys, [1, 2]);
370	/// ```
371	#[inline]
372	pub fn keys(&self) -> Keys<K, V, C> {
373		Keys { inner: self.iter() }
374	}
375
376	/// Gets an iterator over the values of the map, in order by key.
377	///
378	/// # Example
379	///
380	/// ```
381	/// use btree_slab::BTreeMap;
382	///
383	/// let mut a = BTreeMap::new();
384	/// a.insert(1, "hello");
385	/// a.insert(2, "goodbye");
386	///
387	/// let values: Vec<&str> = a.values().cloned().collect();
388	/// assert_eq!(values, ["hello", "goodbye"]);
389	/// ```
390	#[inline]
391	pub fn values(&self) -> Values<K, V, C> {
392		Values { inner: self.iter() }
393	}
394
395	/// Constructs a double-ended iterator over a sub-range of elements in the map.
396	/// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
397	/// yield elements from min (inclusive) to max (exclusive).
398	/// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
399	/// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
400	/// range from 4 to 10.
401	///
402	/// # Panics
403	///
404	/// Panics if range `start > end`.
405	/// Panics if range `start == end` and both bounds are `Excluded`.
406	///
407	/// # Example
408	///
409	/// ```
410	/// use btree_slab::BTreeMap;
411	/// use std::ops::Bound::Included;
412	///
413	/// let mut map = BTreeMap::new();
414	/// map.insert(3, "a");
415	/// map.insert(5, "b");
416	/// map.insert(8, "c");
417	/// for (&key, &value) in map.range((Included(&4), Included(&8))) {
418	///     println!("{}: {}", key, value);
419	/// }
420	/// assert_eq!(Some((&5, &"b")), map.range(4..).next());
421	/// ```
422	#[inline]
423	pub fn range<T: ?Sized, R>(&self, range: R) -> Range<K, V, C>
424	where
425		T: Ord,
426		K: Borrow<T>,
427		R: RangeBounds<T>,
428	{
429		Range::new(self, range)
430	}
431
432	/// Returns `true` if the map contains a value for the specified key.
433	///
434	/// The key may be any borrowed form of the map's key type, but the ordering
435	/// on the borrowed form *must* match the ordering on the key type.
436	///
437	/// # Example
438	/// ```
439	/// use btree_slab::BTreeMap;
440	///
441	/// let mut map: BTreeMap<i32, &str> = BTreeMap::new();
442	/// map.insert(1, "a");
443	/// assert_eq!(map.contains_key(&1), true);
444	/// assert_eq!(map.contains_key(&2), false);
445	/// ```
446	#[inline]
447	pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
448	where
449		K: Borrow<Q>,
450		Q: Ord,
451	{
452		self.get(key).is_some()
453	}
454
455	/// Write the tree in the DOT graph descrption language.
456	///
457	/// Requires the `dot` feature.
458	#[cfg(feature = "dot")]
459	#[inline]
460	pub fn dot_write<W: std::io::Write>(&self, f: &mut W) -> std::io::Result<()>
461	where
462		K: std::fmt::Display,
463		V: std::fmt::Display,
464	{
465		write!(f, "digraph tree {{\n\tnode [shape=record];\n")?;
466		if let Some(id) = self.root {
467			self.dot_write_node(f, id)?
468		}
469		write!(f, "}}")
470	}
471
472	/// Write the given node in the DOT graph descrption language.
473	///
474	/// Requires the `dot` feature.
475	#[cfg(feature = "dot")]
476	#[inline]
477	fn dot_write_node<W: std::io::Write>(&self, f: &mut W, id: usize) -> std::io::Result<()>
478	where
479		K: std::fmt::Display,
480		V: std::fmt::Display,
481	{
482		let name = format!("n{}", id);
483		let node = self.node(id);
484
485		write!(f, "\t{} [label=\"", name)?;
486		if let Some(parent) = node.parent() {
487			write!(f, "({})|", parent)?;
488		}
489
490		node.dot_write_label(f)?;
491		writeln!(f, "({})\"];", id)?;
492
493		for child_id in node.children() {
494			self.dot_write_node(f, child_id)?;
495			let child_name = format!("n{}", child_id);
496			writeln!(f, "\t{} -> {}", name, child_name)?;
497		}
498
499		Ok(())
500	}
501}
502
503impl<K, V, C: SlabMut<Node<K, V>>> BTreeMap<K, V, C>
504where
505	C: SimpleCollectionRef,
506	C: SimpleCollectionMut,
507{
508	/// Clears the map, removing all elements.
509	///
510	/// # Example
511	///
512	/// ```
513	/// use btree_slab::BTreeMap;
514	///
515	/// let mut a = BTreeMap::new();
516	/// a.insert(1, "a");
517	/// a.clear();
518	/// assert!(a.is_empty());
519	/// ```
520	#[inline]
521	pub fn clear(&mut self)
522	where
523		C: cc_traits::Clear,
524	{
525		self.root = None;
526		self.len = 0;
527		self.nodes.clear()
528	}
529
530	/// Returns a mutable reference to the value corresponding to the key.
531	///
532	/// The key may be any borrowed form of the map's key type, but the ordering
533	/// on the borrowed form *must* match the ordering on the key type.
534	///
535	/// # Example
536	///
537	/// ```
538	/// use btree_slab::BTreeMap;
539	///
540	/// let mut map = BTreeMap::new();
541	/// map.insert(1, "a");
542	/// if let Some(x) = map.get_mut(&1) {
543	///     *x = "b";
544	/// }
545	/// assert_eq!(map[&1], "b");
546	/// ```
547	#[inline]
548	pub fn get_mut(&mut self, key: &K) -> Option<&mut V>
549	where
550		K: Ord,
551	{
552		match self.root {
553			Some(id) => self.get_mut_in(key, id),
554			None => None,
555		}
556	}
557
558	/// Gets the given key's corresponding entry in the map for in-place manipulation.
559	///
560	/// # Example
561	///
562	/// ```
563	/// use btree_slab::BTreeMap;
564	///
565	/// let mut letters = BTreeMap::new();
566	///
567	/// for ch in "a short treatise on fungi".chars() {
568	///     let counter = letters.entry(ch).or_insert(0);
569	///     *counter += 1;
570	/// }
571	///
572	/// assert_eq!(letters[&'s'], 2);
573	/// assert_eq!(letters[&'t'], 3);
574	/// assert_eq!(letters[&'u'], 1);
575	/// assert_eq!(letters.get(&'y'), None);
576	/// ```
577	#[inline]
578	pub fn entry(&mut self, key: K) -> Entry<K, V, C>
579	where
580		K: Ord,
581	{
582		match self.address_of(&key) {
583			Ok(addr) => Entry::Occupied(OccupiedEntry { map: self, addr }),
584			Err(addr) => Entry::Vacant(VacantEntry {
585				map: self,
586				key,
587				addr,
588			}),
589		}
590	}
591
592	/// Returns the first entry in the map for in-place manipulation.
593	/// The key of this entry is the minimum key in the map.
594	///
595	/// # Example
596	///
597	/// ```
598	/// use btree_slab::BTreeMap;
599	///
600	/// let mut map = BTreeMap::new();
601	/// map.insert(1, "a");
602	/// map.insert(2, "b");
603	/// if let Some(mut entry) = map.first_entry() {
604	///     if *entry.key() > 0 {
605	///         entry.insert("first");
606	///     }
607	/// }
608	/// assert_eq!(*map.get(&1).unwrap(), "first");
609	/// assert_eq!(*map.get(&2).unwrap(), "b");
610	/// ```
611	#[inline]
612	pub fn first_entry(&mut self) -> Option<OccupiedEntry<K, V, C>> {
613		self.first_item_address()
614			.map(move |addr| OccupiedEntry { map: self, addr })
615	}
616
617	/// Returns the last entry in the map for in-place manipulation.
618	/// The key of this entry is the maximum key in the map.
619	///
620	/// # Example
621	///
622	/// ```
623	/// use btree_slab::BTreeMap;
624	///
625	/// let mut map = BTreeMap::new();
626	/// map.insert(1, "a");
627	/// map.insert(2, "b");
628	/// if let Some(mut entry) = map.last_entry() {
629	///     if *entry.key() > 0 {
630	///         entry.insert("last");
631	///     }
632	/// }
633	/// assert_eq!(*map.get(&1).unwrap(), "a");
634	/// assert_eq!(*map.get(&2).unwrap(), "last");
635	/// ```
636	#[inline]
637	pub fn last_entry(&mut self) -> Option<OccupiedEntry<K, V, C>> {
638		self.last_item_address()
639			.map(move |addr| OccupiedEntry { map: self, addr })
640	}
641
642	/// Insert a key-value pair in the tree.
643	#[inline]
644	pub fn insert(&mut self, key: K, value: V) -> Option<V>
645	where
646		K: Ord,
647	{
648		match self.address_of(&key) {
649			Ok(addr) => Some(self.replace_value_at(addr, value)),
650			Err(addr) => {
651				self.insert_exactly_at(addr, Item::new(key, value), None);
652				None
653			}
654		}
655	}
656
657	/// Replace a key-value pair in the tree.
658	#[inline]
659	pub fn replace(&mut self, key: K, value: V) -> Option<(K, V)>
660	where
661		K: Ord,
662	{
663		match self.address_of(&key) {
664			Ok(addr) => Some(self.replace_at(addr, key, value)),
665			Err(addr) => {
666				self.insert_exactly_at(addr, Item::new(key, value), None);
667				None
668			}
669		}
670	}
671
672	/// Removes and returns the first element in the map.
673	/// The key of this element is the minimum key that was in the map.
674	///
675	/// # Example
676	///
677	/// Draining elements in ascending order, while keeping a usable map each iteration.
678	///
679	/// ```
680	/// use btree_slab::BTreeMap;
681	///
682	/// let mut map = BTreeMap::new();
683	/// map.insert(1, "a");
684	/// map.insert(2, "b");
685	/// while let Some((key, _val)) = map.pop_first() {
686	///     assert!(map.iter().all(|(k, _v)| *k > key));
687	/// }
688	/// assert!(map.is_empty());
689	/// ```
690	#[inline]
691	pub fn pop_first(&mut self) -> Option<(K, V)> {
692		self.first_entry().map(|entry| entry.remove_entry())
693	}
694
695	/// Removes and returns the last element in the map.
696	/// The key of this element is the maximum key that was in the map.
697	///
698	/// # Example
699	///
700	/// Draining elements in descending order, while keeping a usable map each iteration.
701	///
702	/// ```
703	/// use btree_slab::BTreeMap;
704	///
705	/// let mut map = BTreeMap::new();
706	/// map.insert(1, "a");
707	/// map.insert(2, "b");
708	/// while let Some((key, _val)) = map.pop_last() {
709	///     assert!(map.iter().all(|(k, _v)| *k < key));
710	/// }
711	/// assert!(map.is_empty());
712	/// ```
713	#[inline]
714	pub fn pop_last(&mut self) -> Option<(K, V)> {
715		self.last_entry().map(|entry| entry.remove_entry())
716	}
717
718	/// Removes a key from the map, returning the value at the key if the key
719	/// was previously in the map.
720	///
721	/// The key may be any borrowed form of the map's key type, but the ordering
722	/// on the borrowed form *must* match the ordering on the key type.
723	///
724	/// # Example
725	///
726	/// ```
727	/// use btree_slab::BTreeMap;
728	///
729	/// let mut map = BTreeMap::new();
730	/// map.insert(1, "a");
731	/// assert_eq!(map.remove(&1), Some("a"));
732	/// assert_eq!(map.remove(&1), None);
733	/// ```
734	#[inline]
735	pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
736	where
737		K: Borrow<Q>,
738		Q: Ord,
739	{
740		match self.address_of(key) {
741			Ok(addr) => {
742				let (item, _) = self.remove_at(addr).unwrap();
743				Some(item.into_value())
744			}
745			Err(_) => None,
746		}
747	}
748
749	/// Removes a key from the map, returning the stored key and value if the key
750	/// was previously in the map.
751	///
752	/// The key may be any borrowed form of the map's key type, but the ordering
753	/// on the borrowed form *must* match the ordering on the key type.
754	///
755	/// # Example
756	///
757	/// Basic usage:
758	///
759	/// ```
760	/// use btree_slab::BTreeMap;
761	///
762	/// let mut map = BTreeMap::new();
763	/// map.insert(1, "a");
764	/// assert_eq!(map.remove_entry(&1), Some((1, "a")));
765	/// assert_eq!(map.remove_entry(&1), None);
766	/// ```
767	#[inline]
768	pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
769	where
770		K: Borrow<Q>,
771		Q: Ord,
772	{
773		match self.address_of(key) {
774			Ok(addr) => {
775				let (item, _) = self.remove_at(addr).unwrap();
776				Some(item.into_pair())
777			}
778			Err(_) => None,
779		}
780	}
781
782	/// Removes and returns the binding in the map, if any, of which key matches the given one.
783	#[inline]
784	pub fn take<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
785	where
786		K: Borrow<Q>,
787		Q: Ord,
788	{
789		match self.address_of(key) {
790			Ok(addr) => {
791				let (item, _) = self.remove_at(addr).unwrap();
792				Some(item.into_pair())
793			}
794			Err(_) => None,
795		}
796	}
797
798	/// General-purpose update function.
799	///
800	/// This can be used to insert, compare, replace or remove the value associated to the given
801	/// `key` in the tree.
802	/// The action to perform is specified by the `action` function.
803	/// This function is called once with:
804	///  - `Some(value)` when `value` is aready associated to `key` or
805	///  - `None` when the `key` is not associated to any value.
806	///
807	/// The `action` function must return a pair (`new_value`, `result`) where
808	/// `new_value` is the new value to be associated to `key`
809	/// (if it is `None` any previous binding is removed) and
810	/// `result` is the value returned by the entire `update` function call.
811	#[inline]
812	pub fn update<T, F>(&mut self, key: K, action: F) -> T
813	where
814		K: Ord,
815		F: FnOnce(Option<V>) -> (Option<V>, T),
816	{
817		match self.root {
818			Some(id) => self.update_in(id, key, action),
819			None => {
820				let (to_insert, result) = action(None);
821
822				if let Some(value) = to_insert {
823					let new_root = Node::leaf(None, Item::new(key, value));
824					self.root = Some(self.allocate_node(new_root));
825					self.len += 1;
826				}
827
828				result
829			}
830		}
831	}
832
833	/// Gets a mutable iterator over the entries of the map, sorted by key.
834	///
835	/// # Example
836	///
837	/// ```
838	/// use btree_slab::BTreeMap;
839	///
840	/// let mut map = BTreeMap::new();
841	/// map.insert("a", 1);
842	/// map.insert("b", 2);
843	/// map.insert("c", 3);
844	///
845	/// // add 10 to the value if the key isn't "a"
846	/// for (key, value) in map.iter_mut() {
847	///     if key != &"a" {
848	///         *value += 10;
849	///     }
850	/// }
851	/// ```
852	#[inline]
853	pub fn iter_mut(&mut self) -> IterMut<K, V, C> {
854		IterMut::new(self)
855	}
856
857	/// Gets a mutable iterator over the entries of the map, sorted by key, that allows insertion and deletion of the iterated entries.
858	///
859	/// # Correctness
860	///
861	/// It is safe to insert any key-value pair while iterating,
862	/// however this might break the well-formedness
863	/// of the underlying tree, which relies on several invariants.
864	/// To preserve these invariants,
865	/// the inserted key must be *strictly greater* than the previous visited item's key,
866	/// and *strictly less* than the next visited item
867	/// (which you can retrive through [`EntriesMut::peek`] without moving the iterator).
868	/// If this rule is not respected, the data structure will become unusable
869	/// (invalidate the specification of every method of the API).
870	///
871	/// # Example
872	///
873	/// ```
874	/// use btree_slab::BTreeMap;
875	///
876	/// let mut map = BTreeMap::new();
877	/// map.insert("a", 1);
878	/// map.insert("b", 2);
879	/// map.insert("d", 4);
880	///
881	/// let mut entries = map.entries_mut();
882	/// entries.next();
883	/// entries.next();
884	/// entries.insert("c", 3);
885	///
886	/// let entries: Vec<_> = map.into_iter().collect();
887	/// assert_eq!(entries, vec![("a", 1), ("b", 2), ("c", 3), ("d", 4)]);
888	/// ```
889	#[inline]
890	pub fn entries_mut(&mut self) -> EntriesMut<K, V, C> {
891		EntriesMut::new(self)
892	}
893
894	/// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
895	/// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
896	/// yield elements from min (inclusive) to max (exclusive).
897	/// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
898	/// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
899	/// range from 4 to 10.
900	///
901	/// # Panics
902	///
903	/// Panics if range `start > end`.
904	/// Panics if range `start == end` and both bounds are `Excluded`.
905	///
906	/// # Example
907	///
908	/// ```
909	/// use btree_slab::BTreeMap;
910	///
911	/// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
912	///     .iter()
913	///     .map(|&s| (s, 0))
914	///     .collect();
915	/// for (_, balance) in map.range_mut("B".."Cheryl") {
916	///     *balance += 100;
917	/// }
918	/// for (name, balance) in &map {
919	///     println!("{} => {}", name, balance);
920	/// }
921	/// ```
922	#[inline]
923	pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<K, V, C>
924	where
925		T: Ord,
926		K: Borrow<T>,
927		R: RangeBounds<T>,
928	{
929		RangeMut::new(self, range)
930	}
931
932	/// Gets a mutable iterator over the values of the map, in order by key.
933	///
934	/// # Example
935	///
936	/// ```
937	/// use btree_slab::BTreeMap;
938	///
939	/// let mut a = BTreeMap::new();
940	/// a.insert(1, String::from("hello"));
941	/// a.insert(2, String::from("goodbye"));
942	///
943	/// for value in a.values_mut() {
944	///     value.push_str("!");
945	/// }
946	///
947	/// let values: Vec<String> = a.values().cloned().collect();
948	/// assert_eq!(values, [String::from("hello!"),
949	///                     String::from("goodbye!")]);
950	/// ```
951	#[inline]
952	pub fn values_mut(&mut self) -> ValuesMut<K, V, C> {
953		ValuesMut {
954			inner: self.iter_mut(),
955		}
956	}
957
958	/// Creates an iterator which uses a closure to determine if an element should be removed.
959	///
960	/// If the closure returns true, the element is removed from the map and yielded.
961	/// If the closure returns false, or panics, the element remains in the map and will not be
962	/// yielded.
963	///
964	/// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
965	/// whether you choose to keep or remove it.
966	///
967	/// If the iterator is only partially consumed or not consumed at all, each of the remaining
968	/// elements will still be subjected to the closure and removed and dropped if it returns true.
969	///
970	/// It is unspecified how many more elements will be subjected to the closure
971	/// if a panic occurs in the closure, or a panic occurs while dropping an element,
972	/// or if the `DrainFilter` value is leaked.
973	///
974	/// # Example
975	///
976	/// Splitting a map into even and odd keys, reusing the original map:
977	///
978	/// ```
979	/// use btree_slab::BTreeMap;
980	///
981	/// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
982	/// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
983	/// let odds = map;
984	/// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
985	/// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
986	/// ```
987	#[inline]
988	pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<K, V, C, F>
989	where
990		F: FnMut(&K, &mut V) -> bool,
991	{
992		DrainFilter::new(self, pred)
993	}
994
995	/// Retains only the elements specified by the predicate.
996	///
997	/// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
998	///
999	/// # Example
1000	///
1001	/// ```
1002	/// use btree_slab::BTreeMap;
1003	///
1004	/// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
1005	/// // Keep only the elements with even-numbered keys.
1006	/// map.retain(|&k, _| k % 2 == 0);
1007	/// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
1008	/// ```
1009	#[inline]
1010	pub fn retain<F>(&mut self, mut f: F)
1011	where
1012		F: FnMut(&K, &mut V) -> bool,
1013	{
1014		self.drain_filter(|k, v| !f(k, v));
1015	}
1016
1017	/// Moves all elements from `other` into `Self`, leaving `other` empty.
1018	///
1019	/// # Example
1020	///
1021	/// ```
1022	/// use btree_slab::BTreeMap;
1023	///
1024	/// let mut a = BTreeMap::new();
1025	/// a.insert(1, "a");
1026	/// a.insert(2, "b");
1027	/// a.insert(3, "c");
1028	///
1029	/// let mut b = BTreeMap::new();
1030	/// b.insert(3, "d");
1031	/// b.insert(4, "e");
1032	/// b.insert(5, "f");
1033	///
1034	/// a.append(&mut b);
1035	///
1036	/// assert_eq!(a.len(), 5);
1037	/// assert_eq!(b.len(), 0);
1038	///
1039	/// assert_eq!(a[&1], "a");
1040	/// assert_eq!(a[&2], "b");
1041	/// assert_eq!(a[&3], "d");
1042	/// assert_eq!(a[&4], "e");
1043	/// assert_eq!(a[&5], "f");
1044	/// ```
1045	#[inline]
1046	pub fn append(&mut self, other: &mut Self)
1047	where
1048		K: Ord,
1049		C: Default,
1050	{
1051		// Do we have to append anything at all?
1052		if other.is_empty() {
1053			return;
1054		}
1055
1056		// We can just swap `self` and `other` if `self` is empty.
1057		if self.is_empty() {
1058			std::mem::swap(self, other);
1059			return;
1060		}
1061
1062		let other = std::mem::take(other);
1063		for (key, value) in other {
1064			self.insert(key, value);
1065		}
1066	}
1067
1068	/// Creates a consuming iterator visiting all the keys, in sorted order.
1069	/// The map cannot be used after calling this.
1070	/// The iterator element type is `K`.
1071	///
1072	/// # Example
1073	///
1074	/// ```
1075	/// use btree_slab::BTreeMap;
1076	///
1077	/// let mut a = BTreeMap::new();
1078	/// a.insert(2, "b");
1079	/// a.insert(1, "a");
1080	///
1081	/// let keys: Vec<i32> = a.into_keys().collect();
1082	/// assert_eq!(keys, [1, 2]);
1083	/// ```
1084	#[inline]
1085	pub fn into_keys(self) -> IntoKeys<K, V, C> {
1086		IntoKeys {
1087			inner: self.into_iter(),
1088		}
1089	}
1090
1091	/// Creates a consuming iterator visiting all the values, in order by key.
1092	/// The map cannot be used after calling this.
1093	/// The iterator element type is `V`.
1094	///
1095	/// # Example
1096	///
1097	/// ```
1098	/// use btree_slab::BTreeMap;
1099	///
1100	/// let mut a = BTreeMap::new();
1101	/// a.insert(1, "hello");
1102	/// a.insert(2, "goodbye");
1103	///
1104	/// let values: Vec<&str> = a.into_values().collect();
1105	/// assert_eq!(values, ["hello", "goodbye"]);
1106	/// ```
1107	#[inline]
1108	pub fn into_values(self) -> IntoValues<K, V, C> {
1109		IntoValues {
1110			inner: self.into_iter(),
1111		}
1112	}
1113
1114	/// Try to rotate left the node `id` to benefits the child number `deficient_child_index`.
1115	///
1116	/// Returns true if the rotation succeeded, of false if the target child has no right sibling,
1117	/// or if this sibling would underflow.
1118	#[inline]
1119	fn try_rotate_left(
1120		&mut self,
1121		id: usize,
1122		deficient_child_index: usize,
1123		addr: &mut Address,
1124	) -> bool {
1125		let pivot_offset = deficient_child_index.into();
1126		let right_sibling_index = deficient_child_index + 1;
1127		let (right_sibling_id, deficient_child_id) = {
1128			let node = self.node(id);
1129
1130			if right_sibling_index >= node.child_count() {
1131				return false; // no right sibling
1132			}
1133
1134			(
1135				node.child_id(right_sibling_index),
1136				node.child_id(deficient_child_index),
1137			)
1138		};
1139
1140		match self.node_mut(right_sibling_id).pop_left() {
1141			Ok((mut value, opt_child_id)) => {
1142				std::mem::swap(
1143					&mut value,
1144					self.node_mut(id).item_mut(pivot_offset).unwrap(),
1145				);
1146				let left_offset = self
1147					.node_mut(deficient_child_id)
1148					.push_right(value, opt_child_id);
1149
1150				// update opt_child's parent
1151				if let Some(child_id) = opt_child_id {
1152					self.node_mut(child_id).set_parent(Some(deficient_child_id))
1153				}
1154
1155				// update address.
1156				if addr.id == right_sibling_id {
1157					// addressed item is in the right node.
1158					if addr.offset == 0 {
1159						// addressed item is moving to pivot.
1160						addr.id = id;
1161						addr.offset = pivot_offset;
1162					} else {
1163						// addressed item stays on right.
1164						addr.offset.decr();
1165					}
1166				} else if addr.id == id {
1167					// addressed item is in the parent node.
1168					if addr.offset == pivot_offset {
1169						// addressed item is the pivot, moving to the left (deficient) node.
1170						addr.id = deficient_child_id;
1171						addr.offset = left_offset;
1172					}
1173				}
1174
1175				true // rotation succeeded
1176			}
1177			Err(WouldUnderflow) => false, // the right sibling would underflow.
1178		}
1179	}
1180
1181	/// Try to rotate right the node `id` to benefits the child number `deficient_child_index`.
1182	///
1183	/// Returns true if the rotation succeeded, of false if the target child has no left sibling,
1184	/// or if this sibling would underflow.
1185	#[inline]
1186	fn try_rotate_right(
1187		&mut self,
1188		id: usize,
1189		deficient_child_index: usize,
1190		addr: &mut Address,
1191	) -> bool {
1192		if deficient_child_index > 0 {
1193			let left_sibling_index = deficient_child_index - 1;
1194			let pivot_offset = left_sibling_index.into();
1195			let (left_sibling_id, deficient_child_id) = {
1196				let node = self.node(id);
1197				(
1198					node.child_id(left_sibling_index),
1199					node.child_id(deficient_child_index),
1200				)
1201			};
1202			match self.node_mut(left_sibling_id).pop_right() {
1203				Ok((left_offset, mut value, opt_child_id)) => {
1204					std::mem::swap(
1205						&mut value,
1206						self.node_mut(id).item_mut(pivot_offset).unwrap(),
1207					);
1208					self.node_mut(deficient_child_id)
1209						.push_left(value, opt_child_id);
1210
1211					// update opt_child's parent
1212					if let Some(child_id) = opt_child_id {
1213						self.node_mut(child_id).set_parent(Some(deficient_child_id))
1214					}
1215
1216					// update address.
1217					if addr.id == deficient_child_id {
1218						// addressed item is in the right (deficient) node.
1219						addr.offset.incr();
1220					} else if addr.id == left_sibling_id {
1221						// addressed item is in the left node.
1222						if addr.offset == left_offset {
1223							// addressed item is moving to pivot.
1224							addr.id = id;
1225							addr.offset = pivot_offset;
1226						}
1227					} else if addr.id == id {
1228						// addressed item is in the parent node.
1229						if addr.offset == pivot_offset {
1230							// addressed item is the pivot, moving to the left (deficient) node.
1231							addr.id = deficient_child_id;
1232							addr.offset = 0.into();
1233						}
1234					}
1235
1236					true // rotation succeeded
1237				}
1238				Err(WouldUnderflow) => false, // the left sibling would underflow.
1239			}
1240		} else {
1241			false // no left sibling.
1242		}
1243	}
1244
1245	/// Merge the child `deficient_child_index` in node `id` with one of its direct sibling.
1246	#[inline]
1247	fn merge(
1248		&mut self,
1249		id: usize,
1250		deficient_child_index: usize,
1251		mut addr: Address,
1252	) -> (Balance, Address) {
1253		let (offset, left_id, right_id, separator, balance) = if deficient_child_index > 0 {
1254			// merge with left sibling
1255			self.node_mut(id)
1256				.merge(deficient_child_index - 1, deficient_child_index)
1257		} else {
1258			// merge with right sibling
1259			self.node_mut(id)
1260				.merge(deficient_child_index, deficient_child_index + 1)
1261		};
1262
1263		// update children's parent.
1264		let right_node = self.release_node(right_id);
1265		for right_child_id in right_node.children() {
1266			self.node_mut(right_child_id).set_parent(Some(left_id));
1267		}
1268
1269		// actually merge.
1270		let left_offset = self.node_mut(left_id).append(separator, right_node);
1271
1272		// update addr.
1273		if addr.id == id {
1274			match addr.offset.partial_cmp(&offset) {
1275				Some(Ordering::Equal) => {
1276					addr.id = left_id;
1277					addr.offset = left_offset
1278				}
1279				Some(Ordering::Greater) => addr.offset.decr(),
1280				_ => (),
1281			}
1282		} else if addr.id == right_id {
1283			addr.id = left_id;
1284			addr.offset = (addr.offset.unwrap() + left_offset.unwrap() + 1).into();
1285		}
1286
1287		(balance, addr)
1288	}
1289}
1290
1291impl<K: Ord, Q: ?Sized, V, C: Slab<Node<K, V>>> Index<&Q> for BTreeMap<K, V, C>
1292where
1293	K: Borrow<Q>,
1294	Q: Ord,
1295	C: SimpleCollectionRef,
1296{
1297	type Output = V;
1298
1299	/// Returns a reference to the value corresponding to the supplied key.
1300	///
1301	/// # Panics
1302	///
1303	/// Panics if the key is not present in the `BTreeMap`.
1304	#[inline]
1305	fn index(&self, key: &Q) -> &V {
1306		self.get(key).expect("no entry found for key")
1307	}
1308}
1309
1310impl<K, L: PartialEq<K>, V, W: PartialEq<V>, C: Slab<Node<K, V>>, D: Slab<Node<L, W>>>
1311	PartialEq<BTreeMap<L, W, D>> for BTreeMap<K, V, C>
1312where
1313	C: SimpleCollectionRef,
1314	D: SimpleCollectionRef,
1315{
1316	fn eq(&self, other: &BTreeMap<L, W, D>) -> bool {
1317		if self.len() == other.len() {
1318			let mut it1 = self.iter();
1319			let mut it2 = other.iter();
1320
1321			loop {
1322				match (it1.next(), it2.next()) {
1323					(None, None) => break,
1324					(Some((k, v)), Some((l, w))) => {
1325						if l != k || w != v {
1326							return false;
1327						}
1328					}
1329					_ => return false,
1330				}
1331			}
1332
1333			true
1334		} else {
1335			false
1336		}
1337	}
1338}
1339
1340impl<K, V, C: Default> Default for BTreeMap<K, V, C> {
1341	#[inline]
1342	fn default() -> Self {
1343		BTreeMap::new()
1344	}
1345}
1346
1347impl<K: Ord, V, C: SlabMut<Node<K, V>> + Default> FromIterator<(K, V)> for BTreeMap<K, V, C>
1348where
1349	C: SimpleCollectionRef,
1350	C: SimpleCollectionMut,
1351{
1352	#[inline]
1353	fn from_iter<T>(iter: T) -> BTreeMap<K, V, C>
1354	where
1355		T: IntoIterator<Item = (K, V)>,
1356	{
1357		let mut map = BTreeMap::new();
1358
1359		for (key, value) in iter {
1360			map.insert(key, value);
1361		}
1362
1363		map
1364	}
1365}
1366
1367impl<K: Ord, V, C: SlabMut<Node<K, V>>> Extend<(K, V)> for BTreeMap<K, V, C>
1368where
1369	C: SimpleCollectionRef,
1370	C: SimpleCollectionMut,
1371{
1372	#[inline]
1373	fn extend<T>(&mut self, iter: T)
1374	where
1375		T: IntoIterator<Item = (K, V)>,
1376	{
1377		for (key, value) in iter {
1378			self.insert(key, value);
1379		}
1380	}
1381}
1382
1383impl<'a, K: Ord + Copy, V: Copy, C: SlabMut<Node<K, V>>> Extend<(&'a K, &'a V)>
1384	for BTreeMap<K, V, C>
1385where
1386	C: SimpleCollectionRef,
1387	C: SimpleCollectionMut,
1388{
1389	#[inline]
1390	fn extend<T>(&mut self, iter: T)
1391	where
1392		T: IntoIterator<Item = (&'a K, &'a V)>,
1393	{
1394		self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1395	}
1396}
1397
1398impl<K: Eq, V: Eq, C: Slab<Node<K, V>>> Eq for BTreeMap<K, V, C> where C: SimpleCollectionRef {}
1399
1400impl<K, L: PartialOrd<K>, V, W: PartialOrd<V>, C: Slab<Node<K, V>>, D: Slab<Node<L, W>>>
1401	PartialOrd<BTreeMap<L, W, D>> for BTreeMap<K, V, C>
1402where
1403	C: SimpleCollectionRef,
1404	D: SimpleCollectionRef,
1405{
1406	fn partial_cmp(&self, other: &BTreeMap<L, W, D>) -> Option<Ordering> {
1407		let mut it1 = self.iter();
1408		let mut it2 = other.iter();
1409
1410		loop {
1411			match (it1.next(), it2.next()) {
1412				(None, None) => return Some(Ordering::Equal),
1413				(_, None) => return Some(Ordering::Greater),
1414				(None, _) => return Some(Ordering::Less),
1415				(Some((k, v)), Some((l, w))) => match l.partial_cmp(k) {
1416					Some(Ordering::Greater) => return Some(Ordering::Less),
1417					Some(Ordering::Less) => return Some(Ordering::Greater),
1418					Some(Ordering::Equal) => match w.partial_cmp(v) {
1419						Some(Ordering::Greater) => return Some(Ordering::Less),
1420						Some(Ordering::Less) => return Some(Ordering::Greater),
1421						Some(Ordering::Equal) => (),
1422						None => return None,
1423					},
1424					None => return None,
1425				},
1426			}
1427		}
1428	}
1429}
1430
1431impl<K: Ord, V: Ord, C: Slab<Node<K, V>>> Ord for BTreeMap<K, V, C>
1432where
1433	C: SimpleCollectionRef,
1434{
1435	fn cmp(&self, other: &BTreeMap<K, V, C>) -> Ordering {
1436		let mut it1 = self.iter();
1437		let mut it2 = other.iter();
1438
1439		loop {
1440			match (it1.next(), it2.next()) {
1441				(None, None) => return Ordering::Equal,
1442				(_, None) => return Ordering::Greater,
1443				(None, _) => return Ordering::Less,
1444				(Some((k, v)), Some((l, w))) => match l.cmp(k) {
1445					Ordering::Greater => return Ordering::Less,
1446					Ordering::Less => return Ordering::Greater,
1447					Ordering::Equal => match w.cmp(v) {
1448						Ordering::Greater => return Ordering::Less,
1449						Ordering::Less => return Ordering::Greater,
1450						Ordering::Equal => (),
1451					},
1452				},
1453			}
1454		}
1455	}
1456}
1457
1458impl<K: Hash, V: Hash, C: Slab<Node<K, V>>> Hash for BTreeMap<K, V, C>
1459where
1460	C: SimpleCollectionRef,
1461{
1462	#[inline]
1463	fn hash<H: Hasher>(&self, h: &mut H) {
1464		for (k, v) in self {
1465			k.hash(h);
1466			v.hash(h);
1467		}
1468	}
1469}
1470
1471pub struct Iter<'a, K, V, C> {
1472	/// The tree reference.
1473	btree: &'a BTreeMap<K, V, C>,
1474
1475	/// Address of the next item.
1476	addr: Option<Address>,
1477
1478	end: Option<Address>,
1479
1480	len: usize,
1481}
1482
1483impl<'a, K, V, C: Slab<Node<K, V>>> Iter<'a, K, V, C>
1484where
1485	C: SimpleCollectionRef,
1486{
1487	#[inline]
1488	fn new(btree: &'a BTreeMap<K, V, C>) -> Self {
1489		let addr = btree.first_item_address();
1490		let len = btree.len();
1491		Iter {
1492			btree,
1493			addr,
1494			end: None,
1495			len,
1496		}
1497	}
1498}
1499
1500impl<'a, K, V, C: Slab<Node<K, V>>> Iterator for Iter<'a, K, V, C>
1501where
1502	C: SimpleCollectionRef,
1503{
1504	type Item = (&'a K, &'a V);
1505
1506	#[inline]
1507	fn size_hint(&self) -> (usize, Option<usize>) {
1508		(self.len, Some(self.len))
1509	}
1510
1511	#[inline]
1512	fn next(&mut self) -> Option<(&'a K, &'a V)> {
1513		match self.addr {
1514			Some(addr) => {
1515				if self.len > 0 {
1516					self.len -= 1;
1517
1518					let item = self.btree.item(addr).unwrap();
1519					self.addr = self.btree.next_item_address(addr);
1520					Some((item.key(), item.value()))
1521				} else {
1522					None
1523				}
1524			}
1525			None => None,
1526		}
1527	}
1528}
1529
1530impl<'a, K, V, C: Slab<Node<K, V>>> FusedIterator for Iter<'a, K, V, C> where C: SimpleCollectionRef {}
1531impl<'a, K, V, C: Slab<Node<K, V>>> ExactSizeIterator for Iter<'a, K, V, C> where
1532	C: SimpleCollectionRef
1533{
1534}
1535
1536impl<'a, K, V, C: Slab<Node<K, V>>> DoubleEndedIterator for Iter<'a, K, V, C>
1537where
1538	C: SimpleCollectionRef,
1539{
1540	#[inline]
1541	fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1542		if self.len > 0 {
1543			let addr = match self.end {
1544				Some(addr) => self.btree.previous_item_address(addr).unwrap(),
1545				None => self.btree.last_item_address().unwrap(),
1546			};
1547
1548			self.len -= 1;
1549
1550			let item = self.btree.item(addr).unwrap();
1551			self.end = Some(addr);
1552			Some((item.key(), item.value()))
1553		} else {
1554			None
1555		}
1556	}
1557}
1558
1559impl<'a, K, V, C: Slab<Node<K, V>>> IntoIterator for &'a BTreeMap<K, V, C>
1560where
1561	C: SimpleCollectionRef,
1562{
1563	type IntoIter = Iter<'a, K, V, C>;
1564	type Item = (&'a K, &'a V);
1565
1566	#[inline]
1567	fn into_iter(self) -> Iter<'a, K, V, C> {
1568		self.iter()
1569	}
1570}
1571
1572pub struct IterMut<'a, K, V, C> {
1573	/// The tree reference.
1574	btree: &'a mut BTreeMap<K, V, C>,
1575
1576	/// Address of the next item.
1577	addr: Option<Address>,
1578
1579	end: Option<Address>,
1580
1581	len: usize,
1582}
1583
1584impl<'a, K, V, C: SlabMut<Node<K, V>>> IterMut<'a, K, V, C>
1585where
1586	C: SimpleCollectionRef,
1587	C: SimpleCollectionMut,
1588{
1589	#[inline]
1590	fn new(btree: &'a mut BTreeMap<K, V, C>) -> Self {
1591		let addr = btree.first_item_address();
1592		let len = btree.len();
1593		IterMut {
1594			btree,
1595			addr,
1596			end: None,
1597			len,
1598		}
1599	}
1600
1601	#[inline]
1602	fn next_item(&mut self) -> Option<&'a mut Item<K, V>> {
1603		match self.addr {
1604			Some(addr) => {
1605				if self.len > 0 {
1606					self.len -= 1;
1607
1608					self.addr = self.btree.next_item_address(addr);
1609					let item = self.btree.item_mut(addr).unwrap();
1610					Some(unsafe { std::mem::transmute(item) }) // this is safe because only one mutable reference to the same item can be emitted.
1611				} else {
1612					None
1613				}
1614			}
1615			None => None,
1616		}
1617	}
1618
1619	#[inline]
1620	fn next_back_item(&mut self) -> Option<&'a mut Item<K, V>> {
1621		if self.len > 0 {
1622			let addr = match self.end {
1623				Some(addr) => self.btree.previous_item_address(addr).unwrap(),
1624				None => self.btree.last_item_address().unwrap(),
1625			};
1626
1627			self.len -= 1;
1628
1629			let item = self.btree.item_mut(addr).unwrap();
1630			self.end = Some(addr);
1631			Some(unsafe { std::mem::transmute(item) }) // this is safe because only one mutable reference to the same item can be emitted.s
1632		} else {
1633			None
1634		}
1635	}
1636}
1637
1638impl<'a, K, V, C: SlabMut<Node<K, V>>> Iterator for IterMut<'a, K, V, C>
1639where
1640	C: SimpleCollectionRef,
1641	C: SimpleCollectionMut,
1642{
1643	type Item = (&'a K, &'a mut V);
1644
1645	#[inline]
1646	fn size_hint(&self) -> (usize, Option<usize>) {
1647		(self.len, Some(self.len))
1648	}
1649
1650	#[inline]
1651	fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1652		self.next_item().map(|item| {
1653			let (key, value) = item.as_pair_mut();
1654			(key as &'a K, value)
1655		})
1656	}
1657}
1658
1659impl<'a, K, V, C: SlabMut<Node<K, V>>> FusedIterator for IterMut<'a, K, V, C>
1660where
1661	C: SimpleCollectionRef,
1662	C: SimpleCollectionMut,
1663{
1664}
1665impl<'a, K, V, C: SlabMut<Node<K, V>>> ExactSizeIterator for IterMut<'a, K, V, C>
1666where
1667	C: SimpleCollectionRef,
1668	C: SimpleCollectionMut,
1669{
1670}
1671
1672impl<'a, K, V, C: SlabMut<Node<K, V>>> DoubleEndedIterator for IterMut<'a, K, V, C>
1673where
1674	C: SimpleCollectionRef,
1675	C: SimpleCollectionMut,
1676{
1677	#[inline]
1678	fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1679		self.next_back_item().map(|item| {
1680			let (key, value) = item.as_pair_mut();
1681			(key as &'a K, value)
1682		})
1683	}
1684}
1685
1686/// Iterator that can mutate the tree in place.
1687pub struct EntriesMut<'a, K, V, C> {
1688	/// The tree reference.
1689	btree: &'a mut BTreeMap<K, V, C>,
1690
1691	/// Address of the next item, or last valid address.
1692	addr: Address,
1693
1694	len: usize,
1695}
1696
1697impl<'a, K, V, C: SlabMut<Node<K, V>>> EntriesMut<'a, K, V, C>
1698where
1699	C: SimpleCollectionRef,
1700	C: SimpleCollectionMut,
1701{
1702	/// Create a new iterator over all the items of the map.
1703	#[inline]
1704	fn new(btree: &'a mut BTreeMap<K, V, C>) -> EntriesMut<'a, K, V, C> {
1705		let addr = btree.first_back_address();
1706		let len = btree.len();
1707		EntriesMut { btree, addr, len }
1708	}
1709
1710	/// Get the next visited item without moving the iterator position.
1711	#[inline]
1712	pub fn peek(&'a self) -> Option<&'a Item<K, V>> {
1713		self.btree.item(self.addr)
1714	}
1715
1716	/// Get the next visited item without moving the iterator position.
1717	#[inline]
1718	pub fn peek_mut(&'a mut self) -> Option<&'a mut Item<K, V>> {
1719		self.btree.item_mut(self.addr)
1720	}
1721
1722	/// Get the next item and move the iterator to the next position.
1723	#[inline]
1724	pub fn next_item(&mut self) -> Option<&'a mut Item<K, V>> {
1725		let after_addr = self.btree.next_item_or_back_address(self.addr);
1726		match self.btree.item_mut(self.addr) {
1727			Some(item) => unsafe {
1728				self.len -= 1;
1729				self.addr = after_addr.unwrap();
1730				Some(&mut *(item as *mut _)) // this is safe because only one mutable reference to the same item can be emitted.
1731			},
1732			None => None,
1733		}
1734	}
1735
1736	/// Insert a new item in the map before the next item.
1737	///
1738	/// ## Correctness
1739	///
1740	/// It is safe to insert any key-value pair here, however this might break the well-formedness
1741	/// of the underlying tree, which relies on several invariants.
1742	/// To preserve these invariants,
1743	/// the key must be *strictly greater* than the previous visited item's key,
1744	/// and *strictly less* than the next visited item
1745	/// (which you can retrive through `IterMut::peek` without moving the iterator).
1746	/// If this rule is not respected, the data structure will become unusable
1747	/// (invalidate the specification of every method of the API).
1748	#[inline]
1749	pub fn insert(&mut self, key: K, value: V) {
1750		let addr = self.btree.insert_at(self.addr, Item::new(key, value));
1751		self.btree.next_item_or_back_address(addr);
1752		self.len += 1;
1753	}
1754
1755	/// Remove the next item and return it.
1756	#[inline]
1757	pub fn remove(&mut self) -> Option<Item<K, V>> {
1758		match self.btree.remove_at(self.addr) {
1759			Some((item, addr)) => {
1760				self.len -= 1;
1761				self.addr = addr;
1762				Some(item)
1763			}
1764			None => None,
1765		}
1766	}
1767}
1768
1769impl<'a, K, V, C: SlabMut<Node<K, V>>> Iterator for EntriesMut<'a, K, V, C>
1770where
1771	C: SimpleCollectionRef,
1772	C: SimpleCollectionMut,
1773{
1774	type Item = (&'a K, &'a mut V);
1775
1776	#[inline]
1777	fn size_hint(&self) -> (usize, Option<usize>) {
1778		(self.len, Some(self.len))
1779	}
1780
1781	#[inline]
1782	fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1783		match self.next_item() {
1784			Some(item) => {
1785				let (key, value) = item.as_pair_mut();
1786				Some((key, value)) // coerce k from `&mut K` to `&K`
1787			}
1788			None => None,
1789		}
1790	}
1791}
1792
1793/// An owning iterator over the entries of a `BTreeMap`.
1794///
1795/// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
1796/// (provided by the `IntoIterator` trait). See its documentation for more.
1797///
1798/// [`into_iter`]: IntoIterator::into_iter
1799pub struct IntoIter<K, V, C> {
1800	/// The tree reference.
1801	btree: BTreeMap<K, V, C>,
1802
1803	/// Address of the next item, or the last valid address.
1804	addr: Option<Address>,
1805
1806	/// Address following the last item.
1807	end: Option<Address>,
1808
1809	/// Number of remaining items.
1810	len: usize,
1811}
1812
1813impl<K, V, C: SlabMut<Node<K, V>>> IntoIter<K, V, C>
1814where
1815	C: SimpleCollectionRef,
1816{
1817	#[inline]
1818	pub fn new(btree: BTreeMap<K, V, C>) -> Self {
1819		let addr = btree.first_item_address();
1820		let len = btree.len();
1821		IntoIter {
1822			btree,
1823			addr,
1824			end: None,
1825			len,
1826		}
1827	}
1828}
1829
1830impl<K, V, C: SlabMut<Node<K, V>>> FusedIterator for IntoIter<K, V, C>
1831where
1832	C: SimpleCollectionRef,
1833	C: SimpleCollectionMut,
1834{
1835}
1836impl<K, V, C: SlabMut<Node<K, V>>> ExactSizeIterator for IntoIter<K, V, C>
1837where
1838	C: SimpleCollectionRef,
1839	C: SimpleCollectionMut,
1840{
1841}
1842
1843impl<K, V, C: SlabMut<Node<K, V>>> Iterator for IntoIter<K, V, C>
1844where
1845	C: SimpleCollectionRef,
1846	C: SimpleCollectionMut,
1847{
1848	type Item = (K, V);
1849
1850	#[inline]
1851	fn size_hint(&self) -> (usize, Option<usize>) {
1852		(self.len, Some(self.len))
1853	}
1854
1855	#[inline]
1856	fn next(&mut self) -> Option<(K, V)> {
1857		match self.addr {
1858			Some(addr) => {
1859				if self.len > 0 {
1860					self.len -= 1;
1861
1862					let item = unsafe {
1863						// this is safe because the item at `self.addr` exists and is never touched again.
1864						std::ptr::read(self.btree.item(addr).unwrap())
1865					};
1866
1867					if self.len > 0 {
1868						self.addr = self.btree.next_back_address(addr); // an item address is always followed by a valid address.
1869
1870						while let Some(addr) = self.addr {
1871							if addr.offset < self.btree.node(addr.id).item_count() {
1872								break; // we have found an item address.
1873							} else {
1874								self.addr = self.btree.next_back_address(addr);
1875
1876								// we have gove through every item of the node, we can release it.
1877								let node = self.btree.release_node(addr.id);
1878								std::mem::forget(node); // do not call `drop` on the node since items have been moved.
1879							}
1880						}
1881					} else {
1882						// cleanup.
1883						if self.end.is_some() {
1884							while self.addr != self.end {
1885								let addr = self.addr.unwrap();
1886								self.addr = self.btree.next_back_address(addr);
1887
1888								if addr.offset >= self.btree.node(addr.id).item_count() {
1889									let node = self.btree.release_node(addr.id);
1890									std::mem::forget(node); // do not call `drop` on the node since items have been moved.
1891								}
1892							}
1893						}
1894
1895						if let Some(addr) = self.addr {
1896							let mut id = Some(addr.id);
1897							while let Some(node_id) = id {
1898								let node = self.btree.release_node(node_id);
1899								id = node.parent();
1900								std::mem::forget(node); // do not call `drop` on the node since items have been moved.
1901							}
1902						}
1903					}
1904
1905					Some(item.into_pair())
1906				} else {
1907					None
1908				}
1909			}
1910			None => None,
1911		}
1912	}
1913}
1914
1915impl<K, V, C: SlabMut<Node<K, V>>> DoubleEndedIterator for IntoIter<K, V, C>
1916where
1917	C: SimpleCollectionRef,
1918	C: SimpleCollectionMut,
1919{
1920	fn next_back(&mut self) -> Option<(K, V)> {
1921		if self.len > 0 {
1922			let addr = match self.end {
1923				Some(mut addr) => {
1924					addr = self.btree.previous_front_address(addr).unwrap();
1925					while addr.offset.is_before() {
1926						let id = addr.id;
1927						addr = self.btree.previous_front_address(addr).unwrap();
1928
1929						// we have gove through every item of the node, we can release it.
1930						let node = self.btree.release_node(id);
1931						std::mem::forget(node); // do not call `drop` on the node since items have been moved.
1932					}
1933
1934					addr
1935				}
1936				None => self.btree.last_item_address().unwrap(),
1937			};
1938
1939			self.len -= 1;
1940
1941			let item = unsafe {
1942				// this is safe because the item at `self.end` exists and is never touched again.
1943				std::ptr::read(self.btree.item(addr).unwrap())
1944			};
1945
1946			self.end = Some(addr);
1947
1948			if self.len == 0 {
1949				// cleanup.
1950				while self.addr != self.end {
1951					let addr = self.addr.unwrap();
1952					self.addr = self.btree.next_back_address(addr);
1953
1954					if addr.offset >= self.btree.node(addr.id).item_count() {
1955						let node = self.btree.release_node(addr.id);
1956						std::mem::forget(node); // do not call `drop` on the node since items have been moved.
1957					}
1958				}
1959
1960				if let Some(addr) = self.addr {
1961					let mut id = Some(addr.id);
1962					while let Some(node_id) = id {
1963						let node = self.btree.release_node(node_id);
1964						id = node.parent();
1965						std::mem::forget(node); // do not call `drop` on the node since items have been moved.
1966					}
1967				}
1968			}
1969
1970			Some(item.into_pair())
1971		} else {
1972			None
1973		}
1974	}
1975}
1976
1977impl<K, V, C: SlabMut<Node<K, V>>> IntoIterator for BTreeMap<K, V, C>
1978where
1979	C: SimpleCollectionRef,
1980	C: SimpleCollectionMut,
1981{
1982	type IntoIter = IntoIter<K, V, C>;
1983	type Item = (K, V);
1984
1985	#[inline]
1986	fn into_iter(self) -> IntoIter<K, V, C> {
1987		IntoIter::new(self)
1988	}
1989}
1990
1991pub(crate) struct DrainFilterInner<'a, K, V, C> {
1992	/// The tree reference.
1993	btree: &'a mut BTreeMap<K, V, C>,
1994
1995	/// Address of the next item, or last valid address.
1996	addr: Address,
1997
1998	len: usize,
1999}
2000
2001impl<'a, K: 'a, V: 'a, C: SlabMut<Node<K, V>>> DrainFilterInner<'a, K, V, C>
2002where
2003	C: SimpleCollectionRef,
2004	C: SimpleCollectionMut,
2005{
2006	#[inline]
2007	pub fn new(btree: &'a mut BTreeMap<K, V, C>) -> Self {
2008		let addr = btree.first_back_address();
2009		let len = btree.len();
2010		DrainFilterInner { btree, addr, len }
2011	}
2012
2013	#[inline]
2014	pub fn size_hint(&self) -> (usize, Option<usize>) {
2015		(0, Some(self.len))
2016	}
2017
2018	#[inline]
2019	fn next_item<F>(&mut self, pred: &mut F) -> Option<Item<K, V>>
2020	where
2021		F: FnMut(&K, &mut V) -> bool,
2022	{
2023		if self.addr.id == usize::MAX {
2024			return None;
2025		}
2026
2027		loop {
2028			match self.btree.item_mut(self.addr) {
2029				Some(item) => {
2030					let (key, value) = item.as_pair_mut();
2031					self.len -= 1;
2032					if (*pred)(key, value) {
2033						let (item, next_addr) = self.btree.remove_at(self.addr).unwrap();
2034						self.addr = next_addr;
2035						return Some(item);
2036					} else {
2037						self.addr = self.btree.next_item_or_back_address(self.addr).unwrap();
2038					}
2039				}
2040				None => return None,
2041			}
2042		}
2043	}
2044
2045	#[inline]
2046	pub fn next<F>(&mut self, pred: &mut F) -> Option<(K, V)>
2047	where
2048		F: FnMut(&K, &mut V) -> bool,
2049	{
2050		self.next_item(pred).map(Item::into_pair)
2051	}
2052}
2053
2054pub struct DrainFilter<'a, K, V, C: SlabMut<Node<K, V>>, F>
2055where
2056	F: FnMut(&K, &mut V) -> bool,
2057	C: SimpleCollectionRef,
2058	C: SimpleCollectionMut,
2059{
2060	pred: F,
2061
2062	inner: DrainFilterInner<'a, K, V, C>,
2063}
2064
2065impl<'a, K: 'a, V: 'a, C: SlabMut<Node<K, V>>, F> DrainFilter<'a, K, V, C, F>
2066where
2067	F: FnMut(&K, &mut V) -> bool,
2068	C: SimpleCollectionRef,
2069	C: SimpleCollectionMut,
2070{
2071	#[inline]
2072	fn new(btree: &'a mut BTreeMap<K, V, C>, pred: F) -> Self {
2073		DrainFilter {
2074			pred,
2075			inner: DrainFilterInner::new(btree),
2076		}
2077	}
2078}
2079
2080impl<'a, K, V, C: SlabMut<Node<K, V>>, F> FusedIterator for DrainFilter<'a, K, V, C, F>
2081where
2082	F: FnMut(&K, &mut V) -> bool,
2083	C: SimpleCollectionRef,
2084	C: SimpleCollectionMut,
2085{
2086}
2087
2088impl<'a, K, V, C: SlabMut<Node<K, V>>, F> Iterator for DrainFilter<'a, K, V, C, F>
2089where
2090	F: FnMut(&K, &mut V) -> bool,
2091	C: SimpleCollectionRef,
2092	C: SimpleCollectionMut,
2093{
2094	type Item = (K, V);
2095
2096	#[inline]
2097	fn size_hint(&self) -> (usize, Option<usize>) {
2098		self.inner.size_hint()
2099	}
2100
2101	#[inline]
2102	fn next(&mut self) -> Option<(K, V)> {
2103		self.inner.next(&mut self.pred)
2104	}
2105}
2106
2107impl<'a, K, V, C: SlabMut<Node<K, V>>, F> Drop for DrainFilter<'a, K, V, C, F>
2108where
2109	F: FnMut(&K, &mut V) -> bool,
2110	C: SimpleCollectionRef,
2111	C: SimpleCollectionMut,
2112{
2113	#[inline]
2114	fn drop(&mut self) {
2115		loop {
2116			if self.next().is_none() {
2117				break;
2118			}
2119		}
2120	}
2121}
2122
2123pub struct Keys<'a, K, V, C> {
2124	inner: Iter<'a, K, V, C>,
2125}
2126
2127impl<'a, K, V, C: Slab<Node<K, V>>> FusedIterator for Keys<'a, K, V, C> where C: SimpleCollectionRef {}
2128impl<'a, K, V, C: Slab<Node<K, V>>> ExactSizeIterator for Keys<'a, K, V, C> where
2129	C: SimpleCollectionRef
2130{
2131}
2132
2133impl<'a, K, V, C: Slab<Node<K, V>>> Iterator for Keys<'a, K, V, C>
2134where
2135	C: SimpleCollectionRef,
2136{
2137	type Item = &'a K;
2138
2139	#[inline]
2140	fn size_hint(&self) -> (usize, Option<usize>) {
2141		self.inner.size_hint()
2142	}
2143
2144	#[inline]
2145	fn next(&mut self) -> Option<&'a K> {
2146		self.inner.next().map(|(k, _)| k)
2147	}
2148}
2149
2150impl<'a, K, V, C: Slab<Node<K, V>>> DoubleEndedIterator for Keys<'a, K, V, C>
2151where
2152	C: SimpleCollectionRef,
2153{
2154	#[inline]
2155	fn next_back(&mut self) -> Option<&'a K> {
2156		self.inner.next_back().map(|(k, _)| k)
2157	}
2158}
2159
2160impl<K, V, C: SlabMut<Node<K, V>>> FusedIterator for IntoKeys<K, V, C>
2161where
2162	C: SimpleCollectionRef,
2163	C: SimpleCollectionMut,
2164{
2165}
2166impl<K, V, C: SlabMut<Node<K, V>>> ExactSizeIterator for IntoKeys<K, V, C>
2167where
2168	C: SimpleCollectionRef,
2169	C: SimpleCollectionMut,
2170{
2171}
2172
2173pub struct IntoKeys<K, V, C> {
2174	inner: IntoIter<K, V, C>,
2175}
2176
2177impl<K, V, C: SlabMut<Node<K, V>>> Iterator for IntoKeys<K, V, C>
2178where
2179	C: SimpleCollectionRef,
2180	C: SimpleCollectionMut,
2181{
2182	type Item = K;
2183
2184	#[inline]
2185	fn size_hint(&self) -> (usize, Option<usize>) {
2186		self.inner.size_hint()
2187	}
2188
2189	#[inline]
2190	fn next(&mut self) -> Option<K> {
2191		self.inner.next().map(|(k, _)| k)
2192	}
2193}
2194
2195impl<K, V, C: SlabMut<Node<K, V>>> DoubleEndedIterator for IntoKeys<K, V, C>
2196where
2197	C: SimpleCollectionRef,
2198	C: SimpleCollectionMut,
2199{
2200	#[inline]
2201	fn next_back(&mut self) -> Option<K> {
2202		self.inner.next_back().map(|(k, _)| k)
2203	}
2204}
2205
2206impl<'a, K, V, C: Slab<Node<K, V>>> FusedIterator for Values<'a, K, V, C> where
2207	C: SimpleCollectionRef
2208{
2209}
2210impl<'a, K, V, C: Slab<Node<K, V>>> ExactSizeIterator for Values<'a, K, V, C> where
2211	C: SimpleCollectionRef
2212{
2213}
2214
2215pub struct Values<'a, K, V, C> {
2216	inner: Iter<'a, K, V, C>,
2217}
2218
2219impl<'a, K, V, C: Slab<Node<K, V>>> Iterator for Values<'a, K, V, C>
2220where
2221	C: SimpleCollectionRef,
2222{
2223	type Item = &'a V;
2224
2225	#[inline]
2226	fn size_hint(&self) -> (usize, Option<usize>) {
2227		self.inner.size_hint()
2228	}
2229
2230	#[inline]
2231	fn next(&mut self) -> Option<&'a V> {
2232		self.inner.next().map(|(_, v)| v)
2233	}
2234}
2235
2236impl<'a, K, V, C: Slab<Node<K, V>>> DoubleEndedIterator for Values<'a, K, V, C>
2237where
2238	C: SimpleCollectionRef,
2239{
2240	#[inline]
2241	fn next_back(&mut self) -> Option<&'a V> {
2242		self.inner.next_back().map(|(_, v)| v)
2243	}
2244}
2245
2246pub struct ValuesMut<'a, K, V, C> {
2247	inner: IterMut<'a, K, V, C>,
2248}
2249
2250impl<'a, K, V, C: SlabMut<Node<K, V>>> FusedIterator for ValuesMut<'a, K, V, C>
2251where
2252	C: SimpleCollectionRef,
2253	C: SimpleCollectionMut,
2254{
2255}
2256impl<'a, K, V, C: SlabMut<Node<K, V>>> ExactSizeIterator for ValuesMut<'a, K, V, C>
2257where
2258	C: SimpleCollectionRef,
2259	C: SimpleCollectionMut,
2260{
2261}
2262
2263impl<'a, K, V, C: SlabMut<Node<K, V>>> Iterator for ValuesMut<'a, K, V, C>
2264where
2265	C: SimpleCollectionRef,
2266	C: SimpleCollectionMut,
2267{
2268	type Item = &'a mut V;
2269
2270	#[inline]
2271	fn size_hint(&self) -> (usize, Option<usize>) {
2272		self.inner.size_hint()
2273	}
2274
2275	#[inline]
2276	fn next(&mut self) -> Option<&'a mut V> {
2277		self.inner.next().map(|(_, v)| v)
2278	}
2279}
2280
2281pub struct IntoValues<K, V, C> {
2282	inner: IntoIter<K, V, C>,
2283}
2284
2285impl<K, V, C: SlabMut<Node<K, V>>> FusedIterator for IntoValues<K, V, C>
2286where
2287	C: SimpleCollectionRef,
2288	C: SimpleCollectionMut,
2289{
2290}
2291impl<K, V, C: SlabMut<Node<K, V>>> ExactSizeIterator for IntoValues<K, V, C>
2292where
2293	C: SimpleCollectionRef,
2294	C: SimpleCollectionMut,
2295{
2296}
2297
2298impl<K, V, C: SlabMut<Node<K, V>>> Iterator for IntoValues<K, V, C>
2299where
2300	C: SimpleCollectionRef,
2301	C: SimpleCollectionMut,
2302{
2303	type Item = V;
2304
2305	#[inline]
2306	fn size_hint(&self) -> (usize, Option<usize>) {
2307		self.inner.size_hint()
2308	}
2309
2310	#[inline]
2311	fn next(&mut self) -> Option<V> {
2312		self.inner.next().map(|(_, v)| v)
2313	}
2314}
2315
2316impl<K, V, C: SlabMut<Node<K, V>>> DoubleEndedIterator for IntoValues<K, V, C>
2317where
2318	C: SimpleCollectionRef,
2319	C: SimpleCollectionMut,
2320{
2321	#[inline]
2322	fn next_back(&mut self) -> Option<V> {
2323		self.inner.next_back().map(|(_, v)| v)
2324	}
2325}
2326
2327fn is_valid_range<T, R>(range: &R) -> bool
2328where
2329	T: Ord + ?Sized,
2330	R: RangeBounds<T>,
2331{
2332	match (range.start_bound(), range.end_bound()) {
2333		(Bound::Included(start), Bound::Included(end)) => start <= end,
2334		(Bound::Included(start), Bound::Excluded(end)) => start <= end,
2335		(Bound::Included(_), Bound::Unbounded) => true,
2336		(Bound::Excluded(start), Bound::Included(end)) => start <= end,
2337		(Bound::Excluded(start), Bound::Excluded(end)) => start < end,
2338		(Bound::Excluded(_), Bound::Unbounded) => true,
2339		(Bound::Unbounded, _) => true,
2340	}
2341}
2342
2343pub struct Range<'a, K, V, C> {
2344	/// The tree reference.
2345	btree: &'a BTreeMap<K, V, C>,
2346
2347	/// Address of the next item or last back address.
2348	addr: Address,
2349
2350	end: Address,
2351}
2352
2353impl<'a, K, V, C: Slab<Node<K, V>>> Range<'a, K, V, C>
2354where
2355	C: SimpleCollectionRef,
2356{
2357	fn new<T, R>(btree: &'a BTreeMap<K, V, C>, range: R) -> Self
2358	where
2359		T: Ord + ?Sized,
2360		R: RangeBounds<T>,
2361		K: Borrow<T>,
2362	{
2363		if !is_valid_range(&range) {
2364			panic!("Invalid range")
2365		}
2366
2367		let addr = match range.start_bound() {
2368			Bound::Included(start) => match btree.address_of(start) {
2369				Ok(addr) => addr,
2370				Err(addr) => addr,
2371			},
2372			Bound::Excluded(start) => match btree.address_of(start) {
2373				Ok(addr) => btree.next_item_or_back_address(addr).unwrap(),
2374				Err(addr) => addr,
2375			},
2376			Bound::Unbounded => btree.first_back_address(),
2377		};
2378
2379		let end = match range.end_bound() {
2380			Bound::Included(end) => match btree.address_of(end) {
2381				Ok(addr) => btree.next_item_or_back_address(addr).unwrap(),
2382				Err(addr) => addr,
2383			},
2384			Bound::Excluded(end) => match btree.address_of(end) {
2385				Ok(addr) => addr,
2386				Err(addr) => addr,
2387			},
2388			Bound::Unbounded => btree.first_back_address(),
2389		};
2390
2391		Range { btree, addr, end }
2392	}
2393}
2394
2395impl<'a, K, V, C: Slab<Node<K, V>>> Iterator for Range<'a, K, V, C>
2396where
2397	C: SimpleCollectionRef,
2398{
2399	type Item = (&'a K, &'a V);
2400
2401	#[inline]
2402	fn next(&mut self) -> Option<(&'a K, &'a V)> {
2403		if self.addr != self.end {
2404			let item = self.btree.item(self.addr).unwrap();
2405			self.addr = self.btree.next_item_or_back_address(self.addr).unwrap();
2406			Some((item.key(), item.value()))
2407		} else {
2408			None
2409		}
2410	}
2411}
2412
2413impl<'a, K, V, C: Slab<Node<K, V>>> FusedIterator for Range<'a, K, V, C> where C: SimpleCollectionRef
2414{}
2415
2416impl<'a, K, V, C: Slab<Node<K, V>>> DoubleEndedIterator for Range<'a, K, V, C>
2417where
2418	C: SimpleCollectionRef,
2419{
2420	#[inline]
2421	fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
2422		if self.addr != self.end {
2423			let addr = self.btree.previous_item_address(self.addr).unwrap();
2424			let item = self.btree.item(addr).unwrap();
2425			self.end = addr;
2426			Some((item.key(), item.value()))
2427		} else {
2428			None
2429		}
2430	}
2431}
2432
2433pub struct RangeMut<'a, K, V, C> {
2434	/// The tree reference.
2435	btree: &'a mut BTreeMap<K, V, C>,
2436
2437	/// Address of the next item or last back address.
2438	addr: Address,
2439
2440	end: Address,
2441}
2442
2443impl<'a, K, V, C: SlabMut<Node<K, V>>> RangeMut<'a, K, V, C>
2444where
2445	C: SimpleCollectionRef,
2446	C: SimpleCollectionMut,
2447{
2448	fn new<T, R>(btree: &'a mut BTreeMap<K, V, C>, range: R) -> Self
2449	where
2450		T: Ord + ?Sized,
2451		R: RangeBounds<T>,
2452		K: Borrow<T>,
2453	{
2454		if !is_valid_range(&range) {
2455			panic!("Invalid range")
2456		}
2457
2458		let addr = match range.start_bound() {
2459			Bound::Included(start) => match btree.address_of(start) {
2460				Ok(addr) => addr,
2461				Err(addr) => addr,
2462			},
2463			Bound::Excluded(start) => match btree.address_of(start) {
2464				Ok(addr) => btree.next_item_or_back_address(addr).unwrap(),
2465				Err(addr) => addr,
2466			},
2467			Bound::Unbounded => btree.first_back_address(),
2468		};
2469
2470		let end = match range.end_bound() {
2471			Bound::Included(end) => match btree.address_of(end) {
2472				Ok(addr) => btree.next_item_or_back_address(addr).unwrap(),
2473				Err(addr) => addr,
2474			},
2475			Bound::Excluded(end) => match btree.address_of(end) {
2476				Ok(addr) => addr,
2477				Err(addr) => addr,
2478			},
2479			Bound::Unbounded => btree.first_back_address(),
2480		};
2481
2482		RangeMut { btree, addr, end }
2483	}
2484
2485	#[inline]
2486	fn next_item(&mut self) -> Option<&'a mut Item<K, V>> {
2487		if self.addr != self.end {
2488			let addr = self.addr;
2489			self.addr = self.btree.next_item_or_back_address(addr).unwrap();
2490			let item = self.btree.item_mut(addr).unwrap();
2491			Some(unsafe { std::mem::transmute(item) }) // this is safe because only one mutable reference to the same item can be emitted.
2492		} else {
2493			None
2494		}
2495	}
2496
2497	#[inline]
2498	fn next_back_item(&mut self) -> Option<&'a mut Item<K, V>> {
2499		if self.addr != self.end {
2500			let addr = self.btree.previous_item_address(self.addr).unwrap();
2501			let item = self.btree.item_mut(addr).unwrap();
2502			self.end = addr;
2503			Some(unsafe { std::mem::transmute(item) }) // this is safe because only one mutable reference to the same item can be emitted.s
2504		} else {
2505			None
2506		}
2507	}
2508}
2509
2510impl<'a, K, V, C: SlabMut<Node<K, V>>> Iterator for RangeMut<'a, K, V, C>
2511where
2512	C: SimpleCollectionRef,
2513	C: SimpleCollectionMut,
2514{
2515	type Item = (&'a K, &'a mut V);
2516
2517	#[inline]
2518	fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2519		self.next_item().map(|item| {
2520			let (key, value) = item.as_pair_mut();
2521			(key as &'a K, value)
2522		})
2523	}
2524}
2525
2526impl<'a, K, V, C: SlabMut<Node<K, V>>> FusedIterator for RangeMut<'a, K, V, C>
2527where
2528	C: SimpleCollectionRef,
2529	C: SimpleCollectionMut,
2530{
2531}
2532
2533impl<'a, K, V, C: SlabMut<Node<K, V>>> DoubleEndedIterator for RangeMut<'a, K, V, C>
2534where
2535	C: SimpleCollectionRef,
2536	C: SimpleCollectionMut,
2537{
2538	#[inline]
2539	fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
2540		self.next_back_item().map(|item| {
2541			let (key, value) = item.as_pair_mut();
2542			(key as &'a K, value)
2543		})
2544	}
2545}