1
use alloc::borrow::ToOwned;
2
use alloc::vec::{self, Vec};
3
use core::alloc::Layout;
4
use core::borrow::Borrow;
5
use core::cmp::Ordering;
6
use core::fmt::{self, Debug};
7
use core::iter::{FusedIterator, Peekable};
8
use core::ops::{Deref, DerefMut};
9
use core::{mem, slice};
10

            
11
use 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
26
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
25
pub struct Map<Key, Value>
26
where
27
    Key: Sort<Key>,
28
{
29
    fields: Vec<Field<Key, Value>>,
30
}
31

            
32
impl<Key, Value> Default for Map<Key, Value>
33
where
34
    Key: Sort<Key>,
35
{
36
    #[inline]
37
1
    fn default() -> Self {
38
1
        Self::new()
39
1
    }
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.
48
3
const fn scan_limit<Key, Value>() -> usize {
49
3
    let field_layout = Layout::new::<Field<Key, Value>>();
50
3
    let align = field_layout.align();
51
3
    let aligned = ((field_layout.size() + (align - 1)) / align) * align;
52
3
    if aligned == 0 {
53
        return 1;
54
3
    }
55
3

            
56
3
    let scan_limit = 128 / aligned;
57
3
    if scan_limit > 16 {
58
1
        16
59
2
    } else if scan_limit < 4 {
60
1
        4
61
    } else {
62
1
        scan_limit
63
    }
64
3
}
65

            
66
1
#[test]
67
1
fn scan_limit_tests() {
68
1
    // Small sizes seem better to narrow down via binary search up until ~16
69
1
    // elements.
70
1
    assert_eq!(scan_limit::<u8, ()>(), 16);
71
    // Test a mid-point of the heuristic.
72
1
    assert_eq!(scan_limit::<u64, u64>(), 8);
73
    // Large field sizes only scan chunks of 4.
74
1
    assert_eq!(scan_limit::<(u128, u128), (u128, u128)>(), 4);
75
1
}
76

            
77
impl<Key, Value> Map<Key, Value>
78
where
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
13
    pub const fn new() -> Self {
87
13
        Self { fields: Vec::new() }
88
13
    }
89

            
90
    /// Returns a map with enough memory allocated to store `capacity` elements
91
    /// without reallocation.
92
    #[must_use]
93
    #[inline]
94
114
    pub fn with_capacity(capacity: usize) -> Self {
95
114
        Self {
96
114
            fields: Vec::with_capacity(capacity),
97
114
        }
98
114
    }
99

            
100
    /// Returns the current capacity this map can hold before it must
101
    /// reallocate.
102
    #[must_use]
103
    #[inline]
104
13
    pub fn capacity(&self) -> usize {
105
13
        self.fields.capacity()
106
13
    }
107

            
108
    /// Inserts `key` and `value`. If an entry already existed for `key`, the
109
    /// value being overwritten is returned.
110
    #[inline]
111
8262
    pub fn insert(&mut self, key: Key, value: Value) -> Option<Field<Key, Value>> {
112
8262
        let field = Field::new(key, value);
113
8262
        match self.find_key_mut(&field.key) {
114
2
            Ok(existing) => Some(mem::replace(existing, field)),
115
8260
            Err(insert_at) => {
116
8260
                self.fields.insert(insert_at, field);
117
8260
                None
118
            }
119
        }
120
8262
    }
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
14
    pub fn insert_with(&mut self, key: Key, value: impl FnOnce() -> Value) -> Option<Key> {
133
14
        match self.find_key_index(&key) {
134
13
            Err(insert_at) => {
135
13
                self.fields.insert(insert_at, Field::new(key, value()));
136
13
                None
137
            }
138
1
            Ok(_) => Some(key),
139
        }
140
14
    }
141

            
142
    /// Returns true if this object contains `key`.
143
    #[inline]
144
6
    pub fn contains<SearchFor>(&self, key: &SearchFor) -> bool
145
6
    where
146
6
        Key: Sort<SearchFor>,
147
6
        SearchFor: ?Sized,
148
6
    {
149
6
        self.find_key_index(key).is_ok()
150
6
    }
151

            
152
    /// Returns the value associated with `key`, if found.
153
    #[inline]
154
138
    pub fn get<SearchFor>(&self, key: &SearchFor) -> Option<&Value>
155
138
    where
156
138
        Key: Sort<SearchFor>,
157
138
        SearchFor: ?Sized,
158
138
    {
159
138
        self.get_field(key).map(|field| &field.value)
160
138
    }
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
139
    pub fn get_field<SearchFor>(&self, key: &SearchFor) -> Option<&Field<Key, Value>>
175
139
    where
176
139
        Key: Sort<SearchFor>,
177
139
        SearchFor: ?Sized,
178
139
    {
179
139
        self.find_key(key).ok()
180
139
    }
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
5
    pub fn field(&self, index: usize) -> Option<&Field<Key, Value>> {
198
5
        self.fields.get(index)
199
5
    }
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
1
    pub fn field_mut(&mut self, index: usize) -> Option<&mut Field<Key, Value>> {
206
1
        self.fields.get_mut(index)
207
1
    }
208

            
209
    /// Removes the value associated with `key`, if found.
210
    #[inline]
211
26
    pub fn remove<SearchFor>(&mut self, key: &SearchFor) -> Option<Field<Key, Value>>
212
26
    where
213
26
        Key: Sort<SearchFor>,
214
26
        SearchFor: ?Sized,
215
26
    {
216
26
        let index = self.find_key_index(key).ok()?;
217
25
        Some(self.remove_by_index(index))
218
26
    }
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
25
    pub fn remove_by_index(&mut self, index: usize) -> Field<Key, Value> {
228
25
        self.fields.remove(index)
229
25
    }
230

            
231
    /// Returns the number of fields in this object.
232
    #[must_use]
233
    #[inline]
234
132
    pub fn len(&self) -> usize {
235
132
        self.fields.len()
236
132
    }
237

            
238
    /// Returns true if this object has no fields.
239
    #[must_use]
240
    #[inline]
241
5
    pub fn is_empty(&self) -> bool {
242
5
        self.fields.is_empty()
243
5
    }
244

            
245
    /// Returns an [`Entry`] for the associated key.
246
    #[inline]
247
16
    pub fn entry<'key, SearchFor>(
248
16
        &mut self,
249
16
        key: impl Into<SearchKey<'key, Key, SearchFor>>,
250
16
    ) -> Entry<'_, 'key, Key, Value, SearchFor>
