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 //! By default the map is backed by a [`BTreeMap`]. Enable the `preserve_order`
12 //! feature of toml-rs to use [`LinkedHashMap`] instead.
14 //! [`BTreeMap`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html
15 //! [`LinkedHashMap`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html
17 use crate::value
::Value
;
19 use std
::borrow
::Borrow
;
20 use std
::fmt
::{self, Debug}
;
22 use std
::iter
::FromIterator
;
25 #[cfg(not(feature = "preserve_order"))]
26 use std
::collections
::{btree_map, BTreeMap}
;
28 #[cfg(feature = "preserve_order")]
29 use indexmap
::{self, IndexMap}
;
31 /// Represents a TOML key/value type.
32 pub struct Map
<K
, V
> {
36 #[cfg(not(feature = "preserve_order"))]
37 type MapImpl
<K
, V
> = BTreeMap
<K
, V
>;
38 #[cfg(feature = "preserve_order")]
39 type MapImpl
<K
, V
> = IndexMap
<K
, V
>;
41 impl Map
<String
, Value
> {
42 /// Makes a new empty Map.
44 pub fn new() -> Self {
50 #[cfg(not(feature = "preserve_order"))]
51 /// Makes a new empty Map with the given initial capacity.
53 pub fn with_capacity(capacity
: usize) -> Self {
54 // does not support with_capacity
61 #[cfg(feature = "preserve_order")]
62 /// Makes a new empty Map with the given initial capacity.
64 pub fn with_capacity(capacity
: usize) -> Self {
66 map
: IndexMap
::with_capacity(capacity
),
70 /// Clears the map, removing all values.
72 pub fn clear(&mut self) {
76 /// Returns a reference to the value corresponding to the key.
78 /// The key may be any borrowed form of the map's key type, but the ordering
79 /// on the borrowed form *must* match the ordering on the key type.
81 pub fn get
<Q
: ?Sized
>(&self, key
: &Q
) -> Option
<&Value
>
89 /// Returns true if the map contains a value for the specified 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 contains_key
<Q
: ?Sized
>(&self, key
: &Q
) -> bool
99 self.map
.contains_key(key
)
102 /// Returns a mutable reference to the value corresponding to the key.
104 /// The key may be any borrowed form of the map's key type, but the ordering
105 /// on the borrowed form *must* match the ordering on the key type.
107 pub fn get_mut
<Q
: ?Sized
>(&mut self, key
: &Q
) -> Option
<&mut Value
>
112 self.map
.get_mut(key
)
115 /// Inserts a key-value pair into the map.
117 /// If the map did not have this key present, `None` is returned.
119 /// If the map did have this key present, the value is updated, and the old
120 /// value is returned. The key is not updated, though; this matters for
121 /// types that can be `==` without being identical.
123 pub fn insert(&mut self, k
: String
, v
: Value
) -> Option
<Value
> {
124 self.map
.insert(k
, v
)
127 /// Removes a key from the map, returning the value at the key if the key
128 /// was previously in the map.
130 /// The key may be any borrowed form of the map's key type, but the ordering
131 /// on the borrowed form *must* match the ordering on the key type.
133 pub fn remove
<Q
: ?Sized
>(&mut self, key
: &Q
) -> Option
<Value
>
141 /// Gets the given key's corresponding entry in the map for in-place
143 pub fn entry
<S
>(&mut self, key
: S
) -> Entry
<'_
>
147 #[cfg(feature = "preserve_order")]
148 use indexmap
::map
::Entry
as EntryImpl
;
149 #[cfg(not(feature = "preserve_order"))]
150 use std
::collections
::btree_map
::Entry
as EntryImpl
;
152 match self.map
.entry(key
.into()) {
153 EntryImpl
::Vacant(vacant
) => Entry
::Vacant(VacantEntry { vacant }
),
154 EntryImpl
::Occupied(occupied
) => Entry
::Occupied(OccupiedEntry { occupied }
),
158 /// Returns the number of elements in the map.
160 pub fn len(&self) -> usize {
164 /// Returns true if the map contains no elements.
166 pub fn is_empty(&self) -> bool
{
170 /// Gets an iterator over the entries of the map.
172 pub fn iter(&self) -> Iter
<'_
> {
174 iter
: self.map
.iter(),
178 /// Gets a mutable iterator over the entries of the map.
180 pub fn iter_mut(&mut self) -> IterMut
<'_
> {
182 iter
: self.map
.iter_mut(),
186 /// Gets an iterator over the keys of the map.
188 pub fn keys(&self) -> Keys
<'_
> {
190 iter
: self.map
.keys(),
194 /// Gets an iterator over the values of the map.
196 pub fn values(&self) -> Values
<'_
> {
198 iter
: self.map
.values(),
203 impl Default
for Map
<String
, Value
> {
205 fn default() -> Self {
212 impl Clone
for Map
<String
, Value
> {
214 fn clone(&self) -> Self {
216 map
: self.map
.clone(),
221 impl PartialEq
for Map
<String
, Value
> {
223 fn eq(&self, other
: &Self) -> bool
{
224 self.map
.eq(&other
.map
)
228 /// Access an element of this map. Panics if the given key is not present in the
230 impl<'a
, Q
: ?Sized
> ops
::Index
<&'a Q
> for Map
<String
, Value
>
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.
244 impl<'a
, Q
: ?Sized
> ops
::IndexMut
<&'a Q
> for Map
<String
, Value
>
249 fn index_mut(&mut self, index
: &Q
) -> &mut Value
{
250 self.map
.get_mut(index
).expect("no entry found for key")
254 impl Debug
for Map
<String
, Value
> {
256 fn fmt(&self, formatter
: &mut fmt
::Formatter
<'_
>) -> Result
<(), fmt
::Error
> {
257 self.map
.fmt(formatter
)
261 impl ser
::Serialize
for Map
<String
, Value
> {
263 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
267 use serde
::ser
::SerializeMap
;
268 let mut map
= serializer
.serialize_map(Some(self.len()))?
;
270 map
.serialize_key(k
)?
;
271 map
.serialize_value(v
)?
;
277 impl<'de
> de
::Deserialize
<'de
> for Map
<String
, Value
> {
279 fn deserialize
<D
>(deserializer
: D
) -> Result
<Self, D
::Error
>
281 D
: de
::Deserializer
<'de
>,
285 impl<'de
> de
::Visitor
<'de
> for Visitor
{
286 type Value
= Map
<String
, Value
>;
288 fn expecting(&self, formatter
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
289 formatter
.write_str("a map")
293 fn visit_unit
<E
>(self) -> Result
<Self::Value
, E
>
301 fn visit_map
<V
>(self, mut visitor
: V
) -> Result
<Self::Value
, V
::Error
>
303 V
: de
::MapAccess
<'de
>,
305 let mut values
= Map
::new();
307 while let Some((key
, value
)) = visitor
.next_entry()?
{
308 values
.insert(key
, value
);
315 deserializer
.deserialize_map(Visitor
)
319 impl FromIterator
<(String
, Value
)> for Map
<String
, Value
> {
320 fn from_iter
<T
>(iter
: T
) -> Self
322 T
: IntoIterator
<Item
= (String
, Value
)>,
325 map
: FromIterator
::from_iter(iter
),
330 impl Extend
<(String
, Value
)> for Map
<String
, Value
> {
331 fn extend
<T
>(&mut self, iter
: T
)
333 T
: IntoIterator
<Item
= (String
, Value
)>,
335 self.map
.extend(iter
);
339 macro_rules
! delegate_iterator
{
340 (($name
:ident $
($generics
:tt
)*) => $item
:ty
) => {
341 impl $
($generics
)* Iterator
for $name $
($generics
)* {
344 fn next(&mut self) -> Option
<Self::Item
> {
348 fn size_hint(&self) -> (usize, Option
<usize>) {
349 self.iter
.size_hint()
353 impl $
($generics
)* DoubleEndedIterator
for $name $
($generics
)* {
355 fn next_back(&mut self) -> Option
<Self::Item
> {
356 self.iter
.next_back()
360 impl $
($generics
)* ExactSizeIterator
for $name $
($generics
)* {
362 fn len(&self) -> usize {
369 //////////////////////////////////////////////////////////////////////////////
371 /// A view into a single entry in a map, which may either be vacant or occupied.
372 /// This enum is constructed from the [`entry`] method on [`Map`].
374 /// [`entry`]: struct.Map.html#method.entry
375 /// [`Map`]: struct.Map.html
378 Vacant(VacantEntry
<'a
>),
379 /// An occupied Entry.
380 Occupied(OccupiedEntry
<'a
>),
383 /// A vacant Entry. It is part of the [`Entry`] enum.
385 /// [`Entry`]: enum.Entry.html
386 pub struct VacantEntry
<'a
> {
387 vacant
: VacantEntryImpl
<'a
>,
390 /// An occupied Entry. It is part of the [`Entry`] enum.
392 /// [`Entry`]: enum.Entry.html
393 pub struct OccupiedEntry
<'a
> {
394 occupied
: OccupiedEntryImpl
<'a
>,
397 #[cfg(not(feature = "preserve_order"))]
398 type VacantEntryImpl
<'a
> = btree_map
::VacantEntry
<'a
, String
, Value
>;
399 #[cfg(feature = "preserve_order")]
400 type VacantEntryImpl
<'a
> = indexmap
::map
::VacantEntry
<'a
, String
, Value
>;
402 #[cfg(not(feature = "preserve_order"))]
403 type OccupiedEntryImpl
<'a
> = btree_map
::OccupiedEntry
<'a
, String
, Value
>;
404 #[cfg(feature = "preserve_order")]
405 type OccupiedEntryImpl
<'a
> = indexmap
::map
::OccupiedEntry
<'a
, String
, Value
>;
408 /// Returns a reference to this entry's key.
409 pub fn key(&self) -> &String
{
411 Entry
::Vacant(ref e
) => e
.key(),
412 Entry
::Occupied(ref e
) => e
.key(),
416 /// Ensures a value is in the entry by inserting the default if empty, and
417 /// returns a mutable reference to the value in the entry.
418 pub fn or_insert(self, default: Value
) -> &'a
mut Value
{
420 Entry
::Vacant(entry
) => entry
.insert(default),
421 Entry
::Occupied(entry
) => entry
.into_mut(),
425 /// Ensures a value is in the entry by inserting the result of the default
426 /// function if empty, and returns a mutable reference to the value in the
428 pub fn or_insert_with
<F
>(self, default: F
) -> &'a
mut Value
430 F
: FnOnce() -> Value
,
433 Entry
::Vacant(entry
) => entry
.insert(default()),
434 Entry
::Occupied(entry
) => entry
.into_mut(),
439 impl<'a
> VacantEntry
<'a
> {
440 /// Gets a reference to the key that would be used when inserting a value
441 /// through the VacantEntry.
443 pub fn key(&self) -> &String
{
447 /// Sets the value of the entry with the VacantEntry's key, and returns a
448 /// mutable reference to it.
450 pub fn insert(self, value
: Value
) -> &'a
mut Value
{
451 self.vacant
.insert(value
)
455 impl<'a
> OccupiedEntry
<'a
> {
456 /// Gets a reference to the key in the entry.
458 pub fn key(&self) -> &String
{
462 /// Gets a reference to the value in the entry.
464 pub fn get(&self) -> &Value
{
468 /// Gets a mutable reference to the value in the entry.
470 pub fn get_mut(&mut self) -> &mut Value
{
471 self.occupied
.get_mut()
474 /// Converts the entry into a mutable reference to its value.
476 pub fn into_mut(self) -> &'a
mut Value
{
477 self.occupied
.into_mut()
480 /// Sets the value of the entry with the `OccupiedEntry`'s key, and returns
481 /// the entry's old value.
483 pub fn insert(&mut self, value
: Value
) -> Value
{
484 self.occupied
.insert(value
)
487 /// Takes the value of the entry out of the map, and returns it.
489 pub fn remove(self) -> Value
{
490 self.occupied
.remove()
494 //////////////////////////////////////////////////////////////////////////////
496 impl<'a
> IntoIterator
for &'a Map
<String
, Value
> {
497 type Item
= (&'a String
, &'a Value
);
498 type IntoIter
= Iter
<'a
>;
500 fn into_iter(self) -> Self::IntoIter
{
502 iter
: self.map
.iter(),
507 /// An iterator over a toml::Map's entries.
508 pub struct Iter
<'a
> {
512 #[cfg(not(feature = "preserve_order"))]
513 type IterImpl
<'a
> = btree_map
::Iter
<'a
, String
, Value
>;
514 #[cfg(feature = "preserve_order")]
515 type IterImpl
<'a
> = indexmap
::map
::Iter
<'a
, String
, Value
>;
517 delegate_iterator
!((Iter
<'a
>) => (&'a String
, &'a Value
));
519 //////////////////////////////////////////////////////////////////////////////
521 impl<'a
> IntoIterator
for &'a
mut Map
<String
, Value
> {
522 type Item
= (&'a String
, &'a
mut Value
);
523 type IntoIter
= IterMut
<'a
>;
525 fn into_iter(self) -> Self::IntoIter
{
527 iter
: self.map
.iter_mut(),
532 /// A mutable iterator over a toml::Map's entries.
533 pub struct IterMut
<'a
> {
534 iter
: IterMutImpl
<'a
>,
537 #[cfg(not(feature = "preserve_order"))]
538 type IterMutImpl
<'a
> = btree_map
::IterMut
<'a
, String
, Value
>;
539 #[cfg(feature = "preserve_order")]
540 type IterMutImpl
<'a
> = indexmap
::map
::IterMut
<'a
, String
, Value
>;
542 delegate_iterator
!((IterMut
<'a
>) => (&'a String
, &'a
mut Value
));
544 //////////////////////////////////////////////////////////////////////////////
546 impl IntoIterator
for Map
<String
, Value
> {
547 type Item
= (String
, Value
);
548 type IntoIter
= IntoIter
;
550 fn into_iter(self) -> Self::IntoIter
{
552 iter
: self.map
.into_iter(),
557 /// An owning iterator over a toml::Map's entries.
558 pub struct IntoIter
{
562 #[cfg(not(feature = "preserve_order"))]
563 type IntoIterImpl
= btree_map
::IntoIter
<String
, Value
>;
564 #[cfg(feature = "preserve_order")]
565 type IntoIterImpl
= indexmap
::map
::IntoIter
<String
, Value
>;
567 delegate_iterator
!((IntoIter
) => (String
, Value
));
569 //////////////////////////////////////////////////////////////////////////////
571 /// An iterator over a toml::Map's keys.
572 pub struct Keys
<'a
> {
576 #[cfg(not(feature = "preserve_order"))]
577 type KeysImpl
<'a
> = btree_map
::Keys
<'a
, String
, Value
>;
578 #[cfg(feature = "preserve_order")]
579 type KeysImpl
<'a
> = indexmap
::map
::Keys
<'a
, String
, Value
>;
581 delegate_iterator
!((Keys
<'a
>) => &'a String
);
583 //////////////////////////////////////////////////////////////////////////////
585 /// An iterator over a toml::Map's values.
586 pub struct Values
<'a
> {
587 iter
: ValuesImpl
<'a
>,
590 #[cfg(not(feature = "preserve_order"))]
591 type ValuesImpl
<'a
> = btree_map
::Values
<'a
, String
, Value
>;
592 #[cfg(feature = "preserve_order")]
593 type ValuesImpl
<'a
> = indexmap
::map
::Values
<'a
, String
, Value
>;
595 delegate_iterator
!((Values
<'a
>) => &'a Value
);