nonempty_collections/
map.rs

1//! Non-empty [`HashMap`]s.
2
3use core::fmt;
4use std::borrow::Borrow;
5use std::collections::HashMap;
6use std::hash::BuildHasher;
7use std::hash::Hash;
8use std::num::NonZeroUsize;
9
10#[cfg(feature = "serde")]
11use serde::Deserialize;
12#[cfg(feature = "serde")]
13use serde::Serialize;
14
15use crate::FromNonEmptyIterator;
16use crate::IntoIteratorExt;
17use crate::IntoNonEmptyIterator;
18use crate::NonEmptyIterator;
19
20/// Like the [`crate::nev!`] macro, but for Maps. A nice short-hand for
21/// constructing [`NEMap`] values.
22///
23/// ```
24/// use nonempty_collections::nem;
25///
26/// let m = nem! {"elves" => 3000, "orcs" => 10000};
27/// assert_eq!(2, m.len().get());
28/// ```
29#[macro_export]
30macro_rules! nem {
31    ($hk:expr => $hv:expr, $( $xk:expr => $xv:expr ),* $(,)?) => {{
32        let mut map = $crate::NEMap::new($hk, $hv);
33        $( map.insert($xk, $xv); )*
34        map
35    }};
36    ($hk:expr => $hv:expr) => {
37        $crate::NEMap::new($hk, $hv)
38    }
39}
40
41/// A non-empty, growable `HashMap`.
42///
43/// ```
44/// use nonempty_collections::nem;
45///
46/// let m = nem!["elves" => 3000, "orcs" => 10000];
47/// assert_eq!(2, m.len().get());
48/// ```
49#[allow(clippy::unsafe_derive_deserialize)]
50#[cfg_attr(
51    feature = "serde",
52    derive(Deserialize, Serialize),
53    serde(bound(
54        serialize = "K: Eq + Hash + Clone + Serialize, V: Clone + Serialize, S: Clone + BuildHasher",
55        deserialize = "K: Eq + Hash + Clone + Deserialize<'de>, V: Deserialize<'de>, S: Default + BuildHasher"
56    )),
57    serde(into = "HashMap<K, V, S>", try_from = "HashMap<K, V, S>")
58)]
59#[derive(Clone)]
60pub struct NEMap<K, V, S = std::collections::hash_map::RandomState> {
61    inner: HashMap<K, V, S>,
62}
63
64impl<K, V> NEMap<K, V>
65where
66    K: Eq + Hash,
67{
68    /// Creates a new `NEMap` with a single element.
69    #[must_use]
70    pub fn new(k: K, v: V) -> NEMap<K, V> {
71        let mut inner = HashMap::new();
72        inner.insert(k, v);
73        NEMap { inner }
74    }
75
76    /// Creates a new `NEMap` with a single element and specified capacity.
77    /// ```
78    /// use std::num::*;
79    ///
80    /// use nonempty_collections::*;
81    /// let map = NEMap::with_capacity(NonZeroUsize::MIN, 1, 1);
82    /// assert_eq!(nem! { 1 => 1 }, map);
83    /// assert!(map.capacity().get() >= 1);
84    /// ```
85    #[must_use]
86    pub fn with_capacity(capacity: NonZeroUsize, k: K, v: V) -> NEMap<K, V> {
87        let mut inner = HashMap::with_capacity(capacity.get());
88        inner.insert(k, v);
89        NEMap { inner }
90    }
91}
92
93impl<K, V, S> NEMap<K, V, S> {
94    /// Attempt a conversion from [`HashMap`], consuming the given `HashMap`.
95    /// Will return `None` if the `HashMap` is empty.
96    ///
97    /// ```
98    /// use std::collections::*;
99    ///
100    /// use nonempty_collections::*;
101    ///
102    /// let mut map = HashMap::new();
103    /// map.extend([("a", 1), ("b", 2)]);
104    /// assert_eq!(Some(nem! {"a" => 1, "b" => 2}), NEMap::try_from_map(map));
105    /// let map: HashMap<(), ()> = HashMap::new();
106    /// assert_eq!(None, NEMap::try_from_map(map));
107    /// ```
108    #[must_use]
109    pub fn try_from_map(map: HashMap<K, V, S>) -> Option<Self> {
110        if map.is_empty() {
111            None
112        } else {
113            Some(Self { inner: map })
114        }
115    }
116
117    /// Returns the number of elements the map can hold without reallocating.
118    #[must_use]
119    pub fn capacity(&self) -> NonZeroUsize {
120        unsafe { NonZeroUsize::new_unchecked(self.inner.capacity()) }
121    }
122
123    /// Returns a reference to the map's `BuildHasher`.
124    #[must_use]
125    pub fn hasher(&self) -> &S {
126        self.inner.hasher()
127    }
128
129    /// Returns a regular iterator over the entries in this non-empty map.
130    ///
131    /// For a `NonEmptyIterator` see `Self::nonempty_iter()`.
132    pub fn iter(&self) -> std::collections::hash_map::Iter<'_, K, V> {
133        self.inner.iter()
134    }
135
136    /// Returns a regular mutable iterator over the entries in this non-empty
137    /// map.
138    ///
139    /// For a `NonEmptyIterator` see `Self::nonempty_iter_mut()`.
140    pub fn iter_mut(&mut self) -> std::collections::hash_map::IterMut<'_, K, V> {
141        self.inner.iter_mut()
142    }
143
144    /// An iterator visiting all elements in arbitrary order. The iterator
145    /// element type is `(&'a K, &'a V)`.
146    pub fn nonempty_iter(&self) -> Iter<'_, K, V> {
147        Iter {
148            iter: self.inner.iter(),
149        }
150    }
151
152    /// An iterator visiting all elements in arbitrary order. The iterator
153    /// element type is `(&'a K, &'a mut V)`.
154    ///
155    /// # Panics
156    ///
157    /// If you manually advance this iterator until empty and then call `first`,
158    /// you're in for a surprise.
159    pub fn nonempty_iter_mut(&mut self) -> IterMut<'_, K, V> {
160        IterMut {
161            iter: self.inner.iter_mut(),
162        }
163    }
164
165    /// An iterator visiting all keys in arbitrary order. The iterator element
166    /// type is `&'a K`.
167    ///
168    /// ```
169    /// use nonempty_collections::*;
170    ///
171    /// let m = nem!["Valmar" => "Vanyar", "Tirion" => "Noldor", "Alqualondë" => "Teleri"];
172    /// let mut v: NEVec<_> = m.keys().collect();
173    /// v.sort();
174    /// assert_eq!(nev![&"Alqualondë", &"Tirion", &"Valmar"], v);
175    /// ```
176    pub fn keys(&self) -> Keys<'_, K, V> {
177        Keys {
178            inner: self.inner.keys(),
179        }
180    }
181
182    /// Returns the number of elements in the map. Always 1 or more.
183    ///
184    /// ```
185    /// use nonempty_collections::nem;
186    ///
187    /// let m = nem!["a" => 1, "b" => 2];
188    /// assert_eq!(2, m.len().get());
189    /// ```
190    #[must_use]
191    pub fn len(&self) -> NonZeroUsize {
192        unsafe { NonZeroUsize::new_unchecked(self.inner.len()) }
193    }
194
195    /// A `NEMap` is never empty.
196    #[deprecated(since = "0.1.0", note = "A NEMap is never empty.")]
197    #[must_use]
198    pub const fn is_empty(&self) -> bool {
199        false
200    }
201
202    /// An iterator visiting all values in arbitrary order. The iterator element
203    /// type is `&'a V`.
204    ///
205    /// ```
206    /// use nonempty_collections::*;
207    ///
208    /// let m = nem!["Valmar" => "Vanyar", "Tirion" => "Noldor", "Alqualondë" => "Teleri"];
209    /// let mut v: NEVec<_> = m.values().collect();
210    /// v.sort();
211    /// assert_eq!(nev![&"Noldor", &"Teleri", &"Vanyar"], v);
212    /// ```
213    pub fn values(&self) -> Values<'_, K, V> {
214        Values {
215            inner: self.inner.values(),
216        }
217    }
218
219    // /// An iterator visiting all values mutably in arbitrary order. The iterator
220    // /// element type is `&'a mut V`.
221    // ///
222    // /// ```
223    // /// use nonempty_collections::nem;
224    // ///
225    // /// let mut m = nem!["Valmar" => 10000, "Tirion" => 10000, "Alqualondë" =>
226    // 10000]; ///
227    // /// for v in m.values_mut() {
228    // ///     *v += 1000;
229    // /// }
230    // /// ```
231    // pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
232    //     ValuesMut {
233    //         inner: self.iter_mut(),
234    //         head_val: todo!(),
235    //     }
236    // }
237}
238
239impl<K, V, S> NEMap<K, V, S>
240where
241    K: Eq + Hash,
242    S: BuildHasher,
243{
244    /// Returns true if the map contains a value.
245    ///
246    /// ```
247    /// use nonempty_collections::nem;
248    ///
249    /// let m = nem!["Jack" => 8];
250    /// assert!(m.contains_key("Jack"));
251    /// assert!(!m.contains_key("Colin"));
252    /// ```
253    #[must_use]
254    pub fn contains_key<Q>(&self, k: &Q) -> bool
255    where
256        K: Borrow<Q>,
257        Q: Eq + Hash + ?Sized,
258    {
259        self.inner.contains_key(k)
260    }
261
262    /// Returns a reference to the value corresponding to the key.
263    ///
264    /// The key may be any borrowed form of the map's value type, but `Hash` and
265    /// `Eq` on the borrowed form must match those for the key type.
266    ///
267    /// ```
268    /// use nonempty_collections::nem;
269    ///
270    /// let m = nem!["silmarils" => 3];
271    /// assert_eq!(Some(&3), m.get("silmarils"));
272    /// assert_eq!(None, m.get("arkenstone"));
273    /// ```
274    #[must_use]
275    pub fn get<Q>(&self, k: &Q) -> Option<&V>
276    where
277        K: Borrow<Q>,
278        Q: Eq + Hash + ?Sized,
279    {
280        self.inner.get(k)
281    }
282
283    /// Returns the key-value pair corresponding to the key.
284    ///
285    /// The key may be any borrowed form of the map's value type, but `Hash` and
286    /// `Eq` on the borrowed form must match those for the key type.
287    ///
288    /// ```
289    /// use nonempty_collections::nem;
290    ///
291    /// let m = nem!["silmarils" => 3];
292    /// assert_eq!(Some((&"silmarils", &3)), m.get_key_value("silmarils"));
293    /// assert_eq!(None, m.get_key_value("arkenstone"));
294    /// ```
295    #[must_use]
296    pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
297    where
298        K: Borrow<Q>,
299        Q: Eq + Hash + ?Sized,
300    {
301        self.inner.get_key_value(k)
302    }
303
304    /// Returns a reference to the value corresponding to the key.
305    ///
306    /// The key may be any borrowed form of the map's value type, but `Hash` and
307    /// `Eq` on the borrowed form must match those for the key type.
308    ///
309    /// ```
310    /// use nonempty_collections::nem;
311    ///
312    /// let mut m = nem!["silmarils" => 3];
313    /// let mut v = m.get_mut("silmarils").unwrap();
314    ///
315    /// // And thus it came to pass that the Silmarils found their long homes:
316    /// // one in the airs of heaven, and one in the fires of the heart of the
317    /// // world, and one in the deep waters.
318    /// *v -= 3;
319    ///
320    /// assert_eq!(Some(&0), m.get("silmarils"));
321    /// ```
322    #[must_use]
323    pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
324    where
325        K: Borrow<Q>,
326        Q: Eq + Hash + ?Sized,
327    {
328        self.inner.get_mut(k)
329    }
330
331    /// Insert a key-value pair into the map.
332    ///
333    /// If the map did not have this present, [`None`] is returned.
334    ///
335    /// If the map did have this key present, the value is updated, and the old
336    /// value is returned. The key is not updated, though; this matters for
337    /// types that can be `==` without being identical. See [`HashMap::insert`]
338    /// for more.
339    ///
340    /// ```
341    /// use nonempty_collections::nem;
342    ///
343    /// let mut m = nem!["Vilya" => "Elrond", "Nenya" => "Galadriel"];
344    /// assert_eq!(None, m.insert("Narya", "Cirdan"));
345    ///
346    /// // The Ring of Fire was given to Gandalf upon his arrival in Middle Earth.
347    /// assert_eq!(Some("Cirdan"), m.insert("Narya", "Gandalf"));
348    /// ```
349    pub fn insert(&mut self, k: K, v: V) -> Option<V> {
350        self.inner.insert(k, v)
351    }
352
353    /// Shrinks the capacity of the map as much as possible. It will drop down
354    /// as much as possible while maintaining the internal rules and possibly
355    /// leaving some space in accordance with the resize policy.
356    pub fn shrink_to_fit(&mut self) {
357        self.inner.shrink_to_fit();
358    }
359
360    /// See [`HashMap::with_capacity_and_hasher`].
361    #[must_use]
362    pub fn with_capacity_and_hasher(
363        capacity: NonZeroUsize,
364        hasher: S,
365        k: K,
366        v: V,
367    ) -> NEMap<K, V, S> {
368        let mut inner = HashMap::with_capacity_and_hasher(capacity.get(), hasher);
369        inner.insert(k, v);
370        NEMap { inner }
371    }
372
373    /// See [`HashMap::with_hasher`].
374    #[must_use]
375    pub fn with_hasher(hasher: S, k: K, v: V) -> NEMap<K, V, S> {
376        let mut inner = HashMap::with_hasher(hasher);
377        inner.insert(k, v);
378        NEMap { inner }
379    }
380}
381
382impl<K, V, S> AsRef<HashMap<K, V, S>> for NEMap<K, V, S> {
383    fn as_ref(&self) -> &HashMap<K, V, S> {
384        &self.inner
385    }
386}
387
388impl<K, V, S> AsMut<HashMap<K, V, S>> for NEMap<K, V, S> {
389    fn as_mut(&mut self) -> &mut HashMap<K, V, S> {
390        &mut self.inner
391    }
392}
393
394impl<K, V, S> PartialEq for NEMap<K, V, S>
395where
396    K: Eq + Hash,
397    V: PartialEq,
398    S: BuildHasher,
399{
400    /// This is an `O(n)` comparison of each key/value pair, one by one.
401    /// Short-circuits if any comparison fails.
402    ///
403    /// ```
404    /// use nonempty_collections::*;
405    ///
406    /// let m0 = nem!['a' => 1, 'b' => 2];
407    /// let m1 = nem!['b' => 2, 'a' => 1];
408    /// assert_eq!(m0, m1);
409    /// ```
410    fn eq(&self, other: &Self) -> bool {
411        self.inner.eq(&other.inner)
412    }
413}
414
415impl<K, V, S> Eq for NEMap<K, V, S>
416where
417    K: Eq + Hash,
418    V: Eq,
419    S: BuildHasher,
420{
421}
422
423impl<K, V, S> From<NEMap<K, V, S>> for HashMap<K, V, S>
424where
425    K: Eq + Hash,
426    S: BuildHasher,
427{
428    /// ```
429    /// use nonempty_collections::nem;
430    /// use std::collections::HashMap;
431    ///
432    /// let m: HashMap<&str, usize> = nem!["population" => 1000].into();
433    /// assert!(m.contains_key("population"));
434    /// ```
435    fn from(m: NEMap<K, V, S>) -> Self {
436        m.inner
437    }
438}
439
440impl<K, V, S> TryFrom<HashMap<K, V, S>> for NEMap<K, V, S>
441where
442    K: Eq + Hash,
443    S: BuildHasher + Default,
444{
445    type Error = crate::Error;
446
447    fn try_from(map: HashMap<K, V, S>) -> Result<Self, Self::Error> {
448        map.try_into_nonempty_iter()
449            .map(NonEmptyIterator::collect)
450            .ok_or(crate::Error::Empty)
451    }
452}
453
454impl<K, V, S> IntoNonEmptyIterator for NEMap<K, V, S> {
455    type IntoNEIter = IntoIter<K, V>;
456
457    fn into_nonempty_iter(self) -> Self::IntoNEIter {
458        IntoIter {
459            iter: self.inner.into_iter(),
460        }
461    }
462}
463
464impl<'a, K, V, S> IntoNonEmptyIterator for &'a NEMap<K, V, S> {
465    type IntoNEIter = Iter<'a, K, V>;
466
467    fn into_nonempty_iter(self) -> Self::IntoNEIter {
468        self.nonempty_iter()
469    }
470}
471
472impl<K, V, S> IntoIterator for NEMap<K, V, S> {
473    type Item = (K, V);
474
475    type IntoIter = std::collections::hash_map::IntoIter<K, V>;
476
477    fn into_iter(self) -> Self::IntoIter {
478        self.inner.into_iter()
479    }
480}
481
482impl<'a, K, V, S> IntoIterator for &'a NEMap<K, V, S> {
483    type Item = (&'a K, &'a V);
484
485    type IntoIter = std::collections::hash_map::Iter<'a, K, V>;
486
487    fn into_iter(self) -> Self::IntoIter {
488        self.iter()
489    }
490}
491
492impl<'a, K, V, S> IntoIterator for &'a mut NEMap<K, V, S> {
493    type Item = (&'a K, &'a mut V);
494
495    type IntoIter = std::collections::hash_map::IterMut<'a, K, V>;
496
497    fn into_iter(self) -> Self::IntoIter {
498        self.iter_mut()
499    }
500}
501
502/// ```
503/// use nonempty_collections::*;
504///
505/// let v = nev![('a', 1), ('b', 2), ('c', 3), ('a', 4)];
506/// let m0: NEMap<_, _> = v.into_nonempty_iter().collect();
507/// let m1: NEMap<_, _> = nem!['a' => 4, 'b' => 2, 'c' => 3];
508/// assert_eq!(m0, m1);
509/// ```
510impl<K, V, S> FromNonEmptyIterator<(K, V)> for NEMap<K, V, S>
511where
512    K: Eq + Hash,
513    S: BuildHasher + Default,
514{
515    fn from_nonempty_iter<I>(iter: I) -> Self
516    where
517        I: IntoNonEmptyIterator<Item = (K, V)>,
518    {
519        NEMap {
520            inner: iter.into_nonempty_iter().into_iter().collect(),
521        }
522    }
523}
524
525/// A non-empty iterator over the entries of an [`NEMap`].
526#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
527pub struct Iter<'a, K: 'a, V: 'a> {
528    iter: std::collections::hash_map::Iter<'a, K, V>,
529}
530
531impl<K, V> NonEmptyIterator for Iter<'_, K, V> {}
532
533impl<'a, K, V> IntoIterator for Iter<'a, K, V> {
534    type Item = (&'a K, &'a V);
535
536    type IntoIter = std::collections::hash_map::Iter<'a, K, V>;
537
538    fn into_iter(self) -> Self::IntoIter {
539        self.iter
540    }
541}
542
543impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
544    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
545        self.iter.fmt(f)
546    }
547}
548
549/// A non-empty iterator over mutable values of an [`NEMap`].
550#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
551pub struct IterMut<'a, K: 'a, V: 'a> {
552    iter: std::collections::hash_map::IterMut<'a, K, V>,
553}
554
555impl<K, V> NonEmptyIterator for IterMut<'_, K, V> {}
556
557impl<'a, K, V> IntoIterator for IterMut<'a, K, V> {
558    type Item = (&'a K, &'a mut V);
559
560    type IntoIter = std::collections::hash_map::IterMut<'a, K, V>;
561
562    fn into_iter(self) -> Self::IntoIter {
563        self.iter
564    }
565}
566
567impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IterMut<'_, K, V> {
568    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
569        self.iter.fmt(f)
570    }
571}
572
573/// A non-empty iterator over the entries of an [`NEMap`].
574pub struct IntoIter<K, V> {
575    iter: std::collections::hash_map::IntoIter<K, V>,
576}
577
578impl<K, V> NonEmptyIterator for IntoIter<K, V> {}
579
580impl<K, V> IntoIterator for IntoIter<K, V> {
581    type Item = (K, V);
582
583    type IntoIter = std::collections::hash_map::IntoIter<K, V>;
584
585    fn into_iter(self) -> Self::IntoIter {
586        self.iter
587    }
588}
589
590impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
591    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
592        self.iter.fmt(f)
593    }
594}
595
596/// A non-empty iterator over the keys of an [`NEMap`].
597#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
598pub struct Keys<'a, K: 'a, V: 'a> {
599    inner: std::collections::hash_map::Keys<'a, K, V>,
600}
601
602impl<K, V> NonEmptyIterator for Keys<'_, K, V> {}
603
604impl<'a, K, V> IntoIterator for Keys<'a, K, V> {
605    type Item = &'a K;
606
607    type IntoIter = std::collections::hash_map::Keys<'a, K, V>;
608
609    fn into_iter(self) -> Self::IntoIter {
610        self.inner
611    }
612}
613
614impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Keys<'_, K, V> {
615    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
616        self.inner.fmt(f)
617    }
618}
619
620/// A non-empty iterator over the values of an [`NEMap`].
621#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
622pub struct Values<'a, K: 'a, V: 'a> {
623    inner: std::collections::hash_map::Values<'a, K, V>,
624}
625
626impl<K, V> NonEmptyIterator for Values<'_, K, V> {}
627
628impl<'a, K, V> IntoIterator for Values<'a, K, V> {
629    type Item = &'a V;
630
631    type IntoIter = std::collections::hash_map::Values<'a, K, V>;
632
633    fn into_iter(self) -> Self::IntoIter {
634        self.inner
635    }
636}
637
638impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
639    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
640        self.inner.fmt(f)
641    }
642}
643
644impl<K: fmt::Debug, V: fmt::Debug, S> fmt::Debug for NEMap<K, V, S> {
645    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
646        self.inner.fmt(f)
647    }
648}
649
650// /// A non-empty iterator over mutable values of an [`NEMap`].
651// pub struct ValuesMut<'a, K: 'a, V: 'a> {
652//     inner: IterMut<'a, K, V>,
653// }
654
655// impl<'a, K, V> NonEmptyIterator for ValuesMut<'a, K, V> {
656//     type Item = &'a mut V;
657
658//     type Iter = Skip<Chain<Once<&'a mut V>,
659// std::collections::hash_map::IterMut<'a, K, V>>>;
660
661//     fn first(self) -> (Self::Item, Self::Iter) {
662//         (self.head_val, self.inner.skip(1))
663//     }
664
665//     fn next(&mut self) -> Option<Self::Item> {
666//         self.inner.next().map(|(_, v)| v)
667//     }
668// }
669
670#[cfg(test)]
671mod test {
672    use std::num::NonZeroUsize;
673
674    use maplit::hashmap;
675
676    use crate::nem;
677
678    struct Foo {
679        user: String,
680    }
681
682    #[test]
683    fn debug_impl() {
684        let expected = format!("{:?}", hashmap! {0 => 10});
685        let actual = format!("{:?}", nem! {0 => 10});
686        assert_eq!(expected, actual);
687    }
688
689    #[test]
690    fn macro_usage() {
691        let a = Foo {
692            user: "a".to_string(),
693        };
694        let b = Foo {
695            user: "b".to_string(),
696        };
697
698        let map = nem![1 => a, 2 => b];
699        assert_eq!("a", map.get(&1).unwrap().user);
700        assert_eq!("b", map.get(&2).unwrap().user);
701    }
702
703    #[test]
704    fn macro_length() {
705        let map = nem![1 => 'a', 2 => 'b', 1 => 'c'];
706        assert_eq!(unsafe { NonZeroUsize::new_unchecked(2) }, map.len());
707        assert_eq!('c', *map.get(&1).unwrap());
708        assert_eq!('b', *map.get(&2).unwrap());
709    }
710
711    #[test]
712    fn iter_mut() {
713        let mut v = nem! {"a" => 0, "b" => 1, "c" => 2};
714
715        v.iter_mut().for_each(|(_k, v)| {
716            *v += 1;
717        });
718        assert_eq!(nem! {"a" => 1, "b" => 2, "c" => 3}, v);
719
720        for (_k, v) in &mut v {
721            *v -= 1;
722        }
723        assert_eq!(nem! {"a" => 0, "b" => 1, "c" => 2}, v);
724    }
725}
726
727#[cfg(feature = "serde")]
728#[cfg(test)]
729mod serde_tests {
730    use std::collections::HashMap;
731
732    use crate::nem;
733    use crate::NEMap;
734
735    #[test]
736    fn json() {
737        let map0 = nem![1 => 'a', 2 => 'b', 1 => 'c'];
738        let j = serde_json::to_string(&map0).unwrap();
739        let map1 = serde_json::from_str(&j).unwrap();
740        assert_eq!(map0, map1);
741
742        let empty: HashMap<usize, char> = HashMap::new();
743        let j = serde_json::to_string(&empty).unwrap();
744        let bad = serde_json::from_str::<NEMap<usize, char>>(&j);
745        assert!(bad.is_err());
746    }
747}