251
16
    where
252
16
        Key: Sort<SearchFor> + Borrow<SearchFor>,
253
16
        SearchFor: ToOwned<Owned = Key> + ?Sized + 'key,
254
16
    {
255
16
        let key = key.into();
256
16
        match self.find_key_index(key.as_ref()) {
257
6
            Ok(index) => Entry::Occupied(OccupiedEntry::new(self, index)),
258
10
            Err(insert_at) => Entry::Vacant(VacantEntry::new(self, key, insert_at)),
259
        }
260
16
    }
261

            
262
139
    fn find_key<SearchFor>(&self, search_for: &SearchFor) -> Result<&Field<Key, Value>, usize>
263
139
    where
264
139
        Key: Sort<SearchFor>,
265
139
        SearchFor: ?Sized,
266
139
    {
267
139
        self.find_key_index(search_for)
268
139
            .map(|index| &self.fields[index])
269
139
    }
270

            
271
8262
    fn find_key_mut<SearchFor>(
272
8262
        &mut self,
273
8262
        search_for: &SearchFor,
274
8262
    ) -> Result<&mut Field<Key, Value>, usize>
275
8262
    where
276
8262
        Key: Sort<SearchFor>,
277
8262
        SearchFor: ?Sized,
278
8262
    {
279
8262
        self.find_key_index(search_for)
280
8262
            .map(|index| &mut self.fields[index])
281
8262
    }
282

            
283
8463
    fn find_key_index<SearchFor>(&self, search_for: &SearchFor) -> Result<usize, usize>
284
8463
    where
285
8463
        Key: Sort<SearchFor>,
286
8463
        SearchFor: ?Sized,
287
8463
    {
288
8463
        // When the collection contains `Self::SCAN_LIMIT` or fewer elements,
289
8463
        // there should be no jumps before we reach a sequential scan for the
290
8463
        // key. When the collection is larger, we use a binary search to narrow
291
8463
        // the search window until the window is 16 elements or less.
292
8463
        let mut min = 0;
293
8463
        let field_count = self.fields.len();
294
8463
        let mut max = field_count;
295
44116
        loop {
296
44116
            let delta = max - min;
297
44116
            if delta <= Self::SCAN_LIMIT {
298
56544
                for (relative_index, field) in self.fields[min..max].iter().enumerate() {
299
56544
                    let comparison =
300
56544
                        <Key as crate::Sort<SearchFor>>::compare(&field.key, search_for);
301
56544
                    return match comparison {
302
52651
                        Ordering::Less => continue,
303
167
                        Ordering::Equal => Ok(min + relative_index),
304
3726
                        Ordering::Greater => Err(min + relative_index),
305
                    };
306
                }
307

            
308
4561
                return Err(max);
309
35662
            }
310
35662

            
311
35662
            let midpoint = min + delta / 2;
312
35662
            let comparison =
313
35662
                <Key as crate::Sort<SearchFor>>::compare(&self.fields[midpoint].key, search_for);
314
35662

            
315
35662
            match comparison {
316
26402
                Ordering::Less => min = midpoint + 1,
317
9
                Ordering::Equal => return Ok(midpoint),
318
9251
                Ordering::Greater => max = midpoint,
319
            }
320
        }
321
8463
    }
322

            
323
    /// Returns an iterator over the fields in this object.
324
    #[must_use]
325
    #[inline]
326
17
    pub fn iter(&self) -> Iter<'_, Key, Value> {
327
17
        self.into_iter()
328
17
    }
329

            
330
    /// Returns an iterator over the fields in this object, with mutable access.
331
    #[must_use]
332
    #[inline]
333
1
    pub fn iter_mut(&mut self) -> IterMut<'_, Key, Value> {
334
1
        self.into_iter()
335
1
    }
336

            
337
    /// Returns an iterator over the keys in this object.
338
    #[must_use]
339
    #[inline]
340
2
    pub fn keys(&self) -> Keys<'_, Key, Value> {
341
2
        Keys(self.fields.iter())
342
2
    }
343

            
344
    /// Returns an iterator over the values in this object.
345
    #[must_use]
346
    #[inline]
347
1
    pub fn values(&self) -> Values<'_, Key, Value> {
348
1
        Values(self.fields.iter())
349
1
    }
350

            
351
    /// Returns an iterator over the fields in this object, with mutable access.
352
    #[must_use]
353
    #[inline]
354
1
    pub fn values_mut(&mut self) -> ValuesMut<'_, Key, Value> {
355
1
        ValuesMut(self.fields.iter_mut())
356
1
    }
357

            
358
    /// Returns an iterator returning all of the values contained in this
359
    /// object.
360
    #[must_use]
361
    #[inline]
362
1
    pub fn into_values(self) -> IntoValues<Key, Value> {
363
1
        IntoValues(self.fields.into_iter())
364
1
    }
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
2
    pub fn merged_with(
394
2
        mut self,
395
2
        other: &Self,
396
2
        filter: impl FnMut(&Key, &Value) -> Option<Value>,
397
2
        merge: impl FnMut(&Key, &mut Value, &Value),
398
2
    ) -> Self
399
2
    where
400
2
        Key: Clone,
401
2
        Value: Clone,
