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] new() -> Self38 pub fn new() -> Self { 39 Map { 40 map: MapImpl::new(), 41 } 42 } 43 44 /// Makes a new empty Map with the given initial capacity. 45 #[inline] with_capacity(capacity: usize) -> Self46 pub fn with_capacity(capacity: usize) -> Self { 47 Map { 48 #[cfg(not(feature = "preserve_order"))] 49 map: { 50 // does not support with_capacity 51 let _ = capacity; 52 BTreeMap::new() 53 }, 54 #[cfg(feature = "preserve_order")] 55 map: IndexMap::with_capacity(capacity), 56 } 57 } 58 59 /// Clears the map, removing all values. 60 #[inline] clear(&mut self)61 pub fn clear(&mut self) { 62 self.map.clear(); 63 } 64 65 /// Returns a reference to the value corresponding to the key. 66 /// 67 /// The key may be any borrowed form of the map's key type, but the ordering 68 /// on the borrowed form *must* match the ordering on the key type. 69 #[inline] get<Q>(&self, key: &Q) -> Option<&Value> where String: Borrow<Q>, Q: ?Sized + Ord + Eq + Hash,70 pub fn get<Q>(&self, key: &Q) -> Option<&Value> 71 where 72 String: Borrow<Q>, 73 Q: ?Sized + Ord + Eq + Hash, 74 { 75 self.map.get(key) 76 } 77 78 /// Returns true if the map contains a value for the specified key. 79 /// 80 /// The key may be any borrowed form of the map's key type, but the ordering 81 /// on the borrowed form *must* match the ordering on the key type. 82 #[inline] contains_key<Q>(&self, key: &Q) -> bool where String: Borrow<Q>, Q: ?Sized + Ord + Eq + Hash,83 pub fn contains_key<Q>(&self, key: &Q) -> bool 84 where 85 String: Borrow<Q>, 86 Q: ?Sized + Ord + Eq + Hash, 87 { 88 self.map.contains_key(key) 89 } 90 91 /// Returns a mutable reference to the value corresponding to the key. 92 /// 93 /// The key may be any borrowed form of the map's key type, but the ordering 94 /// on the borrowed form *must* match the ordering on the key type. 95 #[inline] get_mut<Q>(&mut self, key: &Q) -> Option<&mut Value> where String: Borrow<Q>, Q: ?Sized + Ord + Eq + Hash,96 pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut Value> 97 where 98 String: Borrow<Q>, 99 Q: ?Sized + Ord + Eq + Hash, 100 { 101 self.map.get_mut(key) 102 } 103 104 /// Returns the key-value pair matching the given key. 105 /// 106 /// The key may be any borrowed form of the map's key type, but the ordering 107 /// on the borrowed form *must* match the ordering on the key type. 108 #[inline] 109 #[cfg(any(feature = "preserve_order", not(no_btreemap_get_key_value)))] get_key_value<Q>(&self, key: &Q) -> Option<(&String, &Value)> where String: Borrow<Q>, Q: ?Sized + Ord + Eq + Hash,110 pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&String, &Value)> 111 where 112 String: Borrow<Q>, 113 Q: ?Sized + Ord + Eq + Hash, 114 { 115 self.map.get_key_value(key) 116 } 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] insert(&mut self, k: String, v: Value) -> Option<Value>125 pub fn insert(&mut self, k: String, v: Value) -> Option<Value> { 126 self.map.insert(k, v) 127 } 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] remove<Q>(&mut self, key: &Q) -> Option<Value> where String: Borrow<Q>, Q: ?Sized + Ord + Eq + Hash,135 pub fn remove<Q>(&mut self, key: &Q) -> Option<Value> 136 where 137 String: Borrow<Q>, 138 Q: ?Sized + Ord + Eq + Hash, 139 { 140 #[cfg(feature = "preserve_order")] 141 return self.map.swap_remove(key); 142 #[cfg(not(feature = "preserve_order"))] 143 return self.map.remove(key); 144 } 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. remove_entry<Q>(&mut self, key: &Q) -> Option<(String, Value)> where String: Borrow<Q>, Q: ?Sized + Ord + Eq + Hash,151 pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(String, Value)> 152 where 153 String: Borrow<Q>, 154 Q: ?Sized + Ord + Eq + Hash, 155 { 156 #[cfg(any(feature = "preserve_order", not(no_btreemap_remove_entry)))] 157 return self.map.remove_entry(key); 158 #[cfg(all( 159 not(feature = "preserve_order"), 160 no_btreemap_remove_entry, 161 not(no_btreemap_get_key_value), 162 ))] 163 { 164 let (key, _value) = self.map.get_key_value(key)?; 165 let key = key.clone(); 166 let value = self.map.remove::<String>(&key)?; 167 Some((key, value)) 168 } 169 #[cfg(all( 170 not(feature = "preserve_order"), 171 no_btreemap_remove_entry, 172 no_btreemap_get_key_value, 173 ))] 174 { 175 use core::ops::{Bound, RangeBounds}; 176 177 struct Key<'a, Q: ?Sized>(&'a Q); 178 179 impl<'a, Q: ?Sized> RangeBounds<Q> for Key<'a, Q> { 180 fn start_bound(&self) -> Bound<&Q> { 181 Bound::Included(self.0) 182 } 183 fn end_bound(&self) -> Bound<&Q> { 184 Bound::Included(self.0) 185 } 186 } 187 188 let mut range = self.map.range(Key(key)); 189 let (key, _value) = range.next()?; 190 let key = key.clone(); 191 let value = self.map.remove::<String>(&key)?; 192 Some((key, value)) 193 } 194 } 195 196 /// Moves all elements from other into self, leaving other empty. 197 #[inline] append(&mut self, other: &mut Self)198 pub fn append(&mut self, other: &mut Self) { 199 #[cfg(feature = "preserve_order")] 200 self.map 201 .extend(mem::replace(&mut other.map, MapImpl::default())); 202 #[cfg(not(feature = "preserve_order"))] 203 self.map.append(&mut other.map); 204 } 205 206 /// Gets the given key's corresponding entry in the map for in-place 207 /// manipulation. entry<S>(&mut self, key: S) -> Entry where S: Into<String>,208 pub fn entry<S>(&mut self, key: S) -> Entry 209 where 210 S: Into<String>, 211 { 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 match self.map.entry(key.into()) { 218 EntryImpl::Vacant(vacant) => Entry::Vacant(VacantEntry { vacant }), 219 EntryImpl::Occupied(occupied) => Entry::Occupied(OccupiedEntry { occupied }), 220 } 221 } 222 223 /// Returns the number of elements in the map. 224 #[inline] len(&self) -> usize225 pub fn len(&self) -> usize { 226 self.map.len() 227 } 228 229 /// Returns true if the map contains no elements. 230 #[inline] is_empty(&self) -> bool231 pub fn is_empty(&self) -> bool { 232 self.map.is_empty() 233 } 234 235 /// Gets an iterator over the entries of the map. 236 #[inline] iter(&self) -> Iter237 pub fn iter(&self) -> Iter { 238 Iter { 239 iter: self.map.iter(), 240 } 241 } 242 243 /// Gets a mutable iterator over the entries of the map. 244 #[inline] iter_mut(&mut self) -> IterMut245 pub fn iter_mut(&mut self) -> IterMut { 246 IterMut { 247 iter: self.map.iter_mut(), 248 } 249 } 250 251 /// Gets an iterator over the keys of the map. 252 #[inline] keys(&self) -> Keys253 pub fn keys(&self) -> Keys { 254 Keys { 255 iter: self.map.keys(), 256 } 257 } 258 259 /// Gets an iterator over the values of the map. 260 #[inline] values(&self) -> Values261 pub fn values(&self) -> Values { 262 Values { 263 iter: self.map.values(), 264 } 265 } 266 267 /// Gets an iterator over mutable values of the map. 268 #[inline] values_mut(&mut self) -> ValuesMut269 pub fn values_mut(&mut self) -> ValuesMut { 270 ValuesMut { 271 iter: self.map.values_mut(), 272 } 273 } 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] retain<F>(&mut self, f: F) where F: FnMut(&String, &mut Value) -> bool,281 pub fn retain<F>(&mut self, f: F) 282 where 283 F: FnMut(&String, &mut Value) -> bool, 284 { 285 self.map.retain(f); 286 } 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] default() -> Self292 fn default() -> Self { 293 Map { 294 map: MapImpl::new(), 295 } 296 } 297 } 298 299 impl Clone for Map<String, Value> { 300 #[inline] clone(&self) -> Self301 fn clone(&self) -> Self { 302 Map { 303 map: self.map.clone(), 304 } 305 } 306 307 #[inline] clone_from(&mut self, source: &Self)308 fn clone_from(&mut self, source: &Self) { 309 self.map.clone_from(&source.map); 310 } 311 } 312 313 impl PartialEq for Map<String, Value> { 314 #[inline] eq(&self, other: &Self) -> bool315 fn eq(&self, other: &Self) -> bool { 316 self.map.eq(&other.map) 317 } 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 index(&self, index: &Q) -> &Value345 fn index(&self, index: &Q) -> &Value { 346 self.map.index(index) 347 } 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 { index_mut(&mut self, index: &Q) -> &mut Value366 fn index_mut(&mut self, index: &Q) -> &mut Value { 367 self.map.get_mut(index).expect("no entry found for key") 368 } 369 } 370 371 impl Debug for Map<String, Value> { 372 #[inline] fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error>373 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { 374 self.map.fmt(formatter) 375 } 376 } 377 378 #[cfg(any(feature = "std", feature = "alloc"))] 379 impl serde::ser::Serialize for Map<String, Value> { 380 #[inline] serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::ser::Serializer,381 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 382 where 383 S: serde::ser::Serializer, 384 { 385 use serde::ser::SerializeMap; 386 let mut map = tri!(serializer.serialize_map(Some(self.len()))); 387 for (k, v) in self { 388 tri!(map.serialize_entry(k, v)); 389 } 390 map.end() 391 } 392 } 393 394 impl<'de> de::Deserialize<'de> for Map<String, Value> { 395 #[inline] deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de>,396 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 397 where 398 D: de::Deserializer<'de>, 399 { 400 struct Visitor; 401 402 impl<'de> de::Visitor<'de> for Visitor { 403 type Value = Map<String, Value>; 404 405 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 406 formatter.write_str("a map") 407 } 408 409 #[inline] 410 fn visit_unit<E>(self) -> Result<Self::Value, E> 411 where 412 E: de::Error, 413 { 414 Ok(Map::new()) 415 } 416 417 #[cfg(any(feature = "std", feature = "alloc"))] 418 #[inline] 419 fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> 420 where 421 V: de::MapAccess<'de>, 422 { 423 let mut values = Map::new(); 424 425 while let Some((key, value)) = tri!(visitor.next_entry()) { 426 values.insert(key, value); 427 } 428 429 Ok(values) 430 } 431 } 432 433 deserializer.deserialize_map(Visitor) 434 } 435 } 436 437 impl FromIterator<(String, Value)> for Map<String, Value> { from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = (String, Value)>,438 fn from_iter<T>(iter: T) -> Self 439 where 440 T: IntoIterator<Item = (String, Value)>, 441 { 442 Map { 443 map: FromIterator::from_iter(iter), 444 } 445 } 446 } 447 448 impl Extend<(String, Value)> for Map<String, Value> { extend<T>(&mut self, iter: T) where T: IntoIterator<Item = (String, Value)>,449 fn extend<T>(&mut self, iter: T) 450 where 451 T: IntoIterator<Item = (String, Value)>, 452 { 453 self.map.extend(iter); 454 } 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 fn next(&mut self) -> Option<Self::Item> { 463 self.iter.next() 464 } 465 #[inline] 466 fn size_hint(&self) -> (usize, Option<usize>) { 467 self.iter.size_hint() 468 } 469 } 470 471 impl $($generics)* DoubleEndedIterator for $name $($generics)* { 472 #[inline] 473 fn next_back(&mut self) -> Option<Self::Item> { 474 self.iter.next_back() 475 } 476 } 477 478 impl $($generics)* ExactSizeIterator for $name $($generics)* { 479 #[inline] 480 fn len(&self) -> usize { 481 self.iter.len() 482 } 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 /// ``` key(&self) -> &String536 pub fn key(&self) -> &String { 537 match self { 538 Entry::Vacant(e) => e.key(), 539 Entry::Occupied(e) => e.key(), 540 } 541 } 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 /// ``` or_insert(self, default: Value) -> &'a mut Value556 pub fn or_insert(self, default: Value) -> &'a mut Value { 557 match self { 558 Entry::Vacant(entry) => entry.insert(default), 559 Entry::Occupied(entry) => entry.into_mut(), 560 } 561 } 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 /// ``` or_insert_with<F>(self, default: F) -> &'a mut Value where F: FnOnce() -> Value,577 pub fn or_insert_with<F>(self, default: F) -> &'a mut Value 578 where 579 F: FnOnce() -> Value, 580 { 581 match self { 582 Entry::Vacant(entry) => entry.insert(default()), 583 Entry::Occupied(entry) => entry.into_mut(), 584 } 585 } 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 /// ``` and_modify<F>(self, f: F) -> Self where F: FnOnce(&mut Value),608 pub fn and_modify<F>(self, f: F) -> Self 609 where 610 F: FnOnce(&mut Value), 611 { 612 match self { 613 Entry::Occupied(mut entry) => { 614 f(entry.get_mut()); 615 Entry::Occupied(entry) 616 } 617 Entry::Vacant(entry) => Entry::Vacant(entry), 618 } 619 } 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] key(&self) -> &String641 pub fn key(&self) -> &String { 642 self.vacant.key() 643 } 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] insert(self, value: Value) -> &'a mut Value665 pub fn insert(self, value: Value) -> &'a mut Value { 666 self.vacant.insert(value) 667 } 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] key(&self) -> &String691 pub fn key(&self) -> &String { 692 self.occupied.key() 693 } 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] get(&self) -> &Value715 pub fn get(&self) -> &Value { 716 self.occupied.get() 717 } 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] get_mut(&mut self) -> &mut Value741 pub fn get_mut(&mut self) -> &mut Value { 742 self.occupied.get_mut() 743 } 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] into_mut(self) -> &'a mut Value767 pub fn into_mut(self) -> &'a mut Value { 768 self.occupied.into_mut() 769 } 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] insert(&mut self, value: Value) -> Value793 pub fn insert(&mut self, value: Value) -> Value { 794 self.occupied.insert(value) 795 } 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] remove(self) -> Value817 pub fn remove(self) -> Value { 818 #[cfg(feature = "preserve_order")] 819 return self.occupied.swap_remove(); 820 #[cfg(not(feature = "preserve_order"))] 821 return self.occupied.remove(); 822 } 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] into_iter(self) -> Self::IntoIter831 fn into_iter(self) -> Self::IntoIter { 832 Iter { 833 iter: self.map.iter(), 834 } 835 } 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] into_iter(self) -> Self::IntoIter856 fn into_iter(self) -> Self::IntoIter { 857 IterMut { 858 iter: self.map.iter_mut(), 859 } 860 } 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] into_iter(self) -> Self::IntoIter881 fn into_iter(self) -> Self::IntoIter { 882 IntoIter { 883 iter: self.map.into_iter(), 884 } 885 } 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); 941