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