turbocow 0.3.0-beta.2

Compact, clone-on-write vectors, strings, maps and sets with inline + referenced storage — a superset of ecow.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
use core::borrow::Borrow;
use core::fmt;
use core::hash::{BuildHasher, Hash};
use core::iter::FusedIterator;
use core::mem::MaybeUninit;
use core::ops::Index;

use hashbrown::HashMap;

use super::group;
use super::types::{InlineMap, SmallMap};

/// Below this entry count, lookups use linear scan (no hashing overhead).
const LINEAR_THRESHOLD: usize = 3;

// ═══════════════════════════════════════════════════════════════════════════
// Constructors
// ═══════════════════════════════════════════════════════════════════════════

impl<K, V, const N: usize, S: Default> SmallMap<K, V, N, S> {
    /// Creates an empty `SmallMap`.
    ///
    /// The map starts with inline storage and will not allocate until
    /// more than `N` entries are inserted.
    #[inline]
    pub fn new() -> Self {
        SmallMap::Inline(InlineMap::new(S::default()))
    }
}

impl<K, V, const N: usize, S> SmallMap<K, V, N, S> {
    /// Creates an empty `SmallMap` with the given hasher.
    #[inline]
    pub fn with_hasher(hasher: S) -> Self {
        SmallMap::Inline(InlineMap::new(hasher))
    }

    /// Creates an empty `SmallMap` that will immediately use heap storage
    /// with at least the specified capacity.
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self
    where
        S: Default,
    {
        if capacity <= N {
            Self::new()
        } else {
            SmallMap::Heap(HashMap::with_capacity_and_hasher(capacity, S::default()))
        }
    }

    /// Returns the number of entries in the map.
    #[inline]
    pub fn len(&self) -> usize {
        match self {
            SmallMap::Inline(inline) => inline.len(),
            SmallMap::Heap(heap) => heap.len(),
        }
    }

    /// Returns `true` if the map contains no entries.
    #[inline]
    pub fn is_empty(&self) -> bool {
        match self {
            SmallMap::Inline(inline) => inline.is_empty(),
            SmallMap::Heap(heap) => heap.is_empty(),
        }
    }

    /// Returns `true` if the map is currently using inline storage.
    #[inline]
    pub fn is_inline(&self) -> bool {
        matches!(self, SmallMap::Inline(_))
    }

    /// Returns a reference to the map's hasher.
    #[inline]
    pub fn hasher(&self) -> &S {
        match self {
            SmallMap::Inline(inline) => inline.hasher(),
            SmallMap::Heap(heap) => heap.hasher(),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Core operations
// ═══════════════════════════════════════════════════════════════════════════

impl<K, V, const N: usize, S> SmallMap<K, V, N, S>
where
    K: Eq + Hash,
    S: BuildHasher,
{
    /// Returns a reference to the value corresponding to the key.
    #[inline]
    pub fn get<Q>(&self, key: &Q) -> Option<&V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        match self {
            SmallMap::Inline(inline) => {
                if inline.len() <= LINEAR_THRESHOLD {
                    inline.get(key)
                } else {
                    let hash = group::make_hash(inline.hasher(), key);
                    inline.get_h2(key, group::h2(hash))
                }
            }
            SmallMap::Heap(heap) => heap.get(key),
        }
    }

    /// Returns a mutable reference to the value corresponding to the key.
    #[inline]
    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        match self {
            SmallMap::Inline(inline) => {
                if inline.len() <= LINEAR_THRESHOLD {
                    inline.get_mut(key)
                } else {
                    let hash = group::make_hash(inline.hasher(), key);
                    inline.get_mut_h2(key, group::h2(hash))
                }
            }
            SmallMap::Heap(heap) => heap.get_mut(key),
        }
    }

    /// Returns the key-value pair corresponding to the key.
    #[inline]
    pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        match self {
            SmallMap::Inline(inline) => {
                if inline.len() <= LINEAR_THRESHOLD {
                    inline.get_key_value(key)
                } else {
                    let hash = group::make_hash(inline.hasher(), key);
                    inline.get_key_value_h2(key, group::h2(hash))
                }
            }
            SmallMap::Heap(heap) => heap.get_key_value(key),
        }
    }

    /// Returns `true` if the map contains the given key.
    #[inline]
    pub fn contains_key<Q>(&self, key: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        self.get(key).is_some()
    }

