Debian Codegraph @

.cargo/vendor/serde_json/src/map.rs

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