Skip to main content

btree_indexmap/
multi_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#[derive(Clone)]
13struct Indexes {
14	first: usize,
15	rest: Vec<usize>,
16}
17
18impl Indexes {
19	fn new(i: usize) -> Self {
20		Self {
21			first: i,
22			rest: Vec::new(),
23		}
24	}
25
26	fn insert(&mut self, mut i: usize) {
27		match i.cmp(&self.first) {
28			Ordering::Equal => return,
29			Ordering::Less => {
30				std::mem::swap(&mut self.first, &mut i);
31			}
32			_ => (),
33		}
34
35		if let Err(offset) = self.rest.binary_search(&i) {
36			self.rest.insert(offset, i);
37		}
38	}
39
40	fn remove(&mut self, i: usize) -> Result<bool, ()> {
41		if self.first == i {
42			if self.rest.is_empty() {
43				Err(())
44			} else {
45				self.first = self.rest.remove(0);
46				Ok(true)
47			}
48		} else {
49			match self.rest.binary_search(&i) {
50				Ok(offset) => {
51					self.rest.remove(offset);
52					Ok(true)
53				}
54				Err(_) => Ok(false),
55			}
56		}
57	}
58
59	fn swap_last(&mut self, j: usize) {
60		match self.rest.pop() {
61			Some(i) => {
62				self.insert(i);
63			}
64			None => self.first = j,
65		}
66	}
67
68	fn len(&self) -> usize {
69		1 + self.rest.len()
70	}
71
72	fn iter(&self) -> IndexesIter<'_> {
73		IndexesIter {
74			first: Some(self.first),
75			rest: self.rest.iter(),
76		}
77	}
78
79	fn iter_mut(&mut self) -> IndexesIterMut<'_> {
80		IndexesIterMut {
81			first: Some(&mut self.first),
82			rest: self.rest.iter_mut(),
83		}
84	}
85}
86
87impl IntoIterator for Indexes {
88	type Item = usize;
89	type IntoIter = IndexesIntoIter;
90
91	fn into_iter(self) -> Self::IntoIter {
92		IndexesIntoIter {
93			first: Some(self.first),
94			rest: self.rest.into_iter(),
95		}
96	}
97}
98
99/// An iterator over the indexes of every entry associated with a key in a
100/// [`BTreeIndexMultiMap`].
101///
102/// See [`BTreeIndexMultiMap::indexes_of`].
103#[derive(Default, Clone)]
104pub struct IndexesIter<'a> {
105	first: Option<usize>,
106	rest: std::slice::Iter<'a, usize>,
107}
108
109impl<'a> Iterator for IndexesIter<'a> {
110	type Item = usize;
111
112	fn size_hint(&self) -> (usize, Option<usize>) {
113		let len = self.rest.len() + if self.first.is_some() { 1 } else { 0 };
114		(len, Some(len))
115	}
116
117	fn next(&mut self) -> Option<Self::Item> {
118		self.first.take().or_else(|| self.rest.next().copied())
119	}
120}
121
122impl<'a> ExactSizeIterator for IndexesIter<'a> {}
123
124#[derive(Default)]
125struct IndexesIterMut<'a> {
126	first: Option<&'a mut usize>,
127	rest: std::slice::IterMut<'a, usize>,
128}
129
130impl<'a> Iterator for IndexesIterMut<'a> {
131	type Item = &'a mut usize;
132
133	fn size_hint(&self) -> (usize, Option<usize>) {
134		let len = self.rest.len() + if self.first.is_some() { 1 } else { 0 };
135		(len, Some(len))
136	}
137
138	fn next(&mut self) -> Option<Self::Item> {
139		self.first.take().or_else(|| self.rest.next())
140	}
141}
142
143impl<'a> ExactSizeIterator for IndexesIterMut<'a> {}
144
145#[derive(Default)]
146struct IndexesIntoIter {
147	first: Option<usize>,
148	rest: std::vec::IntoIter<usize>,
149}
150
151impl Iterator for IndexesIntoIter {
152	type Item = usize;
153
154	fn size_hint(&self) -> (usize, Option<usize>) {
155		let len = self.rest.len() + if self.first.is_some() { 1 } else { 0 };
156		(len, Some(len))
157	}
158
159	fn next(&mut self) -> Option<Self::Item> {
160		self.first.take().or_else(|| self.rest.next())
161	}
162}
163
164impl DoubleEndedIterator for IndexesIntoIter {
165	fn next_back(&mut self) -> Option<Self::Item> {
166		self.rest.next_back().or_else(|| self.first.take())
167	}
168}
169
170impl ExactSizeIterator for IndexesIntoIter {}
171
172/// An iterator over `(index, &key, &value)` for every entry associated
173/// with a key in a [`BTreeIndexMultiMap`].
174///
175/// See [`BTreeIndexMultiMap::get_indexed_entries`].
176pub struct GetIndexedEntries<'a, K, V> {
177	indexes: IndexesIter<'a>,
178	entries: &'a [(K, V)],
179}
180
181impl<'a, K, V> Iterator for GetIndexedEntries<'a, K, V> {
182	type Item = (usize, &'a K, &'a V);
183
184	fn next(&mut self) -> Option<Self::Item> {
185		self.indexes.next().map(|i| {
186			let (k, v) = &self.entries[i];
187			(i, k, v)
188		})
189	}
190}
191
192/// An iterator over `(&key, &value)` for every entry associated with a
193/// key in a [`BTreeIndexMultiMap`].
194///
195/// See [`BTreeIndexMultiMap::get_entries`].
196pub struct GetEntries<'a, K, V>(GetIndexedEntries<'a, K, V>);
197
198impl<'a, K, V> Iterator for GetEntries<'a, K, V> {
199	type Item = (&'a K, &'a V);
200
201	fn next(&mut self) -> Option<Self::Item> {
202		self.0.next().map(|(_, k, v)| (k, v))
203	}
204}
205
206/// An iterator over a reference to the value of every entry associated
207/// with a key in a [`BTreeIndexMultiMap`].
208///
209/// See [`BTreeIndexMultiMap::get`].
210pub struct Get<'a, K, V>(GetIndexedEntries<'a, K, V>);
211
212impl<'a, K, V> Iterator for Get<'a, K, V> {
213	type Item = &'a V;
214
215	fn next(&mut self) -> Option<Self::Item> {
216		self.0.next().map(|(_, _, v)| v)
217	}
218}
219
220/// An iterator over `(index, &value)` for every entry associated with a
221/// key in a [`BTreeIndexMultiMap`].
222///
223/// See [`BTreeIndexMultiMap::get_indexed`].
224pub struct GetIndexed<'a, K, V>(GetIndexedEntries<'a, K, V>);
225
226impl<'a, K, V> Iterator for GetIndexed<'a, K, V> {
227	type Item = (usize, &'a V);
228
229	fn next(&mut self) -> Option<Self::Item> {
230		self.0.next().map(|(i, _, v)| (i, v))
231	}
232}
233
234/// An iterator over `(index, &key, &mut value)` for every entry
235/// associated with a key in a [`BTreeIndexMultiMap`].
236///
237/// See [`BTreeIndexMultiMap::get_indexed_entries_mut`].
238pub struct GetIndexedEntriesMut<'a, K, V> {
239	indexes: IndexesIter<'a>,
240	entries: &'a mut [(K, V)],
241}
242
243impl<'a, K, V> Iterator for GetIndexedEntriesMut<'a, K, V> {
244	type Item = (usize, &'a K, &'a mut V);
245
246	fn next(&mut self) -> Option<Self::Item> {
247		self.indexes.next().map(|i| {
248			let (k, v) = &mut self.entries[i];
249			let (k, v) = unsafe {
250				// SAFEY: values are not aliased, and cannot be borrowed more
251				//        than once.
252				std::mem::transmute::<(&mut K, &mut V), (&'a K, &'a mut V)>((k, v))
253			};
254
255			(i, k, v)
256		})
257	}
258}
259
260/// An iterator over `(&key, &mut value)` for every entry associated with
261/// a key in a [`BTreeIndexMultiMap`].
262///
263/// See [`BTreeIndexMultiMap::get_entries_mut`].
264pub struct GetEntriesMut<'a, K, V>(GetIndexedEntriesMut<'a, K, V>);
265
266impl<'a, K, V> Iterator for GetEntriesMut<'a, K, V> {
267	type Item = (&'a K, &'a mut V);
268
269	fn next(&mut self) -> Option<Self::Item> {
270		self.0.next().map(|(_, k, v)| (k, v))
271	}
272}
273
274/// An iterator over a mutable reference to the value of every entry
275/// associated with a key in a [`BTreeIndexMultiMap`].
276///
277/// See [`BTreeIndexMultiMap::get_mut`].
278pub struct GetMut<'a, K, V>(GetIndexedEntriesMut<'a, K, V>);
279
280impl<'a, K, V> Iterator for GetMut<'a, K, V> {
281	type Item = &'a mut V;
282
283	fn next(&mut self) -> Option<Self::Item> {
284		self.0.next().map(|(_, _, v)| v)
285	}
286}
287
288/// BTree-based multi-map with stable entry indices.
289///
290/// Each key may map to any number of values. Entries are stored in a
291/// [`Vec`] and assigned a *stable index* equal to their position in that
292/// `Vec`. The index of an entry does not change as long as no entry is
293/// removed. A B-tree over the keys provides O(log n) lookup, insertion,
294/// and removal, while the `Vec` backing allows O(1) random access by
295/// index.
296///
297/// # Example
298///
299/// ```
300/// use btree_indexmap::BTreeIndexMultiMap;
301///
302/// let mut map = BTreeIndexMultiMap::new();
303///
304/// // Multiple values per key, each with its own stable index.
305/// map.push_back("fruit", "apple");
306/// map.push_back("veggie", "carrot");
307/// map.push_back("fruit", "banana");
308///
309/// assert_eq!(map.key_occurences("fruit"), 2);
310///
311/// let fruits: Vec<_> = map.get("fruit").copied().collect();
312/// assert_eq!(fruits, ["apple", "banana"]);
313/// ```
314#[derive(Clone)]
315pub struct BTreeIndexMultiMap<K, V> {
316	entries: Vec<(K, V)>,
317	map: RawBTree<Indexes>,
318}
319
320impl<K, V> Default for BTreeIndexMultiMap<K, V> {
321	fn default() -> Self {
322		Self::new()
323	}
324}
325
326impl<K, V> BTreeIndexMultiMap<K, V> {
327	/// Creates a new, empty multi-map.
328	pub fn new() -> Self {
329		Self {
330			entries: Vec::new(),
331			map: RawBTree::new(),
332		}
333	}
334
335	/// Creates a new, empty multi-map with space reserved for at least
336	/// `cap` entries.
337	pub fn with_capacity(cap: usize) -> Self {
338		Self {
339			entries: Vec::with_capacity(cap),
340			map: RawBTree::new(),
341		}
342	}
343
344	/// Creates a new multi-map containing the single `(key, value)` entry.
345	pub fn singleton(key: K, value: V) -> Self
346	where
347		K: Ord,
348	{
349		let mut result = Self::new();
350		result.push_back(key, value);
351		result
352	}
353
354	/// Removes all entries from the map.
355	///
356	/// This keeps the capacity allocated for the entries.
357	pub fn clear(&mut self) {
358		self.entries.clear();
359		self.map.clear();
360	}
361
362	/// Returns the number of entries the map can hold without
363	/// reallocating.
364	pub fn capacity(&self) -> usize {
365		self.entries.capacity()
366	}
367
368	/// Returns the entries of the map as a slice, in insertion (index)
369	/// order.
370	pub fn as_entries(&self) -> &[(K, V)] {
371		&self.entries
372	}
373
374	/// Returns `true` if the map contains no entries.
375	pub fn is_empty(&self) -> bool {
376		self.entries.is_empty()
377	}
378
379	/// Returns the total number of entries in the map.
380	pub fn len(&self) -> usize {
381		self.entries.len()
382	}
383
384	/// Returns the key and value of the first entry in the map (in
385	/// insertion order), if any.
386	pub fn first(&self) -> Option<(&K, &V)> {
387		self.entries.first().map(|(k, v)| (k, v))
388	}
389
390	/// Returns the key and value of the last entry in the map (in
391	/// insertion order), if any.
392	pub fn last(&self) -> Option<(&K, &V)> {
393		self.entries.last().map(|(k, v)| (k, v))
394	}
395
396	/// Returns `true` if the map contains at least one entry for `key`.
397	pub fn contains_key<Q>(&self, key: &Q) -> bool
398	where
399		Q: ?Sized + Comparable<K>,
400	{
401		self.map.get(outer_cmp(&self.entries), key).is_some()
402	}
403
404	/// Returns the number of entries associated with `key`.
405	pub fn key_occurences<Q>(&self, key: &Q) -> usize
406	where
407		Q: ?Sized + Comparable<K>,
408	{
409		self.map
410			.get(outer_cmp(&self.entries), key)
411			.map(|i| i.len())
412			.unwrap_or_default()
413	}
414
415	/// Returns an iterator over the indexes of every entry associated with
416	/// `key`.
417	pub fn indexes_of<Q>(&self, key: &Q) -> IndexesIter<'_>
418	where
419		Q: ?Sized + Comparable<K>,
420	{
421		self.map
422			.get(outer_cmp(&self.entries), key)
423			.map(Indexes::iter)
424			.unwrap_or_default()
425	}
426
427	/// Returns the index of the first entry associated with `key`.
428	pub fn index_of<Q>(&self, key: &Q) -> Option<usize>
429	where
430		Q: ?Sized + Comparable<K>,
431	{
432		self.indexes_of(key).next()
433	}
434
435	/// Returns an iterator over `(index, &key, &value)` for every entry
436	/// associated with `key`.
437	pub fn get_indexed_entries<Q>(&self, key: &Q) -> GetIndexedEntries<'_, K, V>
438	where
439		Q: ?Sized + Comparable<K>,
440	{
441		GetIndexedEntries {
442			indexes: self
443				.map
444				.get(outer_cmp(&self.entries), key)
445				.map(Indexes::iter)
446				.unwrap_or_default(),
447			entries: &self.entries,
448		}
449	}
450
451	/// Returns an iterator over `(index, &key, &value)` for every entry
452	/// associated with `key`, inserting a single new entry with a value
453	/// produced by `f` if `key` was not already present.
454	pub fn get_or_insert_indexed_entries_with(
455		&mut self,
456		key: K,
457		f: impl FnOnce() -> V,
458	) -> GetIndexedEntries<'_, K, V>
459	where
460		K: Ord,
461	{
462		match self.map.address_of(outer_cmp(&self.entries), &key) {
463			Ok(addr) => GetIndexedEntries {
464				indexes: unsafe {
465					// SAFETY: no `self.map` has been deallocated since we found
466					//         `addr`.
467					self.map.get_at(addr)
468				}
469				.unwrap()
470				.iter(),
471				entries: &self.entries,
472			},
473			Err(_) => {
474				let (i, _) = self.push_back(key, f());
475				GetIndexedEntries {
476					indexes: self
477						.map
478						.get(inner_index_cmp(&self.entries), &i)
479						.unwrap()
480						.iter(),
481					entries: &self.entries,
482				}
483			}
484		}
485	}
486
487	/// Returns an iterator over `(index, &key, &value)` for every entry
488	/// associated with `key`, inserting a single new entry with `value` if
489	/// `key` was not already present.
490	pub fn get_or_insert_indexed_entries(&mut self, key: K, value: V) -> GetIndexedEntries<'_, K, V>
491	where
492		K: Ord,
493	{
494		self.get_or_insert_indexed_entries_with(key, || value)
495	}
496
497	/// Returns an iterator over `(&key, &value)` for every entry associated
498	/// with `key`.
499	pub fn get_entries<Q>(&self, key: &Q) -> GetEntries<'_, K, V>
500	where
501		Q: ?Sized + Comparable<K>,
502	{
503		GetEntries(self.get_indexed_entries(key))
504	}
505
506	/// Returns an iterator over `(&key, &value)` for every entry associated
507	/// with `key`, inserting a single new entry with a value produced by
508	/// `f` if `key` was not already present.
509	pub fn get_or_insert_entries_with(
510		&mut self,
511		key: K,
512		f: impl FnOnce() -> V,
513	) -> GetEntries<'_, K, V>
514	where
515		K: Ord,
516	{
517		GetEntries(self.get_or_insert_indexed_entries_with(key, f))
518	}
519
520	/// Returns an iterator over `(&key, &value)` for every entry associated
521	/// with `key`, inserting a single new entry with `value` if `key` was
522	/// not already present.
523	pub fn get_or_insert_entries(&mut self, key: K, value: V) -> GetEntries<'_, K, V>
524	where
525		K: Ord,
526	{
527		self.get_or_insert_entries_with(key, || value)
528	}
529
530	/// Returns an iterator over a reference to the value of every entry
531	/// associated with `key`.
532	pub fn get<Q>(&self, key: &Q) -> Get<'_, K, V>
533	where
534		Q: ?Sized + Comparable<K>,
535	{
536		Get(self.get_indexed_entries(key))
537	}
538
539	/// Returns an iterator over a reference to the value of every entry
540	/// associated with `key`, inserting a single new entry with a value
541	/// produced by `f` if `key` was not already present.
542	pub fn get_or_insert_with(&mut self, key: K, f: impl FnOnce() -> V) -> Get<'_, K, V>
543	where
544		K: Ord,
545	{
546		Get(self.get_or_insert_indexed_entries_with(key, f))
547	}
548
549	/// Returns an iterator over a reference to the value of every entry
550	/// associated with `key`, inserting a single new entry with `value` if
551	/// `key` was not already present.
552	pub fn get_or_insert(&mut self, key: K, value: V) -> Get<'_, K, V>
553	where
554		K: Ord,
555	{
556		self.get_or_insert_with(key, || value)
557	}
558
559	/// Returns an iterator over `(index, &value)` for every entry
560	/// associated with `key`.
561	pub fn get_indexed<Q>(&self, key: &Q) -> GetIndexed<'_, K, V>
562	where
563		Q: ?Sized + Comparable<K>,
564	{
565		GetIndexed(self.get_indexed_entries(key))
566	}
567
568	/// Returns an iterator over `(index, &value)` for every entry
569	/// associated with `key`, inserting a single new entry with a value
570	/// produced by `f` if `key` was not already present.
571	pub fn get_or_insert_indexed_with(
572		&mut self,
573		key: K,
574		f: impl FnOnce() -> V,
575	) -> GetIndexed<'_, K, V>
576	where
577		K: Ord,
578	{
579		GetIndexed(self.get_or_insert_indexed_entries_with(key, f))
580	}
581
582	/// Returns an iterator over `(index, &value)` for every entry
583	/// associated with `key`, inserting a single new entry with `value` if
584	/// `key` was not already present.
585	pub fn get_or_insert_indexed(&mut self, key: K, value: V) -> GetIndexed<'_, K, V>
586	where
587		K: Ord,
588	{
589		self.get_or_insert_indexed_with(key, || value)
590	}
591
592	/// Returns an iterator over `(index, &key, &mut value)` for every entry
593	/// associated with `key`.
594	pub fn get_indexed_entries_mut<Q>(&mut self, key: &Q) -> GetIndexedEntriesMut<'_, K, V>
595	where
596		Q: ?Sized + Comparable<K>,
597	{
598		GetIndexedEntriesMut {
599			indexes: self
600				.map
601				.get(outer_cmp(&self.entries), key)
602				.map(Indexes::iter)
603				.unwrap_or_default(),
604			entries: &mut self.entries,
605		}
606	}
607
608	/// Returns an iterator over `(index, &key, &mut value)` for every entry
609	/// associated with `key`, inserting a single new entry with a value
610	/// produced by `f` if `key` was not already present.
611	pub fn get_or_insert_indexed_entries_mut_with(
612		&mut self,
613		key: K,
614		f: impl FnOnce() -> V,
615	) -> GetIndexedEntriesMut<'_, K, V>
616	where
617		K: Ord,
618	{
619		match self.map.address_of(outer_cmp(&self.entries), &key) {
620			Ok(addr) => GetIndexedEntriesMut {
621				indexes: unsafe {
622					// SAFETY: no `self.map` has been deallocated since we found
623					//         `addr`.
624					self.map.get_at(addr)
625				}
626				.unwrap()
627				.iter(),
628				entries: &mut self.entries,
629			},
630			Err(_) => {
631				let (i, _) = self.push_back(key, f());
632				GetIndexedEntriesMut {
633					indexes: self
634						.map
635						.get(inner_index_cmp(&self.entries), &i)
636						.unwrap()
637						.iter(),
638					entries: &mut self.entries,
639				}
640			}
641		}
642	}
643
644	/// Returns an iterator over `(index, &key, &mut value)` for every entry
645	/// associated with `key`, inserting a single new entry with `value` if
646	/// `key` was not already present.
647	pub fn get_or_insert_indexed_entries_mut(
648		&mut self,
649		key: K,
650		value: V,
651	) -> GetIndexedEntriesMut<'_, K, V>
652	where
653		K: Ord,
654	{
655		self.get_or_insert_indexed_entries_mut_with(key, || value)
656	}
657
658	/// Returns an iterator over `(&key, &mut value)` for every entry
659	/// associated with `key`.
660	pub fn get_entries_mut<Q>(&mut self, key: &Q) -> GetEntriesMut<'_, K, V>
661	where
662		Q: ?Sized + Comparable<K>,
663	{
664		GetEntriesMut(self.get_indexed_entries_mut(key))
665	}
666
667	/// Returns an iterator over `(&key, &mut value)` for every entry
668	/// associated with `key`, inserting a single new entry with a value
669	/// produced by `f` if `key` was not already present.
670	pub fn get_or_insert_entries_mut_with(
671		&mut self,
672		key: K,
673		f: impl FnOnce() -> V,
674	) -> GetEntriesMut<'_, K, V>
675	where
676		K: Ord,
677	{
678		GetEntriesMut(self.get_or_insert_indexed_entries_mut_with(key, f))
679	}
680
681	/// Returns an iterator over `(&key, &mut value)` for every entry
682	/// associated with `key`, inserting a single new entry with `value` if
683	/// `key` was not already present.
684	pub fn get_or_insert_entries_mut(&mut self, key: K, value: V) -> GetEntriesMut<'_, K, V>
685	where
686		K: Ord,
687	{
688		self.get_or_insert_entries_mut_with(key, || value)
689	}
690
691	/// Returns an iterator over a mutable reference to the value of every
692	/// entry associated with `key`.
693	pub fn get_mut<Q>(&mut self, key: &Q) -> GetMut<'_, K, V>
694	where
695		Q: ?Sized + Comparable<K>,
696	{
697		GetMut(self.get_indexed_entries_mut(key))
698	}
699
700	/// Returns an iterator over a mutable reference to the value of every
701	/// entry associated with `key`, inserting a single new entry with a
702	/// value produced by `f` if `key` was not already present.
703	pub fn get_or_insert_mut_with(&mut self, key: K, f: impl FnOnce() -> V) -> GetMut<'_, K, V>
704	where
705		K: Ord,
706	{
707		GetMut(self.get_or_insert_indexed_entries_mut_with(key, f))
708	}
709
710	/// Returns an iterator over a mutable reference to the value of every
711	/// entry associated with `key`, inserting a single new entry with
712	/// `value` if `key` was not already present.
713	pub fn get_or_insert_mut(&mut self, key: K, value: V) -> GetMut<'_, K, V>
714	where
715		K: Ord,
716	{
717		self.get_or_insert_mut_with(key, || value)
718	}
719
720	/// Gets the entry associated with `key` for in-place manipulation.
721	///
722	/// # Example
723	///
724	/// ```
725	/// use btree_indexmap::{BTreeIndexMultiMap, multi_map::Entry};
726	///
727	/// let mut map: BTreeIndexMultiMap<&str, i32> = BTreeIndexMultiMap::new();
728	///
729	/// match map.entry("a") {
730	///     Entry::Vacant(e) => {
731	///         e.insert(1);
732	///     }
733	///     Entry::Occupied(_) => unreachable!(),
734	/// }
735	///
736	/// assert_eq!(map.get("a").next(), Some(&1));
737	/// ```
738	pub fn entry(&mut self, key: K) -> Entry<'_, K, V>
739	where
740		K: Ord,
741	{
742		if let Some(indices) = self.map.get(outer_cmp(&self.entries), &key) {
743			return Entry::Occupied(OccupiedEntry {
744				entries: &mut self.entries,
745				indices,
746			});
747		}
748
749		Entry::Vacant(VacantEntry {
750			map: unsafe {
751				// SAFETY: The compiler thinks `self` is still borrowed at this
752				// point because `indices` has type `&'_ Indices` where `'_`
753				// includes both the outer scope lifetime and the `self.map`
754				// lifetime. However we know that `indices` is dropped before
755				// this line is ever reached.
756				std::mem::transmute_copy(&self)
757			},
758			key,
759		})
760	}
761
762	/// Inserts a new entry at the end of the map.
763	///
764	/// Returns the index of the new entry, and whether `key` was not
765	/// already present in the map.
766	pub fn push_back(&mut self, key: K, value: V) -> (usize, bool)
767	where
768		K: Ord,
769	{
770		let i = self.entries.len();
771		self.entries.push((key, value));
772
773		let unique = match self.map.get_mut(inner_index_cmp(&self.entries), &i) {
774			Some(indexes) => {
775				indexes.rest.push(i);
776				false
777			}
778			None => {
779				self.map.insert(inner_cmp(&self.entries), Indexes::new(i));
780				true
781			}
782		};
783
784		(i, unique)
785	}
786
787	/// Inserts a new entry at the given `index`.
788	///
789	/// Returns whether `key` was not already present in the map.
790	///
791	/// # Panics
792	///
793	/// Panics if `index > len`.
794	pub fn insert_at(&mut self, index: usize, key: K, value: V) -> bool
795	where
796		K: Ord,
797	{
798		for js in self.map.iter_mut() {
799			for j in js.iter_mut() {
800				if *j >= index {
801					*j += 1;
802				}
803			}
804		}
805
806		self.entries.insert(index, (key, value));
807
808		match self.map.get_mut(inner_index_cmp(&self.entries), &index) {
809			Some(indexes) => {
810				indexes.insert(index);
811				false
812			}
813			None => {
814				self.map
815					.insert(inner_cmp(&self.entries), Indexes::new(index));
816				true
817			}
818		}
819	}
820
821	/// Inserts a new entry at the front of the map.
822	///
823	/// Returns whether `key` was not already present in the map.
824	pub fn push_front(&mut self, key: K, value: V) -> bool
825	where
826		K: Ord,
827	{
828		self.insert_at(0, key, value)
829	}
830
831	/// Inserts a `(key, value)` entry, keeping only this occurrence of
832	/// `key`.
833	///
834	/// If `key` was already present, replaces its first occurrence and
835	/// removes every other one (using shift semantics), returning the
836	/// index of the kept entry and an iterator over the values it
837	/// replaced or removed. Otherwise, appends a new entry and returns its
838	/// index with an empty iterator.
839	pub fn shift_insert_full(&mut self, key: K, value: V) -> (usize, ShiftInsert<'_, K, V>)
840	where
841		K: Ord,
842	{
843		match self.map.get_mut(outer_cmp(&self.entries), &key) {
844			Some(indices) => {
845				let i = indices.first;
846				let mut indices = std::mem::replace(indices, Indexes::new(i))
847					.into_iter()
848					.enumerate();
849				indices.next();
850
851				let first = std::mem::replace(&mut self.entries[i].1, value);
852
853				(
854					i,
855					ShiftInsert {
856						first: Some(first),
857						rest: ShiftRemove(ShiftRemoveIndexedEntries { indices, map: self }),
858					},
859				)
860			}
861			None => {
862				let (i, _) = self.push_back(key, value);
863				(
864					i,
865					ShiftInsert {
866						first: None,
867						rest: ShiftRemove(ShiftRemoveIndexedEntries {
868							indices: Default::default(),
869							map: self,
870						}),
871					},
872				)
873			}
874		}
875	}
876
877	/// Inserts a `(key, value)` entry, keeping only this occurrence of
878	/// `key`.
879	///
880	/// See [`Self::shift_insert_full`].
881	pub fn shift_insert(&mut self, key: K, value: V) -> ShiftInsert<'_, K, V>
882	where
883		K: Ord,
884	{
885		self.shift_insert_full(key, value).1
886	}
887
888	/// Inserts a `(key, value)` entry, keeping only this occurrence of
889	/// `key`.
890	///
891	/// If `key` was already present, replaces its first occurrence and
892	/// removes every other one (using swap semantics), returning the
893	/// index of the kept entry and an iterator over the values it
894	/// replaced or removed. Otherwise, appends a new entry and returns its
895	/// index with an empty iterator.
896	pub fn swap_insert_full(&mut self, key: K, value: V) -> (usize, SwapInsert<'_, K, V>)
897	where
898		K: Ord,
899	{
900		match self.map.get_mut(outer_cmp(&self.entries), &key) {
901			Some(indices) => {
902				let i = indices.first;
903				let mut indices = std::mem::replace(indices, Indexes::new(i)).into_iter();
904				indices.next();
905
906				let first = std::mem::replace(&mut self.entries[i].1, value);
907
908				(
909					i,
910					SwapInsert {
911						first: Some(first),
912						rest: SwapRemove(SwapRemoveIndexedEntries { indices, map: self }),
913					},
914				)
915			}
916			None => {
917				let (i, _) = self.push_back(key, value);
918				(
919					i,
920					SwapInsert {
921						first: None,
922						rest: SwapRemove(SwapRemoveIndexedEntries {
923							indices: Default::default(),
924							map: self,
925						}),
926					},
927				)
928			}
929		}
930	}
931
932	/// Inserts a `(key, value)` entry, keeping only this occurrence of
933	/// `key`.
934	///
935	/// See [`Self::swap_insert_full`].
936	pub fn swap_insert(&mut self, key: K, value: V) -> SwapInsert<'_, K, V>
937	where
938		K: Ord,
939	{
940		self.swap_insert_full(key, value).1
941	}
942
943	/// Inserts a `(key, value)` entry at the front of the map, replacing
944	/// every previous occurrence of `key`.
945	///
946	/// Returns an iterator over the values of the removed occurrences,
947	/// removed using shift semantics.
948	pub fn shift_insert_front(&mut self, key: K, value: V) -> ShiftInsertFront<'_, K, V>
949	where
950		K: Ord,
951	{
952		ShiftInsertFront {
953			remove: self.shift_remove(&key),
954			entry: Some((key, value)),
955		}
956	}
957
958	/// Inserts a `(key, value)` entry at the front of the map, replacing
959	/// every previous occurrence of `key`.
960	///
961	/// Returns an iterator over the values of the removed occurrences,
962	/// removed using swap semantics.
963	pub fn swap_insert_front(&mut self, key: K, value: V) -> SwapInsertFront<'_, K, V>
964	where
965		K: Ord,
966	{
967		SwapInsertFront {
968			remove: self.swap_remove(&key),
969			entry: Some((key, value)),
970		}
971	}
972
973	/// Inserts a `(key, value)` entry at the end of the map, replacing
974	/// every previous occurrence of `key`.
975	///
976	/// Returns the index of the new entry and an iterator over the values
977	/// of the removed occurrences, removed using shift semantics.
978	pub fn shift_insert_back_full(&mut self, key: K, value: V) -> (usize, ShiftInsertBack<'_, K, V>)
979	where
980		K: Ord,
981	{
982		let len = self.len();
983		let remove = self.shift_remove(&key);
984		let i = len - remove.len();
985
986		(
987			i,
988			ShiftInsertBack {
989				remove,
990				entry: Some((key, value)),
991			},
992		)
993	}
994
995	/// Inserts a `(key, value)` entry at the end of the map, replacing
996	/// every previous occurrence of `key`.
997	///
998	/// Returns an iterator over the values of the removed occurrences,
999	/// removed using shift semantics.
1000	pub fn shift_insert_back(&mut self, key: K, value: V) -> ShiftInsertBack<'_, K, V>
1001	where
1002		K: Ord,
1003	{
1004		ShiftInsertBack {
1005			remove: self.shift_remove(&key),
1006			entry: Some((key, value)),
1007		}
1008	}
1009
1010	/// Inserts a `(key, value)` entry, keeping only this occurrence of
1011	/// `key`.
1012	///
1013	/// This is an alias for [`Self::shift_insert_back`].
1014	pub fn insert(&mut self, key: K, value: V) -> ShiftInsertBack<'_, K, V>
1015	where
1016		K: Ord,
1017	{
1018		self.shift_insert_back(key, value)
1019	}
1020
1021	/// Inserts a `(key, value)` entry at the end of the map, replacing
1022	/// every previous occurrence of `key`.
1023	///
1024	/// Returns the index of the new entry and an iterator over the values
1025	/// of the removed occurrences, removed using swap semantics.
1026	pub fn swap_insert_back_full(&mut self, key: K, value: V) -> (usize, SwapInsertBack<'_, K, V>)
1027	where
1028		K: Ord,
1029	{
1030		let len = self.len();
1031		let remove = self.swap_remove(&key);
1032		let i = len - remove.len();
1033
1034		(
1035			i,
1036			SwapInsertBack {
1037				remove,
1038				entry: Some((key, value)),
1039			},
1040		)
1041	}
1042
1043	/// Inserts a `(key, value)` entry at the end of the map, replacing
1044	/// every previous occurrence of `key`.
1045	///
1046	/// Returns an iterator over the values of the removed occurrences,
1047	/// removed using swap semantics.
1048	pub fn swap_insert_back(&mut self, key: K, value: V) -> SwapInsertBack<'_, K, V>
1049	where
1050		K: Ord,
1051	{
1052		SwapInsertBack {
1053			remove: self.swap_remove(&key),
1054			entry: Some((key, value)),
1055		}
1056	}
1057
1058	/// Removes the entry at the given `index`, returning its key and value,
1059	/// if it was present.
1060	///
1061	/// Shifts every following entry one index down.
1062	pub fn shift_remove_at(&mut self, i: usize) -> Option<(K, V)>
1063	where
1064		K: Ord,
1065	{
1066		self.map
1067			.address_of(inner_index_cmp(&self.entries), &i)
1068			.ok()
1069			.map(|addr| {
1070				let removed = unsafe { self.map.get_mut_at(addr).unwrap().remove(i) };
1071
1072				if removed.is_err() {
1073					unsafe {
1074						// SAFETY: the node hasn't moved and hasn't been
1075						//         deallocated since we found its address.
1076						self.map.remove_at(addr).unwrap();
1077					}
1078				}
1079
1080				let entry = self.entries.remove(i);
1081
1082				for js in self.map.iter_mut() {
1083					for j in js.iter_mut() {
1084						if *j > i {
1085							*j -= 1;
1086						}
1087					}
1088				}
1089
1090				entry
1091			})
1092	}
1093
1094	/// Removes the entry at the given `index`, returning its key and value,
1095	/// if it was present.
1096	///
1097	/// Moves the last entry into the removed slot.
1098	pub fn swap_remove_at(&mut self, i: usize) -> Option<(K, V)>
1099	where
1100		K: Ord,
1101	{
1102		self.map
1103			.address_of(inner_index_cmp(&self.entries), &i)
1104			.ok()
1105			.map(|addr| {
1106				let removed = unsafe { self.map.get_mut_at(addr).unwrap().remove(i) };
1107
1108				if removed.is_err() {
1109					unsafe {
1110						// SAFETY: the node hasn't moved and hasn't been
1111						//         deallocated since we found its address.
1112						self.map.remove_at(addr).unwrap();
1113					}
1114				}
1115
1116				self.swap_already_removed_at(i)
1117			})
1118	}
1119
1120	fn swap_already_removed_at(&mut self, i: usize) -> (K, V)
1121	where
1122		K: Ord,
1123	{
1124		let last = self.entries.len() - 1;
1125
1126		if i == last {
1127			// The entry being removed is already the last one; just pop it.
1128			self.entries.pop().unwrap()
1129		} else {
1130			let last_key = &self.entries[last].0;
1131			self.map
1132				.get_mut(outer_cmp(&self.entries), last_key)
1133				.unwrap()
1134				.swap_last(i);
1135
1136			self.entries.swap(i, last);
1137			self.entries.pop().unwrap()
1138		}
1139	}
1140
1141	/// Removes every entry associated with `key`, returning an iterator
1142	/// over `(index, key, value)` for each removed entry.
1143	///
1144	/// Shifts the remaining entries down to fill the gaps.
1145	pub fn shift_remove_indexed_entries<Q>(
1146		&mut self,
1147		key: &Q,
1148	) -> ShiftRemoveIndexedEntries<'_, K, V>
1149	where
1150		Q: ?Sized + Comparable<K>,
1151	{
1152		let indices = self
1153			.map
1154			.remove(outer_cmp(&self.entries), key)
1155			.map(Indexes::into_iter)
1156			.unwrap_or_default()
1157			.enumerate();
1158
1159		ShiftRemoveIndexedEntries { indices, map: self }
1160	}
1161
1162	/// Removes every entry associated with `key`, returning an iterator
1163	/// over `(key, value)` for each removed entry.
1164	///
1165	/// Shifts the remaining entries down to fill the gaps.
1166	pub fn shift_remove_entries<Q>(&mut self, key: &Q) -> ShiftRemoveEntries<'_, K, V>
1167	where
1168		Q: ?Sized + Comparable<K>,
1169	{
1170		ShiftRemoveEntries(self.shift_remove_indexed_entries(key))
1171	}
1172
1173	/// Removes every entry associated with `key`, returning an iterator
1174	/// over the value of each removed entry.
1175	///
1176	/// Shifts the remaining entries down to fill the gaps.
1177	pub fn shift_remove<Q>(&mut self, key: &Q) -> ShiftRemove<'_, K, V>
1178	where
1179		Q: ?Sized + Comparable<K>,
1180	{
1181		ShiftRemove(self.shift_remove_indexed_entries(key))
1182	}
1183
1184	/// Removes every entry associated with `key`, returning an iterator
1185	/// over `(index, key, value)` for each removed entry.
1186	///
1187	/// Moves entries from the end of the map into the gaps.
1188	pub fn swap_remove_indexed_entries<Q>(&mut self, key: &Q) -> SwapRemoveIndexedEntries<'_, K, V>
1189	where
1190		Q: ?Sized + Comparable<K>,
1191		K: Ord,
1192	{
1193		let indices = self
1194			.map
1195			.remove(outer_cmp(&self.entries), key)
1196			.map(Indexes::into_iter)
1197			.unwrap_or_default();
1198
1199		SwapRemoveIndexedEntries { indices, map: self }
1200	}
1201
1202	/// Removes every entry associated with `key`, returning an iterator
1203	/// over `(key, value)` for each removed entry.
1204	///
1205	/// Moves entries from the end of the map into the gaps.
1206	pub fn swap_remove_entries<Q>(&mut self, key: &Q) -> SwapRemoveEntries<'_, K, V>
1207	where
1208		Q: ?Sized + Comparable<K>,
1209		K: Ord,
1210	{
1211		SwapRemoveEntries(self.swap_remove_indexed_entries(key))
1212	}
1213
1214	/// Removes every entry associated with `key`, returning an iterator
1215	/// over the value of each removed entry.
1216	///
1217	/// Moves entries from the end of the map into the gaps.
1218	pub fn swap_remove<Q>(&mut self, key: &Q) -> SwapRemove<'_, K, V>
1219	where
1220		Q: ?Sized + Comparable<K>,
1221		K: Ord,
1222	{
1223		SwapRemove(self.swap_remove_indexed_entries(key))
1224	}
1225
1226	/// Returns an iterator over the entries of the map, in insertion
1227	/// (index) order.
1228	pub fn iter(&self) -> Iter<'_, K, V> {
1229		Iter(self.entries.iter())
1230	}
1231
1232	/// Returns an iterator over the entries of the map, with a mutable
1233	/// reference to the value, in insertion (index) order.
1234	pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
1235		IterMut(self.entries.iter_mut())
1236	}
1237
1238	/// Returns an iterator over the entries of the map, sorted by key
1239	/// according to `K`'s implementation of [`Ord`].
1240	///
1241	/// Entries that share the same key are visited in insertion (index)
1242	/// order.
1243	pub fn iter_sorted(&self) -> IterSorted<'_, K, V> {
1244		IterSorted {
1245			remaining: self.entries.len(),
1246			entries: &self.entries,
1247			inner: self.map.iter(),
1248			current: None,
1249		}
1250	}
1251
1252	/// Returns an iterator over the entries of the map, with a mutable
1253	/// reference to the value, sorted by key according to `K`'s
1254	/// implementation of [`Ord`].
1255	///
1256	/// Entries that share the same key are visited in insertion (index)
1257	/// order.
1258	pub fn iter_mut_sorted(&mut self) -> IterMutSorted<'_, K, V> {
1259		IterMutSorted {
1260			remaining: self.entries.len(),
1261			entries: &mut self.entries,
1262			inner: self.map.iter(),
1263			current: None,
1264		}
1265	}
1266
1267	/// Turns this map into an iterator over its entries, sorted by key
1268	/// according to `K`'s implementation of [`Ord`].
1269	///
1270	/// Entries that share the same key are visited in insertion (index)
1271	/// order.
1272	pub fn into_iter_sorted(self) -> IntoIterSorted<K, V> {
1273		IntoIterSorted {
1274			remaining: self.entries.len(),
1275			entries: unsafe {
1276				// SAFETY: `(K, V)` and `MaybeUninit<(K, V)>` have the exact
1277				//         same representation.
1278				std::mem::transmute::<Vec<(K, V)>, Vec<MaybeUninit<(K, V)>>>(self.entries)
1279			},
1280			inner: self.map.into_iter(),
1281			current: None,
1282		}
1283	}
1284
1285	/// Returns an iterator over the keys of the map, in insertion (index)
1286	/// order.
1287	pub fn keys(&self) -> Keys<'_, K, V> {
1288		Keys(self.entries.iter())
1289	}
1290
1291	/// Returns an iterator over the values of the map, in insertion (index)
1292	/// order.
1293	pub fn values(&self) -> Values<'_, K, V> {
1294		Values(self.entries.iter())
1295	}
1296
1297	/// Returns an iterator over mutable references to the values of the
1298	/// map, in insertion (index) order.
1299	pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
1300		ValuesMut(self.entries.iter_mut())
1301	}
1302
1303	/// Sort the entries by key name.
1304	///
1305	/// The relative order of entries with the same key is unchanged.
1306	pub fn sort(&mut self)
1307	where
1308		K: Ord,
1309	{
1310		let this = std::mem::take(self);
1311		self.extend(this.into_iter_sorted())
1312	}
1313}
1314
1315/// An iterator over the values removed by
1316/// [`BTreeIndexMultiMap::shift_insert_front`].
1317pub struct ShiftInsertFront<'a, K: Ord, V> {
1318	remove: ShiftRemove<'a, K, V>,
1319	entry: Option<(K, V)>,
1320}
1321
1322impl<'a, K: Ord, V> Iterator for ShiftInsertFront<'a, K, V> {
1323	type Item = V;
1324
1325	fn next(&mut self) -> Option<Self::Item> {
1326		self.remove.next()
1327	}
1328}
1329
1330impl<'a, K: Ord, V> Drop for ShiftInsertFront<'a, K, V> {
1331	fn drop(&mut self) {
1332		for _ in self.remove.0.by_ref() {}
1333		if let Some((key, value)) = self.entry.take() {
1334			self.remove.0.map.push_front(key, value);
1335		}
1336	}
1337}
1338
1339/// An iterator over the values removed by
1340/// [`BTreeIndexMultiMap::swap_insert_front`].
1341pub struct SwapInsertFront<'a, K: Ord, V> {
1342	remove: SwapRemove<'a, K, V>,
1343	entry: Option<(K, V)>,
1344}
1345
1346impl<'a, K: Ord, V> Iterator for SwapInsertFront<'a, K, V> {
1347	type Item = V;
1348
1349	fn next(&mut self) -> Option<Self::Item> {
1350		self.remove.next()
1351	}
1352}
1353
1354impl<'a, K: Ord, V> Drop for SwapInsertFront<'a, K, V> {
1355	fn drop(&mut self) {
1356		for _ in self.remove.0.by_ref() {}
1357		if let Some((key, value)) = self.entry.take() {
1358			self.remove.0.map.push_front(key, value);
1359		}
1360	}
1361}
1362
1363/// An iterator over the values removed by
1364/// [`BTreeIndexMultiMap::shift_insert_back`].
1365pub struct ShiftInsertBack<'a, K: Ord, V> {
1366	remove: ShiftRemove<'a, K, V>,
1367	entry: Option<(K, V)>,
1368}
1369
1370impl<'a, K: Ord, V> Iterator for ShiftInsertBack<'a, K, V> {
1371	type Item = V;
1372
1373	fn next(&mut self) -> Option<Self::Item> {
1374		self.remove.next()
1375	}
1376}
1377
1378impl<'a, K: Ord, V> Drop for ShiftInsertBack<'a, K, V> {
1379	fn drop(&mut self) {
1380		for _ in self.remove.0.by_ref() {}
1381		if let Some((key, value)) = self.entry.take() {
1382			self.remove.0.map.push_back(key, value);
1383		}
1384	}
1385}
1386
1387/// An iterator over the values removed by
1388/// [`BTreeIndexMultiMap::swap_insert_back`].
1389pub struct SwapInsertBack<'a, K: Ord, V> {
1390	remove: SwapRemove<'a, K, V>,
1391	entry: Option<(K, V)>,
1392}
1393
1394impl<'a, K: Ord, V> Iterator for SwapInsertBack<'a, K, V> {
1395	type Item = V;
1396
1397	fn next(&mut self) -> Option<Self::Item> {
1398		self.remove.next()
1399	}
1400}
1401
1402impl<'a, K: Ord, V> Drop for SwapInsertBack<'a, K, V> {
1403	fn drop(&mut self) {
1404		for _ in self.remove.0.by_ref() {}
1405		if let Some((key, value)) = self.entry.take() {
1406			self.remove.0.map.push_back(key, value);
1407		}
1408	}
1409}
1410
1411/// An iterator over the values replaced or removed by
1412/// [`BTreeIndexMultiMap::shift_insert`].
1413pub struct ShiftInsert<'a, K, V> {
1414	first: Option<V>,
1415	rest: ShiftRemove<'a, K, V>,
1416}
1417
1418impl<'a, K, V> Iterator for ShiftInsert<'a, K, V> {
1419	type Item = V;
1420
1421	fn next(&mut self) -> Option<Self::Item> {
1422		self.first.take().or_else(|| self.rest.next())
1423	}
1424}
1425
1426/// An iterator over the values replaced or removed by
1427/// [`BTreeIndexMultiMap::swap_insert`].
1428pub struct SwapInsert<'a, K: Ord, V> {
1429	first: Option<V>,
1430	rest: SwapRemove<'a, K, V>,
1431}
1432
1433impl<'a, K: Ord, V> Iterator for SwapInsert<'a, K, V> {
1434	type Item = V;
1435
1436	fn next(&mut self) -> Option<Self::Item> {
1437		self.first.take().or_else(|| self.rest.next())
1438	}
1439}
1440
1441/// An iterator over `(index, key, value)` for every entry removed by
1442/// [`BTreeIndexMultiMap::swap_remove_indexed_entries`].
1443pub struct SwapRemoveIndexedEntries<'a, K: Ord, V> {
1444	indices: IndexesIntoIter,
1445	map: &'a mut BTreeIndexMultiMap<K, V>,
1446}
1447
1448impl<'a, K: Ord, V> Iterator for SwapRemoveIndexedEntries<'a, K, V> {
1449	type Item = (usize, K, V);
1450
1451	fn size_hint(&self) -> (usize, Option<usize>) {
1452		self.indices.size_hint()
1453	}
1454
1455	fn next(&mut self) -> Option<Self::Item> {
1456		// Process indices from highest to lowest so that the entry we pop
1457		// from the tail is never one of the entries we are removing.
1458		self.indices.next_back().map(|i| {
1459			let (k, v) = self.map.swap_already_removed_at(i);
1460			(i, k, v)
1461		})
1462	}
1463}
1464
1465impl<'a, K: Ord, V> ExactSizeIterator for SwapRemoveIndexedEntries<'a, K, V> {}
1466
1467impl<'a, K: Ord, V> Drop for SwapRemoveIndexedEntries<'a, K, V> {
1468	fn drop(&mut self) {
1469		// Consume the rest of the iterator to make sure everything is removed.
1470		for _ in self {}
1471	}
1472}
1473
1474/// An iterator over `(key, value)` for every entry removed by
1475/// [`BTreeIndexMultiMap::swap_remove_entries`].
1476pub struct SwapRemoveEntries<'a, K: Ord, V>(SwapRemoveIndexedEntries<'a, K, V>);
1477
1478impl<'a, K: Ord, V> Iterator for SwapRemoveEntries<'a, K, V> {
1479	type Item = (K, V);
1480
1481	fn size_hint(&self) -> (usize, Option<usize>) {
1482		self.0.size_hint()
1483	}
1484
1485	fn next(&mut self) -> Option<Self::Item> {
1486		self.0.next().map(|(_, k, v)| (k, v))
1487	}
1488}
1489
1490impl<'a, K: Ord, V> ExactSizeIterator for SwapRemoveEntries<'a, K, V> {}
1491
1492/// An iterator over the values removed by
1493/// [`BTreeIndexMultiMap::swap_remove`].
1494pub struct SwapRemove<'a, K: Ord, V>(SwapRemoveIndexedEntries<'a, K, V>);
1495
1496impl<'a, K: Ord, V> Iterator for SwapRemove<'a, K, V> {
1497	type Item = V;
1498
1499	fn size_hint(&self) -> (usize, Option<usize>) {
1500		self.0.size_hint()
1501	}
1502
1503	fn next(&mut self) -> Option<Self::Item> {
1504		self.0.next().map(|(_, _, v)| v)
1505	}
1506}
1507
1508impl<'a, K: Ord, V> ExactSizeIterator for SwapRemove<'a, K, V> {}
1509
1510/// An iterator over `(index, key, value)` for every entry removed by
1511/// [`BTreeIndexMultiMap::shift_remove_indexed_entries`].
1512pub struct ShiftRemoveIndexedEntries<'a, K, V> {
1513	indices: std::iter::Enumerate<IndexesIntoIter>,
1514	map: &'a mut BTreeIndexMultiMap<K, V>,
1515}
1516
1517impl<'a, K, V> Iterator for ShiftRemoveIndexedEntries<'a, K, V> {
1518	type Item = (usize, K, V);
1519
1520	fn size_hint(&self) -> (usize, Option<usize>) {
1521		self.indices.size_hint()
1522	}
1523
1524	fn next(&mut self) -> Option<Self::Item> {
1525		self.indices.next().map(|(shift, i)| {
1526			let shifted_i = i - shift;
1527			let (k, v) = self.map.entries.remove(shifted_i);
1528
1529			// Shift larger indices.
1530			for js in self.map.map.iter_mut() {
1531				for j in js.iter_mut() {
1532					if *j >= shifted_i {
1533						*j -= 1;
1534					}
1535				}
1536			}
1537
1538			(i, k, v)
1539		})
1540	}
1541}
1542
1543impl<'a, K, V> ExactSizeIterator for ShiftRemoveIndexedEntries<'a, K, V> {}
1544
1545impl<'a, K, V> Drop for ShiftRemoveIndexedEntries<'a, K, V> {
1546	fn drop(&mut self) {
1547		// Consume the rest of the iterator to make sure everything is removed.
1548		for _ in self {}
1549	}
1550}
1551
1552/// An iterator over `(key, value)` for every entry removed by
1553/// [`BTreeIndexMultiMap::shift_remove_entries`].
1554pub struct ShiftRemoveEntries<'a, K, V>(ShiftRemoveIndexedEntries<'a, K, V>);
1555
1556impl<'a, K, V> Iterator for ShiftRemoveEntries<'a, K, V> {
1557	type Item = (K, V);
1558
1559	fn size_hint(&self) -> (usize, Option<usize>) {
1560		self.0.size_hint()
1561	}
1562
1563	fn next(&mut self) -> Option<Self::Item> {
1564		self.0.next().map(|(_, k, v)| (k, v))
1565	}
1566}
1567
1568impl<'a, K, V> ExactSizeIterator for ShiftRemoveEntries<'a, K, V> {}
1569
1570/// An iterator over the values removed by
1571/// [`BTreeIndexMultiMap::shift_remove`].
1572pub struct ShiftRemove<'a, K, V>(ShiftRemoveIndexedEntries<'a, K, V>);
1573
1574impl<'a, K, V> Iterator for ShiftRemove<'a, K, V> {
1575	type Item = V;
1576
1577	fn size_hint(&self) -> (usize, Option<usize>) {
1578		self.0.size_hint()
1579	}
1580
1581	fn next(&mut self) -> Option<Self::Item> {
1582		self.0.next().map(|(_, _, v)| v)
1583	}
1584}
1585
1586impl<'a, K, V> ExactSizeIterator for ShiftRemove<'a, K, V> {}
1587
1588fn inner_index_cmp<K, V>(
1589	entries: &[(K, V)],
1590) -> impl use<'_, K, V> + Fn(&Indexes, &usize) -> Ordering
1591where
1592	K: Ord,
1593{
1594	|i, &j| entries[i.first].0.cmp(&entries[j].0)
1595}
1596
1597fn inner_cmp<K, V>(entries: &[(K, V)]) -> impl use<'_, K, V> + Fn(&Indexes, &Indexes) -> Ordering
1598where
1599	K: Ord,
1600{
1601	|i, j| entries[i.first].0.cmp(&entries[j.first].0)
1602}
1603
1604fn outer_cmp<K, V, Q>(entries: &[(K, V)]) -> impl use<'_, K, V, Q> + Fn(&Indexes, &Q) -> Ordering
1605where
1606	Q: ?Sized + Comparable<K>,
1607{
1608	|i, q| q.compare(&entries[i.first].0).reverse()
1609}
1610
1611impl<K, V, Q> Index<&Q> for BTreeIndexMultiMap<K, V>
1612where
1613	Q: ?Sized + Comparable<K>,
1614{
1615	type Output = V;
1616
1617	/// # Panics
1618	///
1619	/// Panics if `key` is not found in the map.
1620	fn index(&self, key: &Q) -> &Self::Output {
1621		self.get(key).next().expect("no entry found for key")
1622	}
1623}
1624
1625/// An owning iterator over the entries of a [`BTreeIndexMultiMap`], in
1626/// insertion order.
1627pub type IntoIter<K, V> = std::vec::IntoIter<(K, V)>;
1628
1629impl<K, V> IntoIterator for BTreeIndexMultiMap<K, V> {
1630	type IntoIter = IntoIter<K, V>;
1631	type Item = (K, V);
1632
1633	fn into_iter(self) -> Self::IntoIter {
1634		self.entries.into_iter()
1635	}
1636}
1637
1638impl<K: PartialEq, V: PartialEq> PartialEq for BTreeIndexMultiMap<K, V> {
1639	fn eq(&self, other: &Self) -> bool {
1640		self.iter_sorted().eq(other.iter_sorted())
1641	}
1642}
1643
1644impl<K: Eq, V: Eq> Eq for BTreeIndexMultiMap<K, V> {}
1645
1646impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeIndexMultiMap<K, V> {
1647	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1648		self.iter_sorted().partial_cmp(other.iter_sorted())
1649	}
1650}
1651
1652impl<K: Ord, V: Ord> Ord for BTreeIndexMultiMap<K, V> {
1653	fn cmp(&self, other: &Self) -> Ordering {
1654		self.iter_sorted().cmp(other.iter_sorted())
1655	}
1656}
1657
1658impl<K: Hash, V: Hash> Hash for BTreeIndexMultiMap<K, V> {
1659	fn hash<H: Hasher>(&self, state: &mut H) {
1660		state.write_usize(self.len());
1661		for item in self.iter_sorted() {
1662			item.hash(state);
1663		}
1664	}
1665}
1666
1667impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for BTreeIndexMultiMap<K, V> {
1668	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1669		f.debug_set().entries(self.iter()).finish()
1670	}
1671}
1672
1673impl<K: Ord, V> Extend<(K, V)> for BTreeIndexMultiMap<K, V> {
1674	fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1675		for (key, value) in iter {
1676			self.push_back(key, value);
1677		}
1678	}
1679}
1680
1681impl<K: Ord, V> FromIterator<(K, V)> for BTreeIndexMultiMap<K, V> {
1682	fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
1683		let mut result = Self::new();
1684		result.extend(iter);
1685		result
1686	}
1687}
1688
1689/// An iterator over the entries of a [`BTreeIndexMultiMap`], in insertion
1690/// order.
1691pub struct Iter<'a, K, V>(std::slice::Iter<'a, (K, V)>);
1692
1693impl<K, V> Clone for Iter<'_, K, V> {
1694	fn clone(&self) -> Self {
1695		Self(self.0.clone())
1696	}
1697}
1698
1699impl<'a, K, V> Iterator for Iter<'a, K, V> {
1700	type Item = (&'a K, &'a V);
1701
1702	fn size_hint(&self) -> (usize, Option<usize>) {
1703		self.0.size_hint()
1704	}
1705
1706	fn next(&mut self) -> Option<Self::Item> {
1707		self.0.next().map(|(k, v)| (k, v))
1708	}
1709}
1710
1711impl<K, V> DoubleEndedIterator for Iter<'_, K, V> {
1712	fn next_back(&mut self) -> Option<Self::Item> {
1713		self.0.next_back().map(|(k, v)| (k, v))
1714	}
1715}
1716
1717impl<K, V> ExactSizeIterator for Iter<'_, K, V> {}
1718
1719impl<K, V> FusedIterator for Iter<'_, K, V> {}
1720
1721impl<'a, K, V> IntoIterator for &'a BTreeIndexMultiMap<K, V> {
1722	type IntoIter = Iter<'a, K, V>;
1723	type Item = (&'a K, &'a V);
1724
1725	fn into_iter(self) -> Self::IntoIter {
1726		self.iter()
1727	}
1728}
1729
1730/// An iterator over the entries of a [`BTreeIndexMultiMap`], with a
1731/// mutable reference to the value, in insertion order.
1732pub struct IterMut<'a, K, V>(std::slice::IterMut<'a, (K, V)>);
1733
1734impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1735	type Item = (&'a K, &'a mut V);
1736
1737	fn size_hint(&self) -> (usize, Option<usize>) {
1738		self.0.size_hint()
1739	}
1740
1741	fn next(&mut self) -> Option<Self::Item> {
1742		self.0.next().map(|(k, v)| (&*k, v))
1743	}
1744}
1745
1746impl<K, V> DoubleEndedIterator for IterMut<'_, K, V> {
1747	fn next_back(&mut self) -> Option<Self::Item> {
1748		self.0.next_back().map(|(k, v)| (&*k, v))
1749	}
1750}
1751
1752impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {}
1753
1754impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1755
1756impl<'a, K, V> IntoIterator for &'a mut BTreeIndexMultiMap<K, V> {
1757	type IntoIter = IterMut<'a, K, V>;
1758	type Item = (&'a K, &'a mut V);
1759
1760	fn into_iter(self) -> Self::IntoIter {
1761		self.iter_mut()
1762	}
1763}
1764
1765/// An iterator over the entries of a [`BTreeIndexMultiMap`], sorted by
1766/// key according to `K`'s implementation of [`Ord`].
1767///
1768/// Entries that share the same key are visited in insertion (index)
1769/// order.
1770pub struct IterSorted<'a, K, V> {
1771	entries: &'a [(K, V)],
1772	inner: raw_btree::Iter<'a, Indexes>,
1773	current: Option<IndexesIter<'a>>,
1774	remaining: usize,
1775}
1776
1777impl<K, V> Clone for IterSorted<'_, K, V> {
1778	fn clone(&self) -> Self {
1779		Self {
1780			entries: self.entries,
1781			inner: self.inner,
1782			current: self.current.clone(),
1783			remaining: self.remaining,
1784		}
1785	}
1786}
1787
1788impl<'a, K, V> Iterator for IterSorted<'a, K, V> {
1789	type Item = (&'a K, &'a V);
1790
1791	fn size_hint(&self) -> (usize, Option<usize>) {
1792		(self.remaining, Some(self.remaining))
1793	}
1794
1795	fn next(&mut self) -> Option<Self::Item> {
1796		loop {
1797			match &mut self.current {
1798				Some(indexes) => match indexes.next() {
1799					Some(i) => {
1800						self.remaining -= 1;
1801						let (k, v) = &self.entries[i];
1802						break Some((k, v));
1803					}
1804					None => self.current = None,
1805				},
1806				None => match self.inner.next() {
1807					Some(indexes) => self.current = Some(indexes.iter()),
1808					None => break None,
1809				},
1810			}
1811		}
1812	}
1813}
1814
1815impl<K, V> ExactSizeIterator for IterSorted<'_, K, V> {}
1816
1817impl<K, V> FusedIterator for IterSorted<'_, K, V> {}
1818
1819/// An iterator over the entries of a [`BTreeIndexMultiMap`], with a
1820/// mutable reference to the value, sorted by key according to `K`'s
1821/// implementation of [`Ord`].
1822///
1823/// Entries that share the same key are visited in insertion (index)
1824/// order.
1825pub struct IterMutSorted<'a, K, V> {
1826	entries: &'a mut [(K, V)],
1827	inner: raw_btree::Iter<'a, Indexes>,
1828	current: Option<IndexesIter<'a>>,
1829	remaining: usize,
1830}
1831
1832impl<'a, K, V> Iterator for IterMutSorted<'a, K, V> {
1833	type Item = (&'a K, &'a mut V);
1834
1835	fn size_hint(&self) -> (usize, Option<usize>) {
1836		(self.remaining, Some(self.remaining))
1837	}
1838
1839	fn next(&mut self) -> Option<Self::Item> {
1840		loop {
1841			match &mut self.current {
1842				Some(indexes) => match indexes.next() {
1843					Some(i) => {
1844						self.remaining -= 1;
1845						let (k, v) = unsafe {
1846							std::mem::transmute::<&mut (K, V), &mut (K, V)>(&mut self.entries[i])
1847						};
1848						break Some((k, v));
1849					}
1850					None => self.current = None,
1851				},
1852				None => match self.inner.next() {
1853					Some(indexes) => self.current = Some(indexes.iter()),
1854					None => break None,
1855				},
1856			}
1857		}
1858	}
1859}
1860
1861impl<K, V> ExactSizeIterator for IterMutSorted<'_, K, V> {}
1862
1863impl<K, V> FusedIterator for IterMutSorted<'_, K, V> {}
1864
1865/// An owning iterator over the entries of a [`BTreeIndexMultiMap`],
1866/// sorted by key according to `K`'s implementation of [`Ord`].
1867///
1868/// Entries that share the same key are visited in insertion (index)
1869/// order.
1870pub struct IntoIterSorted<K, V> {
1871	entries: Vec<MaybeUninit<(K, V)>>,
1872	inner: raw_btree::IntoIter<Indexes>,
1873	current: Option<IndexesIntoIter>,
1874	remaining: usize,
1875}
1876
1877impl<K, V> Iterator for IntoIterSorted<K, V> {
1878	type Item = (K, V);
1879
1880	fn size_hint(&self) -> (usize, Option<usize>) {
1881		(self.remaining, Some(self.remaining))
1882	}
1883
1884	fn next(&mut self) -> Option<Self::Item> {
1885		loop {
1886			match &mut self.current {
1887				Some(indexes) => match indexes.next() {
1888					Some(i) => {
1889						self.remaining -= 1;
1890						let (k, v) = unsafe { self.entries[i].assume_init_read() };
1891						break Some((k, v));
1892					}
1893					None => self.current = None,
1894				},
1895				None => match self.inner.next() {
1896					Some(indexes) => self.current = Some(indexes.into_iter()),
1897					None => break None,
1898				},
1899			}
1900		}
1901	}
1902}
1903
1904impl<K, V> ExactSizeIterator for IntoIterSorted<K, V> {}
1905
1906impl<K, V> FusedIterator for IntoIterSorted<K, V> {}
1907
1908impl<K, V> Drop for IntoIterSorted<K, V> {
1909	fn drop(&mut self) {
1910		// Make sure the remaining entries are consumed.
1911		self.last();
1912	}
1913}
1914
1915/// An iterator over the keys of a [`BTreeIndexMultiMap`], in insertion
1916/// order.
1917pub struct Keys<'a, K, V>(std::slice::Iter<'a, (K, V)>);
1918
1919impl<K, V> Clone for Keys<'_, K, V> {
1920	fn clone(&self) -> Self {
1921		Self(self.0.clone())
1922	}
1923}
1924
1925impl<'a, K, V> Iterator for Keys<'a, K, V> {
1926	type Item = &'a K;
1927
1928	fn size_hint(&self) -> (usize, Option<usize>) {
1929		self.0.size_hint()
1930	}
1931
1932	fn next(&mut self) -> Option<Self::Item> {
1933		self.0.next().map(|(k, _)| k)
1934	}
1935}
1936
1937impl<K, V> DoubleEndedIterator for Keys<'_, K, V> {
1938	fn next_back(&mut self) -> Option<Self::Item> {
1939		self.0.next_back().map(|(k, _)| k)
1940	}
1941}
1942
1943impl<K, V> ExactSizeIterator for Keys<'_, K, V> {}
1944
1945impl<K, V> FusedIterator for Keys<'_, K, V> {}
1946
1947/// An iterator over the values of a [`BTreeIndexMultiMap`], in insertion
1948/// order.
1949pub struct Values<'a, K, V>(std::slice::Iter<'a, (K, V)>);
1950
1951impl<K, V> Clone for Values<'_, K, V> {
1952	fn clone(&self) -> Self {
1953		Self(self.0.clone())
1954	}
1955}
1956
1957impl<'a, K, V> Iterator for Values<'a, K, V> {
1958	type Item = &'a V;
1959
1960	fn size_hint(&self) -> (usize, Option<usize>) {
1961		self.0.size_hint()
1962	}
1963
1964	fn next(&mut self) -> Option<Self::Item> {
1965		self.0.next().map(|(_, v)| v)
1966	}
1967}
1968
1969impl<K, V> DoubleEndedIterator for Values<'_, K, V> {
1970	fn next_back(&mut self) -> Option<Self::Item> {
1971		self.0.next_back().map(|(_, v)| v)
1972	}
1973}
1974
1975impl<K, V> ExactSizeIterator for Values<'_, K, V> {}
1976
1977impl<K, V> FusedIterator for Values<'_, K, V> {}
1978
1979/// An iterator over mutable references to the values of a
1980/// [`BTreeIndexMultiMap`], in insertion order.
1981pub struct ValuesMut<'a, K, V>(std::slice::IterMut<'a, (K, V)>);
1982
1983impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1984	type Item = &'a mut V;
1985
1986	fn size_hint(&self) -> (usize, Option<usize>) {
1987		self.0.size_hint()
1988	}
1989
1990	fn next(&mut self) -> Option<Self::Item> {
1991		self.0.next().map(|(_, v)| v)
1992	}
1993}
1994
1995impl<K, V> DoubleEndedIterator for ValuesMut<'_, K, V> {
1996	fn next_back(&mut self) -> Option<Self::Item> {
1997		self.0.next_back().map(|(_, v)| v)
1998	}
1999}
2000
2001impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {}
2002
2003impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2004
2005/// A view into a single entry of a [`BTreeIndexMultiMap`], which may
2006/// either be vacant or occupied.
2007///
2008/// This is returned by [`BTreeIndexMultiMap::entry`].
2009pub enum Entry<'a, K, V> {
2010	Vacant(VacantEntry<'a, K, V>),
2011	Occupied(OccupiedEntry<'a, K, V>),
2012}
2013
2014/// A view into a vacant entry of a [`BTreeIndexMultiMap`].
2015///
2016/// This is part of the [`Entry`] enum.
2017pub struct VacantEntry<'a, K, V> {
2018	map: &'a mut BTreeIndexMultiMap<K, V>,
2019	key: K,
2020}
2021
2022impl<'a, K, V> VacantEntry<'a, K, V> {
2023	/// Returns a reference to the entry's key.
2024	pub fn key(&self) -> &K {
2025		&self.key
2026	}
2027
2028	/// Consumes this entry, returning its key.
2029	pub fn into_key(self) -> K {
2030		self.key
2031	}
2032
2033	/// Inserts `value` in the map for this entry's key, returning the new
2034	/// entry's index, key, and a mutable reference to the value.
2035	pub fn insert_full(self, value: V) -> (usize, &'a K, &'a mut V)
2036	where
2037		K: Ord,
2038	{
2039		let (i, _) = self.map.push_back(self.key, value);
2040		let (k, v) = &mut self.map.entries[i];
2041		(i, &*k, v)
2042	}
2043
2044	/// Inserts `value` in the map for this entry's key, returning the new
2045	/// entry's key and a mutable reference to the value.
2046	pub fn insert_entry(self, value: V) -> (&'a K, &'a mut V)
2047	where
2048		K: Ord,
2049	{
2050		let (_, k, v) = self.insert_full(value);
2051		(k, v)
2052	}
2053
2054	/// Inserts `value` in the map for this entry's key, returning a mutable
2055	/// reference to the value.
2056	pub fn insert(self, value: V) -> &'a mut V
2057	where
2058		K: Ord,
2059	{
2060		self.insert_full(value).2
2061	}
2062}
2063
2064/// A view into an occupied entry of a [`BTreeIndexMultiMap`].
2065///
2066/// This is part of the [`Entry`] enum.
2067pub struct OccupiedEntry<'a, K, V> {
2068	entries: &'a mut Vec<(K, V)>,
2069	indices: &'a Indexes,
2070}
2071
2072impl<'a, K, V> OccupiedEntry<'a, K, V> {
2073	/// Returns a reference to the entry's key.
2074	pub fn key(&self) -> &K {
2075		&self.entries[self.indices.first].0
2076	}
2077
2078	/// Returns an iterator over `(index, &key, &value)` for every value
2079	/// associated with this entry's key.
2080	pub fn get_full(&self) -> GetIndexedEntries<'_, K, V> {
2081		GetIndexedEntries {
2082			indexes: self.indices.iter(),
2083			entries: self.entries,
2084		}
2085	}
2086
2087	/// Returns an iterator over `(&key, &value)` for every value associated
2088	/// with this entry's key.
2089	pub fn get_entry(&self) -> GetEntries<'_, K, V> {
2090		GetEntries(self.get_full())
2091	}
2092
2093	/// Returns an iterator over a reference to every value associated with
2094	/// this entry's key.
2095	pub fn get(&self) -> Get<'_, K, V> {
2096		Get(self.get_full())
2097	}
2098
2099	/// Returns an iterator over `(index, &key, &mut value)` for every value
2100	/// associated with this entry's key.
2101	pub fn get_mut_full(&mut self) -> GetIndexedEntriesMut<'_, K, V> {
2102		GetIndexedEntriesMut {
2103			indexes: self.indices.iter(),
2104			entries: self.entries,
2105		}
2106	}
2107
2108	/// Returns an iterator over `(&key, &mut value)` for every value
2109	/// associated with this entry's key.
2110	pub fn get_mut_entry(&mut self) -> GetEntriesMut<'_, K, V> {
2111		GetEntriesMut(self.get_mut_full())
2112	}
2113
2114	/// Returns an iterator over a mutable reference to every value
2115	/// associated with this entry's key.
2116	pub fn get_mut(&mut self) -> GetMut<'_, K, V> {
2117		GetMut(self.get_mut_full())
2118	}
2119
2120	/// Consumes this entry, returning an iterator over `(index, &key, &mut
2121	/// value)` for every value associated with this entry's key, tied to
2122	/// the lifetime of the map.
2123	pub fn into_mut_full(self) -> GetIndexedEntriesMut<'a, K, V> {
2124		GetIndexedEntriesMut {
2125			indexes: self.indices.iter(),
2126			entries: self.entries,
2127		}
2128	}
2129
2130	/// Consumes this entry, returning an iterator over `(&key, &mut
2131	/// value)` for every value associated with this entry's key, tied to
2132	/// the lifetime of the map.
2133	pub fn into_mut_entry(self) -> GetEntriesMut<'a, K, V> {
2134		GetEntriesMut(self.into_mut_full())
2135	}
2136
2137	/// Consumes this entry, returning an iterator over a mutable reference
2138	/// to every value associated with this entry's key, tied to the
2139	/// lifetime of the map.
2140	pub fn into_mut(self) -> GetMut<'a, K, V> {
2141		GetMut(self.into_mut_full())
2142	}
2143
2144	/// Replaces the value of the first occurrence of this entry's key,
2145	/// returning the previous value.
2146	pub fn insert(&mut self, value: V) -> V {
2147		std::mem::replace(&mut self.entries[self.indices.first].1, value)
2148	}
2149}