    /// Inserts a key-value pair into the map.
    ///
    /// If the key already exists, the value is replaced and the old value
    /// is returned. If the inline storage is full and the key is new,
    /// the map spills to a heap-allocated `HashMap`.
    #[inline]
    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        match self {
            SmallMap::Inline(inline) => {
                // Always hash on insert — we need the h2 for the new entry.
                let hash = group::make_hash(inline.hasher(), &key);
                let h2 = group::h2(hash);

                // h2-filtered scan for existing key.
                let base = inline.entries.as_mut_ptr();
                let mask = unsafe {
                    group::match_h2::<N>(inline.h2_bytes.as_ptr(), inline.len, h2)
                };
                for i in mask {
                    let entry = unsafe { &mut *base.add(i).cast::<(K, V)>() };
                    if entry.0 == key {
                        return Some(core::mem::replace(&mut entry.1, value));
                    }
                }

                // New key — if there's room, append inline.
                if !inline.is_full() {
                    inline.h2_bytes[inline.len] = h2;
                    inline.entries[inline.len] = MaybeUninit::new((key, value));
                    inline.len += 1;
                    None
                } else {
                    // Spill to heap.
                    self.spill_and_insert(key, value)
                }
            }
            SmallMap::Heap(heap) => heap.insert(key, value),
        }
    }

    /// Removes a key from the map, returning the value if it existed.
    #[inline]
    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        self.remove_entry(key).map(|(_, v)| v)
    }

    /// Removes a key from the map, returning the key-value pair if it existed.
    #[inline]
    pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
    where
        K: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        match self {
            SmallMap::Inline(inline) => {
                if inline.len() <= LINEAR_THRESHOLD {
                    inline.remove_entry(key)
                } else {
                    let hash = group::make_hash(inline.hasher(), key);
                    inline.remove_entry_h2(key, group::h2(hash))
                }
            }
            SmallMap::Heap(heap) => heap.remove_entry(key),
        }
    }

    /// Clears the map, removing all key-value pairs.
    ///
    /// If the map was heap-allocated, it remains heap-allocated but empty.
    #[inline]
    pub fn clear(&mut self) {
        match self {
            SmallMap::Inline(inline) => inline.clear(),
            SmallMap::Heap(heap) => heap.clear(),
        }
    }

    /// Retains only the elements specified by the predicate.
    #[inline]
    pub fn retain<F>(&mut self, f: F)
    where
        F: FnMut(&K, &mut V) -> bool,
    {
        match self {
            SmallMap::Inline(inline) => inline.retain(f),
            SmallMap::Heap(heap) => heap.retain(f),
        }
    }

    /// Gets the given key's corresponding entry in the map for in-place
    /// manipulation.
    #[inline]
    pub fn entry(&mut self, key: K) -> super::entry::Entry<'_, K, V, N, S> {
        use super::entry::*;

        // Phase 1: search (borrows self temporarily).
        let probe = match self {
            SmallMap::Inline(inline) => {
                let hash = group::make_hash(inline.hasher(), &key);
                let h2 = group::h2(hash);
                let mask = unsafe {
                    group::match_h2::<N>(inline.h2_bytes.as_ptr(), inline.len, h2)
                };
                let mut found = None;
                for i in mask {
                    let k = unsafe { &inline.entries[i].assume_init_ref().0 };
                    if *k == key {
                        found = Some(i);
                        break;
                    }
                }
                Some((found, h2))
            }
            SmallMap::Heap(_) => None,
        };

        // Phase 2: construct entry (borrows self for 'a).
        match probe {
            Some((Some(index), _)) => Entry::Occupied(OccupiedEntry {
                inner: OccupiedInner::Inline { map: self, index },
            }),
            Some((None, h2)) => Entry::Vacant(VacantEntry {
                inner: VacantInner::Inline { map: self, key, h2 },
            }),
            None => match self {
                SmallMap::Heap(heap) => match heap.entry(key) {
                    hashbrown::hash_map::Entry::Occupied(o) => {
                        Entry::Occupied(OccupiedEntry { inner: OccupiedInner::Heap(o) })
                    }
                    hashbrown::hash_map::Entry::Vacant(v) => {
                        Entry::Vacant(VacantEntry { inner: VacantInner::Heap(v) })
                    }
                },
                _ => unreachable!(),
            },
        }
    }

    /// Spill from inline to heap and insert a new key-value pair.
    /// Called when inline storage is full and a new key must be added.
    #[cold]
    #[inline(never)]
    fn spill_and_insert(&mut self, key: K, value: V) -> Option<V> {
        self.force_spill();
        match self {
            SmallMap::Heap(heap) => heap.insert(key, value),
            _ => unreachable!(),
        }
    }

    /// Move all inline entries to a heap HashMap. No-op if already heap.
    ///
    /// # Safety invariant
    /// After this call, `self` is `SmallMap::Heap`.
    #[cold]
    #[inline(never)]
    pub(super) fn force_spill(&mut self) {
        let inline = match self {
            SmallMap::Inline(inline) => inline,
            SmallMap::Heap(_) => return,
        };

        let len = inline.len;
        // Move hasher out via ptr::read.
        let hasher = unsafe { core::ptr::read(&inline.hasher) };
        let mut heap = HashMap::with_capacity_and_hasher(N * 2, hasher);

        // Move all inline entries to the heap.
        for i in 0..len {
            let (k, v) = unsafe { inline.entries[i].as_ptr().read() };
            heap.insert(k, v);
        }

        // Mark inline as empty so its Drop is a no-op for data elements.
        inline.len = 0;
        *self = SmallMap::Heap(heap);
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Capacity
// ═══════════════════════════════════════════════════════════════════════════

impl<K, V, const N: usize, S> SmallMap<K, V, N, S> {
    /// Returns the number of entries the map can hold without reallocation.
    ///
    /// When using inline storage, this is always `N` (the fixed stack
    /// capacity). When using heap storage, this is the hashbrown `HashMap`
    /// capacity.
    #[inline]
    pub fn capacity(&self) -> usize {
        match self {
            SmallMap::Inline(_) => N,
            SmallMap::Heap(heap) => heap.capacity(),
        }
    }
}

impl<K, V, const N: usize, S> SmallMap<K, V, N, S>
where
    K: Eq + Hash,
    S: BuildHasher + Default,
{
    /// Reserves capacity for at least `additional` more entries.
    ///
    /// If the map is inline and `len + additional > N`, the map is spilled
    /// to heap storage first. Otherwise the heap's `reserve` is called.
    /// Inline maps with sufficient remaining inline capacity need no action.
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        let needs_spill =
            matches!(self, SmallMap::Inline(inline) if inline.len() + additional > N);
        if needs_spill {
            self.force_spill();
        }
        if let SmallMap::Heap(heap) = self {
            heap.reserve(additional);
        }
        // If inline and len + additional <= N, the inline array already
        // has sufficient capacity — no action needed.
    }

    /// Shrinks the capacity as close to the length as possible.
    ///
    /// For inline storage, this is a no-op — the inline array has a fixed
    /// size of `N` and cannot be resized.
    ///
    /// For heap storage, delegates to hashbrown's `shrink_to_fit`, which
    /// reduces bucket count toward the minimum needed to hold the current
    /// entries. Hashbrown may retain slightly more capacity than `len` for
    /// its load-factor invariant.
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        if let SmallMap::Heap(heap) = self {
            heap.shrink_to_fit();
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Iterators
// ═══════════════════════════════════════════════════════════════════════════

/// An iterator over the entries of an [`SmallMap`].
pub enum Iter<'a, K, V> {
    /// Iterating over inline storage.
    Inline {
        /// Pointer to the data.
        ptr: *const (K, V),
        /// Current index.
        index: usize,
        /// Number of initialized elements.
        len: usize,
        /// Lifetime marker.
        _marker: core::marker::PhantomData<&'a (K, V)>,
    },
    /// Iterating over heap storage.
    Heap(hashbrown::hash_map::Iter<'a, K, V>),
}

impl<'a, K, V> Iterator for Iter<'a, K, V> {
    type Item = (&'a K, &'a V);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Iter::Inline { ptr, index, len, .. } => {
                if *index < *len {
                    let kv = unsafe { &*ptr.add(*index) };
                    *index += 1;
                    Some((&kv.0, &kv.1))
                } else {
                    None
                }
            }
            Iter::Heap(iter) => iter.next(),
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.len();
        (remaining, Some(remaining))
    }
}

impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
    #[inline]
    fn len(&self) -> usize {
        match self {
            Iter::Inline { index, len, .. } => len - index,
            Iter::Heap(iter) => iter.len(),
        }
    }
}

