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