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 /// Retains only the elements specified by the predicate.
342 ///
343 /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)`
344 /// returns `false`.
345 #[inline]
346 pub fn retain<F>(&mut self, f: F)
347 where
348 F: FnMut(&String, &mut Value) -> bool,
349 {
350 self.map.retain(f);
351 }
352
353 /// Sorts this map's entries in-place using `str`'s usual ordering.
354 ///
355 /// If serde_json's "preserve_order" feature is not enabled, this method
356 /// does no work because all JSON maps are always kept in a sorted state.
357 ///
358 /// If serde_json's "preserve_order" feature is enabled, this method
359 /// destroys the original source order or insertion order of this map in
360 /// favor of an alphanumerical order that matches how a BTreeMap with the
361 /// same contents would be ordered. This takes **O(n log n + c)** time where
362 /// _n_ is the length of the map and _c_ is the capacity.
363 ///
364 /// Other maps nested within the values of this map are not sorted. If you
365 /// need the entire data structure to be sorted at all levels, you must also
366 /// call
367 /// <code>map.[values_mut]\().for_each([Value::sort_all_objects])</code>.
368 ///
369 /// [values_mut]: Map::values_mut
370 #[inline]
371 pub fn sort_keys(&mut self) {
372 #[cfg(feature = "preserve_order")]
373 self.map.sort_unstable_keys();
374 }
375}
376
377#[allow(clippy::derivable_impls)] // clippy bug: https://github.com/rust-lang/rust-clippy/issues/7655
378impl Default for Map<String, Value> {
379 #[inline]
380 fn default() -> Self {
381 Map {
382 map: MapImpl::new(),
383 }
384 }
385}
386
387impl Clone for Map<String, Value> {
388 #[inline]
389 fn clone(&self) -> Self {
390 Map {
391 map: self.map.clone(),
392 }
393 }
394
395 #[inline]
396 fn clone_from(&mut self, source: &Self) {
397 self.map.clone_from(&source.map);
398 }
399}
400
401impl PartialEq for Map<String, Value> {
402 #[inline]
403 fn eq(&self, other: &Self) -> bool {
404 self.map.eq(&other.map)
405 }
406}
407
408impl Eq for Map<String, Value> {}
409
410impl Hash for Map<String, Value> {
411 fn hash<H: Hasher>(&self, state: &mut H) {
412 #[cfg(not(feature = "preserve_order"))]
413 {
414 self.map.hash(state);
415 }
416
417 #[cfg(feature = "preserve_order")]
418 {
419 let mut kv = Vec::from_iter(&self.map);
420 kv.sort_unstable_by(|a, b| a.0.cmp(b.0));
421 kv.hash(state);
422 }
423 }
424}
425
426/// Access an element of this map. Panics if the given key is not present in the
427/// map.
428///
429/// ```
430/// # use serde_json::Value;
431/// #
432/// # let val = &Value::String("".to_owned());
433/// # let _ =
434/// match val {
435/// Value::String(s) => Some(s.as_str()),
436/// Value::Array(arr) => arr[0].as_str(),
437/// Value::Object(map) => map["type"].as_str(),
438/// _ => None,
439/// }
440/// # ;
441/// ```
442impl<Q> ops::Index<&Q> for Map<String, Value>
443where
444 String: Borrow<Q>,
445 Q: ?Sized + Ord + Eq + Hash,
446{
447 type Output = Value;
448
449 fn index(&self, index: &Q) -> &Value {
450 self.map.index(index)
451 }
452}
453
454/// Mutably access an element of this map. Panics if the given key is not
455/// present in the map.
456///
457/// ```
458/// # use serde_json::json;
459/// #
460/// # let mut map = serde_json::Map::new();
461/// # map.insert("key".to_owned(), serde_json::Value::Null);
462/// #
463/// map["key"] = json!("value");
464/// ```
465impl<Q> ops::IndexMut<&Q> for Map<String, Value>
466where
467 String: Borrow<Q>,
468 Q: ?Sized + Ord + Eq + Hash,
469{
470 fn index_mut(&mut self, index: &Q) -> &mut Value {
471 self.map.get_mut(index).expect("no entry found for key")
472 }
473}
474
475impl Debug for Map<String, Value> {
476 #[inline]
477 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
478 self.map.fmt(formatter)
479 }
480}
481
482#[cfg(any(feature = "std", feature = "alloc"))]
483impl serde::ser::Serialize for Map<String, Value> {
484 #[inline]
485 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
486 where
487 S: serde::ser::Serializer,
488 {
489 use serde::ser::SerializeMap;
490 let mut map = tri!(serializer.serialize_map(Some(self.len())));
491 for (k, v) in self {
492 tri!(map.serialize_entry(k, v));
493 }
494 map.end()
495 }
496}
497
498impl<'de> de::Deserialize<'de> for Map<String, Value> {
499 #[inline]
500 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
501 where
502 D: de::Deserializer<'de>,
503 {
504 struct Visitor;
505
506 impl<'de> de::Visitor<'de> for Visitor {
507 type Value = Map<String, Value>;
508
509 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
510 formatter.write_str("a map")
511 }
512
513 #[inline]
514 fn visit_unit<E>(self) -> Result<Self::Value, E>
515 where
516 E: de::Error,
517 {
518 Ok(Map::new())
519 }
520
521 #[cfg(any(feature = "std", feature = "alloc"))]
522 #[inline]
523 fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
524 where
525 V: de::MapAccess<'de>,
526 {
527 let mut values = Map::new();
528
529 while let Some((key, value)) = tri!(visitor.next_entry()) {
530 values.insert(key, value);
531 }
532
533 Ok(values)
534 }
535 }
536
537 deserializer.deserialize_map(Visitor)
538 }
539}
540
541impl FromIterator<(String, Value)> for Map<String, Value> {
542 fn from_iter<T>(iter: T) -> Self
543 where
544 T: IntoIterator<Item = (String, Value)>,
545 {
546 Map {
547 map: FromIterator::from_iter(iter),
548 }
549 }
550}
551
552impl Extend<(String, Value)> for Map<String, Value> {
553 fn extend<T>(&mut self, iter: T)
554 where
555 T: IntoIterator<Item = (String, Value)>,
556 {
557 self.map.extend(iter);
558 }
559}
560
561macro_rules! delegate_iterator {
562 (($name:ident $($generics:tt)*) => $item:ty) => {
563 impl $($generics)* Iterator for $name $($generics)* {
564 type Item = $item;
565 #[inline]
566 fn next(&mut self) -> Option<Self::Item> {
567 self.iter.next()
568 }
569 #[inline]
570 fn size_hint(&self) -> (usize, Option<usize>) {
571 self.iter.size_hint()
572 }
573 }
574
575 impl $($generics)* DoubleEndedIterator for $name $($generics)* {
576 #[inline]
577 fn next_back(&mut self) -> Option<Self::Item> {
578 self.iter.next_back()
579 }
580 }
581
582 impl $($generics)* ExactSizeIterator for $name $($generics)* {
583 #[inline]
584 fn len(&self) -> usize {
585 self.iter.len()
586 }
587 }
588
589 impl $($generics)* FusedIterator for $name $($generics)* {}
590 }
591}
592
593impl<'de> de::IntoDeserializer<'de, Error> for Map<String, Value> {
594 type Deserializer = Self;
595
596 fn into_deserializer(self) -> Self::Deserializer {
597 self
598 }
599}
600
601impl<'de> de::IntoDeserializer<'de, Error> for &'de Map<String, Value> {
602 type Deserializer = Self;
603
604 fn into_deserializer(self) -> Self::Deserializer {
605 self
606 }
607}
608
609//////////////////////////////////////////////////////////////////////////////
610
611/// A view into a single entry in a map, which may either be vacant or occupied.
612/// This enum is constructed from the [`entry`] method on [`Map`].
613///
614/// [`entry`]: struct.Map.html#method.entry
615/// [`Map`]: struct.Map.html
616pub enum Entry<'a> {
617 /// A vacant Entry.
618 Vacant(VacantEntry<'a>),
619 /// An occupied Entry.
620 Occupied(OccupiedEntry<'a>),
621}
622
623/// A vacant Entry. It is part of the [`Entry`] enum.
624///
625/// [`Entry`]: enum.Entry.html
626pub struct VacantEntry<'a> {
627 vacant: VacantEntryImpl<'a>,
628}
629
630/// An occupied Entry. It is part of the [`Entry`] enum.
631///
632/// [`Entry`]: enum.Entry.html
633pub struct OccupiedEntry<'a> {
634 occupied: OccupiedEntryImpl<'a>,
635}
636
637#[cfg(not(feature = "preserve_order"))]
638type VacantEntryImpl<'a> = btree_map::VacantEntry<'a, String, Value>;
639#[cfg(feature = "preserve_order")]
640type VacantEntryImpl<'a> = indexmap::map::VacantEntry<'a, String, Value>;
641
642#[cfg(not(feature = "preserve_order"))]
643type OccupiedEntryImpl<'a> = btree_map::OccupiedEntry<'a, String, Value>;
644#[cfg(feature = "preserve_order")]
645type OccupiedEntryImpl<'a> = indexmap::map::OccupiedEntry<'a, String, Value>;
646
647impl<'a> Entry<'a> {
648 /// Returns a reference to this entry's key.
649 ///
650 /// # Examples
651 ///
652 /// ```
653 /// let mut map = serde_json::Map::new();
654 /// assert_eq!(map.entry("serde").key(), &"serde");
655 /// ```
656 pub fn key(&self) -> &String {
657 match self {
658 Entry::Vacant(e) => e.key(),
659 Entry::Occupied(e) => e.key(),
660 }
661 }
662
663 /// Ensures a value is in the entry by inserting the default if empty, and
664 /// returns a mutable reference to the value in the entry.
665 ///
666 /// # Examples
667 ///
668 /// ```
669 /// # use serde_json::json;
670 /// #
671 /// let mut map = serde_json::Map::new();
672 /// map.entry("serde").or_insert(json!(12));
673 ///
674 /// assert_eq!(map["serde"], 12);
675 /// ```
676 pub fn or_insert(self, default: Value) -> &'a mut Value {
677 match self {
678 Entry::Vacant(entry) => entry.insert(default),
679 Entry::Occupied(entry) => entry.into_mut(),
680 }
681 }
682
683 /// Ensures a value is in the entry by inserting the result of the default
684 /// function if empty, and returns a mutable reference to the value in the
685 /// entry.
686 ///
687 /// # Examples
688 ///
689 /// ```
690 /// # use serde_json::json;
691 /// #
692 /// let mut map = serde_json::Map::new();
693 /// map.entry("serde").or_insert_with(|| json!("hoho"));
694 ///
695 /// assert_eq!(map["serde"], "hoho".to_owned());
696 /// ```
697 pub fn or_insert_with<F>(self, default: F) -> &'a mut Value
698 where
699 F: FnOnce() -> Value,
700 {
701 match self {
702 Entry::Vacant(entry) => entry.insert(default()),
703 Entry::Occupied(entry) => entry.into_mut(),
704 }
705 }
706
707 /// Provides in-place mutable access to an occupied entry before any
708 /// potential inserts into the map.
709 ///
710 /// # Examples
711 ///
712 /// ```
713 /// # use serde_json::json;
714 /// #
715 /// let mut map = serde_json::Map::new();
716 /// map.entry("serde")
717 /// .and_modify(|e| *e = json!("rust"))
718 /// .or_insert(json!("cpp"));
719 ///
720 /// assert_eq!(map["serde"], "cpp");
721 ///
722 /// map.entry("serde")
723 /// .and_modify(|e| *e = json!("rust"))
724 /// .or_insert(json!("cpp"));
725 ///
726 /// assert_eq!(map["serde"], "rust");
727 /// ```
728 pub fn and_modify<F>(self, f: F) -> Self
729 where
730 F: FnOnce(&mut Value),
731 {
732 match self {
733 Entry::Occupied(mut entry) => {
734 f(entry.get_mut());
735 Entry::Occupied(entry)
736 }
737 Entry::Vacant(entry) => Entry::Vacant(entry),
738 }
739 }
740}
741
742impl<'a> VacantEntry<'a> {
743 /// Gets a reference to the key that would be used when inserting a value
744 /// through the VacantEntry.
745 ///
746 /// # Examples
747 ///
748 /// ```
749 /// use serde_json::map::Entry;
750 ///
751 /// let mut map = serde_json::Map::new();
752 ///
753 /// match map.entry("serde") {
754 /// Entry::Vacant(vacant) => {
755 /// assert_eq!(vacant.key(), &"serde");
756 /// }
757 /// Entry::Occupied(_) => unimplemented!(),
758 /// }
759 /// ```
760 #[inline]
761 pub fn key(&self) -> &String {
762 self.vacant.key()
763 }
764
765 /// Sets the value of the entry with the VacantEntry's key, and returns a
766 /// mutable reference to it.
767 ///
768 /// # Examples
769 ///
770 /// ```
771 /// # use serde_json::json;
772 /// #
773 /// use serde_json::map::Entry;
774 ///
775 /// let mut map = serde_json::Map::new();
776 ///
777 /// match map.entry("serde") {
778 /// Entry::Vacant(vacant) => {
779 /// vacant.insert(json!("hoho"));
780 /// }
781 /// Entry::Occupied(_) => unimplemented!(),
782 /// }
783 /// ```
784 #[inline]
785 pub fn insert(self, value: Value) -> &'a mut Value {
786 self.vacant.insert(value)
787 }
788}
789
790impl<'a> OccupiedEntry<'a> {
791 /// Gets a reference to the key in the entry.
792 ///
793 /// # Examples
794 ///
795 /// ```
796 /// # use serde_json::json;
797 /// #
798 /// use serde_json::map::Entry;
799 ///
800 /// let mut map = serde_json::Map::new();
801 /// map.insert("serde".to_owned(), json!(12));
802 ///
803 /// match map.entry("serde") {
804 /// Entry::Occupied(occupied) => {
805 /// assert_eq!(occupied.key(), &"serde");
806 /// }
807 /// Entry::Vacant(_) => unimplemented!(),
808 /// }
809 /// ```
810 #[inline]
811 pub fn key(&self) -> &String {
812 self.occupied.key()
813 }
814
815 /// Gets a reference to the value in the entry.
816 ///
817 /// # Examples
818 ///
819 /// ```
820 /// # use serde_json::json;
821 /// #
822 /// use serde_json::map::Entry;
823 ///
824 /// let mut map = serde_json::Map::new();
825 /// map.insert("serde".to_owned(), json!(12));
826 ///
827 /// match map.entry("serde") {
828 /// Entry::Occupied(occupied) => {
829 /// assert_eq!(occupied.get(), 12);
830 /// }
831 /// Entry::Vacant(_) => unimplemented!(),
832 /// }
833 /// ```
834 #[inline]
835 pub fn get(&self) -> &Value {
836 self.occupied.get()
837 }
838
839 /// Gets a mutable reference to the value in the entry.
840 ///
841 /// # Examples
842 ///
843 /// ```
844 /// # use serde_json::json;
845 /// #
846 /// use serde_json::map::Entry;
847 ///
848 /// let mut map = serde_json::Map::new();
849 /// map.insert("serde".to_owned(), json!([1, 2, 3]));
850 ///
851 /// match map.entry("serde") {
852 /// Entry::Occupied(mut occupied) => {
853 /// occupied.get_mut().as_array_mut().unwrap().push(json!(4));
854 /// }
855 /// Entry::Vacant(_) => unimplemented!(),
856 /// }
857 ///
858 /// assert_eq!(map["serde"].as_array().unwrap().len(), 4);
859 /// ```
860 #[inline]
861 pub fn get_mut(&mut self) -> &mut Value {
862 self.occupied.get_mut()
863 }
864
865 /// Converts the entry into a mutable reference to its value.
866 ///
867 /// # Examples
868 ///
869 /// ```
870 /// # use serde_json::json;
871 /// #
872 /// use serde_json::map::Entry;
873 ///
874 /// let mut map = serde_json::Map::new();
875 /// map.insert("serde".to_owned(), json!([1, 2, 3]));
876 ///
877 /// match map.entry("serde") {
878 /// Entry::Occupied(mut occupied) => {
879 /// occupied.into_mut().as_array_mut().unwrap().push(json!(4));
880 /// }
881 /// Entry::Vacant(_) => unimplemented!(),
882 /// }
883 ///
884 /// assert_eq!(map["serde"].as_array().unwrap().len(), 4);
885 /// ```
886 #[inline]
887 pub fn into_mut(self) -> &'a mut Value {
888 self.occupied.into_mut()
889 }
890
891 /// Sets the value of the entry with the `OccupiedEntry`'s key, and returns
892 /// the entry's old value.
893 ///
894 /// # Examples
895 ///
896 /// ```
897 /// # use serde_json::json;
898 /// #
899 /// use serde_json::map::Entry;
900 ///
901 /// let mut map = serde_json::Map::new();
902 /// map.insert("serde".to_owned(), json!(12));
903 ///
904 /// match map.entry("serde") {
905 /// Entry::Occupied(mut occupied) => {
906 /// assert_eq!(occupied.insert(json!(13)), 12);
907 /// assert_eq!(occupied.get(), 13);
908 /// }
909 /// Entry::Vacant(_) => unimplemented!(),
910 /// }
911 /// ```
912 #[inline]
913 pub fn insert(&mut self, value: Value) -> Value {
914 self.occupied.insert(value)
915 }
916
917 /// Takes the value of the entry out of the map, and returns it.
918 ///
919 /// If serde_json's "preserve_order" is enabled, `.remove()` is
920 /// equivalent to [`.swap_remove()`][Self::swap_remove], replacing this
921 /// entry's position with the last element. If you need to preserve the
922 /// relative order of the keys in the map, use
923 /// [`.shift_remove()`][Self::shift_remove] instead.
924 ///
925 /// # Examples
926 ///
927 /// ```
928 /// # use serde_json::json;
929 /// #
930 /// use serde_json::map::Entry;
931 ///
932 /// let mut map = serde_json::Map::new();
933 /// map.insert("serde".to_owned(), json!(12));
934 ///
935 /// match map.entry("serde") {
936 /// Entry::Occupied(occupied) => {
937 /// assert_eq!(occupied.remove(), 12);
938 /// }
939 /// Entry::Vacant(_) => unimplemented!(),
940 /// }
941 /// ```
942 #[inline]
943 pub fn remove(self) -> Value {
944 #[cfg(feature = "preserve_order")]
945 return self.swap_remove();
946 #[cfg(not(feature = "preserve_order"))]
947 return self.occupied.remove();
948 }
949
950 /// Takes the value of the entry out of the map, and returns it.
951 ///
952 /// Like [`Vec::swap_remove`], the entry is removed by swapping it with the
953 /// last element of the map and popping it off. This perturbs the position
954 /// of what used to be the last element!
955 ///
956 /// [`Vec::swap_remove`]: std::vec::Vec::swap_remove
957 #[cfg(feature = "preserve_order")]
958 #[cfg_attr(docsrs, doc(cfg(feature = "preserve_order")))]
959 #[inline]
960 pub fn swap_remove(self) -> Value {
961 self.occupied.swap_remove()
962 }
963
964 /// Takes the value of the entry out of the map, and returns it.
965 ///
966 /// Like [`Vec::remove`], the entry is removed by shifting all of the
967 /// elements that follow it, preserving their relative order. This perturbs
968 /// the index of all of those elements!
969 ///
970 /// [`Vec::remove`]: std::vec::Vec::remove
971 #[cfg(feature = "preserve_order")]
972 #[cfg_attr(docsrs, doc(cfg(feature = "preserve_order")))]
973 #[inline]
974 pub fn shift_remove(self) -> Value {
975 self.occupied.shift_remove()
976 }
977
978 /// Removes the entry from the map, returning the stored key and value.
979 ///
980 /// If serde_json's "preserve_order" is enabled, `.remove_entry()` is
981 /// equivalent to [`.swap_remove_entry()`][Self::swap_remove_entry],
982 /// replacing this entry's position with the last element. If you need to
983 /// preserve the relative order of the keys in the map, use
984 /// [`.shift_remove_entry()`][Self::shift_remove_entry] instead.
985 ///
986 /// # Examples
987 ///
988 /// ```
989 /// # use serde_json::json;
990 /// #
991 /// use serde_json::map::Entry;
992 ///
993 /// let mut map = serde_json::Map::new();
994 /// map.insert("serde".to_owned(), json!(12));
995 ///
996 /// match map.entry("serde") {
997 /// Entry::Occupied(occupied) => {
998 /// let (key, value) = occupied.remove_entry();
999 /// assert_eq!(key, "serde");
1000 /// assert_eq!(value, 12);
1001 /// }
1002 /// Entry::Vacant(_) => unimplemented!(),
1003 /// }
1004 /// ```
1005 #[inline]
1006 pub fn remove_entry(self) -> (String, Value) {
1007 #[cfg(feature = "preserve_order")]
1008 return self.swap_remove_entry();
1009 #[cfg(not(feature = "preserve_order"))]
1010 return self.occupied.remove_entry();
1011 }
1012
1013 /// Removes the entry from the map, returning the stored key and value.
1014 ///
1015 /// Like [`Vec::swap_remove`], the entry is removed by swapping it with the
1016 /// last element of the map and popping it off. This perturbs the position
1017 /// of what used to be the last element!
1018 ///
1019 /// [`Vec::swap_remove`]: std::vec::Vec::swap_remove
1020 #[cfg(feature = "preserve_order")]
1021 #[cfg_attr(docsrs, doc(cfg(feature = "preserve_order")))]
1022 #[inline]
1023 pub fn swap_remove_entry(self) -> (String, Value) {
1024 self.occupied.swap_remove_entry()
1025 }
1026
1027 /// Removes the entry from the map, returning the stored key and value.
1028 ///
1029 /// Like [`Vec::remove`], the entry is removed by shifting all of the
1030 /// elements that follow it, preserving their relative order. This perturbs
1031 /// the index of all of those elements!
1032 ///
1033 /// [`Vec::remove`]: std::vec::Vec::remove
1034 #[cfg(feature = "preserve_order")]
1035 #[cfg_attr(docsrs, doc(cfg(feature = "preserve_order")))]
1036 #[inline]
1037 pub fn shift_remove_entry(self) -> (String, Value) {
1038 self.occupied.shift_remove_entry()
1039 }
1040}
1041
1042//////////////////////////////////////////////////////////////////////////////
1043
1044impl<'a> IntoIterator for &'a Map<String, Value> {
1045 type Item = (&'a String, &'a Value);
1046 type IntoIter = Iter<'a>;
1047 #[inline]
1048 fn into_iter(self) -> Self::IntoIter {
1049 Iter {
1050 iter: self.map.iter(),
1051 }
1052 }
1053}
1054
1055/// An iterator over a serde_json::Map's entries.
1056pub struct Iter<'a> {
1057 iter: IterImpl<'a>,
1058}
1059
1060#[cfg(not(feature = "preserve_order"))]
1061type IterImpl<'a> = btree_map::Iter<'a, String, Value>;
1062#[cfg(feature = "preserve_order")]
1063type IterImpl<'a> = indexmap::map::Iter<'a, String, Value>;
1064
1065delegate_iterator!((Iter<'a>) => (&'a String, &'a Value));
1066
1067//////////////////////////////////////////////////////////////////////////////
1068
1069impl<'a> IntoIterator for &'a mut Map<String, Value> {
1070 type Item = (&'a String, &'a mut Value);
1071 type IntoIter = IterMut<'a>;
1072 #[inline]
1073 fn into_iter(self) -> Self::IntoIter {
1074 IterMut {
1075 iter: self.map.iter_mut(),
1076 }
1077 }
1078}
1079
1080/// A mutable iterator over a serde_json::Map's entries.
1081pub struct IterMut<'a> {
1082 iter: IterMutImpl<'a>,
1083}
1084
1085#[cfg(not(feature = "preserve_order"))]
1086type IterMutImpl<'a> = btree_map::IterMut<'a, String, Value>;
1087#[cfg(feature = "preserve_order")]
1088type IterMutImpl<'a> = indexmap::map::IterMut<'a, String, Value>;
1089
1090delegate_iterator!((IterMut<'a>) => (&'a String, &'a mut Value));
1091
1092//////////////////////////////////////////////////////////////////////////////
1093
1094impl IntoIterator for Map<String, Value> {
1095 type Item = (String, Value);
1096 type IntoIter = IntoIter;
1097 #[inline]
1098 fn into_iter(self) -> Self::IntoIter {
1099 IntoIter {
1100 iter: self.map.into_iter(),
1101 }
1102 }
1103}
1104
1105/// An owning iterator over a serde_json::Map's entries.
1106pub struct IntoIter {
1107 iter: IntoIterImpl,
1108}
1109
1110#[cfg(not(feature = "preserve_order"))]
1111type IntoIterImpl = btree_map::IntoIter<String, Value>;
1112#[cfg(feature = "preserve_order")]
1113type IntoIterImpl = indexmap::map::IntoIter<String, Value>;
1114
1115delegate_iterator!((IntoIter) => (String, Value));
1116
1117//////////////////////////////////////////////////////////////////////////////
1118
1119/// An iterator over a serde_json::Map's keys.
1120pub struct Keys<'a> {
1121 iter: KeysImpl<'a>,
1122}
1123
1124#[cfg(not(feature = "preserve_order"))]
1125type KeysImpl<'a> = btree_map::Keys<'a, String, Value>;
1126#[cfg(feature = "preserve_order")]
1127type KeysImpl<'a> = indexmap::map::Keys<'a, String, Value>;
1128
1129delegate_iterator!((Keys<'a>) => &'a String);
1130
1131//////////////////////////////////////////////////////////////////////////////
1132
1133/// An iterator over a serde_json::Map's values.
1134pub struct Values<'a> {
1135 iter: ValuesImpl<'a>,
1136}
1137
1138#[cfg(not(feature = "preserve_order"))]
1139type ValuesImpl<'a> = btree_map::Values<'a, String, Value>;
1140#[cfg(feature = "preserve_order")]
1141type ValuesImpl<'a> = indexmap::map::Values<'a, String, Value>;
1142
1143delegate_iterator!((Values<'a>) => &'a Value);
1144
1145//////////////////////////////////////////////////////////////////////////////
1146
1147/// A mutable iterator over a serde_json::Map's values.
1148pub struct ValuesMut<'a> {
1149 iter: ValuesMutImpl<'a>,
1150}
1151
1152#[cfg(not(feature = "preserve_order"))]
1153type ValuesMutImpl<'a> = btree_map::ValuesMut<'a, String, Value>;
1154#[cfg(feature = "preserve_order")]
1155type ValuesMutImpl<'a> = indexmap::map::ValuesMut<'a, String, Value>;
1156
1157delegate_iterator!((ValuesMut<'a>) => &'a mut Value);