]> git.proxmox.com Git - cargo.git/blob - vendor/toml_edit/src/easy/map.rs
New upstream version 0.63.1
[cargo.git] / vendor / toml_edit / src / easy / map.rs
1 // Copyright 2017 Serde Developers
2 //
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.
8
9 //! A map of String to toml::Value.
10
11 use std::borrow::Borrow;
12 use std::fmt::{self, Debug};
13 use std::hash::Hash;
14 use std::iter::FromIterator;
15 use std::ops;
16
17 use indexmap::map::IndexMap;
18 use serde::{de, ser};
19
20 use crate::easy::value::Value;
21
22 /// Represents a TOML key/value type.
23 pub struct Map<K, V> {
24 map: MapImpl<K, V>,
25 }
26
27 type MapImpl<K, V> = IndexMap<K, V>;
28
29 impl Map<String, Value> {
30 /// Makes a new empty Map.
31 #[inline]
32 pub fn new() -> Self {
33 Map {
34 map: MapImpl::new(),
35 }
36 }
37
38 /// Makes a new empty Map with the given initial capacity.
39 #[inline]
40 pub fn with_capacity(capacity: usize) -> Self {
41 Map {
42 map: IndexMap::with_capacity(capacity),
43 }
44 }
45
46 /// Clears the map, removing all values.
47 #[inline]
48 pub fn clear(&mut self) {
49 self.map.clear()
50 }
51
52 /// Returns a reference to the value corresponding to the key.
53 ///
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.
56 #[inline]
57 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&Value>
58 where
59 String: Borrow<Q>,
60 Q: Ord + Eq + Hash,
61 {
62 self.map.get(key)
63 }
64
65 /// Returns true if the map contains a value for the specified 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 contains_key<Q: ?Sized>(&self, key: &Q) -> bool
71 where
72 String: Borrow<Q>,
73 Q: Ord + Eq + Hash,
74 {
75 self.map.contains_key(key)
76 }
77
78 /// Returns a mutable reference to the value corresponding to the 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 get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut Value>
84 where
85 String: Borrow<Q>,
86 Q: Ord + Eq + Hash,
87 {
88 self.map.get_mut(key)
89 }
90
91 /// Inserts a key-value pair into the map.
92 ///
93 /// If the map did not have this key present, `None` is returned.
94 ///
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.
98 #[inline]
99 pub fn insert(&mut self, k: String, v: Value) -> Option<Value> {
100 self.map.insert(k, v)
101 }
102
103 /// Removes a key from the map, returning the value at the key if the key
104 /// was previously in the map.
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 remove<Q: ?Sized>(&mut self, key: &Q) -> Option<Value>
110 where
111 String: Borrow<Q>,
112 Q: Ord + Eq + Hash,
113 {
114 self.map.remove(key)
115 }
116
117 /// Gets the given key's corresponding entry in the map for in-place
118 /// manipulation.
119 pub fn entry<S>(&mut self, key: S) -> Entry<'_>
120 where
121 S: Into<String>,
122 {
123 use indexmap::map::Entry as EntryImpl;
124
125 match self.map.entry(key.into()) {
126 EntryImpl::Vacant(vacant) => Entry::Vacant(VacantEntry { vacant }),
127 EntryImpl::Occupied(occupied) => Entry::Occupied(OccupiedEntry { occupied }),
128 }
129 }
130
131 /// Returns the number of elements in the map.
132 #[inline]
133 pub fn len(&self) -> usize {
134 self.map.len()
135 }
136
137 /// Returns true if the map contains no elements.
138 #[inline]
139 pub fn is_empty(&self) -> bool {
140 self.map.is_empty()
141 }
142
143 /// Gets an iterator over the entries of the map.
144 #[inline]
145 pub fn iter(&self) -> Iter<'_> {
146 Iter {
147 iter: self.map.iter(),
148 }
149 }
150
151 /// Gets a mutable iterator over the entries of the map.
152 #[inline]
153 pub fn iter_mut(&mut self) -> IterMut<'_> {
154 IterMut {
155 iter: self.map.iter_mut(),
156 }
157 }
158
159 /// Gets an iterator over the keys of the map.
160 #[inline]
161 pub fn keys(&self) -> Keys<'_> {
162 Keys {
163 iter: self.map.keys(),
164 }
165 }
166
167 /// Gets an iterator over the values of the map.
168 #[inline]
169 pub fn values(&self) -> Values<'_> {
170 Values {
171 iter: self.map.values(),
172 }
173 }
174 }
175
176 impl Default for Map<String, Value> {
177 #[inline]
178 fn default() -> Self {
179 Map {
180 map: MapImpl::new(),
181 }
182 }
183 }
184
185 impl Clone for Map<String, Value> {
186 #[inline]
187 fn clone(&self) -> Self {
188 Map {
189 map: self.map.clone(),
190 }
191 }
192 }
193
194 impl PartialEq for Map<String, Value> {
195 #[inline]
196 fn eq(&self, other: &Self) -> bool {
197 self.map.eq(&other.map)
198 }
199 }
200
201 /// Access an element of this map. Panics if the given key is not present in the
202 /// map.
203 impl<'a, Q: ?Sized> ops::Index<&'a Q> for Map<String, Value>
204 where
205 String: Borrow<Q>,
206 Q: Ord + Eq + Hash,
207 {
208 type Output = Value;
209
210 fn index(&self, index: &Q) -> &Value {
211 self.map.index(index)
212 }
213 }
214
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>
218 where
219 String: Borrow<Q>,
220 Q: Ord + Eq + Hash,
221 {
222 fn index_mut(&mut self, index: &Q) -> &mut Value {
223 self.map.get_mut(index).expect("no entry found for key")
224 }
225 }
226
227 impl Debug for Map<String, Value> {
228 #[inline]
229 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
230 self.map.fmt(formatter)
231 }
232 }
233
234 impl ser::Serialize for Map<String, Value> {
235 #[inline]
236 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
237 where
238 S: ser::Serializer,
239 {
240 use serde::ser::SerializeMap;
241 let mut map = serializer.serialize_map(Some(self.len()))?;
242 for (k, v) in self {
243 map.serialize_key(k)?;
244 map.serialize_value(v)?;
245 }
246 map.end()
247 }
248 }
249
250 impl<'de> de::Deserialize<'de> for Map<String, Value> {
251 #[inline]
252 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
253 where
254 D: de::Deserializer<'de>,
255 {
256 struct Visitor;
257
258 impl<'de> de::Visitor<'de> for Visitor {
259 type Value = Map<String, Value>;
260
261 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
262 formatter.write_str("a map")
263 }
264
265 #[inline]
266 fn visit_unit<E>(self) -> Result<Self::Value, E>
267 where
268 E: de::Error,
269 {
270 Ok(Map::new())
271 }
272
273 #[inline]
274 fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
275 where
276 V: de::MapAccess<'de>,
277 {
278 let mut values = Map::new();
279
280 while let Some((key, value)) = visitor.next_entry()? {
281 values.insert(key, value);
282 }
283
284 Ok(values)
285 }
286 }
287
288 deserializer.deserialize_map(Visitor)
289 }
290 }
291
292 impl FromIterator<(String, Value)> for Map<String, Value> {
293 fn from_iter<T>(iter: T) -> Self
294 where
295 T: IntoIterator<Item = (String, Value)>,
296 {
297 Map {
298 map: FromIterator::from_iter(iter),
299 }
300 }
301 }
302
303 impl Extend<(String, Value)> for Map<String, Value> {
304 fn extend<T>(&mut self, iter: T)
305 where
306 T: IntoIterator<Item = (String, Value)>,
307 {
308 self.map.extend(iter);
309 }
310 }
311
312 macro_rules! delegate_iterator {
313 (($name:ident $($generics:tt)*) => $item:ty) => {
314 impl $($generics)* Iterator for $name $($generics)* {
315 type Item = $item;
316 #[inline]
317 fn next(&mut self) -> Option<Self::Item> {
318 self.iter.next()
319 }
320 #[inline]
321 fn size_hint(&self) -> (usize, Option<usize>) {
322 self.iter.size_hint()
323 }
324 }
325
326 impl $($generics)* DoubleEndedIterator for $name $($generics)* {
327 #[inline]
328 fn next_back(&mut self) -> Option<Self::Item> {
329 self.iter.next_back()
330 }
331 }
332
333 impl $($generics)* ExactSizeIterator for $name $($generics)* {
334 #[inline]
335 fn len(&self) -> usize {
336 self.iter.len()
337 }
338 }
339 }
340 }
341
342 //////////////////////////////////////////////////////////////////////////////
343
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`].
346 ///
347 /// [`entry`]: struct.Map.html#method.entry
348 /// [`Map`]: struct.Map.html
349 pub enum Entry<'a> {
350 /// A vacant Entry.
351 Vacant(VacantEntry<'a>),
352 /// An occupied Entry.
353 Occupied(OccupiedEntry<'a>),
354 }
355
356 /// A vacant Entry. It is part of the [`Entry`] enum.
357 ///
358 /// [`Entry`]: enum.Entry.html
359 pub struct VacantEntry<'a> {
360 vacant: VacantEntryImpl<'a>,
361 }
362
363 /// An occupied Entry. It is part of the [`Entry`] enum.
364 ///
365 /// [`Entry`]: enum.Entry.html
366 pub struct OccupiedEntry<'a> {
367 occupied: OccupiedEntryImpl<'a>,
368 }
369
370 type VacantEntryImpl<'a> = indexmap::map::VacantEntry<'a, String, Value>;
371
372 type OccupiedEntryImpl<'a> = indexmap::map::OccupiedEntry<'a, String, Value>;
373
374 impl<'a> Entry<'a> {
375 /// Returns a reference to this entry's key.
376 pub fn key(&self) -> &String {
377 match *self {
378 Entry::Vacant(ref e) => e.key(),
379 Entry::Occupied(ref e) => e.key(),
380 }
381 }
382
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 {
386 match self {
387 Entry::Vacant(entry) => entry.insert(default),
388 Entry::Occupied(entry) => entry.into_mut(),
389 }
390 }
391
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
394 /// entry.
395 pub fn or_insert_with<F>(self, default: F) -> &'a mut Value
396 where
397 F: FnOnce() -> Value,
398 {
399 match self {
400 Entry::Vacant(entry) => entry.insert(default()),
401 Entry::Occupied(entry) => entry.into_mut(),
402 }
403 }
404 }
405
406 impl<'a> VacantEntry<'a> {
407 /// Gets a reference to the key that would be used when inserting a value
408 /// through the VacantEntry.
409 #[inline]
410 pub fn key(&self) -> &String {
411 self.vacant.key()
412 }
413
414 /// Sets the value of the entry with the VacantEntry's key, and returns a
415 /// mutable reference to it.
416 #[inline]
417 pub fn insert(self, value: Value) -> &'a mut Value {
418 self.vacant.insert(value)
419 }
420 }
421
422 impl<'a> OccupiedEntry<'a> {
423 /// Gets a reference to the key in the entry.
424 #[inline]
425 pub fn key(&self) -> &String {
426 self.occupied.key()
427 }
428
429 /// Gets a reference to the value in the entry.
430 #[inline]
431 pub fn get(&self) -> &Value {
432 self.occupied.get()
433 }
434
435 /// Gets a mutable reference to the value in the entry.
436 #[inline]
437 pub fn get_mut(&mut self) -> &mut Value {
438 self.occupied.get_mut()
439 }
440
441 /// Converts the entry into a mutable reference to its value.
442 #[inline]
443 pub fn into_mut(self) -> &'a mut Value {
444 self.occupied.into_mut()
445 }
446
447 /// Sets the value of the entry with the `OccupiedEntry`'s key, and returns
448 /// the entry's old value.
449 #[inline]
450 pub fn insert(&mut self, value: Value) -> Value {
451 self.occupied.insert(value)
452 }
453
454 /// Takes the value of the entry out of the map, and returns it.
455 #[inline]
456 pub fn remove(self) -> Value {
457 self.occupied.remove()
458 }
459 }
460
461 //////////////////////////////////////////////////////////////////////////////
462
463 impl<'a> IntoIterator for &'a Map<String, Value> {
464 type Item = (&'a String, &'a Value);
465 type IntoIter = Iter<'a>;
466 #[inline]
467 fn into_iter(self) -> Self::IntoIter {
468 Iter {
469 iter: self.map.iter(),
470 }
471 }
472 }
473
474 /// An iterator over a toml::Map's entries.
475 pub struct Iter<'a> {
476 iter: IterImpl<'a>,
477 }
478
479 type IterImpl<'a> = indexmap::map::Iter<'a, String, Value>;
480
481 delegate_iterator!((Iter<'a>) => (&'a String, &'a Value));
482
483 //////////////////////////////////////////////////////////////////////////////
484
485 impl<'a> IntoIterator for &'a mut Map<String, Value> {
486 type Item = (&'a String, &'a mut Value);
487 type IntoIter = IterMut<'a>;
488 #[inline]
489 fn into_iter(self) -> Self::IntoIter {
490 IterMut {
491 iter: self.map.iter_mut(),
492 }
493 }
494 }
495
496 /// A mutable iterator over a toml::Map's entries.
497 pub struct IterMut<'a> {
498 iter: IterMutImpl<'a>,
499 }
500
501 type IterMutImpl<'a> = indexmap::map::IterMut<'a, String, Value>;
502
503 delegate_iterator!((IterMut<'a>) => (&'a String, &'a mut Value));
504
505 //////////////////////////////////////////////////////////////////////////////
506
507 impl IntoIterator for Map<String, Value> {
508 type Item = (String, Value);
509 type IntoIter = IntoIter;
510 #[inline]
511 fn into_iter(self) -> Self::IntoIter {
512 IntoIter {
513 iter: self.map.into_iter(),
514 }
515 }
516 }
517
518 /// An owning iterator over a toml::Map's entries.
519 pub struct IntoIter {
520 iter: IntoIterImpl,
521 }
522
523 type IntoIterImpl = indexmap::map::IntoIter<String, Value>;
524
525 delegate_iterator!((IntoIter) => (String, Value));
526
527 //////////////////////////////////////////////////////////////////////////////
528
529 /// An iterator over a toml::Map's keys.
530 pub struct Keys<'a> {
531 iter: KeysImpl<'a>,
532 }
533
534 type KeysImpl<'a> = indexmap::map::Keys<'a, String, Value>;
535
536 delegate_iterator!((Keys<'a>) => &'a String);
537
538 //////////////////////////////////////////////////////////////////////////////
539
540 /// An iterator over a toml::Map's values.
541 pub struct Values<'a> {
542 iter: ValuesImpl<'a>,
543 }
544
545 type ValuesImpl<'a> = indexmap::map::Values<'a, String, Value>;
546
547 delegate_iterator!((Values<'a>) => &'a Value);