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