kempt/
map.rs

1use alloc::borrow::ToOwned;
2use alloc::vec::{self, Vec};
3use core::alloc::Layout;
4use core::borrow::Borrow;
5use core::cmp::Ordering;
6use core::fmt::{self, Debug};
7use core::iter::{FusedIterator, Peekable};
8use core::ops::{Deref, DerefMut};
9use core::{mem, slice};
10
11use crate::Sort;
12
13/// An ordered Key/Value map.
14///
15/// This type is similar to [`BTreeMap`](alloc::collections::BTreeMap), but
16/// utilizes a simpler storage model. Additionally, it provides a more thorough
17/// interface and has a [`merge_with()`](Self::merge_with) function.
18///
19/// This type is designed for collections with a limited number of keys. In
20/// general, this collection excels when there are fewer entries, while
21/// `HashMap` or `BTreeMap` will be better choices with larger numbers of
22/// entries. Additionally, `HashMap` will perform better if comparing the keys
23/// is expensive.
24#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
25pub struct Map<Key, Value>
26where
27    Key: Sort<Key>,
28{
29    fields: Vec<Field<Key, Value>>,
30}
31
32impl<Key, Value> Default for Map<Key, Value>
33where
34    Key: Sort<Key>,
35{
36    #[inline]
37    fn default() -> Self {
38        Self::new()
39    }
40}
41
42/// Returns a heuristic guessing the size that should be allowed to be scanned
43/// sequentially.
44///
45/// This uses the key and value types's layout to calculate based on multiple
46/// cache line widths. Magic numbers are a code smell, but I'm not sure how else
47/// to tune this heuristic based on the information available at compile time.
48const fn scan_limit<Key, Value>() -> usize {
49    let field_layout = Layout::new::<Field<Key, Value>>();
50    let align = field_layout.align();
51    let aligned = ((field_layout.size() + (align - 1)) / align) * align;
52    if aligned == 0 {
53        return 1;
54    }
55
56    let scan_limit = 128 / aligned;
57    if scan_limit > 16 {
58        16
59    } else if scan_limit < 4 {
60        4
61    } else {
62        scan_limit
63    }
64}
65
66#[test]
67fn scan_limit_tests() {
68    // Small sizes seem better to narrow down via binary search up until ~16
69    // elements.
70    assert_eq!(scan_limit::<u8, ()>(), 16);
71    // Test a mid-point of the heuristic.
72    assert_eq!(scan_limit::<u64, u64>(), 8);
73    // Large field sizes only scan chunks of 4.
74    assert_eq!(scan_limit::<(u128, u128), (u128, u128)>(), 4);
75}
76
77impl<Key, Value> Map<Key, Value>
78where
79    Key: Sort<Key>,
80{
81    const SCAN_LIMIT: usize = scan_limit::<Key, Value>();
82
83    /// Returns an empty map.
84    #[must_use]
85    #[inline]
86    pub const fn new() -> Self {
87        Self { fields: Vec::new() }
88    }
89
90    /// Returns a map with enough memory allocated to store `capacity` elements
91    /// without reallocation.
92    #[must_use]
93    #[inline]
94    pub fn with_capacity(capacity: usize) -> Self {
95        Self {
96            fields: Vec::with_capacity(capacity),
97        }
98    }
99
100    /// Returns the current capacity this map can hold before it must
101    /// reallocate.
102    #[must_use]
103    #[inline]
104    pub fn capacity(&self) -> usize {
105        self.fields.capacity()
106    }
107
108    /// Inserts `key` and `value`. If an entry already existed for `key`, the
109    /// value being overwritten is returned.
110    #[inline]
111    pub fn insert(&mut self, key: Key, value: Value) -> Option<Field<Key, Value>> {
112        let field = Field::new(key, value);
113        match self.find_key_mut(&field.key) {
114            Ok(existing) => Some(mem::replace(existing, field)),
115            Err(insert_at) => {
116                self.fields.insert(insert_at, field);
117                None
118            }
119        }
120    }
121
122    /// Inserts an entry with `key` only if the map does not already contain
123    /// that key.
124    ///
125    /// If an existing key is found, `Some(key)` is returned. If an existing key
126    /// isn't found, `value()` will be called, a new entry will be inserted, and
127    /// `None` will be returned.
128    ///
129    /// This is similar to using [`Map::entry`], except this function does not
130    /// require that `Key` implement [`ToOwned`].
131    #[inline]
132    pub fn insert_with(&mut self, key: Key, value: impl FnOnce() -> Value) -> Option<Key> {
133        match self.find_key_index(&key) {
134            Err(insert_at) => {
135                self.fields.insert(insert_at, Field::new(key, value()));
136                None
137            }
138            Ok(_) => Some(key),
139        }
140    }
141
142    /// Returns true if this object contains `key`.
143    #[inline]
144    pub fn contains<SearchFor>(&self, key: &SearchFor) -> bool
145    where
146        Key: Sort<SearchFor>,
147        SearchFor: ?Sized,
148    {
149        self.find_key_index(key).is_ok()
150    }
151
152    /// Returns the value associated with `key`, if found.
153    #[inline]
154    pub fn get<SearchFor>(&self, key: &SearchFor) -> Option<&Value>
155    where
156        Key: Sort<SearchFor>,
157        SearchFor: ?Sized,
158    {
159        self.get_field(key).map(|field| &field.value)
160    }
161
162    /// Returns a mutable value associated with `key`, if found.
163    #[inline]
164    pub fn get_mut<SearchFor>(&mut self, key: &SearchFor) -> Option<&mut Value>
165    where
166        Key: Sort<SearchFor>,
167        SearchFor: ?Sized,
168    {
169        self.get_field_mut(key).map(|field| &mut field.value)
170    }
171
172    /// Returns the field associated with `key`, if found.
173    #[inline]
174    pub fn get_field<SearchFor>(&self, key: &SearchFor) -> Option<&Field<Key, Value>>
175    where
176        Key: Sort<SearchFor>,
177        SearchFor: ?Sized,
178    {
179        self.find_key(key).ok()
180    }
181
182    /// Returns the a mutable reference to the field associated with `key`, if
183    /// found.
184    #[inline]
185    pub fn get_field_mut<SearchFor>(&mut self, key: &SearchFor) -> Option<&mut Field<Key, Value>>
186    where
187        Key: Sort<SearchFor>,
188        SearchFor: ?Sized,
189    {
190        self.find_key_mut(key).ok()
191    }
192
193    /// Returns the [`Field`] at the specified `index`, or None if the index is
194    /// outside of the bounds of this collection.
195    #[inline]
196    #[must_use]
197    pub fn field(&self, index: usize) -> Option<&Field<Key, Value>> {
198        self.fields.get(index)
199    }
200
201    /// Returns a mutable reference to the [`Field`] at the specified `index`,
202    /// or None if the index is outside of the bounds of this collection.
203    #[inline]
204    #[must_use]
205    pub fn field_mut(&mut self, index: usize) -> Option<&mut Field<Key, Value>> {
206        self.fields.get_mut(index)
207    }
208
209    /// Removes the value associated with `key`, if found.
210    #[inline]
211    pub fn remove<SearchFor>(&mut self, key: &SearchFor) -> Option<Field<Key, Value>>
212    where
213        Key: Sort<SearchFor>,
214        SearchFor: ?Sized,
215    {
216        let index = self.find_key_index(key).ok()?;
217        Some(self.remove_by_index(index))
218    }
219
220    /// Removes the field at `index`.
221    ///
222    /// # Panics
223    ///
224    /// This function will panic if `index` is outside of the bounds of this
225    /// collection.
226    #[inline]
227    pub fn remove_by_index(&mut self, index: usize) -> Field<Key, Value> {
228        self.fields.remove(index)
229    }
230
231    /// Returns the number of fields in this object.
232    #[must_use]
233    #[inline]
234    pub fn len(&self) -> usize {
235        self.fields.len()
236    }
237
238    /// Returns true if this object has no fields.
239    #[must_use]
240    #[inline]
241    pub fn is_empty(&self) -> bool {
242        self.fields.is_empty()
243    }
244
245    /// Returns an [`Entry`] for the associated key.
246    #[inline]
247    pub fn entry<'key, SearchFor>(
248        &mut self,
249        key: impl Into<SearchKey<'key, Key, SearchFor>>,
250    ) -> Entry<'_, 'key, Key, Value, SearchFor>
251    where
252        Key: Sort<SearchFor> + Borrow<SearchFor>,
253        SearchFor: ToOwned<Owned = Key> + ?Sized + 'key,
254    {
255        let key = key.into();
256        match self.find_key_index(key.as_ref()) {
257            Ok(index) => Entry::Occupied(OccupiedEntry::new(self, index)),
258            Err(insert_at) => Entry::Vacant(VacantEntry::new(self, key, insert_at)),
259        }
260    }
261
262    fn find_key<SearchFor>(&self, search_for: &SearchFor) -> Result<&Field<Key, Value>, usize>
263    where
264        Key: Sort<SearchFor>,
265        SearchFor: ?Sized,
266    {
267        self.find_key_index(search_for)
268            .map(|index| &self.fields[index])
269    }
270
271    fn find_key_mut<SearchFor>(
272        &mut self,
273        search_for: &SearchFor,
274    ) -> Result<&mut Field<Key, Value>, usize>
275    where
276        Key: Sort<SearchFor>,
277        SearchFor: ?Sized,
278    {
279        self.find_key_index(search_for)
280            .map(|index| &mut self.fields[index])
281    }
282
283    fn find_key_index<SearchFor>(&self, search_for: &SearchFor) -> Result<usize, usize>
284    where
285        Key: Sort<SearchFor>,
286        SearchFor: ?Sized,
287    {
288        // When the collection contains `Self::SCAN_LIMIT` or fewer elements,
289        // there should be no jumps before we reach a sequential scan for the
290        // key. When the collection is larger, we use a binary search to narrow
291        // the search window until the window is 16 elements or less.
292        let mut min = 0;
293        let field_count = self.fields.len();
294        let mut max = field_count;
295        loop {
296            let delta = max - min;
297            if delta <= Self::SCAN_LIMIT {
298                for (relative_index, field) in self.fields[min..max].iter().enumerate() {
299                    let comparison =
300                        <Key as crate::Sort<SearchFor>>::compare(&field.key, search_for);
301                    return match comparison {
302                        Ordering::Less => continue,
303                        Ordering::Equal => Ok(min + relative_index),
304                        Ordering::Greater => Err(min + relative_index),
305                    };
306                }
307
308                return Err(max);
309            }
310
311            let midpoint = min + delta / 2;
312            let comparison =
313                <Key as crate::Sort<SearchFor>>::compare(&self.fields[midpoint].key, search_for);
314
315            match comparison {
316                Ordering::Less => min = midpoint + 1,
317                Ordering::Equal => return Ok(midpoint),
318                Ordering::Greater => max = midpoint,
319            }
320        }
321    }
322
323    /// Returns an iterator over the fields in this object.
324    #[must_use]
325    #[inline]
326    pub fn iter(&self) -> Iter<'_, Key, Value> {
327        self.into_iter()
328    }
329
330    /// Returns an iterator over the fields in this object, with mutable access.
331    #[must_use]
332    #[inline]
333    pub fn iter_mut(&mut self) -> IterMut<'_, Key, Value> {
334        self.into_iter()
335    }
336
337    /// Returns an iterator over the keys in this object.
338    #[must_use]
339    #[inline]
340    pub fn keys(&self) -> Keys<'_, Key, Value> {
341        Keys(self.fields.iter())
342    }
343
344    /// Returns an iterator over the values in this object.
345    #[must_use]
346    #[inline]
347    pub fn values(&self) -> Values<'_, Key, Value> {
348        Values(self.fields.iter())
349    }
350
351    /// Returns an iterator over the fields in this object, with mutable access.
352    #[must_use]
353    #[inline]
354    pub fn values_mut(&mut self) -> ValuesMut<'_, Key, Value> {
355        ValuesMut(self.fields.iter_mut())
356    }
357
358    /// Returns an iterator returning all of the values contained in this
359    /// object.
360    #[must_use]
361    #[inline]
362    pub fn into_values(self) -> IntoValues<Key, Value> {
363        IntoValues(self.fields.into_iter())
364    }
365
366    /// Merges the fields from `self` and `other` into a new object, returning
367    /// the updated object.
368    ///
369    /// * If a field is contained in `other` but not contained in `self`,
370    ///   `filter()` is called. If `filter()` returns a value, the returned
371    ///   value is inserted into the new object using the original key.
372    /// * If a field is contained in both `other` and `self`, `merge()` is
373    ///   called with mutable access to a clone of the value from `self` and a
374    ///   reference to the value from `other`. The `merge()` function is
375    ///   responsible for updating the value if needed to complete the merge.
376    ///   The merged value is inserted into the returned object.
377    /// * If a field is contained in `self` but not in `other`, it is always
378    ///   cloned.
379    ///
380    /// ```rust
381    /// use kempt::Map;
382    ///
383    /// let a: Map<&'static str, usize> = [("a", 1), ("b", 2)].into_iter().collect();
384    /// let b: Map<&'static str, usize> = [("a", 1), ("c", 3)].into_iter().collect();
385    /// let merged = a.merged_with(&b, |_key, b| Some(*b), |_key, a, b| *a += *b);
386    ///
387    /// assert_eq!(merged.get(&"a"), Some(&2));
388    /// assert_eq!(merged.get(&"b"), Some(&2));
389    /// assert_eq!(merged.get(&"c"), Some(&3));
390    /// ```
391    #[inline]
392    #[must_use]
393    pub fn merged_with(
394        mut self,
395        other: &Self,
396        filter: impl FnMut(&Key, &Value) -> Option<Value>,
397        merge: impl FnMut(&Key, &mut Value, &Value),
398    ) -> Self
399    where
400        Key: Clone,
401        Value: Clone,
402    {
403        self.merge_with(other, filter, merge);
404        self
405    }
406
407    /// Merges the fields from `other` into `self`.
408    ///
409    /// * If a field is contained in `other` but not contained in `self`,
410    ///   `filter()` is called. If `filter()` returns a value, the returned
411    ///   value is inserted into `self` using the original key.
412    /// * If a field is contained in both `other` and `self`, `merge()` is
413    ///   called with mutable access to the value from `self` and a reference to
414    ///   the value from `other`. The `merge()` function is responsible for
415    ///   updating the value if needed to complete the merge.
416    /// * If a field is contained in `self` but not in `other`, it is ignored.
417    ///
418    /// ```rust
419    /// use kempt::Map;
420    ///
421    /// let mut a: Map<&'static str, usize> = [("a", 1), ("b", 2)].into_iter().collect();
422    /// let b: Map<&'static str, usize> = [("a", 1), ("c", 3)].into_iter().collect();
423    /// a.merge_with(&b, |_key, b| Some(*b), |_key, a, b| *a += *b);
424    /// assert_eq!(a.get(&"a"), Some(&2));
425    /// assert_eq!(a.get(&"b"), Some(&2));
426    /// assert_eq!(a.get(&"c"), Some(&3));
427    /// ```
428    #[inline]
429    pub fn merge_with(
430        &mut self,
431        other: &Self,
432        mut filter: impl FnMut(&Key, &Value) -> Option<Value>,
433        mut merge: impl FnMut(&Key, &mut Value, &Value),
434    ) where
435        Key: Clone,
436    {
437        let mut self_index = 0;
438        let mut other_index = 0;
439
440        while self_index < self.len() && other_index < other.len() {
441            let self_field = &mut self.fields[self_index];
442            let other_field = &other.fields[other_index];
443            match Key::compare(&self_field.key, &other_field.key) {
444                Ordering::Less => {
445                    // Self has a key that other didn't.
446                    self_index += 1;
447                }
448                Ordering::Equal => {
449                    // Both have the value, we might need to merge.
450                    self_index += 1;
451                    other_index += 1;
452                    merge(&self_field.key, &mut self_field.value, &other_field.value);
453                }
454                Ordering::Greater => {
455                    // Other has a value that self doesn't.
456                    other_index += 1;
457                    let Some(value) = filter(&other_field.key, &other_field.value) else {
458                        continue;
459                    };
460
461                    self.fields
462                        .insert(self_index, Field::new(other_field.key.clone(), value));
463                    self_index += 1;
464                }
465            }
466        }
467
468        if other_index < other.fields.len() {
469            // Other has more entries that we don't have
470            for field in &other.fields[other_index..] {
471                let Some(value) = filter(&field.key, &field.value) else {
472                    continue;
473                };
474
475                self.fields.push(Field::new(field.key.clone(), value));
476            }
477        }
478    }
479
480    /// Returns an iterator that returns all of the elements in this collection.
481    /// After the iterator is dropped, this object will be empty.
482    #[inline]
483    pub fn drain(&mut self) -> Drain<'_, Key, Value> {
484        Drain(self.fields.drain(..))
485    }
486
487    /// Clears the contents of this collection.
488    ///
489    /// This does not return any allocated memory to the OS.
490    #[inline]
491    pub fn clear(&mut self) {
492        self.fields.clear();
493    }
494
495    /// Resizes this collection to fit its contents exactly.
496    ///
497    /// This function will reallocate its internal storage to fit the contents
498    /// of this collection's current size. If the allocation is already the
499    /// correct size, this is a no-op.
500    #[inline]
501    pub fn shrink_to_fit(&mut self) {
502        self.fields.shrink_to_fit();
503    }
504
505    /// Resizes this collection to be able to hold `min_capacity`.
506    ///
507    /// This function will reallocate its internal storage to fit the contents
508    /// of this collection's current size. If the allocation is already the
509    /// correct size, this is a no-op.
510    ///
511    /// If the length of this collection is larger than `min_capacity`, this
512    /// function will behave identically to
513    /// [`shrink_to_fit()`](Self::shrink_to_fit).
514    #[inline]
515    pub fn shrink_to(&mut self, min_capacity: usize) {
516        self.fields.shrink_to(min_capacity);
517    }
518
519    /// Returns an iterator that yields [`Unioned`] entries.
520    ///
521    /// The iterator will return a single result for each unique `Key` contained
522    /// in either `self` or `other`. If both collections contain a key, the
523    /// iterator will contain [`Unioned::Both`] for that key.
524    ///
525    /// This iterator is guaranteed to return results in the sort order of the
526    /// `Key` type.
527    #[must_use]
528    #[inline]
529    pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, Key, Value> {
530        Union {
531            left: self.iter().peekable(),
532            right: other.iter().peekable(),
533        }
534    }
535
536    /// Returns an iterator that yields entries that appear in both `self` and
537    /// `other`.
538    ///
539    /// The iterator will return a result for each `Key` contained in both
540    /// `self` and `other`. If a particular key is only found in one collection,
541    /// it will not be included.
542    ///
543    /// This iterator is guaranteed to return results in the sort order of the
544    /// `Key` type.
545    #[must_use]
546    #[inline]
547    pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, Key, Value> {
548        Intersection {
549            left: self.iter().peekable(),
550            right: other.iter().peekable(),
551        }
552    }
553
554    /// Returns an iterator that yields entries that appear in `self`, but not
555    /// in `other`.
556    ///
557    /// The iterator will return a result for each `Key` contained in `self` but
558    /// not contained in `other`. If a `Key` is only in `other` or is in both
559    /// collections, it will not be returned.
560    ///
561    /// This iterator is guaranteed to return results in the sort order of the
562    /// `Key` type.
563    #[must_use]
564    #[inline]
565    pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, Key, Value> {
566        Difference {
567            left: self.iter().peekable(),
568            right: other.iter().peekable(),
569        }
570    }
571}
572
573impl<'a, SearchFor, Key, V> core::ops::Index<&'a SearchFor> for Map<Key, V>
574where
575    Key: Sort<Key>,
576    Key: Sort<SearchFor>,
577    SearchFor: ?Sized,
578{
579    type Output = V;
580
581    fn index(&self, index: &'a SearchFor) -> &Self::Output {
582        self.get(index).expect("key not found")
583    }
584}
585
586impl<'a, SearchFor, Key, V> core::ops::IndexMut<&'a SearchFor> for Map<Key, V>
587where
588    Key: Sort<Key>,
589    Key: Sort<SearchFor>,
590    SearchFor: ?Sized,
591{
592    fn index_mut(&mut self, index: &'a SearchFor) -> &mut Self::Output {
593        self.get_mut(index).expect("key not found")
594    }
595}
596
597/// A key provided to the [`Map::entry`] function.
598///
599/// This is a [`Cow`](alloc::borrow::Cow)-like type that is slightly more
600/// flexible with `From` implementations. The `Owned` and `Borrowed` types are
601/// kept separate, allowing for more general `From` implementations.
602#[derive(Debug)]
603pub enum SearchKey<'key, Owned, Borrowed>
604where
605    Borrowed: ?Sized,
606{
607    /// A borrowed key.
608    Borrowed(&'key Borrowed),
609    /// An owned key.
610    Owned(Owned),
611}
612
613impl<'key, K> From<K> for SearchKey<'key, K, K> {
614    #[inline]
615    fn from(value: K) -> Self {
616        SearchKey::Owned(value)
617    }
618}
619
620impl<'key, Key, Borrowed> From<&'key Borrowed> for SearchKey<'key, Key, Borrowed>
621where
622    Borrowed: ?Sized,
623{
624    #[inline]
625    fn from(value: &'key Borrowed) -> Self {
626        SearchKey::Borrowed(value)
627    }
628}
629
630impl<'key, Key, Borrowed> SearchKey<'key, Key, Borrowed>
631where
632    Key: Borrow<Borrowed>,
633    Borrowed: ToOwned<Owned = Key> + ?Sized,
634{
635    #[inline]
636    fn as_ref(&self) -> &Borrowed {
637        match self {
638            SearchKey::Borrowed(key) => key,
639            SearchKey::Owned(owned) => owned.borrow(),
640        }
641    }
642
643    #[inline]
644    fn into_owned(self) -> Key {
645        match self {
646            SearchKey::Borrowed(key) => key.to_owned(),
647            SearchKey::Owned(owned) => owned,
648        }
649    }
650}
651
652impl<Key, Value> Debug for Map<Key, Value>
653where
654    Key: Debug + Sort<Key>,
655    Value: Debug,
656{
657    #[inline]
658    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
659        let mut s = f.debug_map();
660        for Field { key, value } in self {
661            s.entry(key, value);
662        }
663        s.finish()
664    }
665}
666
667impl<'a, Key, Value> IntoIterator for &'a Map<Key, Value>
668where
669    Key: Sort<Key>,
670{
671    type IntoIter = Iter<'a, Key, Value>;
672    type Item = &'a Field<Key, Value>;
673
674    #[inline]
675    fn into_iter(self) -> Self::IntoIter {
676        Iter(self.fields.iter())
677    }
678}
679
680impl<'a, Key, Value> IntoIterator for &'a mut Map<Key, Value>
681where
682    Key: Sort<Key>,
683{
684    type IntoIter = IterMut<'a, Key, Value>;
685    type Item = (&'a Key, &'a mut Value);
686
687    #[inline]
688    fn into_iter(self) -> Self::IntoIter {
689        IterMut(self.fields.iter_mut())
690    }
691}
692
693impl<Key, Value> IntoIterator for Map<Key, Value>
694where
695    Key: Sort<Key>,
696{
697    type IntoIter = IntoIter<Key, Value>;
698    type Item = Field<Key, Value>;
699
700    #[inline]
701    fn into_iter(self) -> Self::IntoIter {
702        IntoIter(self.fields.into_iter())
703    }
704}
705
706impl<Key, Value> FromIterator<(Key, Value)> for Map<Key, Value>
707where
708    Key: Sort<Key>,
709{
710    #[inline]
711    fn from_iter<T: IntoIterator<Item = (Key, Value)>>(iter: T) -> Self {
712        let iter = iter.into_iter();
713        let mut obj = Self::with_capacity(iter.size_hint().0);
714        // Insert out of order, then sort before returning.
715        for (key, value) in iter {
716            obj.fields.push(Field::new(key, value));
717        }
718        obj.fields.sort_unstable_by(|a, b| a.key().compare(b.key()));
719        obj
720    }
721}
722
723/// A field in an [`Map`].
724#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
725pub struct Field<Key, Value> {
726    key: Key,
727    /// The value contained in this field.
728    pub value: Value,
729}
730
731impl<Key, Value> Field<Key, Value> {
732    /// Returns a new field with `key` and `value`.
733    #[must_use]
734    #[inline]
735    pub fn new(key: Key, value: Value) -> Self {
736        Self { key, value }
737    }
738
739    /// Returns the key of this field.
740    #[inline]
741    pub fn key(&self) -> &Key {
742        &self.key
743    }
744
745    /// Converts this field into its key.
746    #[inline]
747    pub fn into_key(self) -> Key {
748        self.key
749    }
750
751    /// Returns this field as the contained key and value.
752    pub fn into_parts(self) -> (Key, Value) {
753        (self.key, self.value)
754    }
755}
756
757/// The result of looking up an entry by its key.
758#[derive(Debug)]
759pub enum Entry<'a, 'key, Key, Value, BorrowedKey>
760where
761    Key: Sort<Key>,
762    BorrowedKey: ?Sized,
763{
764    /// A field was found for the given key.
765    Occupied(OccupiedEntry<'a, Key, Value>),
766    /// A field was not found for the given key.
767    Vacant(VacantEntry<'a, 'key, Key, Value, BorrowedKey>),
768}
769
770impl<'a, 'key, Key, Value, BorrowedKey> Entry<'a, 'key, Key, Value, BorrowedKey>
771where
772    Key: Sort<Key>,
773    BorrowedKey: ?Sized,
774{
775    /// Invokes `update()` with the stored entry, if one was found.
776    #[must_use]
777    #[inline]
778    pub fn and_modify(mut self, update: impl FnOnce(&mut Value)) -> Self {
779        if let Self::Occupied(entry) = &mut self {
780            update(&mut *entry);
781        }
782
783        self
784    }
785
786    /// If an entry was not found for the given key, `contents` is invoked to
787    /// populate the entry. A mutable reference to the entry's value is
788    /// returned.
789    #[inline]
790    pub fn or_insert_with(self, contents: impl FnOnce() -> Value) -> &'a mut Value
791    where
792        Key: Borrow<BorrowedKey>,
793        BorrowedKey: ToOwned<Owned = Key>,
794    {
795        match self {
796            Entry::Occupied(entry) => entry.into_mut(),
797            Entry::Vacant(entry) => entry.insert(contents()),
798        }
799    }
800
801    /// If an entry was not found for the given key, `value` is inserted into
802    /// the entry.  A mutable reference to the entry's value is returned.
803    #[inline]
804    pub fn or_insert(self, value: Value) -> &'a mut Value
805    where
806        Key: Borrow<BorrowedKey>,
807        BorrowedKey: ToOwned<Owned = Key>,
808    {
809        match self {
810            Entry::Occupied(entry) => entry.into_mut(),
811            Entry::Vacant(entry) => entry.insert(value),
812        }
813    }
814
815    /// If this entry is vacant, it is populated with `Value::default()`. A
816    /// mutable reference to the entry's value is returned.
817    ///
818    /// This function does not change the entry if it is present.
819    #[inline]
820    pub fn or_default(self) -> &'a mut Value
821    where
822        Key: Borrow<BorrowedKey>,
823        BorrowedKey: ToOwned<Owned = Key>,
824        Value: Default,
825    {
826        #[allow(clippy::unwrap_or_default)] // This is the implementation of said function...
827        self.or_insert_with(Value::default)
828    }
829}
830
831/// An entry that exists in an [`Map`].
832#[derive(Debug)]
833pub struct OccupiedEntry<'a, Key, Value>
834where
835    Key: Sort<Key>,
836{
837    object: &'a mut Map<Key, Value>,
838    index: usize,
839}
840
841impl<'a, Key, Value> OccupiedEntry<'a, Key, Value>
842where
843    Key: Sort<Key>,
844{
845    #[inline]
846    fn new(object: &'a mut Map<Key, Value>, index: usize) -> Self {
847        Self { object, index }
848    }
849
850    #[inline]
851    fn field(&self) -> &Field<Key, Value> {
852        &self.object.fields[self.index]
853    }
854
855    #[inline]
856    fn field_mut(&mut self) -> &mut Field<Key, Value> {
857        &mut self.object.fields[self.index]
858    }
859
860    /// Converts this entry into a mutable reference to the value.
861    ///
862    /// This is different from `DerefMut` because the `DerefMut` extends the
863    /// lifetime to include `self`. This function extracts the reference with
864    /// the original lifetime of the map.
865    #[must_use]
866    #[inline]
867    pub fn into_mut(self) -> &'a mut Value {
868        &mut self.object.fields[self.index].value
869    }
870
871    /// Returns the key of this field.
872    #[must_use]
873    #[inline]
874    pub fn key(&self) -> &Key {
875        &self.field().key
876    }
877
878    /// Replaces the contents of this field with `value`, and returns the
879    /// existing value.
880    #[inline]
881    pub fn replace(self, value: Value) -> Value {
882        core::mem::replace(self.into_mut(), value)
883    }
884
885    /// Removes the entry from the map, and returns the value.
886    #[must_use]
887    #[inline]
888    pub fn remove(self) -> Field<Key, Value> {
889        self.object.fields.remove(self.index)
890    }
891}
892
893impl<'a, Key, Value> Deref for OccupiedEntry<'a, Key, Value>
894where
895    Key: Sort<Key>,
896{
897    type Target = Value;
898
899    #[inline]
900    fn deref(&self) -> &Self::Target {
901        &self.field().value
902    }
903}
904
905impl<'a, Key, Value> DerefMut for OccupiedEntry<'a, Key, Value>
906where
907    Key: Sort<Key>,
908{
909    #[inline]
910    fn deref_mut(&mut self) -> &mut Self::Target {
911        &mut self.field_mut().value
912    }
913}
914
915/// A vacant entry in an [`Map`].
916#[derive(Debug)]
917pub struct VacantEntry<'a, 'key, Key, Value, BorrowedKey>
918where
919    Key: Sort<Key>,
920    BorrowedKey: ?Sized,
921{
922    object: &'a mut Map<Key, Value>,
923    key: SearchKey<'key, Key, BorrowedKey>,
924    insert_at: usize,
925}
926
927impl<'a, 'key, Key, Value, BorrowedKey> VacantEntry<'a, 'key, Key, Value, BorrowedKey>
928where
929    Key: Borrow<BorrowedKey> + Sort<Key>,
930    BorrowedKey: ToOwned<Owned = Key> + ?Sized,
931{
932    #[inline]
933    fn new(
934        object: &'a mut Map<Key, Value>,
935        key: SearchKey<'key, Key, BorrowedKey>,
936        insert_at: usize,
937    ) -> Self {
938        Self {
939            object,
940            key,
941            insert_at,
942        }
943    }
944
945    /// Returns a reference to the key being inserted.
946    #[inline]
947    pub fn key(&self) -> &BorrowedKey {
948        self.key.as_ref()
949    }
950
951    /// Inserts `key` and `value` at this location in the object.
952    ///
953    /// # Panics
954    ///
955    /// This function panics if `key` does not match the original order of the
956    /// key that was passed to [`Map::entry()`].
957    #[inline]
958    pub fn insert(self, value: Value) -> &'a mut Value
959    where
960        Key: Borrow<BorrowedKey>,
961        BorrowedKey: ToOwned<Owned = Key>,
962    {
963        self.object
964            .fields
965            .insert(self.insert_at, Field::new(self.key.into_owned(), value));
966        &mut self.object.fields[self.insert_at].value
967    }
968}
969
970/// An iterator over the [`Field`]s in an [`Map`].
971pub struct Iter<'a, Key, Value>(slice::Iter<'a, Field<Key, Value>>);
972
973impl<'a, Key, Value> Iterator for Iter<'a, Key, Value> {
974    type Item = &'a Field<Key, Value>;
975
976    #[inline]
977    fn next(&mut self) -> Option<Self::Item> {
978        self.0.next()
979    }
980
981    #[inline]
982    fn size_hint(&self) -> (usize, Option<usize>) {
983        self.0.size_hint()
984    }
985
986    #[inline]
987    fn count(self) -> usize
988    where
989        Self: Sized,
990    {
991        self.0.count()
992    }
993
994    #[inline]
995    fn last(self) -> Option<Self::Item>
996    where
997        Self: Sized,
998    {
999        self.0.last()
1000    }
1001
1002    #[inline]
1003    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1004        self.0.nth(n)
1005    }
1006}
1007
1008impl<'a, Key, Value> ExactSizeIterator for Iter<'a, Key, Value> {
1009    #[inline]
1010    fn len(&self) -> usize {
1011        self.0.len()
1012    }
1013}
1014
1015impl<'a, Key, Value> DoubleEndedIterator for Iter<'a, Key, Value> {
1016    #[inline]
1017    fn next_back(&mut self) -> Option<Self::Item> {
1018        self.0.next_back()
1019    }
1020
1021    #[inline]
1022    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1023        self.0.nth_back(n)
1024    }
1025}
1026
1027impl<'a, Key, Value> FusedIterator for Iter<'a, Key, Value> {}
1028
1029/// An iterator over mutable [`Field`]s contained in an [`Map`].
1030pub struct IterMut<'a, Key, Value>(slice::IterMut<'a, Field<Key, Value>>);
1031
1032impl<'a, Key, Value> Iterator for IterMut<'a, Key, Value> {
1033    type Item = (&'a Key, &'a mut Value);
1034
1035    #[inline]
1036    fn next(&mut self) -> Option<Self::Item> {
1037        let field = self.0.next()?;
1038        Some((&field.key, &mut field.value))
1039    }
1040
1041    #[inline]
1042    fn size_hint(&self) -> (usize, Option<usize>) {
1043        self.0.size_hint()
1044    }
1045
1046    #[inline]
1047    fn count(self) -> usize
1048    where
1049        Self: Sized,
1050    {
1051        self.0.count()
1052    }
1053
1054    #[inline]
1055    fn last(self) -> Option<Self::Item>
1056    where
1057        Self: Sized,
1058    {
1059        self.0.last().map(|field| (&field.key, &mut field.value))
1060    }
1061
1062    #[inline]
1063    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1064        self.0.nth(n).map(|field| (&field.key, &mut field.value))
1065    }
1066}
1067
1068impl<'a, Key, Value> ExactSizeIterator for IterMut<'a, Key, Value> {
1069    #[inline]
1070    fn len(&self) -> usize {
1071        self.0.len()
1072    }
1073}
1074
1075impl<'a, Key, Value> DoubleEndedIterator for IterMut<'a, Key, Value> {
1076    #[inline]
1077    fn next_back(&mut self) -> Option<Self::Item> {
1078        self.0
1079            .next_back()
1080            .map(|field| (&field.key, &mut field.value))
1081    }
1082
1083    #[inline]
1084    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1085        self.0
1086            .nth_back(n)
1087            .map(|field| (&field.key, &mut field.value))
1088    }
1089}
1090
1091impl<'a, Key, Value> FusedIterator for IterMut<'a, Key, Value> {}
1092
1093/// An iterator that returns all of the elements of an [`Map`] while
1094/// freeing its underlying memory.
1095pub struct IntoIter<Key, Value>(vec::IntoIter<Field<Key, Value>>);
1096
1097impl<Key, Value> Iterator for IntoIter<Key, Value> {
1098    type Item = Field<Key, Value>;
1099
1100    #[inline]
1101    fn next(&mut self) -> Option<Self::Item> {
1102        self.0.next()
1103    }
1104
1105    #[inline]
1106    fn size_hint(&self) -> (usize, Option<usize>) {
1107        self.0.size_hint()
1108    }
1109
1110    #[inline]
1111    fn count(self) -> usize
1112    where
1113        Self: Sized,
1114    {
1115        self.0.count()
1116    }
1117
1118    #[inline]
1119    fn last(self) -> Option<Self::Item>
1120    where
1121        Self: Sized,
1122    {
1123        self.0.last()
1124    }
1125
1126    #[inline]
1127    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1128        self.0.nth(n)
1129    }
1130}
1131
1132impl<Key, Value> ExactSizeIterator for IntoIter<Key, Value> {
1133    #[inline]
1134    fn len(&self) -> usize {
1135        self.0.len()
1136    }
1137}
1138
1139impl<Key, Value> DoubleEndedIterator for IntoIter<Key, Value> {
1140    #[inline]
1141    fn next_back(&mut self) -> Option<Self::Item> {
1142        self.0.next_back()
1143    }
1144
1145    #[inline]
1146    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1147        self.0.nth_back(n)
1148    }
1149}
1150
1151impl<Key, Value> FusedIterator for IntoIter<Key, Value> {}
1152
1153/// An iterator over the keys in an [`Map`].
1154pub struct Keys<'a, Key, Value>(slice::Iter<'a, Field<Key, Value>>);
1155
1156impl<'a, Key, Value> Iterator for Keys<'a, Key, Value> {
1157    type Item = &'a Key;
1158
1159    #[inline]
1160    fn next(&mut self) -> Option<Self::Item> {
1161        self.0.next().map(Field::key)
1162    }
1163
1164    #[inline]
1165    fn size_hint(&self) -> (usize, Option<usize>) {
1166        self.0.size_hint()
1167    }
1168
1169    #[inline]
1170    fn count(self) -> usize
1171    where
1172        Self: Sized,
1173    {
1174        self.0.count()
1175    }
1176
1177    #[inline]
1178    fn last(self) -> Option<Self::Item>
1179    where
1180        Self: Sized,
1181    {
1182        self.0.last().map(Field::key)
1183    }
1184
1185    #[inline]
1186    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1187        self.0.nth(n).map(Field::key)
1188    }
1189}
1190
1191impl<'a, Key, Value> ExactSizeIterator for Keys<'a, Key, Value> {
1192    #[inline]
1193    fn len(&self) -> usize {
1194        self.0.len()
1195    }
1196}
1197
1198impl<'a, Key, Value> DoubleEndedIterator for Keys<'a, Key, Value> {
1199    #[inline]
1200    fn next_back(&mut self) -> Option<Self::Item> {
1201        self.0.next_back().map(Field::key)
1202    }
1203
1204    #[inline]
1205    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1206        self.0.nth_back(n).map(Field::key)
1207    }
1208}
1209
1210impl<'a, Key, Value> FusedIterator for Keys<'a, Key, Value> {}
1211
1212/// An iterator converting a [`Map`] into a series of owned keys.
1213pub struct IntoKeys<Key, Value>(vec::IntoIter<Field<Key, Value>>);
1214
1215impl<Key, Value> Iterator for IntoKeys<Key, Value> {
1216    type Item = Key;
1217
1218    #[inline]
1219    fn next(&mut self) -> Option<Self::Item> {
1220        self.0.next().map(Field::into_key)
1221    }
1222
1223    #[inline]
1224    fn size_hint(&self) -> (usize, Option<usize>) {
1225        self.0.size_hint()
1226    }
1227
1228    #[inline]
1229    fn count(self) -> usize
1230    where
1231        Self: Sized,
1232    {
1233        self.0.count()
1234    }
1235
1236    #[inline]
1237    fn last(self) -> Option<Self::Item>
1238    where
1239        Self: Sized,
1240    {
1241        self.0.last().map(Field::into_key)
1242    }
1243
1244    #[inline]
1245    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1246        self.0.nth(n).map(Field::into_key)
1247    }
1248}
1249
1250impl<Key, Value> ExactSizeIterator for IntoKeys<Key, Value> {
1251    #[inline]
1252    fn len(&self) -> usize {
1253        self.0.len()
1254    }
1255}
1256
1257impl<Key, Value> DoubleEndedIterator for IntoKeys<Key, Value> {
1258    #[inline]
1259    fn next_back(&mut self) -> Option<Self::Item> {
1260        self.0.next_back().map(Field::into_key)
1261    }
1262
1263    #[inline]
1264    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1265        self.0.nth_back(n).map(Field::into_key)
1266    }
1267}
1268
1269impl<Key, Value> FusedIterator for IntoKeys<Key, Value> {}
1270
1271/// An iterator over the values contained in an [`Map`].
1272pub struct Values<'a, Key, Value>(slice::Iter<'a, Field<Key, Value>>);
1273
1274impl<'a, Key, Value> Iterator for Values<'a, Key, Value> {
1275    type Item = &'a Value;
1276
1277    #[inline]
1278    fn next(&mut self) -> Option<Self::Item> {
1279        let field = self.0.next()?;
1280        Some(&field.value)
1281    }
1282
1283    #[inline]
1284    fn size_hint(&self) -> (usize, Option<usize>) {
1285        self.0.size_hint()
1286    }
1287
1288    #[inline]
1289    fn count(self) -> usize
1290    where
1291        Self: Sized,
1292    {
1293        self.0.count()
1294    }
1295
1296    #[inline]
1297    fn last(self) -> Option<Self::Item>
1298    where
1299        Self: Sized,
1300    {
1301        self.0.last().map(|field| &field.value)
1302    }
1303
1304    #[inline]
1305    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1306        self.0.nth(n).map(|field| &field.value)
1307    }
1308}
1309
1310impl<'a, Key, Value> ExactSizeIterator for Values<'a, Key, Value> {
1311    #[inline]
1312    fn len(&self) -> usize {
1313        self.0.len()
1314    }
1315}
1316
1317impl<'a, Key, Value> DoubleEndedIterator for Values<'a, Key, Value> {
1318    #[inline]
1319    fn next_back(&mut self) -> Option<Self::Item> {
1320        self.0.next_back().map(|field| &field.value)
1321    }
1322
1323    #[inline]
1324    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1325        self.0.nth_back(n).map(|field| &field.value)
1326    }
1327}
1328
1329impl<'a, Key, Value> FusedIterator for Values<'a, Key, Value> {}
1330
1331/// An iterator over mutable values contained in an [`Map`].
1332pub struct ValuesMut<'a, Key, Value>(slice::IterMut<'a, Field<Key, Value>>);
1333
1334impl<'a, Key, Value> Iterator for ValuesMut<'a, Key, Value> {
1335    type Item = &'a mut Value;
1336
1337    #[inline]
1338    fn next(&mut self) -> Option<Self::Item> {
1339        let field = self.0.next()?;
1340        Some(&mut field.value)
1341    }
1342
1343    #[inline]
1344    fn size_hint(&self) -> (usize, Option<usize>) {
1345        self.0.size_hint()
1346    }
1347
1348    #[inline]
1349    fn count(self) -> usize
1350    where
1351        Self: Sized,
1352    {
1353        self.0.count()
1354    }
1355
1356    #[inline]
1357    fn last(self) -> Option<Self::Item>
1358    where
1359        Self: Sized,
1360    {
1361        self.0.last().map(|field| &mut field.value)
1362    }
1363
1364    #[inline]
1365    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1366        self.0.nth(n).map(|field| &mut field.value)
1367    }
1368}
1369
1370impl<'a, Key, Value> ExactSizeIterator for ValuesMut<'a, Key, Value> {
1371    #[inline]
1372    fn len(&self) -> usize {
1373        self.0.len()
1374    }
1375}
1376
1377impl<'a, Key, Value> DoubleEndedIterator for ValuesMut<'a, Key, Value> {
1378    #[inline]
1379    fn next_back(&mut self) -> Option<Self::Item> {
1380        self.0.next_back().map(|field| &mut field.value)
1381    }
1382
1383    #[inline]
1384    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1385        self.0.nth_back(n).map(|field| &mut field.value)
1386    }
1387}
1388
1389impl<'a, Key, Value> FusedIterator for ValuesMut<'a, Key, Value> {}
1390
1391/// An iterator returning all of the values contained in an [`Map`] as its
1392/// underlying storage is freed.
1393pub struct IntoValues<Key, Value>(vec::IntoIter<Field<Key, Value>>);
1394
1395impl<Key, Value> Iterator for IntoValues<Key, Value> {
1396    type Item = Value;
1397
1398    #[inline]
1399    fn next(&mut self) -> Option<Self::Item> {
1400        let field = self.0.next()?;
1401        Some(field.value)
1402    }
1403
1404    #[inline]
1405    fn size_hint(&self) -> (usize, Option<usize>) {
1406        self.0.size_hint()
1407    }
1408
1409    #[inline]
1410    fn count(self) -> usize
1411    where
1412        Self: Sized,
1413    {
1414        self.0.count()
1415    }
1416
1417    #[inline]
1418    fn last(self) -> Option<Self::Item>
1419    where
1420        Self: Sized,
1421    {
1422        self.0.last().map(|field| field.value)
1423    }
1424
1425    #[inline]
1426    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1427        self.0.nth(n).map(|field| field.value)
1428    }
1429}
1430
1431impl<Key, Value> ExactSizeIterator for IntoValues<Key, Value> {
1432    #[inline]
1433    fn len(&self) -> usize {
1434        self.0.len()
1435    }
1436}
1437
1438impl<Key, Value> DoubleEndedIterator for IntoValues<Key, Value> {
1439    #[inline]
1440    fn next_back(&mut self) -> Option<Self::Item> {
1441        self.0.next_back().map(|field| field.value)
1442    }
1443
1444    #[inline]
1445    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1446        self.0.nth_back(n).map(|field| field.value)
1447    }
1448}
1449
1450impl<Key, Value> FusedIterator for IntoValues<Key, Value> {}
1451
1452/// An iterator that removes all of the [`Field`]s of an [`Map`].
1453///
1454/// When this iterator is dropped, the underlying [`Map`] will be empty
1455/// regardless of whether the iterator has been fully exhausted.
1456pub struct Drain<'a, Key, Value>(vec::Drain<'a, Field<Key, Value>>);
1457
1458impl<'a, Key, Value> Iterator for Drain<'a, Key, Value> {
1459    type Item = Field<Key, Value>;
1460
1461    #[inline]
1462    fn next(&mut self) -> Option<Self::Item> {
1463        self.0.next()
1464    }
1465
1466    #[inline]
1467    fn size_hint(&self) -> (usize, Option<usize>) {
1468        self.0.size_hint()
1469    }
1470
1471    #[inline]
1472    fn count(self) -> usize
1473    where
1474        Self: Sized,
1475    {
1476        self.0.count()
1477    }
1478
1479    #[inline]
1480    fn last(self) -> Option<Self::Item>
1481    where
1482        Self: Sized,
1483    {
1484        self.0.last()
1485    }
1486
1487    #[inline]
1488    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1489        self.0.nth(n)
1490    }
1491}
1492
1493impl<'a, Key, Value> ExactSizeIterator for Drain<'a, Key, Value> {
1494    #[inline]
1495    fn len(&self) -> usize {
1496        self.0.len()
1497    }
1498}
1499
1500impl<'a, Key, Value> DoubleEndedIterator for Drain<'a, Key, Value> {
1501    #[inline]
1502    fn next_back(&mut self) -> Option<Self::Item> {
1503        self.0.next_back()
1504    }
1505
1506    #[inline]
1507    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
1508        self.0.nth_back(n)
1509    }
1510}
1511
1512impl<'a, Key, Value> FusedIterator for Drain<'a, Key, Value> {}
1513
1514/// An iterator that yields [`Unioned`] entries for two [`Map`]s.
1515///
1516/// The iterator will return a single result for each unique `Key` contained in
1517/// either map. If both collections contain a key, the iterator will contain
1518/// [`Unioned::Both`] for that key.
1519///
1520/// This iterator is guaranteed to return results in the sort order of the `Key`
1521/// type.
1522pub struct Union<'a, K, V>
1523where
1524    K: Sort,
1525{
1526    left: Peekable<Iter<'a, K, V>>,
1527    right: Peekable<Iter<'a, K, V>>,
1528}
1529
1530impl<'a, K, V> Iterator for Union<'a, K, V>
1531where
1532    K: Sort,
1533{
1534    type Item = Unioned<'a, K, V>;
1535
1536    #[inline]
1537    fn next(&mut self) -> Option<Self::Item> {
1538        if let Some(left) = self.left.peek() {
1539            if let Some(right) = self.right.peek() {
1540                match left.key().compare(right.key()) {
1541                    Ordering::Less => Some(Unioned::left(self.left.next().expect("just peeked"))),
1542                    Ordering::Equal => Some(Unioned::both(
1543                        self.left.next().expect("just peeked"),
1544                        self.right.next().expect("just peeked"),
1545                    )),
1546                    Ordering::Greater => {
1547                        Some(Unioned::right(self.right.next().expect("just peeked")))
1548                    }
1549                }
1550            } else {
1551                Some(Unioned::left(self.left.next().expect("just peeked")))
1552            }
1553        } else {
1554            self.right.next().map(Unioned::right)
1555        }
1556    }
1557
1558    #[inline]
1559    fn size_hint(&self) -> (usize, Option<usize>) {
1560        (self.left.len(), Some(self.left.len() + self.right.len()))
1561    }
1562}
1563
1564/// A unioned entry from a [`Union`] iterator. An entry can be from the left,
1565/// right, or both maps.
1566pub enum Unioned<'a, K, V> {
1567    /// The `self`/left map contained this key/value pair.
1568    Left {
1569        /// The key of the entry.
1570        key: &'a K,
1571        /// The value of the entry.
1572        value: &'a V,
1573    },
1574    /// The `other`/right map contained this key/value pair.
1575    Right {
1576        /// The key of the entry.
1577        key: &'a K,
1578        /// The value of the entry.
1579        value: &'a V,
1580    },
1581    /// Both maps contained this `key`.
1582    Both {
1583        /// The key of the entry.
1584        key: &'a K,
1585        /// The value of the `self`/left entry.
1586        left: &'a V,
1587        /// The value of the `other`/right entry.
1588        right: &'a V,
1589    },
1590}
1591
1592impl<'a, K, V> Unioned<'a, K, V> {
1593    /// If `self` is [`Unioned::Both`] `merge` will be called to produce a
1594    /// single value. If `self` is either [`Unioned::Left`] or
1595    /// [`Unioned::Right`], the key/value will be returned without calling
1596    /// `merge`.
1597    ///
1598    /// ```rust
1599    /// use kempt::Map;
1600    ///
1601    /// fn merge(a: &Map<String, u32>, b: &Map<String, u32>) -> Map<String, u32> {
1602    ///     a.union(b)
1603    ///         .map(|unioned| {
1604    ///             unioned
1605    ///                 .map_both(|_key, left, right| *left + *right)
1606    ///                 .into_owned()
1607    ///         })
1608    ///         .collect()
1609    /// }
1610    ///
1611    /// let mut a = Map::new();
1612    /// a.insert(String::from("a"), 1);
1613    /// a.insert(String::from("b"), 1);
1614    /// a.insert(String::from("c"), 1);
1615    /// let mut b = Map::new();
1616    /// b.insert(String::from("b"), 1);
1617    ///
1618    /// let merged = merge(&a, &b);
1619    /// assert_eq!(merged.get("a"), Some(&1));
1620    /// assert_eq!(merged.get("b"), Some(&2));
1621    /// ```
1622    #[inline]
1623    pub fn map_both<R>(self, merge: impl FnOnce(&'a K, &'a V, &'a V) -> R) -> EntryRef<'a, K, V>
1624    where
1625        R: Into<OwnedOrRef<'a, V>>,
1626    {
1627        match self {
1628            Unioned::Left { key, value } | Unioned::Right { key, value } => EntryRef {
1629                key,
1630                value: OwnedOrRef::Ref(value),
1631            },
1632            Unioned::Both { key, left, right } => EntryRef {
1633                key,
1634                value: merge(key, left, right).into(),
1635            },
1636        }
1637    }
1638}
1639
1640impl<'a, K, V> Unioned<'a, K, V> {
1641    fn both(left: &'a Field<K, V>, right: &'a Field<K, V>) -> Self {
1642        Self::Both {
1643            key: left.key(),
1644            left: &left.value,
1645            right: &right.value,
1646        }
1647    }
1648
1649    fn left(field: &'a Field<K, V>) -> Self {
1650        Self::Left {
1651            key: field.key(),
1652            value: &field.value,
1653        }
1654    }
1655
1656    fn right(field: &'a Field<K, V>) -> Self {
1657        Self::Right {
1658            key: field.key(),
1659            value: &field.value,
1660        }
1661    }
1662}
1663
1664/// A reference to a key from a [`Map`] and an associated value.
1665pub struct EntryRef<'a, K, V> {
1666    /// The key of the entry.
1667    pub key: &'a K,
1668    /// The associated value of this key.
1669    pub value: OwnedOrRef<'a, V>,
1670}
1671
1672impl<'a, K, V> EntryRef<'a, K, V> {
1673    /// Returns the owned versions of the contained key and value, cloning as
1674    /// needed.
1675    #[inline]
1676    pub fn into_owned(self) -> (K, V)
1677    where
1678        K: Clone,
1679        V: Clone,
1680    {
1681        (self.key.clone(), self.value.into_owned())
1682    }
1683}
1684
1685/// An owned value or a reference to a value of that type.
1686///
1687/// This type is similar to [`alloc::borrow::Cow`] except that it does not
1688/// require that the contained type implement `ToOwned`.
1689pub enum OwnedOrRef<'a, K> {
1690    /// An owned value.
1691    Owned(K),
1692    /// A reference to a value.
1693    Ref(&'a K),
1694}
1695
1696impl<'a, K> OwnedOrRef<'a, K> {
1697    /// Converts the contained value into an owned representation, cloning only
1698    /// if needed.
1699    #[inline]
1700    pub fn into_owned(self) -> K
1701    where
1702        K: Clone,
1703    {
1704        match self {
1705            OwnedOrRef::Owned(owned) => owned,
1706            OwnedOrRef::Ref(r) => r.clone(),
1707        }
1708    }
1709}
1710
1711impl<K> From<K> for OwnedOrRef<'_, K> {
1712    #[inline]
1713    fn from(value: K) -> Self {
1714        Self::Owned(value)
1715    }
1716}
1717
1718impl<'a, K> From<&'a K> for OwnedOrRef<'a, K> {
1719    #[inline]
1720    fn from(value: &'a K) -> Self {
1721        Self::Ref(value)
1722    }
1723}
1724
1725/// An iterator that yields entries that appear in two maps.
1726///
1727/// The iterator will return a result for each `Key` contained in both maps. If
1728/// a particular key is only found in one collection, it will not be included.
1729///
1730/// This iterator is guaranteed to return results in the sort order of the `Key`
1731/// type.
1732pub struct Intersection<'a, K, V>
1733where
1734    K: Sort,
1735{
1736    left: Peekable<Iter<'a, K, V>>,
1737    right: Peekable<Iter<'a, K, V>>,
1738}
1739
1740impl<'a, K, V> Iterator for Intersection<'a, K, V>
1741where
1742    K: Sort,
1743{
1744    type Item = (&'a K, &'a V, &'a V);
1745
1746    #[inline]
1747    fn next(&mut self) -> Option<Self::Item> {
1748        loop {
1749            let left = self.left.peek()?;
1750            let right = self.right.peek()?;
1751            match left.key().compare(right.key()) {
1752                Ordering::Less => {
1753                    let _skipped = self.left.next();
1754                }
1755                Ordering::Equal => {
1756                    let left = self.left.next().expect("just peeked");
1757                    let right = self.right.next().expect("just peeked");
1758                    return Some((left.key(), &left.value, &right.value));
1759                }
1760                Ordering::Greater => {
1761                    let _skipped = self.right.next();
1762                }
1763            }
1764        }
1765    }
1766
1767    #[inline]
1768    fn size_hint(&self) -> (usize, Option<usize>) {
1769        (0, Some(self.left.len().min(self.right.len())))
1770    }
1771}
1772
1773/// An iterator over the difference between two [`Map`]s.
1774///
1775/// This iterator will return a result for each `Key` contained in `self` but
1776/// not contained in `other`. If a `Key` is only in `other` or is in both
1777/// collections, it will not be returned.
1778///
1779/// This iterator is guaranteed to return results in the sort order of the `Key`
1780/// type.
1781pub struct Difference<'a, K, V>
1782where
1783    K: Sort,
1784{
1785    left: Peekable<Iter<'a, K, V>>,
1786    right: Peekable<Iter<'a, K, V>>,
1787}
1788
1789impl<'a, K, V> Iterator for Difference<'a, K, V>
1790where
1791    K: Sort,
1792{
1793    type Item = (&'a K, &'a V);
1794
1795    #[inline]
1796    fn next(&mut self) -> Option<Self::Item> {
1797        loop {
1798            let left = self.left.peek()?;
1799            if let Some(right) = self.right.peek() {
1800                match left.key().compare(right.key()) {
1801                    Ordering::Less => {
1802                        let left = self.left.next().expect("just peeked");
1803                        return Some((left.key(), &left.value));
1804                    }
1805                    Ordering::Equal => {
1806                        let _left = self.left.next();
1807                        let _right = self.right.next();
1808                    }
1809                    Ordering::Greater => {
1810                        let _skipped = self.right.next();
1811                    }
1812                }
1813            } else {
1814                let left = self.left.next().expect("just peeked");
1815                return Some((left.key(), &left.value));
1816            }
1817        }
1818    }
1819
1820    #[inline]
1821    fn size_hint(&self) -> (usize, Option<usize>) {
1822        (0, Some(self.left.len()))
1823    }
1824}