impl<K, V> FusedIterator for Iter<'_, K, V> {}

/// A mutable iterator over the entries of an [`SmallMap`].
pub enum IterMut<'a, K, V> {
    /// Iterating over inline storage.
    Inline {
        /// Pointer to the data.
        ptr: *mut (K, V),
        /// Current index.
        index: usize,
        /// Number of initialized elements.
        len: usize,
        /// Lifetime marker.
        _marker: core::marker::PhantomData<&'a mut (K, V)>,
    },
    /// Iterating over heap storage.
    Heap(hashbrown::hash_map::IterMut<'a, K, V>),
}

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

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match self {
            IterMut::Inline { ptr, index, len, .. } => {
                if *index < *len {
                    let kv = unsafe { &mut *ptr.add(*index) };
                    *index += 1;
                    Some((&kv.0, &mut kv.1))
                } else {
                    None
                }
            }
            IterMut::Heap(iter) => iter.next(),
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.len();
        (remaining, Some(remaining))
    }
}

impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
    #[inline]
    fn len(&self) -> usize {
        match self {
            IterMut::Inline { index, len, .. } => len - index,
            IterMut::Heap(iter) => iter.len(),
        }
    }
}

impl<K, V> FusedIterator for IterMut<'_, K, V> {}

/// An owning iterator over the entries of an [`SmallMap`].
pub enum IntoIter<K, V, const N: usize> {
    /// Consuming inline storage.
    Inline {
        /// The inline data array.
        data: [MaybeUninit<(K, V)>; N],
        /// Current index.
        index: usize,
        /// Number of initialized elements.
        len: usize,
    },
    /// Consuming heap storage.
    Heap(hashbrown::hash_map::IntoIter<K, V>),
}

