1 // Copyright 2017 Serde Developers
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
9 //! A map of String to toml::Value.
11 use std
::borrow
::Borrow
;
12 use std
::fmt
::{self, Debug}
;
14 use std
::iter
::FromIterator
;
17 use indexmap
::map
::IndexMap
;
20 use crate::easy
::value
::Value
;
22 /// Represents a TOML key/value type.
23 pub struct Map
<K
, V
> {
27 type MapImpl
<K
, V
> = IndexMap
<K
, V
>;
29 impl Map
<String
, Value
> {
30 /// Makes a new empty Map.
32 pub fn new() -> Self {
38 /// Makes a new empty Map with the given initial capacity.
40 pub fn with_capacity(capacity
: usize) -> Self {
42 map
: IndexMap
::with_capacity(capacity
),
46 /// Clears the map, removing all values.
48 pub fn clear(&mut self) {
52 /// Returns a reference to the value corresponding to the key.
54 /// The key may be any borrowed form of the map's key type, but the ordering
55 /// on the borrowed form *must* match the ordering on the key type.
57 pub fn get
<Q
: ?Sized
>(&self, key
: &Q
) -> Option
<&Value
>
65 /// Returns true if the map contains a value for the specified 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 contains_key
<Q
: ?Sized
>(&self, key
: &Q
) -> bool
75 self.map
.contains_key(key
)
78 /// Returns a mutable reference to the value corresponding to the key.
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.
83 pub fn get_mut
<Q
: ?Sized
>(&mut self, key
: &Q
) -> Option
<&mut Value
>
91 /// Inserts a key-value pair into the map.
93 /// If the map did not have this key present, `None` is returned.
95 /// If the map did have this key present, the value is updated, and the old
96 /// value is returned. The key is not updated, though; this matters for
97 /// types that can be `==` without being identical.
99 pub fn insert(&mut self, k
: String
, v
: Value
) -> Option
<Value
> {
100 self.map
.insert(k
, v
)
103 /// Removes a key from the map, returning the value at the key if the key
104 /// was previously in the map.
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.
109 pub fn remove
<Q
: ?Sized
>(&mut self, key
: &Q
) -> Option
<Value
>
117 /// Gets the given key's corresponding entry in the map for in-place
119 pub fn entry
<S
>(&mut self, key
: S
) -> Entry
<'_
>
123 use indexmap
::map
::Entry
as EntryImpl
;
125 match self.map
.entry(key
.into()) {
126 EntryImpl
::Vacant(vacant
) => Entry
::Vacant(VacantEntry { vacant }
),
127 EntryImpl
::Occupied(occupied
) => Entry
::Occupied(OccupiedEntry { occupied }
),
131 /// Returns the number of elements in the map.
133 pub fn len(&self) -> usize {
137 /// Returns true if the map contains no elements.
139 pub fn is_empty(&self) -> bool
{
143 /// Gets an iterator over the entries of the map.
145 pub fn iter(&self) -> Iter
<'_
> {
147 iter
: self.map
.iter(),
151 /// Gets a mutable iterator over the entries of the map.
153 pub fn iter_mut(&mut self) -> IterMut
<'_
> {
155 iter
: self.map
.iter_mut(),
159 /// Gets an iterator over the keys of the map.
161 pub fn keys(&self) -> Keys
<'_
> {
163 iter
: self.map
.keys(),
167 /// Gets an iterator over the values of the map.
169 pub fn values(&self) -> Values
<'_
> {
171 iter
: self.map
.values(),
176 impl Default
for Map
<String
, Value
> {
178 fn default() -> Self {
185 impl Clone
for Map
<String
, Value
> {
187 fn clone(&self) -> Self {
189 map
: self.map
.clone(),
194 impl PartialEq
for Map
<String
, Value
> {
196 fn eq(&self, other
: &Self) -> bool
{
197 self.map
.eq(&other
.map
)
201 /// Access an element of this map. Panics if the given key is not present in the
203 impl<'a
, Q
: ?Sized
> ops
::Index
<&'a Q
> for Map
<String
, Value
>
210 fn index(&self, index
: &Q
) -> &Value
{
211 self.map
.index(index
)
215 /// Mutably access an element of this map. Panics if the given key is not
216 /// present in the map.
217 impl<'a
, Q
: ?Sized
> ops
::IndexMut
<&'a Q
> for Map
<String
, Value
>
222 fn index_mut(&mut self, index
: &Q
) -> &mut Value
{
223 self.map
.get_mut(index
).expect("no entry found for key")
227 impl Debug
for Map
<String
, Value
> {
229 fn fmt(&self, formatter
: &mut fmt
::Formatter
<'_
>) -> Result
<(), fmt
::Error
> {
230 self.map
.fmt(formatter
)
234 impl ser
::Serialize
for Map
<String
, Value
> {
236 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
240 use serde
::ser
::SerializeMap
;
241 let mut map
= serializer
.serialize_map(Some(self.len()))?
;
243 map
.serialize_key(k
)?
;
244 map
.serialize_value(v
)?
;
250 impl<'de
> de
::Deserialize
<'de
> for Map
<String
, Value
> {
252 fn deserialize
<D
>(deserializer
: D
) -> Result
<Self, D
::Error
>
254 D
: de
::Deserializer
<'de
>,
258 impl<'de
> de
::Visitor
<'de
> for Visitor
{
259 type Value
= Map
<String
, Value
>;
261 fn expecting(&self, formatter
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
262 formatter
.write_str("a map")
266 fn visit_unit
<E
>(self) -> Result
<Self::Value
, E
>
274 fn visit_map
<V
>(self, mut visitor
: V
) -> Result
<Self::Value
, V
::Error
>
276 V
: de
::MapAccess
<'de
>,
278 let mut values
= Map
::new();
280 while let Some((key
, value
)) = visitor
.next_entry()?
{
281 values
.insert(key
, value
);
288 deserializer
.deserialize_map(Visitor
)
292 impl FromIterator
<(String
, Value
)> for Map
<String
, Value
> {
293 fn from_iter
<T
>(iter
: T
) -> Self
295 T
: IntoIterator
<Item
= (String
, Value
)>,
298 map
: FromIterator
::from_iter(iter
),
303 impl Extend
<(String
, Value
)> for Map
<String
, Value
> {
304 fn extend
<T
>(&mut self, iter
: T
)
306 T
: IntoIterator
<Item
= (String
, Value
)>,
308 self.map
.extend(iter
);
312 macro_rules
! delegate_iterator
{
313 (($name
:ident $
($generics
:tt
)*) => $item
:ty
) => {
314 impl $
($generics
)* Iterator
for $name $
($generics
)* {
317 fn next(&mut self) -> Option
<Self::Item
> {
321 fn size_hint(&self) -> (usize, Option
<usize>) {
322 self.iter
.size_hint()
326 impl $
($generics
)* DoubleEndedIterator
for $name $
($generics
)* {
328 fn next_back(&mut self) -> Option
<Self::Item
> {
329 self.iter
.next_back()
333 impl $
($generics
)* ExactSizeIterator
for $name $
($generics
)* {
335 fn len(&self) -> usize {
342 //////////////////////////////////////////////////////////////////////////////
344 /// A view into a single entry in a map, which may either be vacant or occupied.
345 /// This enum is constructed from the [`entry`] method on [`Map`].
347 /// [`entry`]: struct.Map.html#method.entry
348 /// [`Map`]: struct.Map.html
351 Vacant(VacantEntry
<'a
>),
352 /// An occupied Entry.
353 Occupied(OccupiedEntry
<'a
>),
356 /// A vacant Entry. It is part of the [`Entry`] enum.
358 /// [`Entry`]: enum.Entry.html
359 pub struct VacantEntry
<'a
> {
360 vacant
: VacantEntryImpl
<'a
>,
363 /// An occupied Entry. It is part of the [`Entry`] enum.
365 /// [`Entry`]: enum.Entry.html
366 pub struct OccupiedEntry
<'a
> {
367 occupied
: OccupiedEntryImpl
<'a
>,
370 type VacantEntryImpl
<'a
> = indexmap
::map
::VacantEntry
<'a
, String
, Value
>;
372 type OccupiedEntryImpl
<'a
> = indexmap
::map
::OccupiedEntry
<'a
, String
, Value
>;
375 /// Returns a reference to this entry's key.
376 pub fn key(&self) -> &String
{
378 Entry
::Vacant(ref e
) => e
.key(),
379 Entry
::Occupied(ref e
) => e
.key(),
383 /// Ensures a value is in the entry by inserting the default if empty, and
384 /// returns a mutable reference to the value in the entry.
385 pub fn or_insert(self, default: Value
) -> &'a
mut Value
{
387 Entry
::Vacant(entry
) => entry
.insert(default),
388 Entry
::Occupied(entry
) => entry
.into_mut(),
392 /// Ensures a value is in the entry by inserting the result of the default
393 /// function if empty, and returns a mutable reference to the value in the
395 pub fn or_insert_with
<F
>(self, default: F
) -> &'a
mut Value
397 F
: FnOnce() -> Value
,
400 Entry
::Vacant(entry
) => entry
.insert(default()),
401 Entry
::Occupied(entry
) => entry
.into_mut(),
406 impl<'a
> VacantEntry
<'a
> {
407 /// Gets a reference to the key that would be used when inserting a value
408 /// through the VacantEntry.
410 pub fn key(&self) -> &String
{
414 /// Sets the value of the entry with the VacantEntry's key, and returns a
415 /// mutable reference to it.
417 pub fn insert(self, value
: Value
) -> &'a
mut Value
{
418 self.vacant
.insert(value
)
422 impl<'a
> OccupiedEntry
<'a
> {
423 /// Gets a reference to the key in the entry.
425 pub fn key(&self) -> &String
{
429 /// Gets a reference to the value in the entry.
431 pub fn get(&self) -> &Value
{
435 /// Gets a mutable reference to the value in the entry.
437 pub fn get_mut(&mut self) -> &mut Value
{
438 self.occupied
.get_mut()
441 /// Converts the entry into a mutable reference to its value.
443 pub fn into_mut(self) -> &'a
mut Value
{
444 self.occupied
.into_mut()
447 /// Sets the value of the entry with the `OccupiedEntry`'s key, and returns
448 /// the entry's old value.
450 pub fn insert(&mut self, value
: Value
) -> Value
{
451 self.occupied
.insert(value
)
454 /// Takes the value of the entry out of the map, and returns it.
456 pub fn remove(self) -> Value
{
457 self.occupied
.remove()
461 //////////////////////////////////////////////////////////////////////////////
463 impl<'a
> IntoIterator
for &'a Map
<String
, Value
> {
464 type Item
= (&'a String
, &'a Value
);
465 type IntoIter
= Iter
<'a
>;
467 fn into_iter(self) -> Self::IntoIter
{
469 iter
: self.map
.iter(),
474 /// An iterator over a toml::Map's entries.
475 pub struct Iter
<'a
> {
479 type IterImpl
<'a
> = indexmap
::map
::Iter
<'a
, String
, Value
>;
481 delegate_iterator
!((Iter
<'a
>) => (&'a String
, &'a Value
));
483 //////////////////////////////////////////////////////////////////////////////
485 impl<'a
> IntoIterator
for &'a
mut Map
<String
, Value
> {
486 type Item
= (&'a String
, &'a
mut Value
);
487 type IntoIter
= IterMut
<'a
>;
489 fn into_iter(self) -> Self::IntoIter
{
491 iter
: self.map
.iter_mut(),
496 /// A mutable iterator over a toml::Map's entries.
497 pub struct IterMut
<'a
> {
498 iter
: IterMutImpl
<'a
>,
501 type IterMutImpl
<'a
> = indexmap
::map
::IterMut
<'a
, String
, Value
>;
503 delegate_iterator
!((IterMut
<'a
>) => (&'a String
, &'a
mut Value
));
505 //////////////////////////////////////////////////////////////////////////////
507 impl IntoIterator
for Map
<String
, Value
> {
508 type Item
= (String
, Value
);
509 type IntoIter
= IntoIter
;
511 fn into_iter(self) -> Self::IntoIter
{
513 iter
: self.map
.into_iter(),
518 /// An owning iterator over a toml::Map's entries.
519 pub struct IntoIter
{
523 type IntoIterImpl
= indexmap
::map
::IntoIter
<String
, Value
>;
525 delegate_iterator
!((IntoIter
) => (String
, Value
));
527 //////////////////////////////////////////////////////////////////////////////
529 /// An iterator over a toml::Map's keys.
530 pub struct Keys
<'a
> {
534 type KeysImpl
<'a
> = indexmap
::map
::Keys
<'a
, String
, Value
>;
536 delegate_iterator
!((Keys
<'a
>) => &'a String
);
538 //////////////////////////////////////////////////////////////////////////////
540 /// An iterator over a toml::Map's values.
541 pub struct Values
<'a
> {
542 iter
: ValuesImpl
<'a
>,
545 type ValuesImpl
<'a
> = indexmap
::map
::Values
<'a
, String
, Value
>;
547 delegate_iterator
!((Values
<'a
>) => &'a Value
);