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