402
2
    {
403
2
        self.merge_with(other, filter, merge);
404
2
        self
405
2
    }
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
2
    pub fn merge_with(
430
2
        &mut self,
431
2
        other: &Self,
432
2
        mut filter: impl FnMut(&Key, &Value) -> Option<Value>,
433
2
        mut merge: impl FnMut(&Key, &mut Value, &Value),
434
2
    ) where
435
2
        Key: Clone,
436
2
    {
437
2
        let mut self_index = 0;
438
2
        let mut other_index = 0;
439

            
440
61
        while self_index < self.len() && other_index < other.len() {
441
59
            let self_field = &mut self.fields[self_index];
442
59
            let other_field = &other.fields[other_index];
443
59
            match Key::compare(&self_field.key, &other_field.key) {
444
27
                Ordering::Less => {
445
27
                    // Self has a key that other didn't.
446
27
                    self_index += 1;
447
27
                }
448
13
                Ordering::Equal => {
449
13
                    // Both have the value, we might need to merge.
450
13
                    self_index += 1;
451
13
                    other_index += 1;
452
13
                    merge(&self_field.key, &mut self_field.value, &other_field.value);
453
13
                }
454
                Ordering::Greater => {
455
                    // Other has a value that self doesn't.
456
19
                    other_index += 1;
457
19
                    let Some(value) = filter(&other_field.key, &other_field.value) else {
458
6
                        continue;
459
                    };
460

            
461
13
                    self.fields
462
13
                        .insert(self_index, Field::new(other_field.key.clone(), value));
463
13
                    self_index += 1;
464
                }
465
            }
466
        }
467

            
468
2
        if other_index < other.fields.len() {
469
            // Other has more entries that we don't have
470
50
            for field in &other.fields[other_index..] {
471
50
                let Some(value) = filter(&field.key, &field.value) else {
472
9
                    continue;
473
                };
474

            
475
41
                self.fields.push(Field::new(field.key.clone(), value));
476
            }
477
        }
478
2
    }
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
1
    pub fn drain(&mut self) -> Drain<'_, Key, Value> {
484
1
        Drain(self.fields.drain(..))
485
1
    }
486

            
487
    /// Clears the contents of this collection.
488
    ///
489
    /// This does not return any allocated memory to the OS.
490
    #[inline]
491
2
    pub fn clear(&mut self) {
492
2
        self.fields.clear();
493
2
    }
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
2
    pub fn shrink_to_fit(&mut self) {
502
2
        self.fields.shrink_to_fit();
503
2
    }
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
2
    pub fn shrink_to(&mut self, min_capacity: usize) {
516
2
        self.fields.shrink_to(min_capacity);
517
2
    }
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
4
    pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, Key, Value> {
530
4
        Union {
531
4
            left: self.iter().peekable(),
532
4
            right: other.iter().peekable(),
533
4
        }
534
4
    }
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
2
    pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, Key, Value> {
548
2
        Intersection {
549
2
            left: self.iter().peekable(),
550
2
            right: other.iter().peekable(),
551
2
        }
552
2
    }
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
2
    pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, Key, Value> {
566
2
        Difference {
567
2
            left: self.iter().peekable(),
568
2
            right: other.iter().peekable(),
569
2
        }
570
2
    }
571
}
572

            
573
impl<'a, SearchFor, Key, V> core::ops::Index<&'a SearchFor> for Map<Key, V>
574
where
575
    Key: Sort<Key>,
576
    Key: Sort<SearchFor>,
577
    SearchFor: ?Sized,
578
{
579
    type Output = V;
580

            
581
1
    fn index(&self, index: &'a SearchFor) -> &Self::Output {
582
1
        self.get(index).expect("key not found")
583
1
    }
584
}
585

            
586
impl<'a, SearchFor, Key, V> core::ops::IndexMut<&'a SearchFor> for Map<Key, V>
587
where
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)]
603
pub enum SearchKey<'key, Owned, Borrowed>
604
where
605
    Borrowed: ?Sized,
606
{
607
    /// A borrowed key.
608
    Borrowed(&'key Borrowed),
609
    /// An owned key.
610
    Owned(Owned),
611
}
612

            
613
impl<'key, K> From<K> for SearchKey<'key, K, K> {
614
    #[inline]
615
5
    fn from(value: K) -> Self {
616
5
        SearchKey::Owned(value)
617
5
    }
618
}
619

            
620
impl<'key, Key, Borrowed> From<&'key Borrowed> for SearchKey<'key, Key, Borrowed>
621
where
622
    Borrowed: ?Sized,
623
{
624
    #[inline]
625
11
    fn from(value: &'key Borrowed) -> Self {
626
11
        SearchKey::Borrowed(value)
627
11
    }
628
}
629

            
630
impl<'key, Key, Borrowed> SearchKey<'key, Key, Borrowed>
631
where
632
    Key: Borrow<Borrowed>,
633
    Borrowed: ToOwned<Owned = Key> + ?Sized,
634
{
635
    #[inline]
636
18
    fn as_ref(&self) -> &Borrowed {
637
18
        match self {
638
12
            SearchKey::Borrowed(key) => key,
639
6
            SearchKey::Owned(owned) => owned.borrow(),
640
        }
641
18
    }
642

            
643
    #[inline]
644
7
    fn into_owned(self) -> Key {
645
7
        match self {
646
5
            SearchKey::Borrowed(key) => key.to_owned(),
647
2
            SearchKey::Owned(owned) => owned,
648
        }
649
7
    }
650
}
651

            
652
impl<Key, Value> Debug for Map<Key, Value>
653
where
654
    Key: Debug + Sort<Key>,
655
    Value: Debug,
656
{
657
    #[inline]
658
1
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
659
1
        let mut s = f.debug_map();
660
55
        for Field { key, value } in self {
661
54
            s.entry(key, value);
662
54
        }
663
1
        s.finish()
664
1
    }
665
}
666

            
667
impl<'a, Key, Value> IntoIterator for &'a Map<Key, Value>
668
where
669
    Key: Sort<Key>,