impl<K, V, const N: usize> Iterator for IntoIter<K, V, N> {
    type Item = (K, V);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match self {
            IntoIter::Inline { data, index, len } => {
                if *index < *len {
                    let kv = unsafe { data[*index].as_ptr().read() };
                    *index += 1;
                    Some(kv)
                } else {
                    None
                }
            }
            IntoIter::Heap(iter) => iter.next(),
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.len();
        (remaining, Some(remaining))
    }
}

impl<K, V, const N: usize> ExactSizeIterator for IntoIter<K, V, N> {
    #[inline]
    fn len(&self) -> usize {
        match self {
            IntoIter::Inline { index, len, .. } => len - index,
            IntoIter::Heap(iter) => iter.len(),
        }
    }
}

impl<K, V, const N: usize> FusedIterator for IntoIter<K, V, N> {}

impl<K, V, const N: usize> Drop for IntoIter<K, V, N> {
    fn drop(&mut self) {
        // Drop remaining elements for the inline variant.
        if let IntoIter::Inline { data, index, len } = self {
            for slot in data.iter_mut().take(*len).skip(*index) {
                unsafe { core::ptr::drop_in_place(slot.as_mut_ptr()) };
            }
        }
        // Heap variant: hashbrown's IntoIter handles its own drop.
    }
}

/// An iterator over the keys of an [`SmallMap`].
pub struct Keys<'a, K, V>(Iter<'a, K, V>);

impl<'a, K, V> Iterator for Keys<'a, K, V> {
    type Item = &'a K;

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

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

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

impl<K, V> FusedIterator for Keys<'_, K, V> {}

/// An iterator over the values of an [`SmallMap`].
pub struct Values<'a, K, V>(Iter<'a, K, V>);

impl<'a, K, V> Iterator for Values<'a, K, V> {
    type Item = &'a V;

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

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

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

impl<K, V> FusedIterator for Values<'_, K, V> {}

/// A mutable iterator over the values of an [`SmallMap`].
pub struct ValuesMut<'a, K, V>(IterMut<'a, K, V>);

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

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

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

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

impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}

// ═══════════════════════════════════════════════════════════════════════════
// Iterator constructors on SmallMap
// ═══════════════════════════════════════════════════════════════════════════

impl<K, V, const N: usize, S> SmallMap<K, V, N, S> {
    /// An iterator visiting all key-value pairs in arbitrary order.
    #[inline]
    pub fn iter(&self) -> Iter<'_, K, V> {
        match self {
            SmallMap::Inline(inline) => Iter::Inline {
                ptr: inline.entries.as_ptr() as *const (K, V),
                index: 0,
                len: inline.len,
                _marker: core::marker::PhantomData,
            },
            SmallMap::Heap(heap) => Iter::Heap(heap.iter()),
        }
    }

    /// A mutable iterator visiting all key-value pairs in arbitrary order.
    /// The keys are immutable; only the values can be mutated.
    #[inline]
    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
        match self {
            SmallMap::Inline(inline) => IterMut::Inline {
                ptr: inline.entries.as_mut_ptr() as *mut (K, V),
                index: 0,
                len: inline.len,
                _marker: core::marker::PhantomData,
            },
            SmallMap::Heap(heap) => IterMut::Heap(heap.iter_mut()),
        }
    }

    /// An iterator visiting all keys in arbitrary order.
    #[inline]
    pub fn keys(&self) -> Keys<'_, K, V> {
        Keys(self.iter())
    }

    /// An iterator visiting all values in arbitrary order.
    #[inline]
    pub fn values(&self) -> Values<'_, K, V> {
        Values(self.iter())
    }

    /// A mutable iterator visiting all values in arbitrary order.
    #[inline]
    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
        ValuesMut(self.iter_mut())
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// IntoIterator
// ═══════════════════════════════════════════════════════════════════════════

