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
9use crate::value::Value;
10use alloc::string::String;
11use core::borrow::Borrow;
12use core::fmt::{self, Debug};
13use core::hash::Hash;
14use core::iter::{FromIterator, FusedIterator};
15#[cfg(feature = "preserve_order")]
16use core::mem;
17use core::ops;
18use serde::de;
19
20#[cfg(not(feature = "preserve_order"))]
21use alloc::collections::{btree_map, BTreeMap};
22#[cfg(feature = "preserve_order")]
23use indexmap::{self, IndexMap};
24
25/// Represents a JSON key/value type.
26pub struct Map<K, V> {
27 map: MapImpl<K, V>,
28}
29
30#[cfg(not(feature = "preserve_order"))]
31type MapImpl<K, V> = BTreeMap<K, V>;
32#[cfg(feature = "preserve_order")]
33type MapImpl<K, V> = IndexMap<K, V>;
34
35impl Map<String, Value> {
36 /// Makes a new empty Map.
37 #[inline]
38 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]
46 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]
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]
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]
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]
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)))]
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]
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]
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.
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]
198 pub fn append(&mut self, other: &mut Self) {
199 #[cfg(feature = "preserve_order")]
200 self.map
201 .extend(mem::replace(&mut other.map, MapImpl::default()));
202 #[cfg(not(feature = "preserve_order"))]
203 self.map.append(&mut other.map);
204 }
205
206 /// Gets the given key's corresponding entry in the map for in-place
207 /// manipulation.
208 pub fn entry<S>(&mut self, key: S) -> Entry
209 where
210 S: Into<String>,
211 {
212 #[cfg(not(feature = "preserve_order"))]
213 use alloc::collections::btree_map::Entry as EntryImpl;
214 #[cfg(feature = "preserve_order")]
215 use indexmap::map::Entry as EntryImpl;
216
217 match self.map.entry(key.into()) {
218 EntryImpl::Vacant(vacant) => Entry::Vacant(VacantEntry { vacant }),
219 EntryImpl::Occupied(occupied) => Entry::Occupied(OccupiedEntry { occupied }),
220 }
221 }
222
223 /// Returns the number of elements in the map.
224 #[inline]
225 pub fn len(&self) -> usize {
226 self.map.len()
227 }
228
229 /// Returns true if the map contains no elements.
230 #[inline]
231 pub fn is_empty(&self) -> bool {
232 self.map.is_empty()
233 }
234
235 /// Gets an iterator over the entries of the map.
236 #[inline]
237 pub fn iter(&self) -> Iter {
238 Iter {
239 iter: self.map.iter(),
240 }
241 }
242
243 /// Gets a mutable iterator over the entries of the map.
244 #[inline]
245 pub fn iter_mut(&mut self) -> IterMut {
246 IterMut {
247 iter: self.map.iter_mut(),
248 }
249 }
250
251 /// Gets an iterator over the keys of the map.
252 #[inline]
253 pub fn keys(&self) -> Keys {
254 Keys {
255 iter: self.map.keys(),
256 }
257 }
258
259 /// Gets an iterator over the values of the map.
260 #[inline]
261 pub fn values(&self) -> Values {
262 Values {
263 iter: self.map.values(),
264 }
265 }
266
267 /// Gets an iterator over mutable values of the map.
268 #[inline]
269 pub fn values_mut(&mut self) -> ValuesMut {
270 ValuesMut {
271 iter: self.map.values_mut(),
272 }
273 }
274
275 /// Retains only the elements specified by the predicate.
276 ///
277 /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)`
278 /// returns `false`.
279 #[cfg(not(no_btreemap_retain))]
280 #[inline]
281 pub fn retain<F>(&mut self, f: F)
282 where
283 F: FnMut(&String, &mut Value) -> bool,
284 {
285 self.map.retain(f);
286 }
287}
288
289#[allow(clippy::derivable_impls)] // clippy bug: https://github.com/rust-lang/rust-clippy/issues/7655
290impl Default for Map<String, Value> {
291 #[inline]
292 fn default() -> Self {
293 Map {
294 map: MapImpl::new(),
295 }
296 }
297}
298
299impl Clone for Map<String, Value> {
300 #[inline]
301 fn clone(&self) -> Self {
302 Map {
303 map: self.map.clone(),
304 }
305 }
306
307 #[inline]
308 fn clone_from(&mut self, source: &Self) {
309 self.map.clone_from(&source.map);
310 }
311}
312
313impl PartialEq for Map<String, Value> {
314 #[inline]
315 fn eq(&self, other: &Self) -> bool {
316 self.map.eq(&other.map)
317 }
318}
319
320impl Eq for Map<String, Value> {}
321
322/// Access an element of this map. Panics if the given key is not present in the
323/// map.
324///
325/// ```
326/// # use serde_json::Value;
327/// #
328/// # let val = &Value::String("".to_owned());
329/// # let _ =
330/// match val {
331/// Value::String(s) => Some(s.as_str()),
332/// Value::Array(arr) => arr[0].as_str(),
333/// Value::Object(map) => map["type"].as_str(),
334/// _ => None,
335/// }
336/// # ;
337/// ```
338impl<'a, Q> ops::Index<&'a Q> for Map<String, Value>
339where
340 String: Borrow<Q>,
341 Q: ?Sized + Ord + Eq + Hash,
342{
343 type Output = Value;
344
345 fn index(&self, index: &Q) -> &Value {
346 self.map.index(index)
347 }
348}
349
350/// Mutably access an element of this map. Panics if the given key is not
351/// present in the map.
352///
353/// ```
354/// # use serde_json::json;
355/// #
356/// # let mut map = serde_json::Map::new();
357/// # map.insert("key".to_owned(), serde_json::Value::Null);
358/// #
359/// map["key"] = json!("value");
360/// ```
361impl<'a, Q> ops::IndexMut<&'a Q> for Map<String, Value>
362where
363 String: Borrow<Q>,
364 Q: ?Sized + Ord + Eq + Hash,
365{
366 fn index_mut(&mut self, index: &Q) -> &mut Value {
367 self.map.get_mut(index).expect(msg:"no entry found for key")
368 }
369}
370
371impl Debug for Map<String, Value> {
372 #[inline]
373 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
374 self.map.fmt(formatter)
375 }
376}
377
378#[cfg(any(feature = "std", feature = "alloc"))]
379impl serde::ser::Serialize for Map<String, Value> {
380 #[inline]
381 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
382 where
383 S: serde::ser::Serializer,
384 {
385 use serde::ser::SerializeMap;
386 let mut map: ::SerializeMap = tri!(serializer.serialize_map(Some(self.len())));
387 for (k: &String, v: &Value) in self {
388 tri!(map.serialize_entry(k, v));
389 }
390 map.end()
391 }
392}
393
394impl<'de> de::Deserialize<'de> for Map<String, Value> {
395 #[inline]
396 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
397 where
398 D: de::Deserializer<'de>,
399 {
400 struct Visitor;
401
402 impl<'de> de::Visitor<'de> for Visitor {
403 type Value = Map<String, Value>;
404
405 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
406 formatter.write_str("a map")
407 }
408
409 #[inline]
410 fn visit_unit<E>(self) -> Result<Self::Value, E>
411 where
412 E: de::Error,
413 {
414 Ok(Map::new())
415 }
416
417 #[cfg(any(feature = "std", feature = "alloc"))]
418 #[inline]
419 fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
420 where
421 V: de::MapAccess<'de>,
422 {
423 let mut values = Map::new();
424
425 while let Some((key, value)) = tri!(visitor.next_entry()) {
426 values.insert(key, value);
427 }
428
429 Ok(values)
430 }
431 }
432
433 deserializer.deserialize_map(Visitor)
434 }
435}
436
437impl FromIterator<(String, Value)> for Map<String, Value> {
438 fn from_iter<T>(iter: T) -> Self
439 where
440 T: IntoIterator<Item = (String, Value)>,
441 {
442 Map {
443 map: FromIterator::from_iter(iter),
444 }
445 }
446}
447
448impl Extend<(String, Value)> for Map<String, Value> {
449 fn extend<T>(&mut self, iter: T)
450 where
451 T: IntoIterator<Item = (String, Value)>,
452 {
453 self.map.extend(iter);
454 }
455}
456
457macro_rules! delegate_iterator {
458 (($name:ident $($generics:tt)*) => $item:ty) => {
459 impl $($generics)* Iterator for $name $($generics)* {
460 type Item = $item;
461 #[inline]
462 fn next(&mut self) -> Option<Self::Item> {
463 self.iter.next()
464 }
465 #[inline]
466 fn size_hint(&self) -> (usize, Option<usize>) {
467 self.iter.size_hint()
468 }
469 }
470
471 impl $($generics)* DoubleEndedIterator for $name $($generics)* {
472 #[inline]
473 fn next_back(&mut self) -> Option<Self::Item> {
474 self.iter.next_back()
475 }
476 }
477
478 impl $($generics)* ExactSizeIterator for $name $($generics)* {
479 #[inline]
480 fn len(&self) -> usize {
481 self.iter.len()
482 }
483 }
484
485 impl $($generics)* FusedIterator for $name $($generics)* {}
486 }
487}
488
489//////////////////////////////////////////////////////////////////////////////
490
491/// A view into a single entry in a map, which may either be vacant or occupied.
492/// This enum is constructed from the [`entry`] method on [`Map`].
493///
494/// [`entry`]: struct.Map.html#method.entry
495/// [`Map`]: struct.Map.html
496pub enum Entry<'a> {
497 /// A vacant Entry.
498 Vacant(VacantEntry<'a>),
499 /// An occupied Entry.
500 Occupied(OccupiedEntry<'a>),
501}
502
503/// A vacant Entry. It is part of the [`Entry`] enum.
504///
505/// [`Entry`]: enum.Entry.html
506pub struct VacantEntry<'a> {
507 vacant: VacantEntryImpl<'a>,
508}
509
510/// An occupied Entry. It is part of the [`Entry`] enum.
511///
512/// [`Entry`]: enum.Entry.html
513pub struct OccupiedEntry<'a> {
514 occupied: OccupiedEntryImpl<'a>,
515}
516
517#[cfg(not(feature = "preserve_order"))]
518type VacantEntryImpl<'a> = btree_map::VacantEntry<'a, String, Value>;
519#[cfg(feature = "preserve_order")]
520type VacantEntryImpl<'a> = indexmap::map::VacantEntry<'a, String, Value>;
521
522#[cfg(not(feature = "preserve_order"))]
523type OccupiedEntryImpl<'a> = btree_map::OccupiedEntry<'a, String, Value>;
524#[cfg(feature = "preserve_order")]
525type OccupiedEntryImpl<'a> = indexmap::map::OccupiedEntry<'a, String, Value>;
526
527impl<'a> Entry<'a> {
528 /// Returns a reference to this entry's key.
529 ///
530 /// # Examples
531 ///
532 /// ```
533 /// let mut map = serde_json::Map::new();
534 /// assert_eq!(map.entry("serde").key(), &"serde");
535 /// ```
536 pub fn key(&self) -> &String {
537 match self {
538 Entry::Vacant(e) => e.key(),
539 Entry::Occupied(e) => e.key(),
540 }
541 }
542
543 /// Ensures a value is in the entry by inserting the default if empty, and
544 /// returns a mutable reference to the value in the entry.
545 ///
546 /// # Examples
547 ///
548 /// ```
549 /// # use serde_json::json;
550 /// #
551 /// let mut map = serde_json::Map::new();
552 /// map.entry("serde").or_insert(json!(12));
553 ///
554 /// assert_eq!(map["serde"], 12);
555 /// ```
556 pub fn or_insert(self, default: Value) -> &'a mut Value {
557 match self {
558 Entry::Vacant(entry) => entry.insert(default),
559 Entry::Occupied(entry) => entry.into_mut(),
560 }
561 }
562
563 /// Ensures a value is in the entry by inserting the result of the default
564 /// function if empty, and returns a mutable reference to the value in the
565 /// entry.
566 ///
567 /// # Examples
568 ///
569 /// ```
570 /// # use serde_json::json;
571 /// #
572 /// let mut map = serde_json::Map::new();
573 /// map.entry("serde").or_insert_with(|| json!("hoho"));
574 ///
575 /// assert_eq!(map["serde"], "hoho".to_owned());
576 /// ```
577 pub fn or_insert_with<F>(self, default: F) -> &'a mut Value
578 where
579 F: FnOnce() -> Value,
580 {
581 match self {
582 Entry::Vacant(entry) => entry.insert(default()),
583 Entry::Occupied(entry) => entry.into_mut(),
584 }
585 }
586
587 /// Provides in-place mutable access to an occupied entry before any
588 /// potential inserts into the map.
589 ///
590 /// # Examples
591 ///
592 /// ```
593 /// # use serde_json::json;
594 /// #
595 /// let mut map = serde_json::Map::new();
596 /// map.entry("serde")
597 /// .and_modify(|e| *e = json!("rust"))
598 /// .or_insert(json!("cpp"));
599 ///
600 /// assert_eq!(map["serde"], "cpp");
601 ///
602 /// map.entry("serde")
603 /// .and_modify(|e| *e = json!("rust"))
604 /// .or_insert(json!("cpp"));
605 ///
606 /// assert_eq!(map["serde"], "rust");
607 /// ```
608 pub fn and_modify<F>(self, f: F) -> Self
609 where
610 F: FnOnce(&mut Value),
611 {
612 match self {
613 Entry::Occupied(mut entry) => {
614 f(entry.get_mut());
615 Entry::Occupied(entry)
616 }
617 Entry::Vacant(entry) => Entry::Vacant(entry),
618 }
619 }
620}
621
622impl<'a> VacantEntry<'a> {
623 /// Gets a reference to the key that would be used when inserting a value
624 /// through the VacantEntry.
625 ///
626 /// # Examples
627 ///
628 /// ```
629 /// use serde_json::map::Entry;
630 ///
631 /// let mut map = serde_json::Map::new();
632 ///
633 /// match map.entry("serde") {
634 /// Entry::Vacant(vacant) => {
635 /// assert_eq!(vacant.key(), &"serde");
636 /// }
637 /// Entry::Occupied(_) => unimplemented!(),
638 /// }
639 /// ```
640 #[inline]
641 pub fn key(&self) -> &String {
642 self.vacant.key()
643 }
644
645 /// Sets the value of the entry with the VacantEntry's key, and returns a
646 /// mutable reference to it.
647 ///
648 /// # Examples
649 ///
650 /// ```
651 /// # use serde_json::json;
652 /// #
653 /// use serde_json::map::Entry;
654 ///
655 /// let mut map = serde_json::Map::new();
656 ///
657 /// match map.entry("serde") {
658 /// Entry::Vacant(vacant) => {
659 /// vacant.insert(json!("hoho"));
660 /// }
661 /// Entry::Occupied(_) => unimplemented!(),
662 /// }
663 /// ```
664 #[inline]
665 pub fn insert(self, value: Value) -> &'a mut Value {
666 self.vacant.insert(value)
667 }
668}
669
670impl<'a> OccupiedEntry<'a> {
671 /// Gets a reference to the key in the entry.
672 ///
673 /// # Examples
674 ///
675 /// ```
676 /// # use serde_json::json;
677 /// #
678 /// use serde_json::map::Entry;
679 ///
680 /// let mut map = serde_json::Map::new();
681 /// map.insert("serde".to_owned(), json!(12));
682 ///
683 /// match map.entry("serde") {
684 /// Entry::Occupied(occupied) => {
685 /// assert_eq!(occupied.key(), &"serde");
686 /// }
687 /// Entry::Vacant(_) => unimplemented!(),
688 /// }
689 /// ```
690 #[inline]
691 pub fn key(&self) -> &String {
692 self.occupied.key()
693 }
694
695 /// Gets a reference to the value in the entry.
696 ///
697 /// # Examples
698 ///
699 /// ```
700 /// # use serde_json::json;
701 /// #
702 /// use serde_json::map::Entry;
703 ///
704 /// let mut map = serde_json::Map::new();
705 /// map.insert("serde".to_owned(), json!(12));
706 ///
707 /// match map.entry("serde") {
708 /// Entry::Occupied(occupied) => {
709 /// assert_eq!(occupied.get(), 12);
710 /// }
711 /// Entry::Vacant(_) => unimplemented!(),
712 /// }
713 /// ```
714 #[inline]
715 pub fn get(&self) -> &Value {
716 self.occupied.get()
717 }
718
719 /// Gets a mutable reference to the value in the entry.
720 ///
721 /// # Examples
722 ///
723 /// ```
724 /// # use serde_json::json;
725 /// #
726 /// use serde_json::map::Entry;
727 ///
728 /// let mut map = serde_json::Map::new();
729 /// map.insert("serde".to_owned(), json!([1, 2, 3]));
730 ///
731 /// match map.entry("serde") {
732 /// Entry::Occupied(mut occupied) => {
733 /// occupied.get_mut().as_array_mut().unwrap().push(json!(4));
734 /// }
735 /// Entry::Vacant(_) => unimplemented!(),
736 /// }
737 ///
738 /// assert_eq!(map["serde"].as_array().unwrap().len(), 4);
739 /// ```
740 #[inline]
741 pub fn get_mut(&mut self) -> &mut Value {
742 self.occupied.get_mut()
743 }
744
745 /// Converts the entry into a mutable reference to its value.
746 ///
747 /// # Examples
748 ///
749 /// ```
750 /// # use serde_json::json;
751 /// #
752 /// use serde_json::map::Entry;
753 ///
754 /// let mut map = serde_json::Map::new();
755 /// map.insert("serde".to_owned(), json!([1, 2, 3]));
756 ///
757 /// match map.entry("serde") {
758 /// Entry::Occupied(mut occupied) => {
759 /// occupied.into_mut().as_array_mut().unwrap().push(json!(4));
760 /// }
761 /// Entry::Vacant(_) => unimplemented!(),
762 /// }
763 ///
764 /// assert_eq!(map["serde"].as_array().unwrap().len(), 4);
765 /// ```
766 #[inline]
767 pub fn into_mut(self) -> &'a mut Value {
768 self.occupied.into_mut()
769 }
770
771 /// Sets the value of the entry with the `OccupiedEntry`'s key, and returns
772 /// the entry's old value.
773 ///
774 /// # Examples
775 ///
776 /// ```
777 /// # use serde_json::json;
778 /// #
779 /// use serde_json::map::Entry;
780 ///
781 /// let mut map = serde_json::Map::new();
782 /// map.insert("serde".to_owned(), json!(12));
783 ///
784 /// match map.entry("serde") {
785 /// Entry::Occupied(mut occupied) => {
786 /// assert_eq!(occupied.insert(json!(13)), 12);
787 /// assert_eq!(occupied.get(), 13);
788 /// }
789 /// Entry::Vacant(_) => unimplemented!(),
790 /// }
791 /// ```
792 #[inline]
793 pub fn insert(&mut self, value: Value) -> Value {
794 self.occupied.insert(value)
795 }
796
797 /// Takes the value of the entry out of the map, and returns it.
798 ///
799 /// # Examples
800 ///
801 /// ```
802 /// # use serde_json::json;
803 /// #
804 /// use serde_json::map::Entry;
805 ///
806 /// let mut map = serde_json::Map::new();
807 /// map.insert("serde".to_owned(), json!(12));
808 ///
809 /// match map.entry("serde") {
810 /// Entry::Occupied(occupied) => {
811 /// assert_eq!(occupied.remove(), 12);
812 /// }
813 /// Entry::Vacant(_) => unimplemented!(),
814 /// }
815 /// ```
816 #[inline]
817 pub fn remove(self) -> Value {
818 #[cfg(feature = "preserve_order")]
819 return self.occupied.swap_remove();
820 #[cfg(not(feature = "preserve_order"))]
821 return self.occupied.remove();
822 }
823}
824
825//////////////////////////////////////////////////////////////////////////////
826
827impl<'a> IntoIterator for &'a Map<String, Value> {
828 type Item = (&'a String, &'a Value);
829 type IntoIter = Iter<'a>;
830 #[inline]
831 fn into_iter(self) -> Self::IntoIter {
832 Iter {
833 iter: self.map.iter(),
834 }
835 }
836}
837
838/// An iterator over a serde_json::Map's entries.
839pub struct Iter<'a> {
840 iter: IterImpl<'a>,
841}
842
843#[cfg(not(feature = "preserve_order"))]
844type IterImpl<'a> = btree_map::Iter<'a, String, Value>;
845#[cfg(feature = "preserve_order")]
846type IterImpl<'a> = indexmap::map::Iter<'a, String, Value>;
847
848delegate_iterator!((Iter<'a>) => (&'a String, &'a Value));
849
850//////////////////////////////////////////////////////////////////////////////
851
852impl<'a> IntoIterator for &'a mut Map<String, Value> {
853 type Item = (&'a String, &'a mut Value);
854 type IntoIter = IterMut<'a>;
855 #[inline]
856 fn into_iter(self) -> Self::IntoIter {
857 IterMut {
858 iter: self.map.iter_mut(),
859 }
860 }
861}
862
863/// A mutable iterator over a serde_json::Map's entries.
864pub struct IterMut<'a> {
865 iter: IterMutImpl<'a>,
866}
867
868#[cfg(not(feature = "preserve_order"))]
869type IterMutImpl<'a> = btree_map::IterMut<'a, String, Value>;
870#[cfg(feature = "preserve_order")]
871type IterMutImpl<'a> = indexmap::map::IterMut<'a, String, Value>;
872
873delegate_iterator!((IterMut<'a>) => (&'a String, &'a mut Value));
874
875//////////////////////////////////////////////////////////////////////////////
876
877impl IntoIterator for Map<String, Value> {
878 type Item = (String, Value);
879 type IntoIter = IntoIter;
880 #[inline]
881 fn into_iter(self) -> Self::IntoIter {
882 IntoIter {
883 iter: self.map.into_iter(),
884 }
885 }
886}
887
888/// An owning iterator over a serde_json::Map's entries.
889pub struct IntoIter {
890 iter: IntoIterImpl,
891}
892
893#[cfg(not(feature = "preserve_order"))]
894type IntoIterImpl = btree_map::IntoIter<String, Value>;
895#[cfg(feature = "preserve_order")]
896type IntoIterImpl = indexmap::map::IntoIter<String, Value>;
897
898delegate_iterator!((IntoIter) => (String, Value));
899
900//////////////////////////////////////////////////////////////////////////////
901
902/// An iterator over a serde_json::Map's keys.
903pub struct Keys<'a> {
904 iter: KeysImpl<'a>,
905}
906
907#[cfg(not(feature = "preserve_order"))]
908type KeysImpl<'a> = btree_map::Keys<'a, String, Value>;
909#[cfg(feature = "preserve_order")]
910type KeysImpl<'a> = indexmap::map::Keys<'a, String, Value>;
911
912delegate_iterator!((Keys<'a>) => &'a String);
913
914//////////////////////////////////////////////////////////////////////////////
915
916/// An iterator over a serde_json::Map's values.
917pub struct Values<'a> {
918 iter: ValuesImpl<'a>,
919}
920
921#[cfg(not(feature = "preserve_order"))]
922type ValuesImpl<'a> = btree_map::Values<'a, String, Value>;
923#[cfg(feature = "preserve_order")]
924type ValuesImpl<'a> = indexmap::map::Values<'a, String, Value>;
925
926delegate_iterator!((Values<'a>) => &'a Value);
927
928//////////////////////////////////////////////////////////////////////////////
929
930/// A mutable iterator over a serde_json::Map's values.
931pub struct ValuesMut<'a> {
932 iter: ValuesMutImpl<'a>,
933}
934
935#[cfg(not(feature = "preserve_order"))]
936type ValuesMutImpl<'a> = btree_map::ValuesMut<'a, String, Value>;
937#[cfg(feature = "preserve_order")]
938type ValuesMutImpl<'a> = indexmap::map::ValuesMut<'a, String, Value>;
939
940delegate_iterator!((ValuesMut<'a>) => &'a mut Value);
941