670
{
671
    type IntoIter = Iter<'a, Key, Value>;
672
    type Item = &'a Field<Key, Value>;
673

            
674
    #[inline]
675
19
    fn into_iter(self) -> Self::IntoIter {
676
19
        Iter(self.fields.iter())
677
19
    }
678
}
679

            
680
impl<'a, Key, Value> IntoIterator for &'a mut Map<Key, Value>
681
where
682
    Key: Sort<Key>,
683
{
684
    type IntoIter = IterMut<'a, Key, Value>;
685
    type Item = (&'a Key, &'a mut Value);
686

            
687
    #[inline]
688
1
    fn into_iter(self) -> Self::IntoIter {
689
1
        IterMut(self.fields.iter_mut())
690
1
    }
691
}
692

            
693
impl<Key, Value> IntoIterator for Map<Key, Value>
694
where
695
    Key: Sort<Key>,
696
{
697
    type IntoIter = IntoIter<Key, Value>;
698
    type Item = Field<Key, Value>;
699

            
700
    #[inline]
701
1
    fn into_iter(self) -> Self::IntoIter {
702
1
        IntoIter(self.fields.into_iter())
703
1
    }
704
}
705

            
706
impl<Key, Value> FromIterator<(Key, Value)> for Map<Key, Value>
707
where
708
    Key: Sort<Key>,
709
{
710
    #[inline]
711
59
    fn from_iter<T: IntoIterator<Item = (Key, Value)>>(iter: T) -> Self {
712
59
        let iter = iter.into_iter();
713
59
        let mut obj = Self::with_capacity(iter.size_hint().0);
714
        // Insert out of order, then sort before returning.
715
8820
        for (key, value) in iter {
716
8761
            obj.fields.push(Field::new(key, value));
717
8761
        }
718
84814
        obj.fields.sort_unstable_by(|a, b| a.key().compare(b.key()));
719
59
        obj
720
59
    }
721
}
722

            
723
/// A field in an [`Map`].
724
4334
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
725
pub struct Field<Key, Value> {
726
    key: Key,
727
    /// The value contained in this field.
728
    pub value: Value,
729
}
730

            
731
impl<Key, Value> Field<Key, Value> {
732
    /// Returns a new field with `key` and `value`.
733
    #[must_use]
734
    #[inline]
735
17104
    pub fn new(key: Key, value: Value) -> Self {
736
17104
        Self { key, value }
737
17104
    }
738

            
739
    /// Returns the key of this field.
740
    #[inline]
741
169726
    pub fn key(&self) -> &Key {
742
169726
        &self.key
743
169726
    }
744

            
745
    /// Converts this field into its key.
746
    #[inline]
747
1
    pub fn into_key(self) -> Key {
748
1
        self.key
749
1
    }
750

            
751
    /// Returns this field as the contained key and value.
752
3
    pub fn into_parts(self) -> (Key, Value) {
753
3
        (self.key, self.value)
754
3
    }
755
}
756

            
757
/// The result of looking up an entry by its key.
758
#[derive(Debug)]
759
pub enum Entry<'a, 'key, Key, Value, BorrowedKey>
760
where
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

            
770
impl<'a, 'key, Key, Value, BorrowedKey> Entry<'a, 'key, Key, Value, BorrowedKey>
771
where
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
2
    pub fn and_modify(mut self, update: impl FnOnce(&mut Value)) -> Self {
779
2
        if let Self::Occupied(entry) = &mut self {
780
1
            update(&mut *entry);
781
1
        }
782

            
783
2
        self
784
2
    }
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
4
    pub fn or_insert_with(self, contents: impl FnOnce() -> Value) -> &'a mut Value
791
4
    where
792
4
        Key: Borrow<BorrowedKey>,
793
4
        BorrowedKey: ToOwned<Owned = Key>,
794
4
    {
795
4
        match self {
796
2
            Entry::Occupied(entry) => entry.into_mut(),
797
2
            Entry::Vacant(entry) => entry.insert(contents()),
798
        }
799
4
    }
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
7
    pub fn or_insert(self, value: Value) -> &'a mut Value
805
7
    where
806
7
        Key: Borrow<BorrowedKey>,
807
7
        BorrowedKey: ToOwned<Owned = Key>,
808
7
    {
809
7
        match self {
810
2
            Entry::Occupied(entry) => entry.into_mut(),
811
5
            Entry::Vacant(entry) => entry.insert(value),
812
        }
813
7
    }
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
1
    pub fn or_default(self) -> &'a mut Value
821
1
    where
822
1
        Key: Borrow<BorrowedKey>,
823
1
        BorrowedKey: ToOwned<Owned = Key>,
824
1
        Value: Default,
825
1
    {
826
1
        #[allow(clippy::unwrap_or_default)] // This is the implementation of said function...
827
1
        self.or_insert_with(Value::default)
828
1
    }
829
}
830

            
831
/// An entry that exists in an [`Map`].
832
#[derive(Debug)]
833
pub struct OccupiedEntry<'a, Key, Value>
834
where
835
    Key: Sort<Key>,
836
{
837
    object: &'a mut Map<Key, Value>,
838
    index: usize,
839
}
840

            
841
impl<'a, Key, Value> OccupiedEntry<'a, Key, Value>
842
where
843
    Key: Sort<Key>,
844
{
845
    #[inline]
846
6
    fn new(object: &'a mut Map<Key, Value>, index: usize) -> Self {
847
6
        Self { object, index }
848
6
    }
849

            
850
    #[inline]
851
2
    fn field(&self) -> &Field<Key, Value> {
852
2
        &self.object.fields[self.index]
853
2
    }
854

            
855
    #[inline]
856
1
    fn field_mut(&mut self) -> &mut Field<Key, Value> {
857
1
        &mut self.object.fields[self.index]
858
1
    }
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
5
    pub fn into_mut(self) -> &'a mut Value {
868
5
        &mut self.object.fields[self.index].value
869
5
    }
