Coverage Report

Created: 2025-08-28 06:06

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