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