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> PartialEq for NEMap<K, V, S>
383where
384    K: Eq + Hash,
385    V: Eq,
386    S: BuildHasher,
387{
388    /// This is an `O(n)` comparison of each key/value pair, one by one.
389    /// Short-circuits if any comparison fails.
390    ///
391    /// ```
392    /// use nonempty_collections::*;
393    ///
394    /// let m0 = nem!['a' => 1, 'b' => 2];
395    /// let m1 = nem!['b' => 2, 'a' => 1];
396    /// assert_eq!(m0, m1);
397    /// ```
398    fn eq(&self, other: &Self) -> bool {
399        self.inner.eq(&other.inner)
400    }
401}
402
403impl<K, V, S> Eq for NEMap<K, V, S>
404where
405    K: Eq + Hash,
406    V: Eq,
407    S: BuildHasher,
408{
409}
410
411impl<K, V, S> From<NEMap<K, V, S>> for HashMap<K, V, S>
412where
413    K: Eq + Hash,
414    S: BuildHasher,
415{
416    /// ```
417    /// use nonempty_collections::nem;
418    /// use std::collections::HashMap;
419    ///
420    /// let m: HashMap<&str, usize> = nem!["population" => 1000].into();
421    /// assert!(m.contains_key("population"));
422    /// ```
423    fn from(m: NEMap<K, V, S>) -> Self {
424        m.inner
425    }
426}
427
428impl<K, V, S> TryFrom<HashMap<K, V, S>> for NEMap<K, V, S>
429where
430    K: Eq + Hash,
431    S: BuildHasher + Default,
432{
433    type Error = crate::Error;
434
435    fn try_from(map: HashMap<K, V, S>) -> Result<Self, Self::Error> {
436        map.try_into_nonempty_iter()
437            .map(NonEmptyIterator::collect)
438            .ok_or(crate::Error::Empty)
439    }
440}
441
442impl<K, V, S> IntoNonEmptyIterator for NEMap<K, V, S> {
443    type IntoNEIter = IntoIter<K, V>;
444
445    fn into_nonempty_iter(self) -> Self::IntoNEIter {
446        IntoIter {
447            iter: self.inner.into_iter(),
448        }
449    }
450}
451
452impl<'a, K, V, S> IntoNonEmptyIterator for &'a NEMap<K, V, S> {
453    type IntoNEIter = Iter<'a, K, V>;
454
455    fn into_nonempty_iter(self) -> Self::IntoNEIter {
456        self.nonempty_iter()
457    }
458}
459
460impl<K, V, S> IntoIterator for NEMap<K, V, S> {
461    type Item = (K, V);
462
463    type IntoIter = std::collections::hash_map::IntoIter<K, V>;
464
465    fn into_iter(self) -> Self::IntoIter {
466        self.inner.into_iter()
467    }
468}
469
470impl<'a, K, V, S> IntoIterator for &'a NEMap<K, V, S> {
471    type Item = (&'a K, &'a V);
472
473    type IntoIter = std::collections::hash_map::Iter<'a, K, V>;
474
475    fn into_iter(self) -> Self::IntoIter {
476        self.iter()
477    }
478}
479
480impl<'a, K, V, S> IntoIterator for &'a mut NEMap<K, V, S> {
481    type Item = (&'a K, &'a mut V);
482
483    type IntoIter = std::collections::hash_map::IterMut<'a, K, V>;
484
485    fn into_iter(self) -> Self::IntoIter {
486        self.iter_mut()
487    }
488}
489
490/// ```
491/// use nonempty_collections::*;
492///
493/// let v = nev![('a', 1), ('b', 2), ('c', 3), ('a', 4)];
494/// let m0: NEMap<_, _> = v.into_nonempty_iter().collect();
495/// let m1: NEMap<_, _> = nem!['a' => 4, 'b' => 2, 'c' => 3];
496/// assert_eq!(m0, m1);
497/// ```
498impl<K, V, S> FromNonEmptyIterator<(K, V)> for NEMap<K, V, S>
499where
500    K: Eq + Hash,
501    S: BuildHasher + Default,
502{
503    fn from_nonempty_iter<I>(iter: I) -> Self
504    where
505        I: IntoNonEmptyIterator<Item = (K, V)>,
506    {
507        NEMap {
508            inner: iter.into_nonempty_iter().into_iter().collect(),
509        }
510    }
511}
512
513/// A non-empty iterator over the entries of an [`NEMap`].
514#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
515pub struct Iter<'a, K: 'a, V: 'a> {
516    iter: std::collections::hash_map::Iter<'a, K, V>,
517}
518
519impl<K, V> NonEmptyIterator for Iter<'_, K, V> {}
520
521impl<'a, K, V> IntoIterator for Iter<'a, K, V> {
522    type Item = (&'a K, &'a V);
523
524    type IntoIter = std::collections::hash_map::Iter<'a, K, V>;
525
526    fn into_iter(self) -> Self::IntoIter {
527        self.iter
528    }
529}
530
531impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
532    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
533        self.iter.fmt(f)
534    }
535}
536
537/// A non-empty iterator over mutable values of an [`NEMap`].
538#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
539pub struct IterMut<'a, K: 'a, V: 'a> {
540    iter: std::collections::hash_map::IterMut<'a, K, V>,
541}
542
543impl<K, V> NonEmptyIterator for IterMut<'_, K, V> {}
544
545impl<'a, K, V> IntoIterator for IterMut<'a, K, V> {
546    type Item = (&'a K, &'a mut V);
547
548    type IntoIter = std::collections::hash_map::IterMut<'a, K, V>;
549
550    fn into_iter(self) -> Self::IntoIter {
551        self.iter
552    }
553}
554
555impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IterMut<'_, K, V> {
556    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
557        self.iter.fmt(f)
558    }
559}
560
561/// A non-empty iterator over the entries of an [`NEMap`].
562pub struct IntoIter<K, V> {
563    iter: std::collections::hash_map::IntoIter<K, V>,
564}
565
566impl<K, V> NonEmptyIterator for IntoIter<K, V> {}
567
568impl<K, V> IntoIterator for IntoIter<K, V> {
569    type Item = (K, V);
570
571    type IntoIter = std::collections::hash_map::IntoIter<K, V>;
572
573    fn into_iter(self) -> Self::IntoIter {
574        self.iter
575    }
576}
577
578impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
579    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
580        self.iter.fmt(f)
581    }
582}
583
584/// A non-empty iterator over the keys of an [`NEMap`].
585#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
586pub struct Keys<'a, K: 'a, V: 'a> {
587    inner: std::collections::hash_map::Keys<'a, K, V>,
588}
589
590impl<K, V> NonEmptyIterator for Keys<'_, K, V> {}
591
592impl<'a, K, V> IntoIterator for Keys<'a, K, V> {
593    type Item = &'a K;
594
595    type IntoIter = std::collections::hash_map::Keys<'a, K, V>;
596
597    fn into_iter(self) -> Self::IntoIter {
598        self.inner
599    }
600}
601
602impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Keys<'_, K, V> {
603    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
604        self.inner.fmt(f)
605    }
606}
607
608/// A non-empty iterator over the values of an [`NEMap`].
609#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
610pub struct Values<'a, K: 'a, V: 'a> {
611    inner: std::collections::hash_map::Values<'a, K, V>,
612}
613
614impl<K, V> NonEmptyIterator for Values<'_, K, V> {}
615
616impl<'a, K, V> IntoIterator for Values<'a, K, V> {
617    type Item = &'a V;
618
619    type IntoIter = std::collections::hash_map::Values<'a, K, V>;
620
621    fn into_iter(self) -> Self::IntoIter {
622        self.inner
623    }
624}
625
626impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
627    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
628        self.inner.fmt(f)
629    }
630}
631
632impl<K: fmt::Debug, V: fmt::Debug, S> fmt::Debug for NEMap<K, V, S> {
633    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
634        self.inner.fmt(f)
635    }
636}
637
638// /// A non-empty iterator over mutable values of an [`NEMap`].
639// pub struct ValuesMut<'a, K: 'a, V: 'a> {
640//     inner: IterMut<'a, K, V>,
641// }
642
643// impl<'a, K, V> NonEmptyIterator for ValuesMut<'a, K, V> {
644//     type Item = &'a mut V;
645
646//     type Iter = Skip<Chain<Once<&'a mut V>,
647// std::collections::hash_map::IterMut<'a, K, V>>>;
648
649//     fn first(self) -> (Self::Item, Self::Iter) {
650//         (self.head_val, self.inner.skip(1))
651//     }
652
653//     fn next(&mut self) -> Option<Self::Item> {
654//         self.inner.next().map(|(_, v)| v)
655//     }
656// }
657
658#[cfg(test)]
659mod test {
660    use std::num::NonZeroUsize;
661
662    use maplit::hashmap;
663
664    use crate::nem;
665
666    struct Foo {
667        user: String,
668    }
669
670    #[test]
671    fn debug_impl() {
672        let expected = format!("{:?}", hashmap! {0 => 10});
673        let actual = format!("{:?}", nem! {0 => 10});
674        assert_eq!(expected, actual);
675    }
676
677    #[test]
678    fn macro_usage() {
679        let a = Foo {
680            user: "a".to_string(),
681        };
682        let b = Foo {
683            user: "b".to_string(),
684        };
685
686        let map = nem![1 => a, 2 => b];
687        assert_eq!("a", map.get(&1).unwrap().user);
688        assert_eq!("b", map.get(&2).unwrap().user);
689    }
690
691    #[test]
692    fn macro_length() {
693        let map = nem![1 => 'a', 2 => 'b', 1 => 'c'];
694        assert_eq!(unsafe { NonZeroUsize::new_unchecked(2) }, map.len());
695        assert_eq!('c', *map.get(&1).unwrap());
696        assert_eq!('b', *map.get(&2).unwrap());
697    }
698
699    #[test]
700    fn iter_mut() {
701        let mut v = nem! {"a" => 0, "b" => 1, "c" => 2};
702
703        v.iter_mut().for_each(|(_k, v)| {
704            *v += 1;
705        });
706        assert_eq!(nem! {"a" => 1, "b" => 2, "c" => 3}, v);
707
708        for (_k, v) in &mut v {
709            *v -= 1;
710        }
711        assert_eq!(nem! {"a" => 0, "b" => 1, "c" => 2}, v);
712    }
713}
714
715#[cfg(feature = "serde")]
716#[cfg(test)]
717mod serde_tests {
718    use std::collections::HashMap;
719
720    use crate::nem;
721    use crate::NEMap;
722
723    #[test]
724    fn json() {
725        let map0 = nem![1 => 'a', 2 => 'b', 1 => 'c'];
726        let j = serde_json::to_string(&map0).unwrap();
727        let map1 = serde_json::from_str(&j).unwrap();
728        assert_eq!(map0, map1);
729
730        let empty: HashMap<usize, char> = HashMap::new();
731        let j = serde_json::to_string(&empty).unwrap();
732        let bad = serde_json::from_str::<NEMap<usize, char>>(&j);
733        assert!(bad.is_err());
734    }
735}