Skip to main content

btree_indexmap/
map.rs

1use core::fmt;
2use equivalent::Comparable;
3use raw_btree::RawBTree;
4use std::{
5	cmp::Ordering,
6	hash::{Hash, Hasher},
7	iter::FusedIterator,
8	mem::MaybeUninit,
9	ops::Index,
10};
11
12/// BTree-based map with stable entry indices.
13///
14/// Each key maps to exactly one value. Entries are stored in a [`Vec`] and
15/// assigned a *stable index* equal to their position in that `Vec`. The
16/// index of an entry does not change as long as no entry is removed. A
17/// B-tree over the keys provides O(log n) lookup, insertion, and removal,
18/// while the `Vec` backing allows O(1) random access by index.
19///
20/// # Example
21///
22/// ```
23/// use btree_indexmap::BTreeIndexMap;
24///
25/// let mut map = BTreeIndexMap::new();
26///
27/// // Entries are stored in insertion order and assigned a stable index.
28/// map.insert("banana", 3);
29/// map.insert("apple", 5);
30///
31/// // O(1) access by index (insertion order).
32/// assert_eq!(map.as_entries()[0], ("banana", 3));
33/// assert_eq!(map.as_entries()[1], ("apple", 5));
34///
35/// // O(log n) lookup by key, returning the stable index alongside the value.
36/// assert_eq!(map.get_full("apple"), Some((1, &"apple", &5)));
37/// ```
38#[derive(Clone)]
39pub struct BTreeIndexMap<K, V> {
40	entries: Vec<(K, V)>,
41	map: RawBTree<usize>,
42}
43
44impl<K, V> Default for BTreeIndexMap<K, V> {
45	fn default() -> Self {
46		Self::new()
47	}
48}
49
50impl<K, V> BTreeIndexMap<K, V> {
51	/// Creates a new, empty map.
52	pub fn new() -> Self {
53		Self {
54			entries: Vec::new(),
55			map: RawBTree::new(),
56		}
57	}
58
59	/// Creates a new map containing the single `(key, value)` entry.
60	pub fn singleton(key: K, value: V) -> Self
61	where
62		K: Ord,
63	{
64		let mut result = Self::new();
65		result.force_insert_full(key, value);
66		result
67	}
68
69	/// Removes all entries from the map.
70	///
71	/// This keeps the capacity allocated for the entries.
72	pub fn clear(&mut self) {
73		self.entries.clear();
74		self.map.clear();
75	}
76
77	/// Returns the entries of the map as a slice, in insertion (index)
78	/// order.
79	pub fn as_entries(&self) -> &[(K, V)] {
80		&self.entries
81	}
82
83	/// Returns `true` if the map contains no entries.
84	pub fn is_empty(&self) -> bool {
85		self.entries.is_empty()
86	}
87
88	/// Returns the number of entries in the map.
89	pub fn len(&self) -> usize {
90		self.entries.len()
91	}
92
93	/// Returns the index, key, and value of the entry matching `key`, if
94	/// any.
95	pub fn get_full<Q>(&self, key: &Q) -> Option<(usize, &K, &V)>
96	where
97		Q: ?Sized + Comparable<K>,
98	{
99		self.map
100			.get(outer_cmp(&self.entries), key)
101			.copied()
102			.map(|i| {
103				let (k, v) = &self.entries[i];
104				(i, k, v)
105			})
106	}
107
108	/// Returns the key and value of the entry matching `key`, if any.
109	pub fn get_entry<Q>(&self, key: &Q) -> Option<(&K, &V)>
110	where
111		Q: ?Sized + Comparable<K>,
112	{
113		self.get_full(key).map(|(_, k, v)| (k, v))
114	}
115
116	/// Returns a reference to the value associated with `key`, if any.
117	pub fn get<Q>(&self, key: &Q) -> Option<&V>
118	where
119		Q: ?Sized + Comparable<K>,
120	{
121		self.get_full(key).map(|(_, _, v)| v)
122	}
123
124	/// Returns the index, key, and a mutable reference to the value of the
125	/// entry matching `key`, if any.
126	pub fn get_mut_full<Q>(&mut self, key: &Q) -> Option<(usize, &K, &mut V)>
127	where
128		Q: ?Sized + Comparable<K>,
129	{
130		self.map
131			.get(outer_cmp(&self.entries), key)
132			.copied()
133			.map(|i| {
134				let (k, v) = &mut self.entries[i];
135				(i, &*k, v)
136			})
137	}
138
139	/// Returns the key and a mutable reference to the value of the entry
140	/// matching `key`, if any.
141	pub fn get_mut_entry<Q>(&mut self, key: &Q) -> Option<(&K, &mut V)>
142	where
143		Q: ?Sized + Comparable<K>,
144	{
145		self.get_mut_full(key).map(|(_, k, v)| (k, v))
146	}
147
148	/// Returns a mutable reference to the value associated with `key`, if
149	/// any.
150	pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
151	where
152		Q: ?Sized + Comparable<K>,
153	{
154		self.get_mut_full(key).map(|(_, _, v)| v)
155	}
156
157	/// Gets the entry associated with `key` for in-place manipulation.
158	///
159	/// # Example
160	///
161	/// ```
162	/// use btree_indexmap::{BTreeIndexMap, map::Entry};
163	///
164	/// let mut map: BTreeIndexMap<&str, i32> = BTreeIndexMap::new();
165	///
166	/// match map.entry("a") {
167	///     Entry::Vacant(e) => {
168	///         e.insert(1);
169	///     }
170	///     Entry::Occupied(_) => unreachable!(),
171	/// }
172	///
173	/// assert_eq!(map.get("a"), Some(&1));
174	/// ```
175	pub fn entry(&mut self, key: K) -> Entry<'_, K, V>
176	where
177		K: Ord,
178	{
179		match self.map.get(outer_cmp(&self.entries), &key).copied() {
180			Some(i) => Entry::Occupied(OccupiedEntry { map: self, i }),
181			None => Entry::Vacant(VacantEntry { map: self, key }),
182		}
183	}
184
185	/// Inserts a key-value pair in the map, returning the index of the
186	/// entry and, if `key` was already present, its previous value.
187	pub fn insert_full(&mut self, key: K, value: V) -> (usize, Option<V>)
188	where
189		K: Ord,
190	{
191		match self.map.get(outer_cmp(&self.entries), &key).copied() {
192			Some(i) => (i, Some(std::mem::replace(&mut self.entries[i].1, value))),
193			None => {
194				let i = self.force_insert_full(key, value);
195				(i, None)
196			}
197		}
198	}
199
200	fn force_insert_full(&mut self, key: K, value: V) -> usize
201	where
202		K: Ord,
203	{
204		let i = self.entries.len();
205		self.entries.push((key, value));
206		self.map.insert(inner_cmp(&self.entries), i);
207		i
208	}
209
210	/// Inserts a key-value pair in the map, returning the previous value
211	/// associated with `key`, if any.
212	pub fn insert(&mut self, key: K, value: V) -> Option<V>
213	where
214		K: Ord,
215	{
216		self.insert_full(key, value).1
217	}
218
219	/// Removes the entry matching `key`, returning its former index, key,
220	/// and value, if it was present.
221	///
222	/// Shifts every following entry one index down.
223	pub fn shift_remove_full<Q>(&mut self, key: &Q) -> Option<(usize, K, V)>
224	where
225		Q: ?Sized + Comparable<K>,
226	{
227		let i = self.map.remove(outer_cmp(&self.entries), key)?;
228
229		let (k, v) = self.entries.remove(i);
230
231		// Shift larger indices.
232		for j in self.map.iter_mut() {
233			if *j > i {
234				*j -= 1;
235			}
236		}
237
238		Some((i, k, v))
239	}
240
241	/// Removes the entry matching `key`, returning its key and value, if it
242	/// was present.
243	///
244	/// Shifts every following entry one index down.
245	pub fn shift_remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
246	where
247		Q: ?Sized + Comparable<K>,
248	{
249		self.shift_remove_full(key).map(|(_, k, v)| (k, v))
250	}
251
252	/// Removes the entry matching `key`, returning its value, if it was
253	/// present.
254	///
255	/// Shifts every following entry one index down.
256	pub fn shift_remove<Q>(&mut self, key: &Q) -> Option<V>
257	where
258		Q: ?Sized + Comparable<K>,
259	{
260		self.shift_remove_full(key).map(|(_, _, v)| v)
261	}
262
263	/// Removes the entry matching `key`, returning its former index, key,
264	/// and value, if it was present.
265	///
266	/// Moves the last entry into the removed slot.
267	pub fn swap_remove_full<Q>(&mut self, key: &Q) -> Option<(usize, K, V)>
268	where
269		Q: ?Sized + Comparable<K>,
270		K: Ord,
271	{
272		let i = self.map.remove(outer_cmp(&self.entries), key)?;
273
274		let j = self.entries.len() - 1;
275
276		// Swap the entries.
277		if j > i {
278			*self.map.get_mut(inner_cmp(&self.entries), &j).unwrap() = i;
279			self.entries.swap(i, j);
280		}
281
282		let (k, v) = self.entries.pop().unwrap();
283		Some((i, k, v))
284	}
285
286	/// Removes the entry matching `key`, returning its key and value, if it
287	/// was present.
288	///
289	/// Moves the last entry into the removed slot.
290	pub fn swap_remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
291	where
292		Q: ?Sized + Comparable<K>,
293		K: Ord,
294	{
295		self.swap_remove_full(key).map(|(_, k, v)| (k, v))
296	}
297
298	/// Removes the entry matching `key`, returning its value, if it was
299	/// present.
300	///
301	/// Moves the last entry into the removed slot.
302	pub fn swap_remove<Q>(&mut self, key: &Q) -> Option<V>
303	where
304		Q: ?Sized + Comparable<K>,
305		K: Ord,
306	{
307		self.swap_remove_full(key).map(|(_, _, v)| v)
308	}
309
310	/// Returns an iterator over the entries of the map, in insertion
311	/// (index) order.
312	pub fn iter(&self) -> Iter<'_, K, V> {
313		Iter(self.entries.iter())
314	}
315
316	/// Returns an iterator over the entries of the map, with a mutable
317	/// reference to the value, in insertion (index) order.
318	pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
319		IterMut(self.entries.iter_mut())
320	}
321
322	/// Returns an iterator over the entries of the map, sorted according to
323	/// `K`'s implementation of [`Ord`].
324	pub fn iter_sorted(&self) -> IterSorted<'_, K, V> {
325		IterSorted {
326			entries: &self.entries,
327			inner: self.map.iter(),
328		}
329	}
330
331	/// Returns an iterator over the entries of the map, with a mutable
332	/// reference to the value, sorted according to `K`'s implementation of
333	/// [`Ord`].
334	pub fn iter_mut_sorted(&mut self) -> IterMutSorted<'_, K, V> {
335		IterMutSorted {
336			entries: &mut self.entries,
337			inner: self.map.iter(),
338		}
339	}
340
341	/// Turns this map into an iterator over its entries, sorted according
342	/// to `K`'s implementation of [`Ord`].
343	pub fn into_iter_sorted(self) -> IntoIterSorted<K, V> {
344		IntoIterSorted {
345			entries: unsafe {
346				// SAFETY: `(K, V)` and `MaybeUninit<(K, V)>` have the exact
347				//         same representation.
348				std::mem::transmute::<Vec<(K, V)>, Vec<MaybeUninit<(K, V)>>>(self.entries)
349			},
350			inner: self.map.into_iter(),
351		}
352	}
353
354	/// Returns an iterator over the keys of the map, in insertion (index)
355	/// order.
356	pub fn keys(&self) -> Keys<'_, K, V> {
357		Keys(self.entries.iter())
358	}
359
360	/// Returns an iterator over the values of the map, in insertion (index)
361	/// order.
362	pub fn values(&self) -> Values<'_, K, V> {
363		Values(self.entries.iter())
364	}
365
366	/// Returns an iterator over mutable references to the values of the
367	/// map, in insertion (index) order.
368	pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
369		ValuesMut(self.entries.iter_mut())
370	}
371}
372
373fn inner_cmp<K, V>(entries: &[(K, V)]) -> impl use<'_, K, V> + Fn(&usize, &usize) -> Ordering
374where
375	K: Ord,
376{
377	|&i, &j| entries[i].0.cmp(&entries[j].0)
378}
379
380fn outer_cmp<K, V, Q>(entries: &[(K, V)]) -> impl use<'_, K, V, Q> + Fn(&usize, &Q) -> Ordering
381where
382	Q: ?Sized + Comparable<K>,
383{
384	|&i, q| q.compare(&entries[i].0).reverse()
385}
386
387impl<K, V, Q> Index<&Q> for BTreeIndexMap<K, V>
388where
389	Q: ?Sized + Comparable<K>,
390{
391	type Output = V;
392
393	/// # Panics
394	///
395	/// Panics if `key` is not found in the map.
396	fn index(&self, key: &Q) -> &Self::Output {
397		self.get(key).expect("no entry found for key")
398	}
399}
400
401/// An owning iterator over the entries of a [`BTreeIndexMap`], in
402/// insertion order.
403pub type IntoIter<K, V> = std::vec::IntoIter<(K, V)>;
404
405impl<K, V> IntoIterator for BTreeIndexMap<K, V> {
406	type IntoIter = IntoIter<K, V>;
407	type Item = (K, V);
408
409	fn into_iter(self) -> Self::IntoIter {
410		self.entries.into_iter()
411	}
412}
413
414impl<K: PartialEq, V: PartialEq> PartialEq for BTreeIndexMap<K, V> {
415	fn eq(&self, other: &Self) -> bool {
416		self.iter_sorted().eq(other.iter_sorted())
417	}
418}
419
420impl<K: Eq, V: Eq> Eq for BTreeIndexMap<K, V> {}
421
422impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeIndexMap<K, V> {
423	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
424		self.iter_sorted().partial_cmp(other.iter_sorted())
425	}
426}
427
428impl<K: Ord, V: Ord> Ord for BTreeIndexMap<K, V> {
429	fn cmp(&self, other: &Self) -> Ordering {
430		self.iter_sorted().cmp(other.iter_sorted())
431	}
432}
433
434impl<K: Hash, V: Hash> Hash for BTreeIndexMap<K, V> {
435	fn hash<H: Hasher>(&self, state: &mut H) {
436		state.write_usize(self.len());
437		for item in self.iter_sorted() {
438			item.hash(state);
439		}
440	}
441}
442
443impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for BTreeIndexMap<K, V> {
444	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445		f.debug_set().entries(self.iter()).finish()
446	}
447}
448
449impl<K: Ord, V> Extend<(K, V)> for BTreeIndexMap<K, V> {
450	fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
451		for (key, value) in iter {
452			self.insert(key, value);
453		}
454	}
455}
456
457impl<K: Ord, V> FromIterator<(K, V)> for BTreeIndexMap<K, V> {
458	fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
459		let mut result = Self::new();
460		result.extend(iter);
461		result
462	}
463}
464
465/// An iterator over the entries of a [`BTreeIndexMap`], in insertion order.
466pub struct Iter<'a, K, V>(std::slice::Iter<'a, (K, V)>);
467
468impl<K, V> Clone for Iter<'_, K, V> {
469	fn clone(&self) -> Self {
470		Self(self.0.clone())
471	}
472}
473
474impl<'a, K, V> Iterator for Iter<'a, K, V> {
475	type Item = (&'a K, &'a V);
476
477	fn size_hint(&self) -> (usize, Option<usize>) {
478		self.0.size_hint()
479	}
480
481	fn next(&mut self) -> Option<Self::Item> {
482		self.0.next().map(|(k, v)| (k, v))
483	}
484}
485
486impl<K, V> DoubleEndedIterator for Iter<'_, K, V> {
487	fn next_back(&mut self) -> Option<Self::Item> {
488		self.0.next_back().map(|(k, v)| (k, v))
489	}
490}
491
492impl<K, V> ExactSizeIterator for Iter<'_, K, V> {}
493
494impl<K, V> FusedIterator for Iter<'_, K, V> {}
495
496impl<'a, K, V> IntoIterator for &'a BTreeIndexMap<K, V> {
497	type IntoIter = Iter<'a, K, V>;
498	type Item = (&'a K, &'a V);
499
500	fn into_iter(self) -> Self::IntoIter {
501		self.iter()
502	}
503}
504
505/// An iterator over the entries of a [`BTreeIndexMap`], with a mutable
506/// reference to the value, in insertion order.
507pub struct IterMut<'a, K, V>(std::slice::IterMut<'a, (K, V)>);
508
509impl<'a, K, V> Iterator for IterMut<'a, K, V> {
510	type Item = (&'a K, &'a mut V);
511
512	fn size_hint(&self) -> (usize, Option<usize>) {
513		self.0.size_hint()
514	}
515
516	fn next(&mut self) -> Option<Self::Item> {
517		self.0.next().map(|(k, v)| (&*k, v))
518	}
519}
520
521impl<K, V> DoubleEndedIterator for IterMut<'_, K, V> {
522	fn next_back(&mut self) -> Option<Self::Item> {
523		self.0.next_back().map(|(k, v)| (&*k, v))
524	}
525}
526
527impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {}
528
529impl<K, V> FusedIterator for IterMut<'_, K, V> {}
530
531impl<'a, K, V> IntoIterator for &'a mut BTreeIndexMap<K, V> {
532	type IntoIter = IterMut<'a, K, V>;
533	type Item = (&'a K, &'a mut V);
534
535	fn into_iter(self) -> Self::IntoIter {
536		self.iter_mut()
537	}
538}
539
540/// An iterator over the entries of a [`BTreeIndexMap`], sorted according
541/// to `K`'s implementation of [`Ord`].
542pub struct IterSorted<'a, K, V> {
543	entries: &'a [(K, V)],
544	inner: raw_btree::Iter<'a, usize>,
545}
546
547impl<K, V> Clone for IterSorted<'_, K, V> {
548	fn clone(&self) -> Self {
549		Self {
550			entries: self.entries,
551			inner: self.inner,
552		}
553	}
554}
555
556impl<'a, K, V> Iterator for IterSorted<'a, K, V> {
557	type Item = (&'a K, &'a V);
558
559	fn size_hint(&self) -> (usize, Option<usize>) {
560		self.inner.size_hint()
561	}
562
563	fn next(&mut self) -> Option<Self::Item> {
564		self.inner.next().copied().map(|i| {
565			let (k, v) = &self.entries[i];
566			(k, v)
567		})
568	}
569}
570
571impl<K, V> DoubleEndedIterator for IterSorted<'_, K, V> {
572	fn next_back(&mut self) -> Option<Self::Item> {
573		self.inner.next_back().copied().map(|i| {
574			let (k, v) = &self.entries[i];
575			(k, v)
576		})
577	}
578}
579
580impl<K, V> ExactSizeIterator for IterSorted<'_, K, V> {}
581
582impl<K, V> FusedIterator for IterSorted<'_, K, V> {}
583
584/// An iterator over the entries of a [`BTreeIndexMap`], with a mutable
585/// reference to the value, sorted according to `K`'s implementation of
586/// [`Ord`].
587pub struct IterMutSorted<'a, K, V> {
588	entries: &'a mut [(K, V)],
589	inner: raw_btree::Iter<'a, usize>,
590}
591
592impl<'a, K, V> Iterator for IterMutSorted<'a, K, V> {
593	type Item = (&'a K, &'a mut V);
594
595	fn size_hint(&self) -> (usize, Option<usize>) {
596		self.inner.size_hint()
597	}
598
599	fn next(&mut self) -> Option<Self::Item> {
600		self.inner.next().copied().map(|i| {
601			let (k, v) = &mut self.entries[i];
602			(
603				unsafe {
604					// SAFETY: `k` is cannot be borrowed again as long as the
605					//         iterator lives.
606					std::mem::transmute::<&mut K, &'a K>(k)
607				},
608				unsafe {
609					// SAFETY: `v` is cannot be borrowed again as long as the
610					//         iterator lives.
611					std::mem::transmute::<&mut V, &'a mut V>(v)
612				},
613			)
614		})
615	}
616}
617
618impl<'a, K, V> DoubleEndedIterator for IterMutSorted<'a, K, V> {
619	fn next_back(&mut self) -> Option<Self::Item> {
620		self.inner.next_back().copied().map(|i| {
621			let (k, v) = &mut self.entries[i];
622			(
623				unsafe {
624					// SAFETY: `k` is cannot be borrowed again as long as the
625					//         iterator lives.
626					std::mem::transmute::<&mut K, &'a K>(k)
627				},
628				unsafe {
629					// SAFETY: `v` is cannot be borrowed again as long as the
630					//         iterator lives.
631					std::mem::transmute::<&mut V, &'a mut V>(v)
632				},
633			)
634		})
635	}
636}
637
638impl<K, V> ExactSizeIterator for IterMutSorted<'_, K, V> {}
639
640impl<K, V> FusedIterator for IterMutSorted<'_, K, V> {}
641
642/// An owning iterator over the entries of a [`BTreeIndexMap`], sorted
643/// according to `K`'s implementation of [`Ord`].
644pub struct IntoIterSorted<K, V> {
645	entries: Vec<MaybeUninit<(K, V)>>,
646	inner: raw_btree::IntoIter<usize>,
647}
648
649impl<K, V> Iterator for IntoIterSorted<K, V> {
650	type Item = (K, V);
651
652	fn size_hint(&self) -> (usize, Option<usize>) {
653		self.inner.size_hint()
654	}
655
656	fn next(&mut self) -> Option<Self::Item> {
657		self.inner.next().map(|i| {
658			unsafe {
659				// SAFETY: each index is visited exactly once, so there is no
660				//         risk of reading the same entry twice.
661				self.entries[i].assume_init_read()
662			}
663		})
664	}
665}
666
667impl<K, V> DoubleEndedIterator for IntoIterSorted<K, V> {
668	fn next_back(&mut self) -> Option<Self::Item> {
669		self.inner.next_back().map(|i| {
670			unsafe {
671				// SAFETY: each index is visited exactly once, so there is no
672				//         risk of reading the same entry twice.
673				self.entries[i].assume_init_read()
674			}
675		})
676	}
677}
678
679impl<K, V> ExactSizeIterator for IntoIterSorted<K, V> {}
680
681impl<K, V> FusedIterator for IntoIterSorted<K, V> {}
682
683impl<K, V> Drop for IntoIterSorted<K, V> {
684	fn drop(&mut self) {
685		// Make sure the remaining entries are consumed.
686		self.last();
687	}
688}
689
690/// An iterator over the keys of a [`BTreeIndexMap`], in insertion order.
691pub struct Keys<'a, K, V>(std::slice::Iter<'a, (K, V)>);
692
693impl<K, V> Clone for Keys<'_, K, V> {
694	fn clone(&self) -> Self {
695		Self(self.0.clone())
696	}
697}
698
699impl<'a, K, V> Iterator for Keys<'a, K, V> {
700	type Item = &'a K;
701
702	fn size_hint(&self) -> (usize, Option<usize>) {
703		self.0.size_hint()
704	}
705
706	fn next(&mut self) -> Option<Self::Item> {
707		self.0.next().map(|(k, _)| k)
708	}
709}
710
711impl<K, V> DoubleEndedIterator for Keys<'_, K, V> {
712	fn next_back(&mut self) -> Option<Self::Item> {
713		self.0.next_back().map(|(k, _)| k)
714	}
715}
716
717impl<K, V> ExactSizeIterator for Keys<'_, K, V> {}
718
719impl<K, V> FusedIterator for Keys<'_, K, V> {}
720
721/// An iterator over the values of a [`BTreeIndexMap`], in insertion order.
722pub struct Values<'a, K, V>(std::slice::Iter<'a, (K, V)>);
723
724impl<K, V> Clone for Values<'_, K, V> {
725	fn clone(&self) -> Self {
726		Self(self.0.clone())
727	}
728}
729
730impl<'a, K, V> Iterator for Values<'a, K, V> {
731	type Item = &'a V;
732
733	fn size_hint(&self) -> (usize, Option<usize>) {
734		self.0.size_hint()
735	}
736
737	fn next(&mut self) -> Option<Self::Item> {
738		self.0.next().map(|(_, v)| v)
739	}
740}
741
742impl<K, V> DoubleEndedIterator for Values<'_, K, V> {
743	fn next_back(&mut self) -> Option<Self::Item> {
744		self.0.next_back().map(|(_, v)| v)
745	}
746}
747
748impl<K, V> ExactSizeIterator for Values<'_, K, V> {}
749
750impl<K, V> FusedIterator for Values<'_, K, V> {}
751
752/// An iterator over mutable references to the values of a
753/// [`BTreeIndexMap`], in insertion order.
754pub struct ValuesMut<'a, K, V>(std::slice::IterMut<'a, (K, V)>);
755
756impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
757	type Item = &'a mut V;
758
759	fn size_hint(&self) -> (usize, Option<usize>) {
760		self.0.size_hint()
761	}
762
763	fn next(&mut self) -> Option<Self::Item> {
764		self.0.next().map(|(_, v)| v)
765	}
766}
767
768impl<K, V> DoubleEndedIterator for ValuesMut<'_, K, V> {
769	fn next_back(&mut self) -> Option<Self::Item> {
770		self.0.next_back().map(|(_, v)| v)
771	}
772}
773
774impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {}
775
776impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
777
778/// A view into a single entry of a [`BTreeIndexMap`], which may either be
779/// vacant or occupied.
780///
781/// This is returned by [`BTreeIndexMap::entry`].
782pub enum Entry<'a, K, V> {
783	Vacant(VacantEntry<'a, K, V>),
784	Occupied(OccupiedEntry<'a, K, V>),
785}
786
787/// A view into a vacant entry of a [`BTreeIndexMap`].
788///
789/// This is part of the [`Entry`] enum.
790pub struct VacantEntry<'a, K, V> {
791	map: &'a mut BTreeIndexMap<K, V>,
792	key: K,
793}
794
795impl<'a, K, V> VacantEntry<'a, K, V> {
796	/// Returns a reference to the entry's key.
797	pub fn key(&self) -> &K {
798		&self.key
799	}
800
801	/// Consumes this entry, returning its key.
802	pub fn into_key(self) -> K {
803		self.key
804	}
805
806	/// Inserts `value` in the map for this entry's key, returning the new
807	/// entry's index, key, and a mutable reference to the value.
808	pub fn insert_full(self, value: V) -> (usize, &'a K, &'a mut V)
809	where
810		K: Ord,
811	{
812		let i = self.map.force_insert_full(self.key, value);
813		let (k, v) = &mut self.map.entries[i];
814		(i, &*k, v)
815	}
816
817	/// Inserts `value` in the map for this entry's key, returning the new
818	/// entry's key and a mutable reference to the value.
819	pub fn insert_entry(self, value: V) -> (&'a K, &'a mut V)
820	where
821		K: Ord,
822	{
823		let (_, k, v) = self.insert_full(value);
824		(k, v)
825	}
826
827	/// Inserts `value` in the map for this entry's key, returning a mutable
828	/// reference to the value.
829	pub fn insert(self, value: V) -> &'a mut V
830	where
831		K: Ord,
832	{
833		self.insert_full(value).2
834	}
835}
836
837/// A view into an occupied entry of a [`BTreeIndexMap`].
838///
839/// This is part of the [`Entry`] enum.
840pub struct OccupiedEntry<'a, K, V> {
841	map: &'a mut BTreeIndexMap<K, V>,
842	i: usize,
843}
844
845impl<'a, K, V> OccupiedEntry<'a, K, V> {
846	/// Returns a reference to the entry's key.
847	pub fn key(&self) -> &K {
848		&self.map.entries[self.i].0
849	}
850
851	/// Returns the entry's index, key, and a reference to its value.
852	pub fn get_full(&self) -> (usize, &K, &V) {
853		let (k, v) = &self.map.entries[self.i];
854		(self.i, k, v)
855	}
856
857	/// Returns the entry's key and a reference to its value.
858	pub fn get_entry(&self) -> (&K, &V) {
859		let (k, v) = &self.map.entries[self.i];
860		(k, v)
861	}
862
863	/// Returns a reference to the entry's value.
864	pub fn get(&self) -> &V {
865		&self.map.entries[self.i].1
866	}
867
868	/// Returns the entry's index, key, and a mutable reference to its
869	/// value.
870	pub fn get_mut_full(&mut self) -> (usize, &K, &mut V) {
871		let (k, v) = &mut self.map.entries[self.i];
872		(self.i, &*k, v)
873	}
874
875	/// Returns the entry's key and a mutable reference to its value.
876	pub fn get_mut_entry(&mut self) -> (&K, &mut V) {
877		let (k, v) = &mut self.map.entries[self.i];
878		(&*k, v)
879	}
880
881	/// Returns a mutable reference to the entry's value.
882	pub fn get_mut(&mut self) -> &mut V {
883		&mut self.map.entries[self.i].1
884	}
885
886	/// Consumes this entry, returning its index, key, and a mutable
887	/// reference to its value, tied to the lifetime of the map.
888	pub fn into_mut_full(self) -> (usize, &'a K, &'a mut V) {
889		let (k, v) = &mut self.map.entries[self.i];
890		(self.i, &*k, v)
891	}
892
893	/// Consumes this entry, returning its key and a mutable reference to
894	/// its value, tied to the lifetime of the map.
895	pub fn into_mut_entry(self) -> (&'a K, &'a mut V) {
896		let (k, v) = &mut self.map.entries[self.i];
897		(&*k, v)
898	}
899
900	/// Consumes this entry, returning a mutable reference to its value,
901	/// tied to the lifetime of the map.
902	pub fn into_mut(self) -> &'a mut V {
903		&mut self.map.entries[self.i].1
904	}
905
906	/// Replaces the entry's value, returning the previous value.
907	pub fn insert(&mut self, value: V) -> V {
908		std::mem::replace(&mut self.map.entries[self.i].1, value)
909	}
910}