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