fixed_map/
map.rs

1//! Contains the fixed [`Map`] implementation.
2
3mod entry;
4pub use self::entry::Entry;
5
6pub(crate) mod storage;
7pub use self::storage::{MapStorage, OccupiedEntry, VacantEntry};
8
9use core::cmp::{Ord, Ordering, PartialOrd};
10use core::fmt;
11use core::hash::{Hash, Hasher};
12
13use crate::Key;
14
15/// The iterator produced by [`Map::iter`].
16pub type Iter<'a, K, V> = <<K as Key>::MapStorage<V> as MapStorage<K, V>>::Iter<'a>;
17
18/// The iterator produced by [`Map::keys`].
19pub type Keys<'a, K, V> = <<K as Key>::MapStorage<V> as MapStorage<K, V>>::Keys<'a>;
20
21/// The iterator produced by [`Map::values`].
22pub type Values<'a, K, V> = <<K as Key>::MapStorage<V> as MapStorage<K, V>>::Values<'a>;
23
24/// The iterator produced by [`Map::iter`].
25pub type IterMut<'a, K, V> = <<K as Key>::MapStorage<V> as MapStorage<K, V>>::IterMut<'a>;
26
27/// The iterator produced by [`Map::values_mut`].
28pub type ValuesMut<'a, K, V> = <<K as Key>::MapStorage<V> as MapStorage<K, V>>::ValuesMut<'a>;
29
30/// The iterator produced by [`Map::into_iter`].
31pub type IntoIter<K, V> = <<K as Key>::MapStorage<V> as MapStorage<K, V>>::IntoIter;
32
33/// A fixed map with storage specialized through the [`Key`] trait.
34///
35/// # Examples
36///
37/// ```
38/// use fixed_map::{Key, Map};
39///
40/// #[derive(Clone, Copy, Key)]
41/// enum Part {
42///     One,
43///     Two,
44/// }
45///
46/// #[derive(Clone, Copy, Key)]
47/// enum MyKey {
48///     Simple,
49///     Composite(Part),
50///     # #[cfg(feature = "hashbrown")]
51///     String(&'static str),
52///     # #[cfg(feature = "hashbrown")]
53///     Number(u32),
54///     Singleton(()),
55///     Option(Option<Part>),
56///     Boolean(bool),
57/// }
58///
59/// let mut map = Map::new();
60///
61/// map.insert(MyKey::Simple, 1);
62/// map.insert(MyKey::Composite(Part::One), 2);
63/// # #[cfg(feature = "hashbrown")]
64/// map.insert(MyKey::String("foo"), 3);
65/// # #[cfg(feature = "hashbrown")]
66/// map.insert(MyKey::Number(1), 4);
67/// map.insert(MyKey::Singleton(()), 5);
68/// map.insert(MyKey::Option(None), 6);
69/// map.insert(MyKey::Option(Some(Part::One)), 7);
70/// map.insert(MyKey::Boolean(true), 8);
71///
72/// assert_eq!(map.get(MyKey::Simple), Some(&1));
73/// assert_eq!(map.get(MyKey::Composite(Part::One)), Some(&2));
74/// assert_eq!(map.get(MyKey::Composite(Part::Two)), None);
75/// # #[cfg(feature = "hashbrown")]
76/// assert_eq!(map.get(MyKey::String("foo")), Some(&3));
77/// # #[cfg(feature = "hashbrown")]
78/// assert_eq!(map.get(MyKey::String("bar")), None);
79/// # #[cfg(feature = "hashbrown")]
80/// assert_eq!(map.get(MyKey::Number(1)), Some(&4));
81/// # #[cfg(feature = "hashbrown")]
82/// assert_eq!(map.get(MyKey::Number(2)), None);
83/// assert_eq!(map.get(MyKey::Singleton(())), Some(&5));
84/// assert_eq!(map.get(MyKey::Option(None)), Some(&6));
85/// assert_eq!(map.get(MyKey::Option(Some(Part::One))), Some(&7));
86/// assert_eq!(map.get(MyKey::Option(Some(Part::Two))), None);
87/// assert_eq!(map.get(MyKey::Boolean(true)), Some(&8));
88/// assert_eq!(map.get(MyKey::Boolean(false)), None);
89/// ```
90///
91/// Storing references:
92///
93/// ```
94/// use fixed_map::{Key, Map};
95///
96/// #[derive(Debug, Clone, Copy, Key)]
97/// enum MyKey {
98///     First,
99///     Second,
100/// }
101///
102/// let mut map = Map::new();
103/// let a = 42u32;
104///
105/// map.insert(MyKey::First, &a);
106///
107/// assert_eq!(map.values().cloned().collect::<Vec<_>>(), vec![&42u32]);
108/// ```
109#[repr(transparent)]
110pub struct Map<K, V>
111where
112    K: Key,
113{
114    storage: K::MapStorage<V>,
115}
116
117/// A map implementation that uses fixed storage.
118///
119/// # Examples
120///
121/// ```
122/// use fixed_map::{Key, Map};
123///
124/// #[derive(Clone, Copy, Key)]
125/// enum MyKey {
126///     One,
127///     Two,
128/// }
129///
130/// let mut m = Map::new();
131/// m.insert(MyKey::One, 1);
132///
133/// assert_eq!(m.get(MyKey::One), Some(&1));
134/// assert_eq!(m.get(MyKey::Two), None);
135/// ```
136///
137/// Using a composite key:
138///
139/// ```
140/// use fixed_map::{Key, Map};
141///
142/// #[derive(Clone, Copy, Key)]
143/// enum Part {
144///     A,
145///     B,
146/// }
147///
148/// #[derive(Clone, Copy, Key)]
149/// enum MyKey {
150///     Simple,
151///     Composite(Part),
152/// }
153///
154/// let mut m = Map::new();
155/// m.insert(MyKey::Simple, 1);
156/// m.insert(MyKey::Composite(Part::A), 2);
157///
158/// assert_eq!(m.get(MyKey::Simple), Some(&1));
159/// assert_eq!(m.get(MyKey::Composite(Part::A)), Some(&2));
160/// assert_eq!(m.get(MyKey::Composite(Part::B)), None);
161/// ```
162impl<K, V> Map<K, V>
163where
164    K: Key,
165{
166    /// Creates an empty [`Map`].
167    ///
168    /// # Examples
169    ///
170    /// ```
171    /// use fixed_map::{Key, Map};
172    ///
173    /// #[derive(Clone, Copy, Key)]
174    /// enum MyKey {
175    ///     One,
176    ///     Two,
177    /// }
178    ///
179    /// let mut map: Map<MyKey, i32> = Map::new();
180    /// ```
181    #[inline]
182    #[must_use]
183    pub fn new() -> Map<K, V> {
184        Map {
185            storage: K::MapStorage::empty(),
186        }
187    }
188
189    /// An iterator visiting all key-value pairs in arbitrary order.
190    /// The iterator element type is `(K, &'a V)`.
191    ///
192    /// # Examples
193    ///
194    /// ```
195    /// use fixed_map::{Key, Map};
196    ///
197    /// #[derive(Debug, Clone, Copy, PartialEq, Eq, Key)]
198    /// enum MyKey {
199    ///     One,
200    ///     Two,
201    ///     Three,
202    /// }
203    ///
204    /// let mut map = Map::new();
205    /// map.insert(MyKey::One, 1);
206    /// map.insert(MyKey::Two, 2);
207    ///
208    /// assert_eq!(map.iter().collect::<Vec<_>>(), vec![(MyKey::One, &1), (MyKey::Two, &2)]);
209    /// ```
210    #[inline]
211    pub fn iter(&self) -> Iter<'_, K, V> {
212        self.storage.iter()
213    }
214
215    /// An iterator visiting all keys in arbitrary order.
216    /// The iterator element type is `K`.
217    ///
218    /// # Examples
219    ///
220    /// ```
221    /// use fixed_map::{Key, Map};
222    ///
223    /// #[derive(Debug, Clone, Copy, PartialEq, Eq, Key)]
224    /// pub enum MyKey {
225    ///     First,
226    ///     Second,
227    ///     Third,
228    /// }
229    ///
230    /// let mut map = Map::new();
231    /// map.insert(MyKey::First, 1);
232    /// map.insert(MyKey::Second, 2);
233    ///
234    /// assert!(map.keys().eq([MyKey::First, MyKey::Second]));
235    /// assert!(map.keys().rev().eq([MyKey::Second, MyKey::First]));
236    /// ```
237    ///
238    /// Using a composite key:
239    ///
240    /// ```
241    /// use fixed_map::{Key, Map};
242    ///
243    /// #[derive(Debug, Clone, Copy, PartialEq, Eq, Key)]
244    /// pub enum MyKey {
245    ///     First,
246    ///     Second(bool),
247    ///     Third,
248    /// }
249    ///
250    /// let mut map = Map::new();
251    /// map.insert(MyKey::First, 1);
252    /// map.insert(MyKey::Second(false), 2);
253    ///
254    /// dbg!(map.keys().collect::<Vec<_>>());
255    ///
256    /// assert!(map.keys().eq([MyKey::First, MyKey::Second(false)]));
257    /// assert!(map.keys().rev().eq([MyKey::Second(false), MyKey::First]));
258    /// ```
259    #[inline]
260    pub fn keys(&self) -> Keys<'_, K, V> {
261        self.storage.keys()
262    }
263
264    /// An iterator visiting all values in arbitrary order.
265    /// The iterator element type is `&'a V`.
266    ///
267    /// # Examples
268    ///
269    /// ```
270    /// use fixed_map::{Key, Map};
271    ///
272    /// #[derive(Debug, Clone, Copy, PartialEq, Eq, Key)]
273    /// pub enum MyKey {
274    ///     First,
275    ///     Second,
276    ///     Third,
277    /// }
278    ///
279    /// let mut map = Map::new();
280    /// map.insert(MyKey::First, 1);
281    /// map.insert(MyKey::Second, 2);
282    ///
283    /// assert!(map.values().copied().eq([1, 2]));
284    /// assert!(map.values().rev().copied().eq([2, 1]));
285    /// ```
286    ///
287    /// Using a composite key:
288    ///
289    /// ```
290    /// use fixed_map::{Key, Map};
291    ///
292    /// #[derive(Debug, Clone, Copy, PartialEq, Eq, Key)]
293    /// pub enum MyKey {
294    ///     First(bool),
295    ///     Second,
296    ///     Third,
297    /// }
298    ///
299    /// let mut map = Map::new();
300    /// map.insert(MyKey::First(false), 1);
301    /// map.insert(MyKey::Second, 2);
302    ///
303    /// assert!(map.values().copied().eq([1, 2]));
304    /// assert!(map.values().rev().copied().eq([2, 1]));
305    /// ```
306    #[inline]
307    pub fn values(&self) -> Values<'_, K, V> {
308        self.storage.values()
309    }
310
311    /// An iterator visiting all key-value pairs in arbitrary order,
312    /// with mutable references to the values.
313    /// The iterator element type is `(K, &'a mut V)`.
314    ///
315    /// # Examples
316    ///
317    /// ```
318    /// use fixed_map::{Key, Map};
319    ///
320    /// #[derive(Debug, Clone, Copy, PartialEq, Eq, Key)]
321    /// enum MyKey {
322    ///     First,
323    ///     Second,
324    /// }
325    ///
326    /// let mut map = Map::new();
327    /// map.insert(MyKey::First, 1);
328    /// map.insert(MyKey::Second, 2);
329    ///
330    /// // Update all values
331    /// for (_, val) in map.iter_mut() {
332    ///     *val *= 2;
333    /// }
334    ///
335    /// assert!(map.iter().eq([(MyKey::First, &2), (MyKey::Second, &4)]));
336    /// ```
337    ///
338    /// Using a composite key:
339    ///
340    /// ```
341    /// use fixed_map::{Key, Map};
342    ///
343    /// #[derive(Debug, Clone, Copy, PartialEq, Eq, Key)]
344    /// enum MyKey {
345    ///     First(bool),
346    ///     Second,
347    /// }
348    ///
349    /// let mut map = Map::new();
350    /// map.insert(MyKey::First(true), 1);
351    /// map.insert(MyKey::Second, 2);
352    ///
353    /// // Update all values
354    /// for (_, val) in map.iter_mut() {
355    ///     *val *= 2;
356    /// }
357    ///
358    /// assert!(map.iter().eq([(MyKey::First(true), &2), (MyKey::Second, &4)]));
359    /// ```
360    #[inline]
361    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
362        self.storage.iter_mut()
363    }
364
365    /// An iterator visiting all values mutably in arbitrary order.
366    /// The iterator element type is `&'a mut V`.
367    ///
368    /// # Examples
369    ///
370    /// ```
371    /// use fixed_map::{Key, Map};
372    ///
373    /// #[derive(Debug, Clone, Copy, PartialEq, Eq, Key)]
374    /// pub enum MyKey {
375    ///     First,
376    ///     Second,
377    /// }
378    ///
379    /// let mut map = Map::new();
380    /// map.insert(MyKey::First, 2);
381    /// map.insert(MyKey::Second, 5);
382    ///
383    /// for (index, val) in map.values_mut().enumerate() {
384    ///     *val *= index + 1;
385    /// }
386    ///
387    /// assert!(map.values().copied().eq([2, 10]));
388    ///
389    /// let mut map = Map::new();
390    /// map.insert(MyKey::First, 2);
391    /// map.insert(MyKey::Second, 5);
392    ///
393    /// for (index, val) in map.values_mut().rev().enumerate() {
394    ///     *val *= index + 1;
395    /// }
396    ///
397    /// assert!(map.values().copied().eq([4, 5]));
398    /// ```
399    ///
400    /// Using a composite key:
401    ///
402    /// ```
403    /// use fixed_map::{Key, Map};
404    ///
405    /// #[derive(Debug, Clone, Copy, PartialEq, Eq, Key)]
406    /// pub enum MyKey {
407    ///     First(bool),
408    ///     Second,
409    /// }
410    ///
411    /// let mut map = Map::new();
412    /// map.insert(MyKey::First(false), 2);
413    /// map.insert(MyKey::Second, 5);
414    ///
415    /// for (index, val) in map.values_mut().enumerate() {
416    ///     *val *= index + 1;
417    /// }
418    ///
419    /// assert!(map.values().copied().eq([2, 10]));
420    ///
421    /// let mut map = Map::new();
422    /// map.insert(MyKey::First(false), 2);
423    /// map.insert(MyKey::Second, 5);
424    ///
425    /// for (index, val) in map.values_mut().rev().enumerate() {
426    ///     *val *= index + 1;
427    /// }
428    ///
429    /// assert!(map.values().copied().eq([4, 5]));
430    /// ```
431    #[inline]
432    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
433        self.storage.values_mut()
434    }
435
436    /// Returns `true` if the map currently contains the given key.
437    ///
438    /// # Examples
439    ///
440    /// ```
441    /// use fixed_map::{Key, Map};
442    ///
443    /// #[derive(Clone, Copy, Key)]
444    /// enum MyKey {
445    ///     First,
446    ///     Second,
447    /// }
448    ///
449    /// let mut map = Map::new();
450    /// map.insert(MyKey::First, "a");
451    /// assert_eq!(map.contains_key(MyKey::First), true);
452    /// assert_eq!(map.contains_key(MyKey::Second), false);
453    /// ```
454    #[inline]
455    pub fn contains_key(&self, key: K) -> bool {
456        self.storage.contains_key(key)
457    }
458
459    /// Returns a reference to the value corresponding to the key.
460    ///
461    /// # Examples
462    ///
463    /// ```
464    /// use fixed_map::{Key, Map};
465    ///
466    /// #[derive(Clone, Copy, Key)]
467    /// enum MyKey {
468    ///     First,
469    ///     Second,
470    /// }
471    ///
472    /// let mut map = Map::new();
473    /// map.insert(MyKey::First, "a");
474    /// assert_eq!(map.get(MyKey::First).copied(), Some("a"));
475    /// assert_eq!(map.get(MyKey::Second), None);
476    /// ```
477    ///
478    /// Using a composite key:
479    ///
480    /// ```
481    /// use fixed_map::{Key, Map};
482    ///
483    /// #[derive(Clone, Copy, Key)]
484    /// enum MyKey {
485    ///     First(bool),
486    ///     Second,
487    /// }
488    ///
489    /// let mut map = Map::new();
490    /// map.insert(MyKey::First(true), "a");
491    /// assert_eq!(map.get(MyKey::First(true)).copied(), Some("a"));
492    /// assert_eq!(map.get(MyKey::Second), None);
493    /// ```
494    #[inline]
495    pub fn get(&self, key: K) -> Option<&V> {
496        self.storage.get(key)
497    }
498
499    /// Returns a mutable reference to the value corresponding to the key.
500    ///
501    /// # Examples
502    ///
503    /// ```
504    /// use fixed_map::{Key, Map};
505    ///
506    /// #[derive(Clone, Copy, Key)]
507    /// enum MyKey {
508    ///     First,
509    ///     Second,
510    /// }
511    ///
512    /// let mut map = Map::new();
513    /// map.insert(MyKey::First, "a");
514    ///
515    /// if let Some(x) = map.get_mut(MyKey::First) {
516    ///     *x = "b";
517    /// }
518    ///
519    /// assert_eq!(map.get(MyKey::First).copied(), Some("b"));
520    /// ```
521    ///
522    /// Using a composite key:
523    ///
524    /// ```
525    /// use fixed_map::{Key, Map};
526    ///
527    /// #[derive(Clone, Copy, Key)]
528    /// enum MyKey {
529    ///     First(bool),
530    ///     Second(()),
531    ///     Third,
532    /// }
533    ///
534    /// let mut map = Map::new();
535    /// map.insert(MyKey::First(true), "a");
536    ///
537    /// if let Some(x) = map.get_mut(MyKey::First(true)) {
538    ///     *x = "b";
539    /// }
540    ///
541    /// assert_eq!(map.get(MyKey::First(true)).copied(), Some("b"));
542    /// ```
543    #[inline]
544    pub fn get_mut(&mut self, key: K) -> Option<&mut V> {
545        self.storage.get_mut(key)
546    }
547
548    /// Inserts a key-value pair into the map.
549    ///
550    /// If the map did not have this key present, [`None`] is returned.
551    ///
552    /// If the map did have this key present, the value is updated, and the old
553    /// value is returned.
554    ///
555    /// # Examples
556    ///
557    /// ```
558    /// use fixed_map::{Key, Map};
559    ///
560    /// #[derive(Clone, Copy, Key)]
561    /// enum MyKey {
562    ///     One,
563    ///     Two,
564    /// }
565    ///
566    /// let mut map = Map::new();
567    /// assert_eq!(map.insert(MyKey::One, "a"), None);
568    /// assert_eq!(map.is_empty(), false);
569    ///
570    /// map.insert(MyKey::Two, "b");
571    /// assert_eq!(map.insert(MyKey::Two, "c"), Some("b"));
572    /// assert_eq!(map.get(MyKey::Two), Some(&"c"));
573    /// ```
574    #[inline]
575    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
576        self.storage.insert(key, value)
577    }
578
579    /// Removes a key from the map, returning the value at the key if the key
580    /// was previously in the map.
581    ///
582    /// # Examples
583    ///
584    /// ```
585    /// use fixed_map::{Key, Map};
586    ///
587    /// #[derive(Clone, Copy, Key)]
588    /// enum MyKey {
589    ///     One,
590    ///     Two,
591    /// }
592    ///
593    /// let mut map = Map::new();
594    /// map.insert(MyKey::One, "a");
595    /// assert_eq!(map.remove(MyKey::One), Some("a"));
596    /// assert_eq!(map.remove(MyKey::One), None);
597    /// ```
598    #[inline]
599    pub fn remove(&mut self, key: K) -> Option<V> {
600        self.storage.remove(key)
601    }
602
603    /// Retains only the elements specified by the predicate.
604    ///
605    /// In other words, remove all pairs (k, v) for which f(k, &mut v) returns false.
606    /// The elements are visited in unsorted (and unspecified) order.
607    ///
608    /// # Examples
609    ///
610    /// ```
611    /// use fixed_map::{Key, Map};
612    ///
613    /// #[derive(Clone, Copy, Key)]
614    /// enum MyKey {
615    ///     First,
616    ///     Second,
617    /// }
618    ///
619    /// let mut map: Map<MyKey, i32> = Map::new();
620    ///
621    /// map.insert(MyKey::First, 42);
622    /// map.insert(MyKey::Second, -10);
623    ///
624    /// map.retain(|k, v| *v > 0);
625    ///
626    /// assert_eq!(map.len(), 1);
627    /// assert_eq!(map.get(MyKey::First), Some(&42));
628    /// assert_eq!(map.get(MyKey::Second), None);
629    /// ```
630    ///
631    /// Using a composite key:
632    ///
633    /// ```
634    /// use fixed_map::{Key, Map};
635    ///
636    /// #[derive(Clone, Copy, Key)]
637    /// enum MyKey {
638    ///     First(bool),
639    ///     Second,
640    /// }
641    ///
642    /// let mut map: Map<MyKey, i32> = Map::new();
643    ///
644    /// map.insert(MyKey::First(true), 42);
645    /// map.insert(MyKey::First(false), -31);
646    /// map.insert(MyKey::Second, 100);
647    ///
648    /// let mut other = map.clone();
649    /// assert_eq!(map.len(), 3);
650    ///
651    /// map.retain(|k, v| *v > 0);
652    ///
653    /// assert_eq!(map.len(), 2);
654    /// assert_eq!(map.get(MyKey::First(true)), Some(&42));
655    /// assert_eq!(map.get(MyKey::First(false)), None);
656    /// assert_eq!(map.get(MyKey::Second), Some(&100));
657    ///
658    /// other.retain(|k, v| matches!(k, MyKey::First(_)));
659    ///
660    /// assert_eq!(other.len(), 2);
661    /// assert_eq!(other.get(MyKey::First(true)), Some(&42));
662    /// assert_eq!(other.get(MyKey::First(false)), Some(&-31));
663    /// assert_eq!(other.get(MyKey::Second), None);
664    /// ```
665    #[inline]
666    pub fn retain<F>(&mut self, f: F)
667    where
668        F: FnMut(K, &mut V) -> bool,
669    {
670        self.storage.retain(f);
671    }
672
673    /// Clears the map, removing all key-value pairs. Keeps the allocated memory
674    /// for reuse.
675    ///
676    /// # Examples
677    ///
678    /// ```
679    /// use fixed_map::{Key, Map};
680    ///
681    /// #[derive(Clone, Copy, Key)]
682    /// enum MyKey {
683    ///     One,
684    ///     Two,
685    /// }
686    ///
687    /// let mut map = Map::new();
688    /// map.insert(MyKey::One, "a");
689    /// map.clear();
690    /// assert!(map.is_empty());
691    /// ```
692    #[inline]
693    pub fn clear(&mut self) {
694        self.storage.clear();
695    }
696
697    /// Returns true if the map contains no elements.
698    ///
699    /// # Examples
700    ///
701    /// ```
702    /// use fixed_map::{Key, Map};
703    ///
704    /// #[derive(Clone, Copy, Key)]
705    /// enum MyKey {
706    ///     First,
707    ///     Second,
708    /// }
709    ///
710    /// let mut map = Map::new();
711    /// assert!(map.is_empty());
712    /// map.insert(MyKey::First, 1);
713    /// assert!(!map.is_empty());
714    /// ```
715    ///
716    /// An empty key:
717    ///
718    /// ```
719    /// use fixed_map::{Key, Map};
720    ///
721    /// #[derive(Clone, Copy, Key)]
722    /// enum MyKey {}
723    ///
724    /// let map = Map::<MyKey, u32>::new();
725    /// assert!(map.is_empty());
726    /// ```
727    #[inline]
728    pub fn is_empty(&self) -> bool {
729        self.storage.is_empty()
730    }
731
732    /// Gets the current length of a [`Map`].
733    ///
734    /// # Examples
735    ///
736    /// ```
737    /// use fixed_map::{Key, Map};
738    ///
739    /// #[derive(Clone, Copy, Key)]
740    /// enum MyKey {
741    ///     First,
742    ///     Second,
743    /// }
744    ///
745    /// let mut map: Map<MyKey, i32> = Map::new();
746    /// assert_eq!(map.len(), 0);
747    ///
748    /// map.insert(MyKey::First, 42);
749    /// assert_eq!(map.len(), 1);
750    ///
751    /// map.insert(MyKey::First, 42);
752    /// assert_eq!(map.len(), 1);
753    ///
754    /// map.remove(MyKey::First);
755    /// assert_eq!(map.len(), 0);
756    /// ```
757    ///
758    /// Using a composite key:
759    ///
760    /// ```
761    /// use fixed_map::{Key, Map};
762    ///
763    /// #[derive(Clone, Copy, Key)]
764    /// enum MyKey {
765    ///     First(bool),
766    ///     Second,
767    /// }
768    ///
769    /// let mut map: Map<MyKey, i32> = Map::new();
770    /// assert_eq!(map.len(), 0);
771    ///
772    /// map.insert(MyKey::First(true), 42);
773    /// assert_eq!(map.len(), 1);
774    ///
775    /// map.insert(MyKey::First(false), 42);
776    /// assert_eq!(map.len(), 2);
777    ///
778    /// map.remove(MyKey::First(true));
779    /// assert_eq!(map.len(), 1);
780    /// ```
781    #[inline]
782    pub fn len(&self) -> usize {
783        self.storage.len()
784    }
785
786    /// Gets the given key’s corresponding [`Entry`] in the [`Map`] for in-place manipulation.
787    ///
788    /// # Examples
789    ///
790    /// ```
791    /// use fixed_map::{Key, Map};
792    ///
793    /// #[derive(Clone, Copy, Key)]
794    /// enum MyKey {
795    ///     Even,
796    ///     Odd,
797    /// }
798    ///
799    /// let mut map: Map<MyKey, u32> = Map::new();
800    ///
801    /// for n in [3, 45, 3, 23, 2, 10, 59, 11, 51, 70] {
802    ///     map
803    ///         .entry(if n % 2 == 0 { MyKey::Even } else { MyKey::Odd })
804    ///         .and_modify(|x| *x += 1)
805    ///         .or_insert(1);
806    /// }
807    ///
808    /// assert_eq!(map.get(MyKey::Even), Some(&3));
809    /// assert_eq!(map.get(MyKey::Odd), Some(&7));
810    /// ```
811    ///
812    /// Using a composite key:
813    ///
814    /// ```
815    /// use fixed_map::{Key, Map};
816    ///
817    /// #[derive(Clone, Copy, Key)]
818    /// enum MyKey {
819    ///     First(bool),
820    ///     Second,
821    /// }
822    ///
823    /// let mut map: Map<MyKey, Vec<i32>> = Map::new();
824    ///
825    /// map.entry(MyKey::First(true)).or_default().push(1);
826    /// map.entry(MyKey::Second).or_insert_with(|| vec![2; 8]).truncate(4);
827    ///
828    /// assert_eq!(map.get(MyKey::First(true)), Some(&vec![1]));
829    /// assert_eq!(map.get(MyKey::Second), Some(&vec![2; 4]));
830    /// ```
831    #[inline]
832    pub fn entry(&mut self, key: K) -> Entry<'_, K::MapStorage<V>, K, V> {
833        K::MapStorage::entry(&mut self.storage, key)
834    }
835}
836
837/// [`Clone`] implementation for a [`Map`].
838///
839/// # Examples
840///
841/// ```
842/// use fixed_map::{Key, Map};
843///
844/// #[derive(Debug, Clone, Copy, Key)]
845/// enum MyKey {
846///     First(bool),
847///     Second,
848/// }
849///
850/// let mut a = Map::new();
851/// a.insert(MyKey::First(true), 1);
852/// let mut b = a.clone();
853/// b.insert(MyKey::Second, 2);
854///
855/// assert_ne!(a, b);
856///
857/// assert_eq!(a.get(MyKey::First(true)), Some(&1));
858/// assert_eq!(a.get(MyKey::Second), None);
859///
860/// assert_eq!(b.get(MyKey::First(true)), Some(&1));
861/// assert_eq!(b.get(MyKey::Second), Some(&2));
862/// ```
863impl<K, V> Clone for Map<K, V>
864where
865    K: Key,
866    K::MapStorage<V>: Clone,
867{
868    #[inline]
869    fn clone(&self) -> Map<K, V> {
870        Map {
871            storage: self.storage.clone(),
872        }
873    }
874}
875
876/// The [`Copy`] implementation for a [`Map`] depends on its [`Key`]. If the
877/// derived key only consists of unit variants the corresponding [`Map`] will be
878/// [`Copy`] as well.
879///
880/// # Examples
881///
882/// ```
883/// use fixed_map::{Key, Map};
884///
885/// #[derive(Debug, Clone, Copy, Key)]
886/// enum MyKey {
887///     First,
888///     Second,
889/// }
890///
891/// let mut a = Map::new();
892/// a.insert(MyKey::First, 1);
893/// let mut b = a;
894/// b.insert(MyKey::Second, 2);
895///
896/// assert_ne!(a, b);
897///
898/// assert_eq!(a.get(MyKey::First), Some(&1));
899/// assert_eq!(a.get(MyKey::Second), None);
900///
901/// assert_eq!(b.get(MyKey::First), Some(&1));
902/// assert_eq!(b.get(MyKey::Second), Some(&2));
903/// ```
904impl<K, V> Copy for Map<K, V>
905where
906    K: Key,
907    K::MapStorage<V>: Copy,
908{
909}
910
911/// The [`Default`] implementation for a [`Map`] produces an empty map.
912///
913/// # Examples
914///
915/// ```
916/// use fixed_map::{Key, Map};
917///
918/// #[derive(Debug, Clone, Copy, Key)]
919/// enum MyKey {
920///     First,
921///     Second,
922/// }
923///
924/// let a = Map::<MyKey, u32>::default();
925/// let b = Map::<MyKey, u32>::new();
926///
927/// assert_eq!(a, b);
928/// ```
929impl<K, V> Default for Map<K, V>
930where
931    K: Key,
932{
933    #[inline]
934    fn default() -> Self {
935        Self::new()
936    }
937}
938
939/// The [`Debug`][fmt::Debug] implementation for a [`Map`].
940///
941/// # Examples
942///
943/// ```
944/// use fixed_map::{Key, Map};
945///
946/// #[derive(Debug, Clone, Copy, Key)]
947/// enum MyKey {
948///     First,
949///     Second,
950/// }
951///
952/// let mut a = Map::new();
953/// a.insert(MyKey::First, 42);
954///
955/// assert_eq!("{First: 42}", format!("{:?}", a));
956/// ```
957impl<K, V> fmt::Debug for Map<K, V>
958where
959    K: Key + fmt::Debug,
960    V: fmt::Debug,
961{
962    #[inline]
963    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
964        f.debug_map().entries(self.iter()).finish()
965    }
966}
967
968/// [`PartialEq`] implementation for a [`Map`].
969///
970/// # Examples
971///
972/// ```
973/// use fixed_map::{Key, Map};
974///
975/// #[derive(Debug, Clone, Copy, Key)]
976/// enum MyKey {
977///     First,
978///     Second,
979/// }
980///
981/// let mut a = Map::new();
982/// a.insert(MyKey::First, 42);
983/// // Note: `a` is Copy since it's using a simple key.
984/// let mut b = a;
985///
986/// assert_eq!(a, b);
987///
988/// b.insert(MyKey::Second, 42);
989/// assert_ne!(a, b);
990/// ```
991///
992/// Using a composite key:
993///
994/// ```
995/// use fixed_map::{Key, Map};
996///
997/// #[derive(Debug, Clone, Copy, Key)]
998/// enum MyKey {
999///     First(bool),
1000///     Second,
1001/// }
1002///
1003/// let mut a = Map::new();
1004/// a.insert(MyKey::First(true), 42);
1005/// let mut b = a.clone();
1006///
1007/// assert_eq!(a, b);
1008///
1009/// b.insert(MyKey::Second, 42);
1010/// assert_ne!(a, b);
1011/// ```
1012impl<K, V> PartialEq for Map<K, V>
1013where
1014    K: Key,
1015    K::MapStorage<V>: PartialEq,
1016{
1017    #[inline]
1018    fn eq(&self, other: &Self) -> bool {
1019        self.storage == other.storage
1020    }
1021}
1022
1023impl<K, V> Eq for Map<K, V>
1024where
1025    K: Key,
1026    K::MapStorage<V>: Eq,
1027{
1028}
1029
1030/// [`Hash`] implementation for a [`Set`].
1031///
1032/// [`Set`]: crate::Set
1033///
1034/// # Examples
1035///
1036/// ```
1037/// use std::collections::HashSet;
1038///
1039/// use fixed_map::{Key, Map};
1040///
1041/// #[derive(Debug, Clone, Copy, Hash, Key)]
1042/// enum MyKey {
1043///     First,
1044///     Second,
1045/// }
1046///
1047/// let mut a = Map::new();
1048/// a.insert(MyKey::First, 1);
1049///
1050/// let mut set = HashSet::new();
1051/// set.insert(a);
1052/// ```
1053///
1054/// Using a composite key:
1055///
1056/// ```
1057/// use std::collections::HashSet;
1058///
1059/// use fixed_map::{Key, Map};
1060///
1061/// #[derive(Debug, Clone, Copy, Hash, Key)]
1062/// enum MyKey {
1063///     First(bool),
1064///     Second,
1065/// }
1066///
1067/// let mut a = Map::new();
1068/// a.insert(MyKey::First(true), 1);
1069///
1070/// // TODO: support this
1071/// // let mut set = HashSet::new();
1072/// // set.insert(a);
1073/// ```
1074impl<K, V> Hash for Map<K, V>
1075where
1076    K: Key,
1077    K::MapStorage<V>: Hash,
1078{
1079    #[inline]
1080    fn hash<H>(&self, state: &mut H)
1081    where
1082        H: Hasher,
1083    {
1084        self.storage.hash(state);
1085    }
1086}
1087
1088/// [`PartialOrd`] implementation for a [`Map`].
1089///
1090/// For more details on ordering, see the [`Key`] documentation.
1091///
1092/// # Examples
1093///
1094/// ```
1095/// use fixed_map::{Key, Map};
1096///
1097/// #[derive(Debug, Clone, Copy, Hash, Key)]
1098/// enum MyKey {
1099///     First,
1100///     Second,
1101///     Third,
1102/// }
1103///
1104/// let mut a = Map::new();
1105/// a.insert(MyKey::First, 1);
1106///
1107/// let mut b = Map::new();
1108/// b.insert(MyKey::Third, 1);
1109///
1110/// assert!(a < b);
1111///
1112/// let mut empty = Map::new();
1113/// assert!(empty < a);
1114/// assert!(empty < b);
1115/// ```
1116///
1117/// Using a composite key:
1118///
1119/// ```
1120/// use fixed_map::{Key, Map};
1121///
1122/// #[derive(Debug, Clone, Copy, Hash, Key)]
1123/// enum MyKey {
1124///     First(bool),
1125///     Second,
1126/// }
1127///
1128/// let mut a = Map::new();
1129/// a.insert(MyKey::First(true), 1);
1130///
1131/// let mut b = Map::new();
1132/// b.insert(MyKey::Second, 1);
1133///
1134/// // TODO: support this
1135/// // assert!(a < b);
1136/// ```
1137impl<K, V> PartialOrd for Map<K, V>
1138where
1139    K: Key,
1140    K::MapStorage<V>: PartialOrd,
1141{
1142    #[inline]
1143    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1144        self.storage.partial_cmp(&other.storage)
1145    }
1146
1147    #[inline]
1148    fn lt(&self, other: &Self) -> bool {
1149        self.storage.lt(&other.storage)
1150    }
1151
1152    #[inline]
1153    fn le(&self, other: &Self) -> bool {
1154        self.storage.le(&other.storage)
1155    }
1156
1157    #[inline]
1158    fn gt(&self, other: &Self) -> bool {
1159        self.storage.gt(&other.storage)
1160    }
1161
1162    #[inline]
1163    fn ge(&self, other: &Self) -> bool {
1164        self.storage.ge(&other.storage)
1165    }
1166}
1167
1168/// [`Ord`] implementation for a [`Map`].
1169///
1170/// For more details on ordering, see the [`Key`] documentation.
1171///
1172/// # Examples
1173///
1174/// ```
1175/// use fixed_map::{Key, Map};
1176///
1177/// #[derive(Debug, Clone, Copy, Hash, Key)]
1178/// enum MyKey {
1179///     First,
1180///     Second,
1181/// }
1182///
1183/// let mut a = Map::new();
1184/// a.insert(MyKey::First, 1);
1185///
1186/// let mut b = Map::new();
1187/// b.insert(MyKey::Second, 1);
1188///
1189/// let mut list = vec![b, a];
1190/// list.sort();
1191///
1192/// assert_eq!(list, [a, b]);
1193/// ```
1194///
1195/// Using a composite key:
1196///
1197/// ```
1198/// use fixed_map::{Key, Map};
1199///
1200/// #[derive(Debug, Clone, Copy, Hash, Key)]
1201/// enum MyKey {
1202///     First(bool),
1203///     Second,
1204/// }
1205///
1206/// let mut a = Map::new();
1207/// a.insert(MyKey::First(true), 1);
1208///
1209/// let mut b = Map::new();
1210/// b.insert(MyKey::Second, 1);
1211///
1212/// // TODO: support this
1213/// // let mut list = vec![a, b];
1214/// // list.sort();
1215/// ```
1216impl<K, V> Ord for Map<K, V>
1217where
1218    K: Key,
1219    K::MapStorage<V>: Ord,
1220{
1221    #[inline]
1222    fn cmp(&self, other: &Self) -> Ordering {
1223        self.storage.cmp(&other.storage)
1224    }
1225
1226    #[inline]
1227    fn max(self, other: Self) -> Self {
1228        Self {
1229            storage: self.storage.max(other.storage),
1230        }
1231    }
1232
1233    #[inline]
1234    fn min(self, other: Self) -> Self {
1235        Self {
1236            storage: self.storage.min(other.storage),
1237        }
1238    }
1239
1240    #[inline]
1241    fn clamp(self, min: Self, max: Self) -> Self {
1242        Self {
1243            storage: self.storage.clamp(min.storage, max.storage),
1244        }
1245    }
1246}
1247
1248impl<'a, K, V> IntoIterator for &'a Map<K, V>
1249where
1250    K: Key,
1251{
1252    type Item = (K, &'a V);
1253    type IntoIter = Iter<'a, K, V>;
1254
1255    #[inline]
1256    fn into_iter(self) -> Self::IntoIter {
1257        self.iter()
1258    }
1259}
1260
1261/// [`IntoIterator`] implementation which uses [`Map::iter_mut`]. See its
1262/// documentation for more.
1263impl<'a, K, V> IntoIterator for &'a mut Map<K, V>
1264where
1265    K: Key,
1266{
1267    type Item = (K, &'a mut V);
1268    type IntoIter = IterMut<'a, K, V>;
1269
1270    #[inline]
1271    fn into_iter(self) -> Self::IntoIter {
1272        self.iter_mut()
1273    }
1274}
1275
1276/// Produce an owning iterator visiting all key-value pairs of the [`Map`] in an
1277/// arbitrary order. The iterator element type is `(K, V)`.
1278///
1279/// # Examples
1280///
1281/// ```
1282/// use fixed_map::{Key, Map};
1283///
1284/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Key)]
1285/// enum MyKey {
1286///     First,
1287///     Second,
1288///     Third,
1289/// }
1290///
1291/// let mut map = Map::new();
1292/// map.insert(MyKey::First, 1);
1293/// map.insert(MyKey::Third, 3);
1294///
1295/// let mut it = map.into_iter();
1296/// assert_eq!(it.next(), Some((MyKey::First, 1)));
1297/// assert_eq!(it.next(), Some((MyKey::Third, 3)));
1298/// assert_eq!(it.next(), None);
1299///
1300/// let mut it = map.into_iter().rev();
1301/// assert_eq!(it.next(), Some((MyKey::Third, 3)));
1302/// assert_eq!(it.next(), Some((MyKey::First, 1)));
1303/// assert_eq!(it.next(), None);
1304/// ```
1305///
1306/// Into iterator with a composite key:
1307///
1308/// ```
1309/// use fixed_map::{Key, Map};
1310///
1311/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Key)]
1312/// enum MyKey {
1313///     First(bool),
1314///     Second,
1315///     Third,
1316/// }
1317///
1318/// let mut map = Map::<_, u32>::new();
1319/// map.insert(MyKey::First(false), 1);
1320/// map.insert(MyKey::Third, 3);
1321///
1322/// let mut it = map.into_iter();
1323/// assert_eq!(it.next(), Some((MyKey::First(false), 1)));
1324/// assert_eq!(it.next(), Some((MyKey::Third, 3)));
1325/// assert_eq!(it.next(), None);
1326///
1327/// let mut it = map.into_iter().rev();
1328/// assert_eq!(it.next(), Some((MyKey::Third, 3)));
1329/// assert_eq!(it.next(), Some((MyKey::First(false), 1)));
1330/// assert_eq!(it.next(), None);
1331/// ```
1332impl<K, V> IntoIterator for Map<K, V>
1333where
1334    K: Key,
1335{
1336    type Item = (K, V);
1337    type IntoIter = IntoIter<K, V>;
1338
1339    #[inline]
1340    fn into_iter(self) -> Self::IntoIter {
1341        self.storage.into_iter()
1342    }
1343}
1344
1345/// A simple [`FromIterator`] implementation for [`Map`].
1346///
1347/// # Example
1348///
1349/// ```
1350/// use fixed_map::{Key, Map};
1351///
1352/// #[derive(Debug, Clone, Copy, Key)]
1353/// enum MyKey {
1354///     First,
1355///     Second,
1356/// }
1357///
1358/// let v = vec![(MyKey::First, 1), (MyKey::Second, 2), (MyKey::First, 3)];
1359/// let m: Map<_, u8> = v.into_iter().collect();
1360///
1361/// let mut n = Map::new();
1362/// n.insert(MyKey::Second, 2);
1363/// n.insert(MyKey::First, 3);
1364///
1365/// assert_eq!(m, n);
1366/// ```
1367impl<K, V> FromIterator<(K, V)> for Map<K, V>
1368where
1369    K: Key,
1370{
1371    #[inline]
1372    fn from_iter<T>(iter: T) -> Self
1373    where
1374        T: IntoIterator<Item = (K, V)>,
1375    {
1376        let mut map = Self::new();
1377        for (k, v) in iter {
1378            map.insert(k, v);
1379        }
1380        map
1381    }
1382}
1383
1384#[cfg(feature = "serde")]
1385impl<K, V> serde::Serialize for Map<K, V>
1386where
1387    K: Key + serde::Serialize,
1388    V: serde::Serialize,
1389{
1390    #[inline]
1391    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1392    where
1393        S: serde::Serializer,
1394    {
1395        use serde::ser::SerializeMap as _;
1396
1397        let mut map = serializer.serialize_map(Some(self.len()))?;
1398
1399        for (k, v) in self {
1400            map.serialize_entry(&k, v)?;
1401        }
1402
1403        map.end()
1404    }
1405}
1406
1407#[cfg(feature = "serde")]
1408impl<'de, K, V> serde::de::Deserialize<'de> for Map<K, V>
1409where
1410    K: Key + serde::de::Deserialize<'de>,
1411    V: serde::Deserialize<'de>,
1412{
1413    #[inline]
1414    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1415    where
1416        D: serde::Deserializer<'de>,
1417    {
1418        struct MapVisitor<K, V>(core::marker::PhantomData<(K, V)>);
1419
1420        impl<'de, K, V> serde::de::Visitor<'de> for MapVisitor<K, V>
1421        where
1422            K: Key + serde::de::Deserialize<'de>,
1423            V: serde::Deserialize<'de>,
1424        {
1425            type Value = Map<K, V>;
1426
1427            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1428                formatter.write_str("a map")
1429            }
1430
1431            #[inline]
1432            fn visit_map<T>(self, mut visitor: T) -> Result<Self::Value, T::Error>
1433            where
1434                T: serde::de::MapAccess<'de>,
1435            {
1436                let mut map = Map::new();
1437
1438                while let Some((key, value)) = visitor.next_entry()? {
1439                    map.insert(key, value);
1440                }
1441
1442                Ok(map)
1443            }
1444        }
1445
1446        deserializer.deserialize_map(MapVisitor(core::marker::PhantomData))
1447    }
1448}