impl<K, V, const N: usize, S> IntoIterator for SmallMap<K, V, N, S> {
    type Item = (K, V);
    type IntoIter = IntoIter<K, V, N>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        match self {
            SmallMap::Inline(inline) => {
                let len = inline.len;
                // Read data out, forget inline to skip its Drop.
                let data = unsafe { core::ptr::read(&inline.entries) };
                core::mem::forget(inline);
                IntoIter::Inline { data, index: 0, len }
            }
            SmallMap::Heap(heap) => IntoIter::Heap(heap.into_iter()),
        }
    }
}

impl<'a, K, V, const N: usize, S> IntoIterator for &'a SmallMap<K, V, N, S> {
    type Item = (&'a K, &'a V);
    type IntoIter = Iter<'a, K, V>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, K, V, const N: usize, S> IntoIterator for &'a mut SmallMap<K, V, N, S> {
    type Item = (&'a K, &'a mut V);
    type IntoIter = IterMut<'a, K, V>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Trait implementations
// ═══════════════════════════════════════════════════════════════════════════

impl<K: Clone, V: Clone, const N: usize, S: Clone> Clone for SmallMap<K, V, N, S> {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            SmallMap::Inline(inline) => SmallMap::Inline(inline.clone()),
            SmallMap::Heap(heap) => SmallMap::Heap(heap.clone()),
        }
    }
}

impl<K: fmt::Debug, V: fmt::Debug, const N: usize, S> fmt::Debug
    for SmallMap<K, V, N, S>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut map = f.debug_map();
        for (k, v) in self.iter() {
            map.entry(k, v);
        }
        map.finish()
    }
}

impl<K, V, const N: usize, S> PartialEq for SmallMap<K, V, N, S>
where
    K: Eq + Hash,
    V: PartialEq,
    S: BuildHasher,
{
    fn eq(&self, other: &Self) -> bool {
        if self.len() != other.len() {
            return false;
        }
        self.iter().all(|(k, v)| other.get(k) == Some(v))
    }
}

impl<K, V, const N: usize, S> Eq for SmallMap<K, V, N, S>
where
    K: Eq + Hash,
    V: Eq,
    S: BuildHasher,
{
}

impl<K, V, const N: usize, S: Default> Default for SmallMap<K, V, N, S> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<K, V, Q, const N: usize, S> Index<&Q> for SmallMap<K, V, N, S>
where
    K: Eq + Hash + Borrow<Q>,
    Q: Eq + Hash + ?Sized,
    S: BuildHasher,
{
    type Output = V;

    #[inline]
    fn index(&self, key: &Q) -> &V {
        self.get(key).expect("no entry found for key")
    }
}

impl<K, V, const N: usize, S> Extend<(K, V)> for SmallMap<K, V, N, S>
where
    K: Eq + Hash,
    S: BuildHasher + Default,
{
    #[inline]
    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
        for (k, v) in iter {
            self.insert(k, v);
        }
    }
}

impl<K, V, const N: usize, S> FromIterator<(K, V)> for SmallMap<K, V, N, S>
where
    K: Eq + Hash,
    S: BuildHasher + Default,
{
    #[inline]
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        let iter = iter.into_iter();
        let (hint, _) = iter.size_hint();
        // If the hint exceeds inline capacity, skip inline entirely.
        let mut map = if hint > N { Self::with_capacity(hint) } else { Self::new() };
        for (k, v) in iter {
            map.insert(k, v);
        }
        map
    }
}

#[cfg(feature = "std")]
impl<K, V, const N: usize> From<std::collections::HashMap<K, V>> for SmallMap<K, V, N>
where
    K: Eq + Hash,
{
    fn from(map: std::collections::HashMap<K, V>) -> Self {
        let mut eco = Self::new();
        for (k, v) in map {
            eco.insert(k, v);
        }
        eco
    }
}