• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! A map of String to serde_json::Value.
2 //!
3 //! By default the map is backed by a [`BTreeMap`]. Enable the `preserve_order`
4 //! feature of serde_json to use [`IndexMap`] instead.
5 //!
6 //! [`BTreeMap`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html
7 //! [`IndexMap`]: https://docs.rs/indexmap/*/indexmap/map/struct.IndexMap.html
8 
9 use crate::value::Value;
10 use alloc::string::String;
11 use core::borrow::Borrow;
12 use core::fmt::{self, Debug};
13 use core::hash::Hash;
14 use core::iter::{FromIterator, FusedIterator};
15 #[cfg(feature = "preserve_order")]
16 use core::mem;
17 use core::ops;
18 use serde::de;
19 
20 #[cfg(not(feature = "preserve_order"))]
21 use alloc::collections::{btree_map, BTreeMap};
22 #[cfg(feature = "preserve_order")]
23 use indexmap::{self, IndexMap};
24 
25 /// Represents a JSON key/value type.
26 pub struct Map<K, V> {
27     map: MapImpl<K, V>,
28 }
29 
30 #[cfg(not(feature = "preserve_order"))]
31 type MapImpl<K, V> = BTreeMap<K, V>;
32 #[cfg(feature = "preserve_order")]
33 type MapImpl<K, V> = IndexMap<K, V>;
34 
35 impl Map<String, Value> {
36     /// Makes a new empty Map.
37     #[inline]
new() -> Self38     pub fn new() -> Self {
39         Map {
40             map: MapImpl::new(),
41         }
42     }
43 
44     /// Makes a new empty Map with the given initial capacity.
45     #[inline]
with_capacity(capacity: usize) -> Self46     pub fn with_capacity(capacity: usize) -> Self {
47         Map {
48             #[cfg(not(feature = "preserve_order"))]
49             map: {
50                 // does not support with_capacity
51                 let _ = capacity;
52                 BTreeMap::new()
53             },
54             #[cfg(feature = "preserve_order")]
55             map: IndexMap::with_capacity(capacity),
56         }
57     }
58 
59     /// Clears the map, removing all values.
60     #[inline]
clear(&mut self)61     pub fn clear(&mut self) {
62         self.map.clear();
63     }
64 
65     /// Returns a reference to the value corresponding to the key.
66     ///
67     /// The key may be any borrowed form of the map's key type, but the ordering
68     /// on the borrowed form *must* match the ordering on the key type.
69     #[inline]
get<Q>(&self, key: &Q) -> Option<&Value> where String: Borrow<Q>, Q: ?Sized + Ord + Eq + Hash,70     pub fn get<Q>(&self, key: &Q) -> Option<&Value>
71     where
72         String: Borrow<Q>,
73         Q: ?Sized + Ord + Eq + Hash,
74     {
75         self.map.get(key)
76     }
77 
78     /// Returns true if the map contains a value for the specified key.
79     ///
80     /// The key may be any borrowed form of the map's key type, but the ordering
81     /// on the borrowed form *must* match the ordering on the key type.
82     #[inline]
contains_key<Q>(&self, key: &Q) -> bool where String: Borrow<Q>, Q: ?Sized + Ord + Eq + Hash,83     pub fn contains_key<Q>(&self, key: &Q) -> bool
84     where
85         String: Borrow<Q>,
86         Q: ?Sized + Ord + Eq + Hash,
87     {
88         self.map.contains_key(key)
89     }
90 
91     /// Returns a mutable reference to the value corresponding to the key.
92     ///
93     /// The key may be any borrowed form of the map's key type, but the ordering
94     /// on the borrowed form *must* match the ordering on the key type.
95     #[inline]
get_mut<Q>(&mut self, key: &Q) -> Option<&mut Value> where String: Borrow<Q>, Q: ?Sized + Ord + Eq + Hash,96     pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut Value>
97     where
98         String: Borrow<Q>,
99         Q: ?Sized + Ord + Eq + Hash,
100     {
101         self.map.get_mut(key)
102     }
103 
104     /// Returns the key-value pair matching the given key.
105     ///
106     /// The key may be any borrowed form of the map's key type, but the ordering
107     /// on the borrowed form *must* match the ordering on the key type.
108     #[inline]
109     #[cfg(any(feature = "preserve_order", not(no_btreemap_get_key_value)))]
get_key_value<Q>(&self, key: &Q) -> Option<(&String, &Value)> where String: Borrow<Q>, Q: ?Sized + Ord + Eq + Hash,110     pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&String, &Value)>
111     where
112         String: Borrow<Q>,
113         Q: ?Sized + Ord + Eq + Hash,
114     {
115         self.map.get_key_value(key)
116     }
117 
118     /// Inserts a key-value pair into the map.
119     ///
120     /// If the map did not have this key present, `None` is returned.
121     ///
122     /// If the map did have this key present, the value is updated, and the old
123     /// value is returned.
124     #[inline]
insert(&mut self, k: String, v: Value) -> Option<Value>125     pub fn insert(&mut self, k: String, v: Value) -> Option<Value> {
126         self.map.insert(k, v)
127     }
128 
129     /// Removes a key from the map, returning the value at the key if the key
130     /// was previously in the map.
131     ///
132     /// The key may be any borrowed form of the map's key type, but the ordering
133     /// on the borrowed form *must* match the ordering on the key type.
134     #[inline]
remove<Q>(&mut self, key: &Q) -> Option<Value> where String: Borrow<Q>, Q: ?Sized + Ord + Eq + Hash,135     pub fn remove<Q>(&mut self, key: &Q) -> Option<Value>
136     where
137         String: Borrow<Q>,
138         Q: ?Sized + Ord + Eq + Hash,
139     {
140         #[cfg(feature = "preserve_order")]
141         return self.map.swap_remove(key);
142         #[cfg(not(feature = "preserve_order"))]
143         return self.map.remove(key);
144     }
145 
146     /// Removes a key from the map, returning the stored key and value if the
147     /// key was previously in the map.
148     ///
149     /// The key may be any borrowed form of the map's key type, but the ordering
150     /// on the borrowed form *must* match the ordering on the key type.
remove_entry<Q>(&mut self, key: &Q) -> Option<(String, Value)> where String: Borrow<Q>, Q: ?Sized + Ord + Eq + Hash,151     pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(String, Value)>
152     where
153         String: Borrow<Q>,
154         Q: ?Sized + Ord + Eq + Hash,
155     {
156         #[cfg(any(feature = "preserve_order", not(no_btreemap_remove_entry)))]
157         return self.map.remove_entry(key);
158         #[cfg(all(
159             not(feature = "preserve_order"),
160             no_btreemap_remove_entry,
161             not(no_btreemap_get_key_value),
162         ))]
163         {
164             let (key, _value) = self.map.get_key_value(key)?;
165             let key = key.clone();
166             let value = self.map.remove::<String>(&key)?;
167             Some((key, value))
168         }
169         #[cfg(all(
170             not(feature = "preserve_order"),
171             no_btreemap_remove_entry,
172             no_btreemap_get_key_value,
173         ))]
174         {
175             use core::ops::{Bound, RangeBounds};
176 
177             struct Key<'a, Q: ?Sized>(&'a Q);
178 
179             impl<'a, Q: ?Sized> RangeBounds<Q> for Key<'a, Q> {
180                 fn start_bound(&self) -> Bound<&Q> {
181                     Bound::Included(self.0)
182                 }
183                 fn end_bound(&self) -> Bound<&Q> {
184                     Bound::Included(self.0)
185                 }
186             }
187 
188             let mut range = self.map.range(Key(key));
189             let (key, _value) = range.next()?;
190             let key = key.clone();
191             let value = self.map.remove::<String>(&key)?;
192             Some((key, value))
193         }
194     }
195 
196     /// Moves all elements from other into Self, leaving other empty.
197     #[inline]
append(&mut self, other: &mut Self)198     pub fn append(&mut self, other: &mut Self) {
199         #[cfg(feature = "preserve_order")]
200         for (k, v) in mem::replace(&mut other.map, MapImpl::default()) {
201             self.map.insert(k, v);
202         }
203         #[cfg(not(feature = "preserve_order"))]
204         self.map.append(&mut other.map);
205     }
206 
207     /// Gets the given key's corresponding entry in the map for in-place
208     /// manipulation.
entry<S>(&mut self, key: S) -> Entry where S: Into<String>,209     pub fn entry<S>(&mut self, key: S) -> Entry
210     where
211         S: Into<String>,
212     {
213         #[cfg(not(feature = "preserve_order"))]
214         use alloc::collections::btree_map::Entry as EntryImpl;
215         #[cfg(feature = "preserve_order")]
216         use indexmap::map::Entry as EntryImpl;
217 
218         match self.map.entry(key.into()) {
219             EntryImpl::Vacant(vacant) => Entry::Vacant(VacantEntry { vacant }),
220             EntryImpl::Occupied(occupied) => Entry::Occupied(OccupiedEntry { occupied }),
221         }
222     }
223 
224     /// Returns the number of elements in the map.
225     #[inline]
len(&self) -> usize226     pub fn len(&self) -> usize {
227         self.map.len()
228     }
229 
230     /// Returns true if the map contains no elements.
231     #[inline]
is_empty(&self) -> bool232     pub fn is_empty(&self) -> bool {
233         self.map.is_empty()
234     }
235 
236     /// Gets an iterator over the entries of the map.
237     #[inline]
iter(&self) -> Iter238     pub fn iter(&self) -> Iter {
239         Iter {
240             iter: self.map.iter(),
241         }
242     }
243 
244     /// Gets a mutable iterator over the entries of the map.
245     #[inline]
iter_mut(&mut self) -> IterMut246     pub fn iter_mut(&mut self) -> IterMut {
247         IterMut {
248             iter: self.map.iter_mut(),
249         }
250     }
251 
252     /// Gets an iterator over the keys of the map.
253     #[inline]
keys(&self) -> Keys254     pub fn keys(&self) -> Keys {
255         Keys {
256             iter: self.map.keys(),
257         }
258     }
259 
260     /// Gets an iterator over the values of the map.
261     #[inline]
values(&self) -> Values262     pub fn values(&self) -> Values {
263         Values {
264             iter: self.map.values(),
265         }
266     }
267 
268     /// Gets an iterator over mutable values of the map.
269     #[inline]
values_mut(&mut self) -> ValuesMut270     pub fn values_mut(&mut self) -> ValuesMut {
271         ValuesMut {
272             iter: self.map.values_mut(),
273         }
274     }
275 
276     /// Retains only the elements specified by the predicate.
277     ///
278     /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)`
279     /// returns `false`.
280     #[cfg(not(no_btreemap_retain))]
281     #[inline]
retain<F>(&mut self, f: F) where F: FnMut(&String, &mut Value) -> bool,282     pub fn retain<F>(&mut self, f: F)
283     where
284         F: FnMut(&String, &mut Value) -> bool,
285     {
286         self.map.retain(f);
287     }
288 }
289 
290 #[allow(clippy::derivable_impls)] // clippy bug: https://github.com/rust-lang/rust-clippy/issues/7655
291 impl Default for Map<String, Value> {
292     #[inline]
default() -> Self293     fn default() -> Self {
294         Map {
295             map: MapImpl::new(),
296         }
297     }
298 }
299 
300 impl Clone for Map<String, Value> {
301     #[inline]
clone(&self) -> Self302     fn clone(&self) -> Self {
303         Map {
304             map: self.map.clone(),
305         }
306     }
307 }
308 
309 impl PartialEq for Map<String, Value> {
310     #[inline]
eq(&self, other: &Self) -> bool311     fn eq(&self, other: &Self) -> bool {
312         self.map.eq(&other.map)
313     }
314 }
315 
316 impl Eq for Map<String, Value> {}
317 
318 /// Access an element of this map. Panics if the given key is not present in the
319 /// map.
320 ///
321 /// ```
322 /// # use serde_json::Value;
323 /// #
324 /// # let val = &Value::String("".to_owned());
325 /// # let _ =
326 /// match *val {
327 ///     Value::String(ref s) => Some(s.as_str()),
328 ///     Value::Array(ref arr) => arr[0].as_str(),
329 ///     Value::Object(ref map) => map["type"].as_str(),
330 ///     _ => None,
331 /// }
332 /// # ;
333 /// ```
334 impl<'a, Q> ops::Index<&'a Q> for Map<String, Value>
335 where
336     String: Borrow<Q>,
337     Q: ?Sized + Ord + Eq + Hash,
338 {
339     type Output = Value;
340 
index(&self, index: &Q) -> &Value341     fn index(&self, index: &Q) -> &Value {
342         self.map.index(index)
343     }
344 }
345 
346 /// Mutably access an element of this map. Panics if the given key is not
347 /// present in the map.
348 ///
349 /// ```
350 /// # use serde_json::json;
351 /// #
352 /// # let mut map = serde_json::Map::new();
353 /// # map.insert("key".to_owned(), serde_json::Value::Null);
354 /// #
355 /// map["key"] = json!("value");
356 /// ```
357 impl<'a, Q> ops::IndexMut<&'a Q> for Map<String, Value>
358 where
359     String: Borrow<Q>,
360     Q: ?Sized + Ord + Eq + Hash,
361 {
index_mut(&mut self, index: &Q) -> &mut Value362     fn index_mut(&mut self, index: &Q) -> &mut Value {
363         self.map.get_mut(index).expect("no entry found for key")
364     }
365 }
366 
367 impl Debug for Map<String, Value> {
368     #[inline]
fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error>369     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
370         self.map.fmt(formatter)
371     }
372 }
373 
374 #[cfg(any(feature = "std", feature = "alloc"))]
375 impl serde::ser::Serialize for Map<String, Value> {
376     #[inline]
serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::ser::Serializer,377     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
378     where
379         S: serde::ser::Serializer,
380     {
381         use serde::ser::SerializeMap;
382         let mut map = tri!(serializer.serialize_map(Some(self.len())));
383         for (k, v) in self {
384             tri!(map.serialize_entry(k, v));
385         }
386         map.end()
387     }
388 }
389 
390 impl<'de> de::Deserialize<'de> for Map<String, Value> {
391     #[inline]
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de>,392     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
393     where
394         D: de::Deserializer<'de>,
395     {
396         struct Visitor;
397 
398         impl<'de> de::Visitor<'de> for Visitor {
399             type Value = Map<String, Value>;
400 
401             fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
402                 formatter.write_str("a map")
403             }
404 
405             #[inline]
406             fn visit_unit<E>(self) -> Result<Self::Value, E>
407             where
408                 E: de::Error,
409             {
410                 Ok(Map::new())
411             }
412 
413             #[cfg(any(feature = "std", feature = "alloc"))]
414             #[inline]
415             fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
416             where
417                 V: de::MapAccess<'de>,
418             {
419                 let mut values = Map::new();
420 
421                 while let Some((key, value)) = tri!(visitor.next_entry()) {
422                     values.insert(key, value);
423                 }
424 
425                 Ok(values)
426             }
427         }
428 
429         deserializer.deserialize_map(Visitor)
430     }
431 }
432 
433 impl FromIterator<(String, Value)> for Map<String, Value> {
from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = (String, Value)>,434     fn from_iter<T>(iter: T) -> Self
435     where
436         T: IntoIterator<Item = (String, Value)>,
437     {
438         Map {
439             map: FromIterator::from_iter(iter),
440         }
441     }
442 }
443 
444 impl Extend<(String, Value)> for Map<String, Value> {
extend<T>(&mut self, iter: T) where T: IntoIterator<Item = (String, Value)>,445     fn extend<T>(&mut self, iter: T)
446     where
447         T: IntoIterator<Item = (String, Value)>,
448     {
449         self.map.extend(iter);
450     }
451 }
452 
453 macro_rules! delegate_iterator {
454     (($name:ident $($generics:tt)*) => $item:ty) => {
455         impl $($generics)* Iterator for $name $($generics)* {
456             type Item = $item;
457             #[inline]
458             fn next(&mut self) -> Option<Self::Item> {
459                 self.iter.next()
460             }
461             #[inline]
462             fn size_hint(&self) -> (usize, Option<usize>) {
463                 self.iter.size_hint()
464             }
465         }
466 
467         impl $($generics)* DoubleEndedIterator for $name $($generics)* {
468             #[inline]
469             fn next_back(&mut self) -> Option<Self::Item> {
470                 self.iter.next_back()
471             }
472         }
473 
474         impl $($generics)* ExactSizeIterator for $name $($generics)* {
475             #[inline]
476             fn len(&self) -> usize {
477                 self.iter.len()
478             }
479         }
480 
481         impl $($generics)* FusedIterator for $name $($generics)* {}
482     }
483 }
484 
485 //////////////////////////////////////////////////////////////////////////////
486 
487 /// A view into a single entry in a map, which may either be vacant or occupied.
488 /// This enum is constructed from the [`entry`] method on [`Map`].
489 ///
490 /// [`entry`]: struct.Map.html#method.entry
491 /// [`Map`]: struct.Map.html
492 pub enum Entry<'a> {
493     /// A vacant Entry.
494     Vacant(VacantEntry<'a>),
495     /// An occupied Entry.
496     Occupied(OccupiedEntry<'a>),
497 }
498 
499 /// A vacant Entry. It is part of the [`Entry`] enum.
500 ///
501 /// [`Entry`]: enum.Entry.html
502 pub struct VacantEntry<'a> {
503     vacant: VacantEntryImpl<'a>,
504 }
505 
506 /// An occupied Entry. It is part of the [`Entry`] enum.
507 ///
508 /// [`Entry`]: enum.Entry.html
509 pub struct OccupiedEntry<'a> {
510     occupied: OccupiedEntryImpl<'a>,
511 }
512 
513 #[cfg(not(feature = "preserve_order"))]
514 type VacantEntryImpl<'a> = btree_map::VacantEntry<'a, String, Value>;
515 #[cfg(feature = "preserve_order")]
516 type VacantEntryImpl<'a> = indexmap::map::VacantEntry<'a, String, Value>;
517 
518 #[cfg(not(feature = "preserve_order"))]
519 type OccupiedEntryImpl<'a> = btree_map::OccupiedEntry<'a, String, Value>;
520 #[cfg(feature = "preserve_order")]
521 type OccupiedEntryImpl<'a> = indexmap::map::OccupiedEntry<'a, String, Value>;
522 
523 impl<'a> Entry<'a> {
524     /// Returns a reference to this entry's key.
525     ///
526     /// # Examples
527     ///
528     /// ```
529     /// let mut map = serde_json::Map::new();
530     /// assert_eq!(map.entry("serde").key(), &"serde");
531     /// ```
key(&self) -> &String532     pub fn key(&self) -> &String {
533         match *self {
534             Entry::Vacant(ref e) => e.key(),
535             Entry::Occupied(ref e) => e.key(),
536         }
537     }
538 
539     /// Ensures a value is in the entry by inserting the default if empty, and
540     /// returns a mutable reference to the value in the entry.
541     ///
542     /// # Examples
543     ///
544     /// ```
545     /// # use serde_json::json;
546     /// #
547     /// let mut map = serde_json::Map::new();
548     /// map.entry("serde").or_insert(json!(12));
549     ///
550     /// assert_eq!(map["serde"], 12);
551     /// ```
or_insert(self, default: Value) -> &'a mut Value552     pub fn or_insert(self, default: Value) -> &'a mut Value {
553         match self {
554             Entry::Vacant(entry) => entry.insert(default),
555             Entry::Occupied(entry) => entry.into_mut(),
556         }
557     }
558 
559     /// Ensures a value is in the entry by inserting the result of the default
560     /// function if empty, and returns a mutable reference to the value in the
561     /// entry.
562     ///
563     /// # Examples
564     ///
565     /// ```
566     /// # use serde_json::json;
567     /// #
568     /// let mut map = serde_json::Map::new();
569     /// map.entry("serde").or_insert_with(|| json!("hoho"));
570     ///
571     /// assert_eq!(map["serde"], "hoho".to_owned());
572     /// ```
or_insert_with<F>(self, default: F) -> &'a mut Value where F: FnOnce() -> Value,573     pub fn or_insert_with<F>(self, default: F) -> &'a mut Value
574     where
575         F: FnOnce() -> Value,
576     {
577         match self {
578             Entry::Vacant(entry) => entry.insert(default()),
579             Entry::Occupied(entry) => entry.into_mut(),
580         }
581     }
582 
583     /// Provides in-place mutable access to an occupied entry before any
584     /// potential inserts into the map.
585     ///
586     /// # Examples
587     ///
588     /// ```
589     /// # use serde_json::json;
590     /// #
591     /// let mut map = serde_json::Map::new();
592     /// map.entry("serde")
593     ///     .and_modify(|e| *e = json!("rust"))
594     ///     .or_insert(json!("cpp"));
595     ///
596     /// assert_eq!(map["serde"], "cpp");
597     ///
598     /// map.entry("serde")
599     ///     .and_modify(|e| *e = json!("rust"))
600     ///     .or_insert(json!("cpp"));
601     ///
602     /// assert_eq!(map["serde"], "rust");
603     /// ```
and_modify<F>(self, f: F) -> Self where F: FnOnce(&mut Value),604     pub fn and_modify<F>(self, f: F) -> Self
605     where
606         F: FnOnce(&mut Value),
607     {
608         match self {
609             Entry::Occupied(mut entry) => {
610                 f(entry.get_mut());
611                 Entry::Occupied(entry)
612             }
613             Entry::Vacant(entry) => Entry::Vacant(entry),
614         }
615     }
616 }
617 
618 impl<'a> VacantEntry<'a> {
619     /// Gets a reference to the key that would be used when inserting a value
620     /// through the VacantEntry.
621     ///
622     /// # Examples
623     ///
624     /// ```
625     /// use serde_json::map::Entry;
626     ///
627     /// let mut map = serde_json::Map::new();
628     ///
629     /// match map.entry("serde") {
630     ///     Entry::Vacant(vacant) => {
631     ///         assert_eq!(vacant.key(), &"serde");
632     ///     }
633     ///     Entry::Occupied(_) => unimplemented!(),
634     /// }
635     /// ```
636     #[inline]
key(&self) -> &String637     pub fn key(&self) -> &String {
638         self.vacant.key()
639     }
640 
641     /// Sets the value of the entry with the VacantEntry's key, and returns a
642     /// mutable reference to it.
643     ///
644     /// # Examples
645     ///
646     /// ```
647     /// # use serde_json::json;
648     /// #
649     /// use serde_json::map::Entry;
650     ///
651     /// let mut map = serde_json::Map::new();
652     ///
653     /// match map.entry("serde") {
654     ///     Entry::Vacant(vacant) => {
655     ///         vacant.insert(json!("hoho"));
656     ///     }
657     ///     Entry::Occupied(_) => unimplemented!(),
658     /// }
659     /// ```
660     #[inline]
insert(self, value: Value) -> &'a mut Value661     pub fn insert(self, value: Value) -> &'a mut Value {
662         self.vacant.insert(value)
663     }
664 }
665 
666 impl<'a> OccupiedEntry<'a> {
667     /// Gets a reference to the key in the entry.
668     ///
669     /// # Examples
670     ///
671     /// ```
672     /// # use serde_json::json;
673     /// #
674     /// use serde_json::map::Entry;
675     ///
676     /// let mut map = serde_json::Map::new();
677     /// map.insert("serde".to_owned(), json!(12));
678     ///
679     /// match map.entry("serde") {
680     ///     Entry::Occupied(occupied) => {
681     ///         assert_eq!(occupied.key(), &"serde");
682     ///     }
683     ///     Entry::Vacant(_) => unimplemented!(),
684     /// }
685     /// ```
686     #[inline]
key(&self) -> &String687     pub fn key(&self) -> &String {
688         self.occupied.key()
689     }
690 
691     /// Gets a reference to the value in the entry.
692     ///
693     /// # Examples
694     ///
695     /// ```
696     /// # use serde_json::json;
697     /// #
698     /// use serde_json::map::Entry;
699     ///
700     /// let mut map = serde_json::Map::new();
701     /// map.insert("serde".to_owned(), json!(12));
702     ///
703     /// match map.entry("serde") {
704     ///     Entry::Occupied(occupied) => {
705     ///         assert_eq!(occupied.get(), 12);
706     ///     }
707     ///     Entry::Vacant(_) => unimplemented!(),
708     /// }
709     /// ```
710     #[inline]
get(&self) -> &Value711     pub fn get(&self) -> &Value {
712         self.occupied.get()
713     }
714 
715     /// Gets a mutable reference to the value in the entry.
716     ///
717     /// # Examples
718     ///
719     /// ```
720     /// # use serde_json::json;
721     /// #
722     /// use serde_json::map::Entry;
723     ///
724     /// let mut map = serde_json::Map::new();
725     /// map.insert("serde".to_owned(), json!([1, 2, 3]));
726     ///
727     /// match map.entry("serde") {
728     ///     Entry::Occupied(mut occupied) => {
729     ///         occupied.get_mut().as_array_mut().unwrap().push(json!(4));
730     ///     }
731     ///     Entry::Vacant(_) => unimplemented!(),
732     /// }
733     ///
734     /// assert_eq!(map["serde"].as_array().unwrap().len(), 4);
735     /// ```
736     #[inline]
get_mut(&mut self) -> &mut Value737     pub fn get_mut(&mut self) -> &mut Value {
738         self.occupied.get_mut()
739     }
740 
741     /// Converts the entry into a mutable reference to its value.
742     ///
743     /// # Examples
744     ///
745     /// ```
746     /// # use serde_json::json;
747     /// #
748     /// use serde_json::map::Entry;
749     ///
750     /// let mut map = serde_json::Map::new();
751     /// map.insert("serde".to_owned(), json!([1, 2, 3]));
752     ///
753     /// match map.entry("serde") {
754     ///     Entry::Occupied(mut occupied) => {
755     ///         occupied.into_mut().as_array_mut().unwrap().push(json!(4));
756     ///     }
757     ///     Entry::Vacant(_) => unimplemented!(),
758     /// }
759     ///
760     /// assert_eq!(map["serde"].as_array().unwrap().len(), 4);
761     /// ```
762     #[inline]
into_mut(self) -> &'a mut Value763     pub fn into_mut(self) -> &'a mut Value {
764         self.occupied.into_mut()
765     }
766 
767     /// Sets the value of the entry with the `OccupiedEntry`'s key, and returns
768     /// the entry's old value.
769     ///
770     /// # Examples
771     ///
772     /// ```
773     /// # use serde_json::json;
774     /// #
775     /// use serde_json::map::Entry;
776     ///
777     /// let mut map = serde_json::Map::new();
778     /// map.insert("serde".to_owned(), json!(12));
779     ///
780     /// match map.entry("serde") {
781     ///     Entry::Occupied(mut occupied) => {
782     ///         assert_eq!(occupied.insert(json!(13)), 12);
783     ///         assert_eq!(occupied.get(), 13);
784     ///     }
785     ///     Entry::Vacant(_) => unimplemented!(),
786     /// }
787     /// ```
788     #[inline]
insert(&mut self, value: Value) -> Value789     pub fn insert(&mut self, value: Value) -> Value {
790         self.occupied.insert(value)
791     }
792 
793     /// Takes the value of the entry out of the map, and returns it.
794     ///
795     /// # Examples
796     ///
797     /// ```
798     /// # use serde_json::json;
799     /// #
800     /// use serde_json::map::Entry;
801     ///
802     /// let mut map = serde_json::Map::new();
803     /// map.insert("serde".to_owned(), json!(12));
804     ///
805     /// match map.entry("serde") {
806     ///     Entry::Occupied(occupied) => {
807     ///         assert_eq!(occupied.remove(), 12);
808     ///     }
809     ///     Entry::Vacant(_) => unimplemented!(),
810     /// }
811     /// ```
812     #[inline]
remove(self) -> Value813     pub fn remove(self) -> Value {
814         #[cfg(feature = "preserve_order")]
815         return self.occupied.swap_remove();
816         #[cfg(not(feature = "preserve_order"))]
817         return self.occupied.remove();
818     }
819 }
820 
821 //////////////////////////////////////////////////////////////////////////////
822 
823 impl<'a> IntoIterator for &'a Map<String, Value> {
824     type Item = (&'a String, &'a Value);
825     type IntoIter = Iter<'a>;
826     #[inline]
into_iter(self) -> Self::IntoIter827     fn into_iter(self) -> Self::IntoIter {
828         Iter {
829             iter: self.map.iter(),
830         }
831     }
832 }
833 
834 /// An iterator over a serde_json::Map's entries.
835 pub struct Iter<'a> {
836     iter: IterImpl<'a>,
837 }
838 
839 #[cfg(not(feature = "preserve_order"))]
840 type IterImpl<'a> = btree_map::Iter<'a, String, Value>;
841 #[cfg(feature = "preserve_order")]
842 type IterImpl<'a> = indexmap::map::Iter<'a, String, Value>;
843 
844 delegate_iterator!((Iter<'a>) => (&'a String, &'a Value));
845 
846 //////////////////////////////////////////////////////////////////////////////
847 
848 impl<'a> IntoIterator for &'a mut Map<String, Value> {
849     type Item = (&'a String, &'a mut Value);
850     type IntoIter = IterMut<'a>;
851     #[inline]
into_iter(self) -> Self::IntoIter852     fn into_iter(self) -> Self::IntoIter {
853         IterMut {
854             iter: self.map.iter_mut(),
855         }
856     }
857 }
858 
859 /// A mutable iterator over a serde_json::Map's entries.
860 pub struct IterMut<'a> {
861     iter: IterMutImpl<'a>,
862 }
863 
864 #[cfg(not(feature = "preserve_order"))]
865 type IterMutImpl<'a> = btree_map::IterMut<'a, String, Value>;
866 #[cfg(feature = "preserve_order")]
867 type IterMutImpl<'a> = indexmap::map::IterMut<'a, String, Value>;
868 
869 delegate_iterator!((IterMut<'a>) => (&'a String, &'a mut Value));
870 
871 //////////////////////////////////////////////////////////////////////////////
872 
873 impl IntoIterator for Map<String, Value> {
874     type Item = (String, Value);
875     type IntoIter = IntoIter;
876     #[inline]
into_iter(self) -> Self::IntoIter877     fn into_iter(self) -> Self::IntoIter {
878         IntoIter {
879             iter: self.map.into_iter(),
880         }
881     }
882 }
883 
884 /// An owning iterator over a serde_json::Map's entries.
885 pub struct IntoIter {
886     iter: IntoIterImpl,
887 }
888 
889 #[cfg(not(feature = "preserve_order"))]
890 type IntoIterImpl = btree_map::IntoIter<String, Value>;
891 #[cfg(feature = "preserve_order")]
892 type IntoIterImpl = indexmap::map::IntoIter<String, Value>;
893 
894 delegate_iterator!((IntoIter) => (String, Value));
895 
896 //////////////////////////////////////////////////////////////////////////////
897 
898 /// An iterator over a serde_json::Map's keys.
899 pub struct Keys<'a> {
900     iter: KeysImpl<'a>,
901 }
902 
903 #[cfg(not(feature = "preserve_order"))]
904 type KeysImpl<'a> = btree_map::Keys<'a, String, Value>;
905 #[cfg(feature = "preserve_order")]
906 type KeysImpl<'a> = indexmap::map::Keys<'a, String, Value>;
907 
908 delegate_iterator!((Keys<'a>) => &'a String);
909 
910 //////////////////////////////////////////////////////////////////////////////
911 
912 /// An iterator over a serde_json::Map's values.
913 pub struct Values<'a> {
914     iter: ValuesImpl<'a>,
915 }
916 
917 #[cfg(not(feature = "preserve_order"))]
918 type ValuesImpl<'a> = btree_map::Values<'a, String, Value>;
919 #[cfg(feature = "preserve_order")]
920 type ValuesImpl<'a> = indexmap::map::Values<'a, String, Value>;
921 
922 delegate_iterator!((Values<'a>) => &'a Value);
923 
924 //////////////////////////////////////////////////////////////////////////////
925 
926 /// A mutable iterator over a serde_json::Map's values.
927 pub struct ValuesMut<'a> {
928     iter: ValuesMutImpl<'a>,
929 }
930 
931 #[cfg(not(feature = "preserve_order"))]
932 type ValuesMutImpl<'a> = btree_map::ValuesMut<'a, String, Value>;
933 #[cfg(feature = "preserve_order")]
934 type ValuesMutImpl<'a> = indexmap::map::ValuesMut<'a, String, Value>;
935 
936 delegate_iterator!((ValuesMut<'a>) => &'a mut Value);
937