tower_sesh/value/
map.rs

1// Adapted from https://github.com/serde-rs/json.
2
3//! A map of `String` to [`Value`].
4
5use std::{
6    borrow::Borrow,
7    collections::{btree_map, BTreeMap},
8    fmt,
9    hash::Hash,
10    iter::FusedIterator,
11    ops,
12};
13
14use serde::{Deserialize, Serialize};
15
16use super::Value;
17
18/// Represents a serializable key/value type.
19pub struct Map<K, V> {
20    map: MapImpl<K, V>,
21}
22
23type MapImpl<K, V> = BTreeMap<K, V>;
24
25impl Map<String, Value> {
26    /// Makes a new, empty `Map`.
27    ///
28    /// # Examples
29    ///
30    /// ```
31    /// use tower_sesh::value::Map;
32    ///
33    /// let mut map = Map::new();
34    ///
35    /// // entries can now be inserted into the empty map
36    /// map.insert("sesh".to_owned(), "a".into());
37    /// ```
38    #[inline]
39    #[must_use]
40    pub fn new() -> Map<String, Value> {
41        Map {
42            map: MapImpl::new(),
43        }
44    }
45
46    /// Clears the map, removing all elements.
47    ///
48    /// # Examples
49    ///
50    /// ```
51    /// use tower_sesh::value::Map;
52    ///
53    /// let mut a = Map::new();
54    /// a.insert("sesh".to_owned(), "a".into());
55    /// a.clear();
56    /// assert!(a.is_empty());
57    /// ```
58    #[inline]
59    pub fn clear(&mut self) {
60        self.map.clear()
61    }
62
63    /// Returns a reference to the value corresponding to the key.
64    ///
65    /// The key may be any borrowed form of the map's key type, but the ordering
66    /// on the borrowed form *must* match the ordering on the key type.
67    ///
68    /// # Examples
69    ///
70    /// ```
71    /// use tower_sesh::value::Map;
72    ///
73    /// let mut map = Map::new();
74    /// map.insert("sesh".to_owned(), "a".into());
75    /// assert_eq!(map.get("sesh").and_then(|v| v.as_str()), Some("a"));
76    /// assert_eq!(map.get("notexist"), None);
77    /// ```
78    #[inline]
79    pub fn get<Q>(&self, key: &Q) -> Option<&Value>
80    where
81        String: Borrow<Q>,
82        Q: ?Sized + Ord + Eq + Hash,
83    {
84        self.map.get(key)
85    }
86
87    /// Returns the key-value pair matching the given key.
88    ///
89    /// The key may be any borrowed form of the map's key type, but the ordering
90    /// on the borrowed form *must* match the ordering on the key type.
91    ///
92    /// # Examples
93    ///
94    /// ```
95    /// use tower_sesh::value::Map;
96    ///
97    /// let mut map = Map::new();
98    /// map.insert("sesh".to_owned(), "a".into());
99    /// let entry = map
100    ///     .get_key_value("sesh")
101    ///     .and_then(|(k, v)| Some(k.as_str()).zip(v.as_str()));
102    /// assert_eq!(entry, Some(("sesh", "a")));
103    /// assert_eq!(map.get_key_value("notexist"), None);
104    /// ```
105    #[inline]
106    pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&String, &Value)>
107    where
108        String: Borrow<Q>,
109        Q: ?Sized + Ord + Eq + Hash,
110    {
111        self.map.get_key_value(key)
112    }
113
114    /// Returns true if the map contains a value for the specified key.
115    ///
116    /// The key may be any borrowed form of the map's key type, but the ordering
117    /// on the borrowed form *must* match the ordering on the key type.
118    ///
119    /// # Examples
120    ///
121    /// ```
122    /// use tower_sesh::value::Map;
123    ///
124    /// let mut map = Map::new();
125    /// map.insert("sesh".to_owned(), "a".into());
126    /// assert_eq!(map.contains_key("sesh"), true);
127    /// assert_eq!(map.contains_key("notexist"), false);
128    /// ```
129    #[inline]
130    pub fn contains_key<Q>(&self, key: &Q) -> bool
131    where
132        String: Borrow<Q>,
133        Q: ?Sized + Ord + Eq + Hash,
134    {
135        self.map.contains_key(key)
136    }
137
138    /// Returns a mutable reference to the value corresponding to the key.
139    ///
140    /// The key may be any borrowed form of the map's key type, but the ordering
141    /// on the borrowed form *must* match the ordering on the key type.
142    ///
143    /// # Examples
144    ///
145    /// ```
146    /// use tower_sesh::value::Map;
147    ///
148    /// let mut map = Map::new();
149    /// map.insert("sesh".to_owned(), "a".into());
150    /// if let Some(x) = map.get_mut("sesh") {
151    ///     *x = "b".into();
152    /// }
153    /// assert_eq!(map["sesh"], "b");
154    /// ```
155    #[inline]
156    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut Value>
157    where
158        String: Borrow<Q>,
159        Q: ?Sized + Ord + Eq + Hash,
160    {
161        self.map.get_mut(key)
162    }
163
164    /// Inserts a key-value pair into the map.
165    ///
166    /// If the map did not have this key present, `None` is returned.
167    ///
168    /// If the map did have this key present, the value is updated, and the old
169    /// value is returned.
170    ///
171    /// # Examples
172    ///
173    /// ```
174    /// use tower_sesh::value::Map;
175    ///
176    /// let mut map = Map::new();
177    /// assert_eq!(map.insert("sesh".to_owned(), "a".into()), None);
178    /// assert_eq!(map.is_empty(), false);
179    ///
180    /// map.insert("sesh".to_owned(), "b".into());
181    /// let prev = map.insert("sesh".to_owned(), "c".into());
182    /// assert_eq!(prev.as_ref().and_then(|v| v.as_str()), Some("b"));
183    /// assert_eq!(map["sesh"], "c");
184    /// ```
185    #[inline]
186    pub fn insert(&mut self, key: String, value: Value) -> Option<Value> {
187        self.map.insert(key, value)
188    }
189
190    /// Removes a key from the map, returning the value at the key if the key
191    /// was previously in the map.
192    ///
193    /// The key may be any borrowed form of the map's key type, but the ordering
194    /// on the borrowed form *must* match the ordering on the key type.
195    ///
196    /// # Examples
197    ///
198    /// ```
199    /// use tower_sesh::value::Map;
200    ///
201    /// let mut map = Map::new();
202    /// map.insert("sesh".to_owned(), "a".into());
203    /// assert_eq!(map.remove("sesh").as_ref().and_then(|v| v.as_str()), Some("a"));
204    /// assert_eq!(map.remove("sesh"), None);
205    /// ```
206    #[inline]
207    pub fn remove<Q>(&mut self, key: &Q) -> Option<Value>
208    where
209        String: Borrow<Q>,
210        Q: ?Sized + Ord + Eq + Hash,
211    {
212        self.map.remove(key)
213    }
214
215    /// Removes a key from the map, returning the stored key and value if the
216    /// key was previously in the map.
217    ///
218    /// The key may be any borrowed form of the map's key type, but the ordering
219    /// on the borrowed form *must* match the ordering on the key type.
220    ///
221    /// # Examples
222    ///
223    /// ```
224    /// use tower_sesh::value::Map;
225    ///
226    /// let mut map = Map::new();
227    /// map.insert("sesh".to_owned(), "a".into());
228    /// let entry = map.remove_entry("sesh");
229    /// assert_eq!(
230    ///     entry.as_ref()
231    ///         .and_then(|(k, v)| Some(k.as_str()).zip(v.as_str())),
232    ///     Some(("sesh", "a"))
233    /// );
234    /// assert_eq!(map.remove_entry("sesh"), None);
235    /// ```
236    #[inline]
237    pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(String, Value)>
238    where
239        String: Borrow<Q>,
240        Q: ?Sized + Ord + Eq + Hash,
241    {
242        self.map.remove_entry(key)
243    }
244
245    /// Retains only the elements specified by the predicate.
246    ///
247    /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)`
248    /// returns `false`.
249    ///
250    /// # Examples
251    ///
252    /// ```
253    /// use tower_sesh::{value::Map, Value};
254    ///
255    /// let mut map = Map::from_iter([
256    ///     ("rust".into(), "a".into()),
257    ///     ("sesh".into(), "b".into()),
258    ///     ("tower".into(), "c".into()),
259    /// ]);
260    /// // Keep only the elements with keys of length 4.
261    /// map.retain(|k, _| k.len() == 4);
262    /// let elements = map.into_iter().collect::<Vec<(String, Value)>>();
263    /// assert_eq!(
264    ///     elements,
265    ///     vec![("rust".into(), "a".into()), ("sesh".into(), "b".into())]
266    /// );
267    /// ```
268    #[inline]
269    pub fn retain<F>(&mut self, f: F)
270    where
271        F: FnMut(&String, &mut Value) -> bool,
272    {
273        self.map.retain(f)
274    }
275
276    /// Moves all elements from other into self, leaving other empty.
277    ///
278    /// If a key from `other` is already present in `self`, the respective
279    /// value from `self` will be overwritten with the respective value from
280    /// `other`.
281    ///
282    /// # Examples
283    ///
284    /// ```
285    /// use tower_sesh::value::Map;
286    ///
287    /// let mut a = Map::new();
288    /// a.insert("one".to_owned(), "a".into());
289    /// a.insert("two".to_owned(), "b".into());
290    /// a.insert("three".to_owned(), "c".into()); // Note: Key ("three") also present in b.
291    ///
292    /// let mut b = Map::new();
293    /// b.insert("three".to_owned(), "d".into()); // Note: Key ("three") also present in a.
294    /// b.insert("four".to_owned(), "e".into());
295    /// b.insert("five".to_owned(), "f".into());
296    ///
297    /// a.append(&mut b);
298    ///
299    /// assert_eq!(a.len(), 5);
300    /// assert_eq!(b.len(), 0);
301    ///
302    /// assert_eq!(a["one"], "a");
303    /// assert_eq!(a["two"], "b");
304    /// assert_eq!(a["three"], "d"); // Note: "c" has been overwritten.
305    /// assert_eq!(a["four"], "e");
306    /// assert_eq!(a["five"], "f");
307    /// ```
308    #[inline]
309    pub fn append(&mut self, other: &mut Map<String, Value>) {
310        self.map.append(&mut other.map)
311    }
312
313    /// Gets the given key's corresponding entry in the map for in-place
314    /// manipulation.
315    ///
316    /// # Examples
317    ///
318    /// ```
319    /// use tower_sesh::value::Map;
320    ///
321    /// let mut count = Map::new();
322    ///
323    /// // count the number of occurrences of letters in the vec
324    /// for x in ["a", "b", "a", "c", "a", "b"] {
325    ///     count.entry(x)
326    ///         .and_modify(|curr| *curr = (curr.as_u64().unwrap_or(0) + 1).into())
327    ///         .or_insert_with(|| 1.into());
328    /// }
329    ///
330    /// assert_eq!(count["a"], 3);
331    /// assert_eq!(count["b"], 2);
332    /// assert_eq!(count["c"], 1);
333    /// ```
334    pub fn entry<S>(&mut self, key: S) -> Entry
335    where
336        S: Into<String>,
337    {
338        use btree_map::Entry as EntryImpl;
339
340        match self.map.entry(key.into()) {
341            EntryImpl::Vacant(vacant) => Entry::Vacant(VacantEntry { vacant }),
342            EntryImpl::Occupied(occupied) => Entry::Occupied(OccupiedEntry { occupied }),
343        }
344    }
345
346    /// Returns the number of elements in the map.
347    ///
348    /// # Examples
349    ///
350    /// ```
351    /// use tower_sesh::value::Map;
352    ///
353    /// let mut a = Map::new();
354    /// assert_eq!(a.len(), 0);
355    /// a.insert("sesh".to_owned(), "a".into());
356    /// assert_eq!(a.len(), 1);
357    /// ```
358    #[inline]
359    #[must_use]
360    pub fn len(&self) -> usize {
361        self.map.len()
362    }
363
364    /// Returns `true` if the map contains no elements.
365    ///
366    /// # Examples
367    ///
368    /// ```
369    /// use tower_sesh::value::Map;
370    ///
371    /// let mut a = Map::new();
372    /// assert!(a.is_empty());
373    /// a.insert("sesh".to_owned(), "a".into());
374    /// assert!(!a.is_empty());
375    /// ```
376    #[inline]
377    #[must_use]
378    pub fn is_empty(&self) -> bool {
379        self.map.is_empty()
380    }
381
382    /// Gets an iterator over the entries of the map.
383    ///
384    /// # Examples
385    ///
386    /// ```
387    /// use tower_sesh::value::Map;
388    ///
389    /// let mut map = Map::new();
390    /// map.insert("1".to_owned(), "a".into());
391    /// map.insert("2".to_owned(), "b".into());
392    /// map.insert("3".to_owned(), "c".into());
393    ///
394    /// for (key, value) in map.iter() {
395    ///     println!("{key}: {value:?}");
396    /// }
397    ///
398    /// let (first_key, first_value) = map.iter().next().unwrap();
399    /// assert_eq!((first_key.as_str(), first_value.as_str().unwrap()), ("1", "a"));
400    /// ```
401    #[inline]
402    pub fn iter(&self) -> Iter<'_> {
403        Iter {
404            iter: self.map.iter(),
405        }
406    }
407
408    /// Gets a mutable iterator over the entries of the map.
409    ///
410    /// # Examples
411    ///
412    /// ```
413    /// use tower_sesh::value::Map;
414    ///
415    /// let mut map = Map::from_iter([
416    ///     ("a".to_owned(), 1.into()),
417    ///     ("b".to_owned(), 2.into()),
418    ///     ("c".to_owned(), 3.into()),
419    /// ]);
420    ///
421    /// // add 10 to the value if the key isn't "a"
422    /// for (key, value) in map.iter_mut() {
423    ///     if key != "a" {
424    ///         *value = (value.as_u64().unwrap_or(0) + 10).into();
425    ///     }
426    /// }
427    ///
428    /// assert_eq!(map["a"], 1);
429    /// assert_eq!(map["b"], 12);
430    /// assert_eq!(map["c"], 13);
431    /// ```
432    #[inline]
433    pub fn iter_mut(&mut self) -> IterMut<'_> {
434        IterMut {
435            iter: self.map.iter_mut(),
436        }
437    }
438
439    /// Gets an iterator over the keys of the map.
440    ///
441    /// # Examples
442    ///
443    /// ```
444    /// use tower_sesh::value::Map;
445    ///
446    /// let mut a = Map::new();
447    /// a.insert("rust".to_owned(), "a".into());
448    /// a.insert("sesh".to_owned(), "b".into());
449    ///
450    /// let keys: Vec<_> = a.keys().cloned().collect();
451    /// assert_eq!(keys, ["rust", "sesh"]);
452    /// ```
453    #[inline]
454    pub fn keys(&self) -> Keys<'_> {
455        Keys {
456            iter: self.map.keys(),
457        }
458    }
459
460    /// Gets an iterator over the values of the map.
461    ///
462    /// # Examples
463    ///
464    /// ```
465    /// use tower_sesh::value::Map;
466    ///
467    /// let mut a = Map::new();
468    /// a.insert("rust".to_owned(), "hello".into());
469    /// a.insert("sesh".to_owned(), "goodbye".into());
470    ///
471    /// let values: Vec<_> = a.values().cloned().collect();
472    /// assert_eq!(values, ["hello", "goodbye"]);
473    /// ```
474    #[inline]
475    pub fn values(&self) -> Values<'_> {
476        Values {
477            iter: self.map.values(),
478        }
479    }
480
481    /// Gets a mutable iterator over the values of the map.
482    ///
483    /// # Examples
484    ///
485    /// ```
486    /// use tower_sesh::{value::Map, Value};
487    ///
488    /// let mut a = Map::new();
489    /// a.insert("rust".to_owned(), "hello".into());
490    /// a.insert("sesh".to_owned(), "goodbye".into());
491    ///
492    /// for value in a.values_mut() {
493    ///     match value {
494    ///         Value::String(s) => s.push_str("!"),
495    ///         _ => unimplemented!(),
496    ///     }
497    /// }
498    ///
499    /// let values: Vec<_> = a.values().cloned().collect();
500    /// assert_eq!(values, ["hello!", "goodbye!"]);
501    /// ```
502    #[inline]
503    pub fn values_mut(&mut self) -> ValuesMut<'_> {
504        ValuesMut {
505            iter: self.map.values_mut(),
506        }
507    }
508
509    /// Creates a consuming iterator visiting all the values of the map.
510    /// The map cannot be used after calling this.
511    ///
512    /// # Examples
513    ///
514    /// ```
515    /// use tower_sesh::value::Map;
516    ///
517    /// let mut a = Map::new();
518    /// a.insert("rust".to_owned(), "hello".into());
519    /// a.insert("sesh".to_owned(), "goodbye".into());
520    ///
521    /// let values: Vec<_> = a.into_values().collect();
522    /// assert_eq!(values, ["hello", "goodbye"]);
523    /// ```
524    #[inline]
525    pub fn into_values(self) -> IntoValues {
526        IntoValues {
527            iter: self.map.into_values(),
528        }
529    }
530}
531
532impl Default for Map<String, Value> {
533    /// Creates an empty `Map`.
534    #[inline]
535    fn default() -> Self {
536        Map::new()
537    }
538}
539
540impl Clone for Map<String, Value> {
541    #[inline]
542    fn clone(&self) -> Self {
543        Map {
544            map: self.map.clone(),
545        }
546    }
547
548    #[inline]
549    fn clone_from(&mut self, source: &Self) {
550        self.map.clone_from(&source.map)
551    }
552}
553
554impl PartialEq for Map<String, Value> {
555    #[inline]
556    fn eq(&self, other: &Self) -> bool {
557        self.map.eq(&other.map)
558    }
559}
560
561impl Eq for Map<String, Value> {}
562
563/// Access an element of this map. Panics if the given key is not present in the
564/// map.
565///
566/// ```
567/// # use tower_sesh::Value;
568/// #
569/// # let val = &Value::String("".to_owned());
570/// # let _ =
571/// match val {
572///     Value::String(s) => Some(s.as_str()),
573///     Value::Array(arr) => arr[0].as_str(),
574///     Value::Map(map) => map["type"].as_str(),
575///     _ => None,
576/// }
577/// # ;
578/// ```
579impl<Q> ops::Index<&Q> for Map<String, Value>
580where
581    String: Borrow<Q>,
582    Q: ?Sized + Ord + Eq + Hash,
583{
584    type Output = Value;
585
586    fn index(&self, index: &Q) -> &Self::Output {
587        self.map.index(index)
588    }
589}
590
591/// Mutably access an element of this map. Panics if the given key is not
592/// present in the map.
593///
594/// ```
595/// # use tower_sesh::{value::Map, Value};
596/// #
597/// # let mut map = Map::new();
598/// # map.insert("key".to_owned(), Value::Null);
599/// #
600/// map["key"] = Value::String("value".to_owned());
601/// ```
602impl<Q> ops::IndexMut<&Q> for Map<String, Value>
603where
604    String: Borrow<Q>,
605    Q: ?Sized + Ord + Eq + Hash,
606{
607    fn index_mut(&mut self, index: &Q) -> &mut Self::Output {
608        self.map.get_mut(index).expect("no entry found for key")
609    }
610}
611
612impl fmt::Debug for Map<String, Value> {
613    #[inline]
614    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
615        self.map.fmt(f)
616    }
617}
618
619impl Serialize for Map<String, Value> {
620    #[inline]
621    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
622    where
623        S: serde::Serializer,
624    {
625        use serde::ser::SerializeMap;
626
627        let mut map = serializer.serialize_map(Some(self.len()))?;
628
629        for (k, v) in self {
630            map.serialize_entry(k, v)?;
631        }
632
633        map.end()
634    }
635}
636
637impl<'de> Deserialize<'de> for Map<String, Value> {
638    #[inline]
639    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
640    where
641        D: serde::Deserializer<'de>,
642    {
643        struct Visitor;
644
645        impl<'de> serde::de::Visitor<'de> for Visitor {
646            type Value = Map<String, Value>;
647
648            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
649                formatter.write_str("a map")
650            }
651
652            #[inline]
653            fn visit_unit<E>(self) -> Result<Self::Value, E>
654            where
655                E: serde::de::Error,
656            {
657                Ok(Map::new())
658            }
659
660            #[inline]
661            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
662            where
663                A: serde::de::MapAccess<'de>,
664            {
665                let mut values = Map::new();
666
667                while let Some((key, value)) = map.next_entry()? {
668                    values.insert(key, value);
669                }
670
671                Ok(values)
672            }
673        }
674
675        deserializer.deserialize_map(Visitor)
676    }
677}
678
679impl FromIterator<(String, Value)> for Map<String, Value> {
680    fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
681        Map {
682            map: FromIterator::from_iter(iter),
683        }
684    }
685}
686
687impl Extend<(String, Value)> for Map<String, Value> {
688    fn extend<T: IntoIterator<Item = (String, Value)>>(&mut self, iter: T) {
689        self.map.extend(iter)
690    }
691}
692
693////////////////////////////////////////////////////////////////////////////////
694
695/// A view into a single entry in a map, which may be either vacant or occupied.
696///
697/// This `enum` is constructed from the [`entry`] method on [`Map`].
698///
699/// [`entry`]: Map::entry
700pub enum Entry<'a> {
701    Vacant(VacantEntry<'a>),
702    Occupied(OccupiedEntry<'a>),
703}
704
705impl fmt::Debug for Entry<'_> {
706    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
707        match self {
708            Entry::Vacant(v) => f.debug_tuple("Entry").field(v).finish(),
709            Entry::Occupied(o) => f.debug_tuple("Entry").field(o).finish(),
710        }
711    }
712}
713
714/// A view into a vacant entry in a `Map`.
715/// It is part of the [`Entry`] enum.
716pub struct VacantEntry<'a> {
717    vacant: VacantEntryImpl<'a>,
718}
719
720impl fmt::Debug for VacantEntry<'_> {
721    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
722        f.debug_tuple("VacantEntry").field(self.key()).finish()
723    }
724}
725
726/// A view into an occupied entry in a `Map`.
727/// It is part of the [`Entry`] enum.
728pub struct OccupiedEntry<'a> {
729    occupied: OccupiedEntryImpl<'a>,
730}
731
732impl fmt::Debug for OccupiedEntry<'_> {
733    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
734        f.debug_struct("OccupiedEntry")
735            .field("key", self.key())
736            .field("value", self.get())
737            .finish()
738    }
739}
740
741type VacantEntryImpl<'a> = btree_map::VacantEntry<'a, String, Value>;
742
743type OccupiedEntryImpl<'a> = btree_map::OccupiedEntry<'a, String, Value>;
744
745impl<'a> Entry<'a> {
746    /// Returns a reference to this entry's key.
747    ///
748    /// # Examples
749    ///
750    /// ```
751    /// let mut map = tower_sesh::value::Map::new();
752    /// assert_eq!(map.entry("sesh").key(), &"sesh");
753    /// ```
754    pub fn key(&self) -> &String {
755        match self {
756            Entry::Vacant(e) => e.key(),
757            Entry::Occupied(e) => e.key(),
758        }
759    }
760
761    /// Ensures a value is in the entry by inserting the default if empty, and
762    /// returns a mutable reference to the value in the entry.
763    ///
764    /// # Examples
765    ///
766    /// ```
767    /// # use tower_sesh::Value;
768    /// #
769    /// let mut map = tower_sesh::value::Map::new();
770    /// map.entry("sesh").or_insert(Value::from(12));
771    ///
772    /// assert_eq!(map["sesh"], 12);
773    /// ```
774    pub fn or_insert(self, default: Value) -> &'a mut Value {
775        match self {
776            Entry::Vacant(e) => e.insert(default),
777            Entry::Occupied(e) => e.into_mut(),
778        }
779    }
780
781    /// Ensures a value is in the entry by inserting the result of the default
782    /// function if empty, and returns a mutable reference to the value in the
783    /// entry.
784    ///
785    /// # Examples
786    ///
787    /// ```
788    /// # use tower_sesh::Value;
789    /// #
790    /// let mut map = tower_sesh::value::Map::new();
791    /// map.entry("sesh").or_insert_with(|| Value::from("hoho"));
792    ///
793    /// assert_eq!(map["sesh"], "hoho".to_owned());
794    /// ```
795    pub fn or_insert_with<F>(self, default: F) -> &'a mut Value
796    where
797        F: FnOnce() -> Value,
798    {
799        match self {
800            Entry::Vacant(e) => e.insert(default()),
801            Entry::Occupied(e) => e.into_mut(),
802        }
803    }
804
805    /// Provides in-place mutable access to an occupied entry before any
806    /// potential inserts into the map.
807    ///
808    /// # Examples
809    ///
810    /// ```
811    /// # use tower_sesh::Value;
812    /// #
813    /// let mut map = tower_sesh::value::Map::new();
814    /// map.entry("sesh")
815    ///     .and_modify(|e| *e = Value::from("rust"))
816    ///     .or_insert_with(|| Value::from("cpp"));
817    ///
818    /// assert_eq!(map["sesh"], "cpp");
819    ///
820    /// map.entry("sesh")
821    ///     .and_modify(|e| *e = Value::from("rust"))
822    ///     .or_insert_with(|| Value::from("cpp"));
823    ///
824    /// assert_eq!(map["sesh"], "rust");
825    /// ```
826    pub fn and_modify<F>(self, f: F) -> Entry<'a>
827    where
828        F: FnOnce(&mut Value),
829    {
830        match self {
831            Entry::Vacant(e) => Entry::Vacant(e),
832            Entry::Occupied(mut e) => {
833                f(e.get_mut());
834                Entry::Occupied(e)
835            }
836        }
837    }
838}
839
840impl<'a> VacantEntry<'a> {
841    /// Gets a reference to the key that would be used when inserting a value
842    /// through the `VacantEntry`.
843    ///
844    /// # Examples
845    ///
846    /// ```
847    /// use tower_sesh::value::{map::Entry, Map};
848    ///
849    /// let mut map = Map::new();
850    ///
851    /// match map.entry("sesh") {
852    ///     Entry::Vacant(vacant) => {
853    ///         assert_eq!(vacant.key(), &"sesh");
854    ///     }
855    ///     Entry::Occupied(_) => unimplemented!(),
856    /// }
857    /// ```
858    #[inline]
859    pub fn key(&self) -> &String {
860        self.vacant.key()
861    }
862
863    /// Sets the value of the entry with the `VacantEntry`'s key, and returns a
864    /// mutable reference to it.
865    ///
866    /// # Examples
867    ///
868    /// ```
869    /// use tower_sesh::value::{map::Entry, Map, Value};
870    ///
871    /// let mut map = Map::new();
872    ///
873    /// match map.entry("sesh") {
874    ///     Entry::Vacant(vacant) => {
875    ///         vacant.insert(Value::from("hoho"));
876    ///     }
877    ///     Entry::Occupied(_) => unimplemented!(),
878    /// }
879    /// ```
880    #[inline]
881    pub fn insert(self, value: Value) -> &'a mut Value {
882        self.vacant.insert(value)
883    }
884}
885
886impl<'a> OccupiedEntry<'a> {
887    /// Gets a reference to the key in the entry.
888    ///
889    /// # Examples
890    ///
891    /// ```
892    /// use tower_sesh::value::{map::Entry, Map, Value};
893    ///
894    /// let mut map = Map::new();
895    /// map.insert("sesh".to_owned(), Value::from(12));
896    ///
897    /// match map.entry("sesh") {
898    ///     Entry::Occupied(occupied) => {
899    ///         assert_eq!(occupied.key(), &"sesh");
900    ///     }
901    ///     Entry::Vacant(_) => unimplemented!(),
902    /// }
903    /// ```
904    #[inline]
905    pub fn key(&self) -> &String {
906        self.occupied.key()
907    }
908
909    /// Gets a reference to the value in the entry.
910    ///
911    /// # Examples
912    ///
913    /// ```
914    /// use tower_sesh::value::{map::Entry, Map, Value};
915    ///
916    /// let mut map = Map::new();
917    /// map.insert("sesh".to_owned(), Value::from(12));
918    ///
919    /// match map.entry("sesh") {
920    ///     Entry::Occupied(occupied) => {
921    ///         assert_eq!(occupied.get(), 12);
922    ///     }
923    ///     Entry::Vacant(_) => unimplemented!(),
924    /// }
925    /// ```
926    #[inline]
927    pub fn get(&self) -> &Value {
928        self.occupied.get()
929    }
930
931    /// Gets a mutable reference to the value in the entry.
932    ///
933    /// # Examples
934    ///
935    /// ```
936    /// use tower_sesh::value::{map::Entry, Map, Value};
937    ///
938    /// let mut map = Map::new();
939    /// map.insert("sesh".to_owned(), Value::from([1, 2, 3]));
940    ///
941    /// match map.entry("sesh") {
942    ///     Entry::Occupied(mut occupied) => {
943    ///         occupied.get_mut().as_array_mut().unwrap().push(Value::from(4));
944    ///     }
945    ///     Entry::Vacant(_) => unimplemented!(),
946    /// }
947    ///
948    /// assert_eq!(map["sesh"].as_array().unwrap().len(), 4);
949    /// ```
950    #[inline]
951    pub fn get_mut(&mut self) -> &mut Value {
952        self.occupied.get_mut()
953    }
954
955    /// Converts the entry into a mutable reference to its value.
956    ///
957    /// # Examples
958    ///
959    /// ```
960    /// use tower_sesh::value::{map::Entry, Map, Value};
961    ///
962    /// let mut map = Map::new();
963    /// map.insert("sesh".to_owned(), Value::from([1, 2, 3]));
964    ///
965    /// match map.entry("sesh") {
966    ///     Entry::Occupied(mut occupied) => {
967    ///         occupied.into_mut().as_array_mut().unwrap().push(Value::from(4));
968    ///     }
969    ///     Entry::Vacant(_) => unimplemented!(),
970    /// }
971    ///
972    /// assert_eq!(map["sesh"].as_array().unwrap().len(), 4);
973    /// ```
974    #[inline]
975    pub fn into_mut(self) -> &'a mut Value {
976        self.occupied.into_mut()
977    }
978
979    /// Takes the value of the entry out of the map, and returns it.
980    ///
981    /// # Examples
982    ///
983    /// ```
984    /// use tower_sesh::value::{map::Entry, Map, Value};
985    ///
986    /// let mut map = Map::new();
987    /// map.insert("sesh".to_owned(), Value::from(12));
988    ///
989    /// match map.entry("sesh") {
990    ///     Entry::Occupied(occupied) => {
991    ///         assert_eq!(occupied.remove(), 12);
992    ///     }
993    ///     Entry::Vacant(_) => unimplemented!(),
994    /// }
995    /// ```
996    #[inline]
997    pub fn remove(self) -> Value {
998        self.occupied.remove()
999    }
1000
1001    /// Removes the entry from the map, returning the stored key and value.
1002    ///
1003    /// # Examples
1004    ///
1005    /// ```
1006    /// use tower_sesh::value::{map::Entry, Map, Value};
1007    ///
1008    /// let mut map = Map::new();
1009    /// map.insert("sesh".to_owned(), Value::from(12));
1010    ///
1011    /// match map.entry("sesh") {
1012    ///     Entry::Occupied(occupied) => {
1013    ///         let (key, value) = occupied.remove_entry();
1014    ///         assert_eq!(key, "sesh");
1015    ///         assert_eq!(value, 12);
1016    ///     }
1017    ///     Entry::Vacant(_) => unimplemented!(),
1018    /// }
1019    /// ```
1020    #[inline]
1021    pub fn remove_entry(self) -> (String, Value) {
1022        self.occupied.remove_entry()
1023    }
1024}
1025
1026macro_rules! delegate_iterator {
1027    (($name:ident $($generics:tt)*) => $item:ty) => {
1028        impl $($generics)* Iterator for $name $($generics)* {
1029            type Item = $item;
1030
1031            #[inline]
1032            fn next(&mut self) -> Option<Self::Item> {
1033                self.iter.next()
1034            }
1035
1036            #[inline]
1037            fn size_hint(&self) -> (usize, Option<usize>) {
1038                self.iter.size_hint()
1039            }
1040        }
1041
1042        impl $($generics)* DoubleEndedIterator for $name $($generics)* {
1043            #[inline]
1044            fn next_back(&mut self) -> Option<Self::Item> {
1045                self.iter.next_back()
1046            }
1047        }
1048
1049        impl $($generics)* ExactSizeIterator for $name $($generics)* {
1050            #[inline]
1051            fn len(&self) -> usize {
1052                self.iter.len()
1053            }
1054        }
1055
1056        impl $($generics)* FusedIterator for $name $($generics)* {}
1057    };
1058}
1059
1060macro_rules! delegate_debug {
1061    ($name:ident $($generics:tt)*) => {
1062        impl $($generics)* std::fmt::Debug for $name $($generics)* {
1063            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1064                std::fmt::Debug::fmt(&self.iter, f)
1065            }
1066        }
1067    };
1068}
1069
1070////////////////////////////////////////////////////////////////////////////////
1071
1072impl<'a> IntoIterator for &'a Map<String, Value> {
1073    type Item = <Self::IntoIter as Iterator>::Item;
1074    type IntoIter = Iter<'a>;
1075
1076    #[inline]
1077    fn into_iter(self) -> Self::IntoIter {
1078        Iter {
1079            iter: self.map.iter(),
1080        }
1081    }
1082}
1083
1084impl<'a> IntoIterator for &'a mut Map<String, Value> {
1085    type Item = <Self::IntoIter as Iterator>::Item;
1086    type IntoIter = IterMut<'a>;
1087
1088    #[inline]
1089    fn into_iter(self) -> Self::IntoIter {
1090        IterMut {
1091            iter: self.map.iter_mut(),
1092        }
1093    }
1094}
1095
1096/// An iterator over the entries of a `Map`.
1097///
1098/// This `struct` is created by the [`iter`] method on [`Map`]. See its
1099/// documentation for more.
1100///
1101/// [`iter`]: Map::iter
1102#[must_use = "iterators are lazy and do nothing unless consumed"]
1103#[derive(Clone, Default)]
1104pub struct Iter<'a> {
1105    iter: IterImpl<'a>,
1106}
1107
1108type IterImpl<'a> = btree_map::Iter<'a, String, Value>;
1109
1110delegate_iterator!((Iter<'a>) => (&'a String, &'a Value));
1111delegate_debug!(Iter<'a>);
1112
1113/// A mutable iterator over the entries of a `Map`.
1114///
1115/// This `struct` is created by the [`iter_mut`] method on [`Map`]. See its
1116/// documentation for more.
1117///
1118/// [`iter_mut`]: Map::iter_mut
1119#[must_use = "iterators are lazy and do nothing unless consumed"]
1120#[derive(Default)]
1121pub struct IterMut<'a> {
1122    iter: IterMutImpl<'a>,
1123}
1124
1125type IterMutImpl<'a> = btree_map::IterMut<'a, String, Value>;
1126
1127delegate_iterator!((IterMut<'a>) => (&'a String, &'a mut Value));
1128delegate_debug!(IterMut<'a>);
1129
1130////////////////////////////////////////////////////////////////////////////////
1131
1132impl IntoIterator for Map<String, Value> {
1133    type Item = <Self::IntoIter as Iterator>::Item;
1134    type IntoIter = IntoIter;
1135
1136    fn into_iter(self) -> Self::IntoIter {
1137        IntoIter {
1138            iter: self.map.into_iter(),
1139        }
1140    }
1141}
1142
1143/// An owning iterator over the entries of a `Map`.
1144///
1145/// This `struct` is created by the [`into_iter`] method on [`Map`]
1146/// (provided by the [`IntoIterator`] trait). See its documentation for more.
1147///
1148/// [`into_iter`]: IntoIterator::into_iter
1149#[derive(Default)]
1150pub struct IntoIter {
1151    iter: IntoIterImpl,
1152}
1153
1154type IntoIterImpl = btree_map::IntoIter<String, Value>;
1155
1156delegate_iterator!((IntoIter) => (String, Value));
1157delegate_debug!(IntoIter);
1158
1159////////////////////////////////////////////////////////////////////////////////
1160
1161/// An iterator over the keys of a `Map`.
1162///
1163/// This `struct` is created by the [`keys`] method on [`Map`]. See its
1164/// documentation for more.
1165///
1166/// [`keys`]: Map::keys
1167#[must_use = "iterators are lazy and do nothing unless consumed"]
1168#[derive(Clone, Default)]
1169pub struct Keys<'a> {
1170    iter: KeysImpl<'a>,
1171}
1172
1173type KeysImpl<'a> = btree_map::Keys<'a, String, Value>;
1174
1175delegate_iterator!((Keys<'a>) => &'a String);
1176delegate_debug!(Keys<'a>);
1177
1178////////////////////////////////////////////////////////////////////////////////
1179
1180/// An iterator over the values of a `Map`.
1181///
1182/// This `struct` is created by the [`values`] method on [`Map`]. See its
1183/// documentation for more.
1184///
1185/// [`values`]: Map::values
1186#[must_use = "iterators are lazy and do nothing unless consumed"]
1187#[derive(Clone, Default)]
1188pub struct Values<'a> {
1189    iter: ValuesImpl<'a>,
1190}
1191
1192type ValuesImpl<'a> = btree_map::Values<'a, String, Value>;
1193
1194delegate_iterator!((Values<'a>) => &'a Value);
1195delegate_debug!(Values<'a>);
1196
1197//////////////////////////////////////////////////////////////////////////////
1198
1199/// A mutable iterator over the values of a `Map`.
1200///
1201/// This `struct` is created by the [`values_mut`] method on [`Map`]. See its
1202/// documentation for more.
1203///
1204/// [`values_mut`]: Map::values_mut
1205#[must_use = "iterators are lazy and do nothing unless consumed"]
1206// NOTE: `impl Default for btree_map::ValuesMut` was stabilized in 1.82.0
1207// #[derive(Default)]
1208pub struct ValuesMut<'a> {
1209    iter: ValuesMutImpl<'a>,
1210}
1211
1212type ValuesMutImpl<'a> = btree_map::ValuesMut<'a, String, Value>;
1213
1214delegate_iterator!((ValuesMut<'a>) => &'a mut Value);
1215delegate_debug!(ValuesMut<'a>);
1216
1217////////////////////////////////////////////////////////////////////////////////
1218
1219/// An owning iterator over the values of a `Map`.
1220///
1221/// This `struct` is created by the [`into_values`] method on [`Map`]. See its
1222/// documentation for more.
1223///
1224/// [`into_values`]: Map::into_values
1225#[must_use = "iterators are lazy and do nothing unless consumed"]
1226#[derive(Default)]
1227pub struct IntoValues {
1228    iter: IntoValuesImpl,
1229}
1230
1231type IntoValuesImpl = btree_map::IntoValues<String, Value>;
1232
1233delegate_iterator!((IntoValues) => Value);
1234delegate_debug!(IntoValues);
1235
1236#[cfg(test)]
1237#[test]
1238fn test_debug() {
1239    let mut map = Map::from_iter([
1240        ("rust".to_owned(), "now".into()),
1241        ("sesh".to_owned(), "wow".into()),
1242    ]);
1243    assert_eq!(
1244        format!("{:?}", map),
1245        r#"{"rust": String("now"), "sesh": String("wow")}"#
1246    );
1247    assert_eq!(
1248        format!("{:?}", map.entry("notexist")),
1249        r#"Entry(VacantEntry("notexist"))"#
1250    );
1251    assert_eq!(
1252        format!("{:?}", map.entry("rust")),
1253        r#"Entry(OccupiedEntry { key: "rust", value: String("now") })"#
1254    );
1255    assert_eq!(
1256        format!("{:?}", map.iter()),
1257        r#"[("rust", String("now")), ("sesh", String("wow"))]"#
1258    );
1259    assert_eq!(
1260        format!("{:?}", map.iter_mut()),
1261        r#"[("rust", String("now")), ("sesh", String("wow"))]"#
1262    );
1263    assert_eq!(
1264        format!("{:?}", map.clone().into_iter()),
1265        r#"[("rust", String("now")), ("sesh", String("wow"))]"#
1266    );
1267    assert_eq!(format!("{:?}", map.keys()), r#"["rust", "sesh"]"#);
1268    assert_eq!(
1269        format!("{:?}", map.values()),
1270        r#"[String("now"), String("wow")]"#
1271    );
1272    assert_eq!(
1273        format!("{:?}", map.values_mut()),
1274        r#"[String("now"), String("wow")]"#
1275    );
1276    assert_eq!(
1277        format!("{:?}", map.clone().into_values()),
1278        r#"[String("now"), String("wow")]"#
1279    );
1280}