870

            
871
    /// Returns the key of this field.
872
    #[must_use]
873
    #[inline]
874
1
    pub fn key(&self) -> &Key {
875
1
        &self.field().key
876
1
    }
877

            
878
    /// Replaces the contents of this field with `value`, and returns the
879
    /// existing value.
880
    #[inline]
881
1
    pub fn replace(self, value: Value) -> Value {
882
1
        core::mem::replace(self.into_mut(), value)
883
1
    }
884

            
885
    /// Removes the entry from the map, and returns the value.
886
    #[must_use]
887
    #[inline]
888
1
    pub fn remove(self) -> Field<Key, Value> {
889
1
        self.object.fields.remove(self.index)
890
1
    }
891
}
892

            
893
impl<'a, Key, Value> Deref for OccupiedEntry<'a, Key, Value>
894
where
895
    Key: Sort<Key>,
896
{
897
    type Target = Value;
898

            
899
    #[inline]
900
1
    fn deref(&self) -> &Self::Target {
901
1
        &self.field().value
902
1
    }
903
}
904

            
905
impl<'a, Key, Value> DerefMut for OccupiedEntry<'a, Key, Value>
906
where
907
    Key: Sort<Key>,
908
{
909
    #[inline]
910
1
    fn deref_mut(&mut self) -> &mut Self::Target {
911
1
        &mut self.field_mut().value
912
1
    }
913
}
914

            
915
/// A vacant entry in an [`Map`].
916
#[derive(Debug)]
917
pub struct VacantEntry<'a, 'key, Key, Value, BorrowedKey>
918
where
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

            
927
impl<'a, 'key, Key, Value, BorrowedKey> VacantEntry<'a, 'key, Key, Value, BorrowedKey>
928
where
929
    Key: Borrow<BorrowedKey> + Sort<Key>,
930
    BorrowedKey: ToOwned<Owned = Key> + ?Sized,
