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