1 //! A map of String to serde_json::Value.
3 //! By default the map is backed by a BTreeMap. Enable the `preserve_order`
4 //! feature of serde_json to use LinkedHashMap instead.
7 use std
::fmt
::{self, Debug}
;
10 use std
::iter
::FromIterator
;
11 use std
::borrow
::Borrow
;
14 #[cfg(not(feature = "preserve_order"))]
15 use std
::collections
::{BTreeMap, btree_map}
;
17 #[cfg(feature = "preserve_order")]
18 use linked_hash_map
::{self, LinkedHashMap}
;
20 /// Represents a JSON key/value type.
21 pub struct Map
<K
, V
> {
25 #[cfg(not(feature = "preserve_order"))]
26 type MapImpl
<K
, V
> = BTreeMap
<K
, V
>;
27 #[cfg(feature = "preserve_order")]
28 type MapImpl
<K
, V
> = LinkedHashMap
<K
, V
>;
30 impl Map
<String
, Value
> {
31 /// Makes a new empty Map.
33 pub fn new() -> Self {
39 #[cfg(not(feature = "preserve_order"))]
40 /// Makes a new empty Map with the given initial capacity.
42 pub fn with_capacity(capacity
: usize) -> Self {
43 // does not support with_capacity
50 #[cfg(feature = "preserve_order")]
51 /// Makes a new empty Map with the given initial capacity.
53 pub fn with_capacity(capacity
: usize) -> Self {
55 map
: LinkedHashMap
::with_capacity(capacity
),
59 /// Clears the map, removing all values.
61 pub fn clear(&mut self) {
65 /// Returns a reference to the value corresponding to the key.
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.
70 pub fn get
<Q
: ?Sized
>(&self, key
: &Q
) -> Option
<&Value
>
71 where String
: Borrow
<Q
>,
77 /// Returns true if the map contains a value for the specified key.
79 /// The key may be any borrowed form of the map's key type, but the ordering
80 /// on the borrowed form *must* match the ordering on the key type.
82 pub fn contains_key
<Q
: ?Sized
>(&self, key
: &Q
) -> bool
83 where String
: Borrow
<Q
>,
86 self.map
.contains_key(key
)
89 /// Returns a mutable reference to the value corresponding to the key.
91 /// The key may be any borrowed form of the map's key type, but the ordering
92 /// on the borrowed form *must* match the ordering on the key type.
94 pub fn get_mut
<Q
: ?Sized
>(&mut self, key
: &Q
) -> Option
<&mut Value
>
95 where String
: Borrow
<Q
>,
101 /// Inserts a key-value pair into the map.
103 /// If the map did not have this key present, `None` is returned.
105 /// If the map did have this key present, the value is updated, and the old
106 /// value is returned. The key is not updated, though; this matters for
107 /// types that can be `==` without being identical.
109 pub fn insert(&mut self, k
: String
, v
: Value
) -> Option
<Value
> {
110 self.map
.insert(k
, v
)
113 /// Removes a key from the map, returning the value at the key if the key
114 /// was previously in the map.
116 /// The key may be any borrowed form of the map's key type, but the ordering
117 /// on the borrowed form *must* match the ordering on the key type.
119 pub fn remove
<Q
: ?Sized
>(&mut self, key
: &Q
) -> Option
<Value
>
120 where String
: Borrow
<Q
>,
126 /// Gets the given key's corresponding entry in the map for in-place
128 pub fn entry
<S
>(&mut self, key
: S
) -> Entry
129 where S
: Into
<String
>
131 #[cfg(not(feature = "preserve_order"))]
132 use std
::collections
::btree_map
::Entry
as EntryImpl
;
133 #[cfg(feature = "preserve_order")]
134 use linked_hash_map
::Entry
as EntryImpl
;
136 match self.map
.entry(key
.into()) {
137 EntryImpl
::Vacant(vacant
) => {
138 Entry
::Vacant(VacantEntry { vacant: vacant }
)
140 EntryImpl
::Occupied(occupied
) => {
141 Entry
::Occupied(OccupiedEntry { occupied: occupied }
)
146 /// Returns the number of elements in the map.
148 pub fn len(&self) -> usize {
152 /// Returns true if the map contains no elements.
154 pub fn is_empty(&self) -> bool
{
158 /// Gets an iterator over the entries of the map.
160 pub fn iter(&self) -> Iter
{
162 iter
: self.map
.iter(),
166 /// Gets a mutable iterator over the entries of the map.
168 pub fn iter_mut(&mut self) -> IterMut
{
170 iter
: self.map
.iter_mut(),
174 /// Gets an iterator over the keys of the map.
176 pub fn keys(&self) -> Keys
{
178 iter
: self.map
.keys(),
182 /// Gets an iterator over the values of the map.
184 pub fn values(&self) -> Values
{
186 iter
: self.map
.values(),
191 impl Default
for Map
<String
, Value
> {
193 fn default() -> Self {
200 impl Clone
for Map
<String
, Value
> {
202 fn clone(&self) -> Self {
204 map
: self.map
.clone(),
209 impl PartialEq
for Map
<String
, Value
> {
211 fn eq(&self, other
: &Self) -> bool
{
212 self.map
.eq(&other
.map
)
216 /// Access an element of this map. Panics if the given key is not present in the
220 /// # use serde_json::Value;
221 /// # let val = &Value::String("".to_owned());
224 /// Value::String(ref s) => Some(s.as_str()),
225 /// Value::Array(ref arr) => arr[0].as_str(),
226 /// Value::Object(ref map) => map["type"].as_str(),
231 impl<'a
, Q
: ?Sized
> ops
::Index
<&'a Q
> for Map
<String
, Value
>
232 where String
: Borrow
<Q
>,
237 fn index(&self, index
: &Q
) -> &Value
{
238 self.map
.index(index
)
242 /// Mutably access an element of this map. Panics if the given key is not
243 /// present in the map.
246 /// # #[macro_use] extern crate serde_json;
248 /// # let mut map = serde_json::Map::new();
249 /// # map.insert("key".to_owned(), serde_json::Value::Null);
250 /// map["key"] = json!("value");
253 impl<'a
, Q
: ?Sized
> ops
::IndexMut
<&'a Q
> for Map
<String
, Value
>
254 where String
: Borrow
<Q
>,
257 fn index_mut(&mut self, index
: &Q
) -> &mut Value
{
258 self.map
.get_mut(index
).expect("no entry found for key")
262 impl Debug
for Map
<String
, Value
> {
264 fn fmt(&self, formatter
: &mut fmt
::Formatter
) -> Result
<(), fmt
::Error
> {
265 self.map
.fmt(formatter
)
269 impl ser
::Serialize
for Map
<String
, Value
> {
271 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
272 where S
: ser
::Serializer
274 use serde
::ser
::SerializeMap
;
275 let mut map
= try
!(serializer
.serialize_map(Some(self.len())));
277 try
!(map
.serialize_key(k
));
278 try
!(map
.serialize_value(v
));
284 impl de
::Deserialize
for Map
<String
, Value
> {
286 fn deserialize
<D
>(deserializer
: D
) -> Result
<Self, D
::Error
>
287 where D
: de
::Deserializer
291 impl de
::Visitor
for Visitor
{
292 type Value
= Map
<String
, Value
>;
294 fn expecting(&self, formatter
: &mut fmt
::Formatter
) -> fmt
::Result
{
295 formatter
.write_str("a map")
299 fn visit_unit
<E
>(self) -> Result
<Self::Value
, E
>
306 fn visit_map
<V
>(self, mut visitor
: V
) -> Result
<Self::Value
, V
::Error
>
307 where V
: de
::MapVisitor
309 let mut values
= Map
::with_capacity(visitor
.size_hint().0);
311 while let Some((key
, value
)) = try
!(visitor
.visit()) {
312 values
.insert(key
, value
);
319 deserializer
.deserialize_map(Visitor
)
323 impl FromIterator
<(String
, Value
)> for Map
<String
, Value
> {
324 fn from_iter
<T
>(iter
: T
) -> Self where T
: IntoIterator
<Item
=(String
, Value
)> {
326 map
: FromIterator
::from_iter(iter
)
331 impl Extend
<(String
, Value
)> for Map
<String
, Value
> {
332 fn extend
<T
>(&mut self, iter
: T
) where T
: IntoIterator
<Item
=(String
, Value
)> {
333 self.map
.extend(iter
);
337 macro_rules
! delegate_iterator
{
338 (($name
:ident $
($generics
:tt
)*) => $item
:ty
) => {
339 impl $
($generics
)* Iterator
for $name $
($generics
)* {
342 fn next(&mut self) -> Option
<Self::Item
> {
346 fn size_hint(&self) -> (usize, Option
<usize>) {
347 self.iter
.size_hint()
351 impl $
($generics
)* DoubleEndedIterator
for $name $
($generics
)* {
353 fn next_back(&mut self) -> Option
<Self::Item
> {
354 self.iter
.next_back()
358 impl $
($generics
)* ExactSizeIterator
for $name $
($generics
)* {
360 fn len(&self) -> usize {
367 //////////////////////////////////////////////////////////////////////////////
369 /// A view into a single entry in a map, which may either be vacant or occupied.
370 /// This enum is constructed from the [`entry`] method on [`Map`].
372 /// [`entry`]: struct.Map.html#method.entry
373 /// [`BTreeMap`]: struct.Map.html
376 Vacant(VacantEntry
<'a
>),
377 /// An occupied Entry.
378 Occupied(OccupiedEntry
<'a
>),
381 /// A vacant Entry. It is part of the [`Entry`] enum.
383 /// [`Entry`]: enum.Entry.html
384 pub struct VacantEntry
<'a
> {
385 vacant
: VacantEntryImpl
<'a
>,
388 /// An occupied Entry. It is part of the [`Entry`] enum.
390 /// [`Entry`]: enum.Entry.html
391 pub struct OccupiedEntry
<'a
> {
392 occupied
: OccupiedEntryImpl
<'a
>,
395 #[cfg(not(feature = "preserve_order"))]
396 type VacantEntryImpl
<'a
> = btree_map
::VacantEntry
<'a
, String
, Value
>;
397 #[cfg(feature = "preserve_order")]
398 type VacantEntryImpl
<'a
> = linked_hash_map
::VacantEntry
<'a
, String
, Value
>;
400 #[cfg(not(feature = "preserve_order"))]
401 type OccupiedEntryImpl
<'a
> = btree_map
::OccupiedEntry
<'a
, String
, Value
>;
402 #[cfg(feature = "preserve_order")]
403 type OccupiedEntryImpl
<'a
> = linked_hash_map
::OccupiedEntry
<'a
, String
, Value
>;
406 /// Returns a reference to this entry's key.
411 /// let mut map = serde_json::Map::new();
412 /// assert_eq!(map.entry("serde").key(), &"serde");
414 pub fn key(&self) -> &String
{
416 Entry
::Vacant(ref e
) => e
.key(),
417 Entry
::Occupied(ref e
) => e
.key(),
421 /// Ensures a value is in the entry by inserting the default if empty, and
422 /// returns a mutable reference to the value in the entry.
427 /// # #[macro_use] extern crate serde_json;
429 /// let mut map = serde_json::Map::new();
430 /// map.entry("serde").or_insert(json!(12));
432 /// assert_eq!(map["serde"], 12);
435 pub fn or_insert(self, default: Value
) -> &'a
mut Value
{
437 Entry
::Vacant(entry
) => entry
.insert(default.into()),
438 Entry
::Occupied(entry
) => entry
.into_mut(),
442 /// Ensures a value is in the entry by inserting the result of the default
443 /// function if empty, and returns a mutable reference to the value in the
449 /// # #[macro_use] extern crate serde_json;
451 /// let mut map = serde_json::Map::new();
452 /// map.entry("serde").or_insert_with(|| json!("hoho"));
454 /// assert_eq!(map["serde"], "hoho".to_owned());
457 pub fn or_insert_with
<F
>(self, default: F
) -> &'a
mut Value
458 where F
: FnOnce() -> Value
461 Entry
::Vacant(entry
) => entry
.insert(default()),
462 Entry
::Occupied(entry
) => entry
.into_mut(),
467 impl<'a
> VacantEntry
<'a
> {
468 /// Gets a reference to the key that would be used when inserting a value
469 /// through the VacantEntry.
474 /// use serde_json::map::Entry;
476 /// let mut map = serde_json::Map::new();
478 /// match map.entry("serde") {
479 /// Entry::Vacant(vacant) => {
480 /// assert_eq!(vacant.key(), &"serde");
482 /// Entry::Occupied(_) => unimplemented!(),
486 pub fn key(&self) -> &String
{
490 /// Sets the value of the entry with the VacantEntry's key, and returns a
491 /// mutable reference to it.
496 /// # #[macro_use] extern crate serde_json;
498 /// use serde_json::map::Entry;
500 /// let mut map = serde_json::Map::new();
502 /// match map.entry("serde") {
503 /// Entry::Vacant(vacant) => {
504 /// vacant.insert(json!("hoho"));
506 /// Entry::Occupied(_) => unimplemented!(),
511 pub fn insert(self, value
: Value
) -> &'a
mut Value
{
512 self.vacant
.insert(value
.into())
516 impl<'a
> OccupiedEntry
<'a
> {
517 /// Gets a reference to the key in the entry.
522 /// # #[macro_use] extern crate serde_json;
524 /// use serde_json::map::Entry;
526 /// let mut map = serde_json::Map::new();
527 /// map.insert("serde".to_owned(), json!(12));
529 /// match map.entry("serde") {
530 /// Entry::Occupied(occupied) => {
531 /// assert_eq!(occupied.key(), &"serde");
533 /// Entry::Vacant(_) => unimplemented!(),
538 pub fn key(&self) -> &String
{
542 /// Gets a reference to the value in the entry.
547 /// # #[macro_use] extern crate serde_json;
549 /// use serde_json::map::Entry;
551 /// let mut map = serde_json::Map::new();
552 /// map.insert("serde".to_owned(), json!(12));
554 /// match map.entry("serde") {
555 /// Entry::Occupied(occupied) => {
556 /// assert_eq!(occupied.get(), 12);
558 /// Entry::Vacant(_) => unimplemented!(),
563 pub fn get(&self) -> &Value
{
567 /// Gets a mutable reference to the value in the entry.
572 /// # #[macro_use] extern crate serde_json;
574 /// use serde_json::map::Entry;
576 /// let mut map = serde_json::Map::new();
577 /// map.insert("serde".to_owned(), json!([1, 2, 3]));
579 /// match map.entry("serde") {
580 /// Entry::Occupied(mut occupied) => {
581 /// occupied.get_mut().as_array_mut().unwrap().push(json!(4));
583 /// Entry::Vacant(_) => unimplemented!(),
586 /// assert_eq!(map["serde"].as_array().unwrap().len(), 4);
590 pub fn get_mut(&mut self) -> &mut Value
{
591 self.occupied
.get_mut()
594 /// Converts the entry into a mutable reference to its value.
599 /// # #[macro_use] extern crate serde_json;
601 /// use serde_json::map::Entry;
603 /// let mut map = serde_json::Map::new();
604 /// map.insert("serde".to_owned(), json!([1, 2, 3]));
606 /// match map.entry("serde") {
607 /// Entry::Occupied(mut occupied) => {
608 /// occupied.into_mut().as_array_mut().unwrap().push(json!(4));
610 /// Entry::Vacant(_) => unimplemented!(),
613 /// assert_eq!(map["serde"].as_array().unwrap().len(), 4);
617 pub fn into_mut(self) -> &'a
mut Value
{
618 self.occupied
.into_mut()
621 /// Sets the value of the entry with the `OccupiedEntry`'s key, and returns
622 /// the entry's old value.
627 /// # #[macro_use] extern crate serde_json;
629 /// use serde_json::map::Entry;
631 /// let mut map = serde_json::Map::new();
632 /// map.insert("serde".to_owned(), json!(12));
634 /// match map.entry("serde") {
635 /// Entry::Occupied(mut occupied) => {
636 /// assert_eq!(occupied.insert(json!(13)), 12);
637 /// assert_eq!(occupied.get(), 13);
639 /// Entry::Vacant(_) => unimplemented!(),
644 pub fn insert(&mut self, value
: Value
) -> Value
{
645 self.occupied
.insert(value
.into())
648 /// Takes the value of the entry out of the map, and returns it.
653 /// # #[macro_use] extern crate serde_json;
655 /// use serde_json::map::Entry;
657 /// let mut map = serde_json::Map::new();
658 /// map.insert("serde".to_owned(), json!(12));
660 /// match map.entry("serde") {
661 /// Entry::Occupied(occupied) => {
662 /// assert_eq!(occupied.remove(), 12);
664 /// Entry::Vacant(_) => unimplemented!(),
669 pub fn remove(self) -> Value
{
670 self.occupied
.remove()
674 //////////////////////////////////////////////////////////////////////////////
676 impl<'a
> IntoIterator
for &'a Map
<String
, Value
> {
677 type Item
= (&'a String
, &'a Value
);
678 type IntoIter
= Iter
<'a
>;
680 fn into_iter(self) -> Self::IntoIter
{
682 iter
: self.map
.iter(),
687 /// An iterator over a serde_json::Map's entries.
688 pub struct Iter
<'a
> {
692 #[cfg(not(feature = "preserve_order"))]
693 type IterImpl
<'a
> = btree_map
::Iter
<'a
, String
, Value
>;
694 #[cfg(feature = "preserve_order")]
695 type IterImpl
<'a
> = linked_hash_map
::Iter
<'a
, String
, Value
>;
697 delegate_iterator
!((Iter
<'a
>) => (&'a String
, &'a Value
));
699 //////////////////////////////////////////////////////////////////////////////
701 impl<'a
> IntoIterator
for &'a
mut Map
<String
, Value
> {
702 type Item
= (&'a String
, &'a
mut Value
);
703 type IntoIter
= IterMut
<'a
>;
705 fn into_iter(self) -> Self::IntoIter
{
707 iter
: self.map
.iter_mut(),
712 /// A mutable iterator over a serde_json::Map's entries.
713 pub struct IterMut
<'a
> {
714 iter
: IterMutImpl
<'a
>,
717 #[cfg(not(feature = "preserve_order"))]
718 type IterMutImpl
<'a
> = btree_map
::IterMut
<'a
, String
, Value
>;
719 #[cfg(feature = "preserve_order")]
720 type IterMutImpl
<'a
> = linked_hash_map
::IterMut
<'a
, String
, Value
>;
722 delegate_iterator
!((IterMut
<'a
>) => (&'a String
, &'a
mut Value
));
724 //////////////////////////////////////////////////////////////////////////////
726 impl IntoIterator
for Map
<String
, Value
> {
727 type Item
= (String
, Value
);
728 type IntoIter
= IntoIter
;
730 fn into_iter(self) -> Self::IntoIter
{
732 iter
: self.map
.into_iter(),
737 /// An owning iterator over a serde_json::Map's entries.
738 pub struct IntoIter
{
742 #[cfg(not(feature = "preserve_order"))]
743 type IntoIterImpl
= btree_map
::IntoIter
<String
, Value
>;
744 #[cfg(feature = "preserve_order")]
745 type IntoIterImpl
= linked_hash_map
::IntoIter
<String
, Value
>;
747 delegate_iterator
!((IntoIter
) => (String
, Value
));
749 //////////////////////////////////////////////////////////////////////////////
751 /// An iterator over a serde_json::Map's keys.
752 pub struct Keys
<'a
> {
756 #[cfg(not(feature = "preserve_order"))]
757 type KeysImpl
<'a
> = btree_map
::Keys
<'a
, String
, Value
>;
758 #[cfg(feature = "preserve_order")]
759 type KeysImpl
<'a
> = linked_hash_map
::Keys
<'a
, String
, Value
>;
761 delegate_iterator
!((Keys
<'a
>) => &'a String
);
763 //////////////////////////////////////////////////////////////////////////////
765 /// An iterator over a serde_json::Map's values.
766 pub struct Values
<'a
> {
767 iter
: ValuesImpl
<'a
>,
770 #[cfg(not(feature = "preserve_order"))]
771 type ValuesImpl
<'a
> = btree_map
::Values
<'a
, String
, Value
>;
772 #[cfg(feature = "preserve_order")]
773 type ValuesImpl
<'a
> = linked_hash_map
::Values
<'a
, String
, Value
>;
775 delegate_iterator
!((Values
<'a
>) => &'a Value
);