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