931
{
932
    #[inline]
933
10
    fn new(
934
10
        object: &'a mut Map<Key, Value>,
935
10
        key: SearchKey<'key, Key, BorrowedKey>,
936
10
        insert_at: usize,
937
10
    ) -> Self {
938
10
        Self {
939
10
            object,
940
10
            key,
941
10
            insert_at,
942
10
        }
943
10
    }
944

            
945
    /// Returns a reference to the key being inserted.
946
    #[inline]
947
2
    pub fn key(&self) -> &BorrowedKey {
948
2
        self.key.as_ref()
949
2
    }
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
7
    pub fn insert(self, value: Value) -> &'a mut Value
959
7
    where
960
7
        Key: Borrow<BorrowedKey>,
961
7
        BorrowedKey: ToOwned<Owned = Key>,
962
7
    {
963
7
        self.object
964
7
            .fields
965
7
            .insert(self.insert_at, Field::new(self.key.into_owned(), value));
966
7
        &mut self.object.fields[self.insert_at].value
967
7
    }
968
}
969

            
970
/// An iterator over the [`Field`]s in an [`Map`].
971
pub struct Iter<'a, Key, Value>(slice::Iter<'a, Field<Key, Value>>);
972

            
973
impl<'a, Key, Value> Iterator for Iter<'a, Key, Value> {
974
    type Item = &'a Field<Key, Value>;
975

            
976
    #[inline]
977
118
    fn next(&mut self) -> Option<Self::Item> {
978
118
        self.0.next()
979
118
    }
980

            
981
    #[inline]
982
18
    fn size_hint(&self) -> (usize, Option<usize>) {
983
18
        self.0.size_hint()
984
18
    }
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()
    }

            
    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth(n)
    }
}

            
impl<'a, Key, Value> ExactSizeIterator for Iter<'a, Key, Value> {
    #[inline]
    fn len(&self) -> usize {
        self.0.len()
    }
}

            
impl<'a, Key, Value> DoubleEndedIterator for Iter<'a, Key, Value> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back()
    }

            
    #[inline]
    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth_back(n)
    }
}

            
impl<'a, Key, Value> FusedIterator for Iter<'a, Key, Value> {}

            
/// An iterator over mutable [`Field`]s contained in an [`Map`].
pub struct IterMut<'a, Key, Value>(slice::IterMut<'a, Field<Key, Value>>);

            
impl<'a, Key, Value> Iterator for IterMut<'a, Key, Value> {
    type Item = (&'a Key, &'a mut Value);

            
    #[inline]
3
    fn next(&mut self) -> Option<Self::Item> {
3
        let field = self.0.next()?;
2
        Some((&field.key, &mut field.value))
3
    }

            
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }

            
    #[inline]
    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.0.count()
    }

            
    #[inline]
    fn last(self) -> Option<Self::Item>
    where
        Self: Sized,
    {
        self.0.last().map(|field| (&field.key, &mut field.value))
    }

            
    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth(n).map(|field| (&field.key, &mut field.value))
    }
}

            
impl<'a, Key, Value> ExactSizeIterator for IterMut<'a, Key, Value> {
    #[inline]
    fn len(&self) -> usize {
        self.0.len()
    }
}

            
impl<'a, Key, Value> DoubleEndedIterator for IterMut<'a, Key, Value> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0
            .next_back()
            .map(|field| (&field.key, &mut field.value))
    }

            
    #[inline]
    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        self.0
            .nth_back(n)
            .map(|field| (&field.key, &mut field.value))
    }
}

            
impl<'a, Key, Value> FusedIterator for IterMut<'a, Key, Value> {}

            
/// An iterator that returns all of the elements of an [`Map`] while
/// freeing its underlying memory.
pub struct IntoIter<Key, Value>(vec::IntoIter<Field<Key, Value>>);

            
impl<Key, Value> Iterator for IntoIter<Key, Value> {
    type Item = Field<Key, Value>;

            
    #[inline]
2
    fn next(&mut self) -> Option<Self::Item> {
2
        self.0.next()
2
    }

            
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }

            
    #[inline]
    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.0.count()
    }

            
    #[inline]
    fn last(self) -> Option<Self::Item>
    where
        Self: Sized,
    {
        self.0.last()
    }

            
    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth(n)
    }
}

            
impl<Key, Value> ExactSizeIterator for IntoIter<Key, Value> {
    #[inline]
    fn len(&self) -> usize {
        self.0.len()
    }
}

            
impl<Key, Value> DoubleEndedIterator for IntoIter<Key, Value> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back()
    }

            
    #[inline]
    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth_back(n)
    }
}

            
impl<Key, Value> FusedIterator for IntoIter<Key, Value> {}

            
/// An iterator over the keys in an [`Map`].
pub struct Keys<'a, Key, Value>(slice::Iter<'a, Field<Key, Value>>);

            
impl<'a, Key, Value> Iterator for Keys<'a, Key, Value> {
    type Item = &'a Key;

            
    #[inline]
7
    fn next(&mut self) -> Option<Self::Item> {
7
        self.0.next().map(Field::key)
7
    }

            
    #[inline]
1
    fn size_hint(&self) -> (usize, Option<usize>) {
1
        self.0.size_hint()
1
    }

            
    #[inline]
    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.0.count()
    }

            
    #[inline]
    fn last(self) -> Option<Self::Item>
    where
        Self: Sized,
    {
        self.0.last().map(Field::key)
    }

            
    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth(n).map(Field::key)
    }
}

            
impl<'a, Key, Value> ExactSizeIterator for Keys<'a, Key, Value> {
    #[inline]
    fn len(&self) -> usize {
        self.0.len()
    }
}

            
impl<'a, Key, Value> DoubleEndedIterator for Keys<'a, Key, Value> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back().map(Field::key)
    }

            
    #[inline]
    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth_back(n).map(Field::key)
    }
}

            
impl<'a, Key, Value> FusedIterator for Keys<'a, Key, Value> {}

            
/// An iterator converting a [`Map`] into a series of owned keys.
pub struct IntoKeys<Key, Value>(vec::IntoIter<Field<Key, Value>>);

            
impl<Key, Value> Iterator for IntoKeys<Key, Value> {
    type Item = Key;

            
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(Field::into_key)
    }

            
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }

            
    #[inline]
    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.0.count()
    }

            
    #[inline]
    fn last(self) -> Option<Self::Item>
    where
        Self: Sized,
    {
        self.0.last().map(Field::into_key)
    }

            
    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth(n).map(Field::into_key)
    }
}

            
impl<Key, Value> ExactSizeIterator for IntoKeys<Key, Value> {
    #[inline]
    fn len(&self) -> usize {
        self.0.len()
    }
}

            
impl<Key, Value> DoubleEndedIterator for IntoKeys<Key, Value> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back().map(Field::into_key)
    }

            
    #[inline]
    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth_back(n).map(Field::into_key)
    }
}

            
impl<Key, Value> FusedIterator for IntoKeys<Key, Value> {}

            
/// An iterator over the values contained in an [`Map`].
pub struct Values<'a, Key, Value>(slice::Iter<'a, Field<Key, Value>>);

            
impl<'a, Key, Value> Iterator for Values<'a, Key, Value> {
    type Item = &'a Value;

            
    #[inline]
2
    fn next(&mut self) -> Option<Self::Item> {
2
        let field = self.0.next()?;
2
        Some(&field.value)
2
    }

            
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }

            
    #[inline]
    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.0.count()
    }

            
    #[inline]
    fn last(self) -> Option<Self::Item>
    where
        Self: Sized,
    {
        self.0.last().map(|field| &field.value)
    }

            
    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth(n).map(|field| &field.value)
    }
}

            
impl<'a, Key, Value> ExactSizeIterator for Values<'a, Key, Value> {
    #[inline]
    fn len(&self) -> usize {
        self.0.len()
    }
}

            
impl<'a, Key, Value> DoubleEndedIterator for Values<'a, Key, Value> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back().map(|field| &field.value)
    }

            
    #[inline]
    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth_back(n).map(|field| &field.value)
    }
}

            
impl<'a, Key, Value> FusedIterator for Values<'a, Key, Value> {}

            
/// An iterator over mutable values contained in an [`Map`].
pub struct ValuesMut<'a, Key, Value>(slice::IterMut<'a, Field<Key, Value>>);

            
impl<'a, Key, Value> Iterator for ValuesMut<'a, Key, Value> {
    type Item = &'a mut Value;

            
    #[inline]
3
    fn next(&mut self) -> Option<Self::Item> {
3
        let field = self.0.next()?;
2
        Some(&mut field.value)
3
    }

            
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }

            
    #[inline]
    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.0.count()
    }

            
    #[inline]
    fn last(self) -> Option<Self::Item>
    where
        Self: Sized,
    {
        self.0.last().map(|field| &mut field.value)
    }

            
    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth(n).map(|field| &mut field.value)
    }
}

            
impl<'a, Key, Value> ExactSizeIterator for ValuesMut<'a, Key, Value> {
    #[inline]
    fn len(&self) -> usize {
        self.0.len()
    }
}

            
impl<'a, Key, Value> DoubleEndedIterator for ValuesMut<'a, Key, Value> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back().map(|field| &mut field.value)
    }

            
    #[inline]
    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth_back(n).map(|field| &mut field.value)
    }
}

            
impl<'a, Key, Value> FusedIterator for ValuesMut<'a, Key, Value> {}

            
/// An iterator returning all of the values contained in an [`Map`] as its
/// underlying storage is freed.
pub struct IntoValues<Key, Value>(vec::IntoIter<Field<Key, Value>>);

            
impl<Key, Value> Iterator for IntoValues<Key, Value> {
    type Item = Value;

            
    #[inline]
2
    fn next(&mut self) -> Option<Self::Item> {
2
        let field = self.0.next()?;
2
        Some(field.value)
2
    }

            
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }

            
    #[inline]
    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.0.count()
    }

            
    #[inline]
    fn last(self) -> Option<Self::Item>
    where
        Self: Sized,
    {
        self.0.last().map(|field| field.value)
    }

            
    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth(n).map(|field| field.value)
    }
}

            
impl<Key, Value> ExactSizeIterator for IntoValues<Key, Value> {
    #[inline]
    fn len(&self) -> usize {
        self.0.len()
    }
}

            
impl<Key, Value> DoubleEndedIterator for IntoValues<Key, Value> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back().map(|field| field.value)
    }

            
    #[inline]
    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth_back(n).map(|field| field.value)
    }
}

            
impl<Key, Value> FusedIterator for IntoValues<Key, Value> {}

            
/// An iterator that removes all of the [`Field`]s of an [`Map`].
///
/// When this iterator is dropped, the underlying [`Map`] will be empty
/// regardless of whether the iterator has been fully exhausted.
pub struct Drain<'a, Key, Value>(vec::Drain<'a, Field<Key, Value>>);

            
impl<'a, Key, Value> Iterator for Drain<'a, Key, Value> {
    type Item = Field<Key, Value>;

            
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }

            
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }

            
    #[inline]
    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.0.count()
    }

            
    #[inline]
    fn last(self) -> Option<Self::Item>
    where
        Self: Sized,
    {
        self.0.last()
    }

            
    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth(n)
    }
}

            
impl<'a, Key, Value> ExactSizeIterator for Drain<'a, Key, Value> {
    #[inline]
    fn len(&self) -> usize {
        self.0.len()
    }
}

            
impl<'a, Key, Value> DoubleEndedIterator for Drain<'a, Key, Value> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back()
    }

            
    #[inline]
    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth_back(n)
    }
}

            
impl<'a, Key, Value> FusedIterator for Drain<'a, Key, Value> {}

            
/// An iterator that yields [`Unioned`] entries for two [`Map`]s.
///
/// The iterator will return a single result for each unique `Key` contained in
/// either map. If both collections contain a key, the iterator will contain
/// [`Unioned::Both`] for that key.
///
/// This iterator is guaranteed to return results in the sort order of the `Key`
/// type.
pub struct Union<'a, K, V>
where
    K: Sort,
{
    left: Peekable<Iter<'a, K, V>>,
    right: Peekable<Iter<'a, K, V>>,
}

            
impl<'a, K, V> Iterator for Union<'a, K, V>
where
    K: Sort,
{
    type Item = Unioned<'a, K, V>;

            
    #[inline]
22
    fn next(&mut self) -> Option<Self::Item> {
22
        if let Some(left) = self.left.peek() {
15
            if let Some(right) = self.right.peek() {
14
                match left.key().compare(right.key()) {
7
                    Ordering::Less => Some(Unioned::left(self.left.next().expect("just peeked"))),
4
                    Ordering::Equal => Some(Unioned::both(
4
                        self.left.next().expect("just peeked"),
4
                        self.right.next().expect("just peeked"),
4
                    )),
                    Ordering::Greater => {
3
                        Some(Unioned::right(self.right.next().expect("just peeked")))
                    }
                }
            } else {
1
                Some(Unioned::left(self.left.next().expect("just peeked")))
            }
        } else {
7
            self.right.next().map(Unioned::right)
        }
22
    }

            
    #[inline]
4
    fn size_hint(&self) -> (usize, Option<usize>) {
4
        (self.left.len(), Some(self.left.len() + self.right.len()))
4
    }
}

            
/// A unioned entry from a [`Union`] iterator. An entry can be from the left,
/// right, or both maps.
pub enum Unioned<'a, K, V> {
    /// The `self`/left map contained this key/value pair.
    Left {
        /// The key of the entry.
        key: &'a K,
        /// The value of the entry.
        value: &'a V,
    },
    /// The `other`/right map contained this key/value pair.
    Right {
        /// The key of the entry.
        key: &'a K,
        /// The value of the entry.
        value: &'a V,
    },
    /// Both maps contained this `key`.
    Both {
        /// The key of the entry.
        key: &'a K,
        /// The value of the `self`/left entry.
        left: &'a V,
        /// The value of the `other`/right entry.
        right: &'a V,
    },
}

            
impl<'a, K, V> Unioned<'a, K, V> {
    /// If `self` is [`Unioned::Both`] `merge` will be called to produce a
    /// single value. If `self` is either [`Unioned::Left`] or
    /// [`Unioned::Right`], the key/value will be returned without calling
    /// `merge`.
    ///
    /// ```rust
    /// use kempt::Map;
    ///
    /// fn merge(a: &Map<String, u32>, b: &Map<String, u32>) -> Map<String, u32> {
    ///     a.union(b)
    ///         .map(|unioned| {
    ///             unioned
    ///                 .map_both(|_key, left, right| *left + *right)
    ///                 .into_owned()
    ///         })
    ///         .collect()
    /// }
    ///
    /// let mut a = Map::new();
    /// a.insert(String::from("a"), 1);
    /// a.insert(String::from("b"), 1);
    /// a.insert(String::from("c"), 1);
    /// let mut b = Map::new();
    /// b.insert(String::from("b"), 1);
    ///
    /// let merged = merge(&a, &b);
    /// assert_eq!(merged.get("a"), Some(&1));
    /// assert_eq!(merged.get("b"), Some(&2));
    /// ```
    #[inline]
18
    pub fn map_both<R>(self, merge: impl FnOnce(&'a K, &'a V, &'a V) -> R) -> EntryRef<'a, K, V>
18
    where
18
        R: Into<OwnedOrRef<'a, V>>,
18
    {
18
        match self {
14
            Unioned::Left { key, value } | Unioned::Right { key, value } => EntryRef {
14
                key,
14
                value: OwnedOrRef::Ref(value),
14
            },
4
            Unioned::Both { key, left, right } => EntryRef {
4
                key,
4
                value: merge(key, left, right).into(),
4
            },
        }
18
    }
}

            
impl<'a, K, V> Unioned<'a, K, V> {
4
    fn both(left: &'a Field<K, V>, right: &'a Field<K, V>) -> Self {
4
        Self::Both {
4
            key: left.key(),
4
            left: &left.value,
4
            right: &right.value,
4
        }
4
    }

            
8
    fn left(field: &'a Field<K, V>) -> Self {
8
        Self::Left {
8
            key: field.key(),
8
            value: &field.value,
8
        }
8
    }

            
6
    fn right(field: &'a Field<K, V>) -> Self {
6
        Self::Right {
6
            key: field.key(),
6
            value: &field.value,
6
        }
6
    }
}

            
/// A reference to a key from a [`Map`] and an associated value.
pub struct EntryRef<'a, K, V> {
    /// The key of the entry.
    pub key: &'a K,
    /// The associated value of this key.
    pub value: OwnedOrRef<'a, V>,
}

            
impl<'a, K, V> EntryRef<'a, K, V> {
    /// Returns the owned versions of the contained key and value, cloning as
    /// needed.
    #[inline]
8
    pub fn into_owned(self) -> (K, V)
8
    where
8
        K: Clone,
8
        V: Clone,
8
    {
8
        (self.key.clone(), self.value.into_owned())
8
    }
}

            
/// An owned value or a reference to a value of that type.
///
/// This type is similar to [`alloc::borrow::Cow`] except that it does not
/// require that the contained type implement `ToOwned`.
pub enum OwnedOrRef<'a, K> {
    /// An owned value.
    Owned(K),
    /// A reference to a value.
    Ref(&'a K),
}

            
impl<'a, K> OwnedOrRef<'a, K> {
    /// Converts the contained value into an owned representation, cloning only
    /// if needed.
    #[inline]
8
    pub fn into_owned(self) -> K
8
    where
8
        K: Clone,
8
    {
8
        match self {
1
            OwnedOrRef::Owned(owned) => owned,
7
            OwnedOrRef::Ref(r) => r.clone(),
        }
8
    }
}

            
impl<K> From<K> for OwnedOrRef<'_, K> {
    #[inline]
1
    fn from(value: K) -> Self {
1
        Self::Owned(value)
1
    }
}

            
impl<'a, K> From<&'a K> for OwnedOrRef<'a, K> {
    #[inline]
1
    fn from(value: &'a K) -> Self {
1
        Self::Ref(value)
1
    }
}

            
/// An iterator that yields entries that appear in two maps.
///
/// The iterator will return a result for each `Key` contained in both maps. If
/// a particular key is only found in one collection, it will not be included.
///
/// This iterator is guaranteed to return results in the sort order of the `Key`
/// type.
pub struct Intersection<'a, K, V>
where
    K: Sort,
{
    left: Peekable<Iter<'a, K, V>>,
    right: Peekable<Iter<'a, K, V>>,
}

            
impl<'a, K, V> Iterator for Intersection<'a, K, V>
where
    K: Sort,
{
    type Item = (&'a K, &'a V, &'a V);

            
    #[inline]
4
    fn next(&mut self) -> Option<Self::Item> {
        loop {
10
            let left = self.left.peek()?;
9
            let right = self.right.peek()?;
8
            match left.key().compare(right.key()) {
3
                Ordering::Less => {
3
                    let _skipped = self.left.next();
3
                }
                Ordering::Equal => {
2
                    let left = self.left.next().expect("just peeked");
2
                    let right = self.right.next().expect("just peeked");
2
                    return Some((left.key(), &left.value, &right.value));
                }
3
                Ordering::Greater => {
3
                    let _skipped = self.right.next();
3
                }
            }
        }
4
    }

            
    #[inline]
2
    fn size_hint(&self) -> (usize, Option<usize>) {
2
        (0, Some(self.left.len().min(self.right.len())))
2
    }
}

            
/// An iterator over the difference between two [`Map`]s.
///
/// This iterator will return a result for each `Key` contained in `self` but
/// not contained in `other`. If a `Key` is only in `other` or is in both
/// collections, it will not be returned.
///
/// This iterator is guaranteed to return results in the sort order of the `Key`
/// type.
pub struct Difference<'a, K, V>
where
    K: Sort,
{
    left: Peekable<Iter<'a, K, V>>,
    right: Peekable<Iter<'a, K, V>>,
}

            
impl<'a, K, V> Iterator for Difference<'a, K, V>
where
    K: Sort,
{
    type Item = (&'a K, &'a V);

            
    #[inline]
6
    fn next(&mut self) -> Option<Self::Item> {
        loop {
11
            let left = self.left.peek()?;
9
            if let Some(right) = self.right.peek() {
8
                match left.key().compare(right.key()) {
                    Ordering::Less => {
3
                        let left = self.left.next().expect("just peeked");
3
                        return Some((left.key(), &left.value));
                    }
2
                    Ordering::Equal => {
2
                        let _left = self.left.next();
2
                        let _right = self.right.next();
2
                    }
3
                    Ordering::Greater => {
3
                        let _skipped = self.right.next();
3
                    }
                }
            } else {
1
                let left = self.left.next().expect("just peeked");
1
                return Some((left.key(), &left.value));
            }
        }
6
    }

            
    #[inline]
2
    fn size_hint(&self) -> (usize, Option<usize>) {
2
        (0, Some(self.left.len()))
2
    }
}