Debian Codegraph @

third_party/rust/plist/src/dictionary.rs

raw
1 //! A map of String to plist::Value.
2 //!
3 //! The map is currently backed by an [`IndexMap`]. This may be changed in a future minor release.
4 //!
5 //! [`IndexMap`]: https://docs.rs/indexmap/latest/indexmap/map/struct.IndexMap.html
6
7 use indexmap::{map, IndexMap};
8 use std::{
9 fmt::{self, Debug},
10 iter::FromIterator,
11 ops,
12 };
13
14 use crate::Value;
15
16 /// Represents a plist dictionary type.
17 pub struct Dictionary {
18 map: IndexMap<String, Value>,
19 }
20
21 impl Dictionary {
22 /// Makes a new empty `Dictionary`.
23 #[inline]
24 pub fn new() -> Self {
25 Dictionary {
26 map: IndexMap::new(),
27 }
28 }
29
30 /// Clears the dictionary, removing all values.
31 #[inline]
32 pub fn clear(&mut self) {
33 self.map.clear()
34 }
35
36 /// Returns a reference to the value corresponding to the key.
37 #[inline]
38 pub fn get(&self, key: &str) -> Option<&Value> {
39 self.map.get(key)
40 }
41
42 /// Returns true if the dictionary contains a value for the specified key.
43 #[inline]
44 pub fn contains_key(&self, key: &str) -> bool {
45 self.map.contains_key(key)
46 }
47
48 /// Returns a mutable reference to the value corresponding to the key.
49 #[inline]
50 pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
51 self.map.get_mut(key)
52 }
53
54 /// Inserts a key-value pair into the dictionary.
55 ///
56 /// If the dictionary did not have this key present, `None` is returned.
57 ///
58 /// If the dictionary did have this key present, the value is updated, and the old value is
59 /// returned.
60 #[inline]
61 pub fn insert(&mut self, k: String, v: Value) -> Option<Value> {
62 self.map.insert(k, v)
63 }
64
65 /// Removes a key from the dictionary, returning the value at the key if the key was previously
66 /// in the dictionary.
67 #[inline]
68 pub fn remove(&mut self, key: &str) -> Option<Value> {
69 self.map.remove(key)
70 }
71
72 /// Scan through each key-value pair in the map and keep those where the
73 /// closure `keep` returns `true`.
74 #[inline]
75 pub fn retain<F>(&mut self, keep: F)
76 where
77 F: FnMut(&String, &mut Value) -> bool,
78 {
79 self.map.retain(keep)
80 }
81
82 /// Sort the dictionary keys.
83 ///
84 /// This uses the default ordering defined on [`str`].
85 ///
86 /// This function is useful if you are serializing to XML, and wish to
87 /// ensure a consistent key order.
88 #[inline]
89 pub fn sort_keys(&mut self) {
90 self.map.sort_keys()
91 }
92
93 /// Gets the given key's corresponding entry in the dictionary for in-place manipulation.
94 // Entry functionality is unstable until I can figure out how to use either Cow<str> or
95 // T: AsRef<str> + Into<String>
96 #[cfg(any(
97 test,
98 feature = "enable_unstable_features_that_may_break_with_minor_version_bumps"
99 ))]
100 pub fn entry<S>(&mut self, key: S) -> Entry
101 where
102 S: Into<String>,
103 {
104 match self.map.entry(key.into()) {
105 map::Entry::Vacant(vacant) => Entry::Vacant(VacantEntry { vacant }),
106 map::Entry::Occupied(occupied) => Entry::Occupied(OccupiedEntry { occupied }),
107 }
108 }
109
110 /// Returns the number of elements in the dictionary.
111 #[inline]
112 pub fn len(&self) -> usize {
113 self.map.len()
114 }
115
116 /// Returns true if the dictionary contains no elements.
117 #[inline]
118 pub fn is_empty(&self) -> bool {
119 self.map.is_empty()
120 }
121
122 /// Gets an iterator over the entries of the dictionary.
123 #[inline]
124 pub fn iter(&self) -> Iter {
125 Iter {
126 iter: self.map.iter(),
127 }
128 }
129
130 /// Gets a mutable iterator over the entries of the dictionary.
131 #[inline]
132 pub fn iter_mut(&mut self) -> IterMut {
133 IterMut {
134 iter: self.map.iter_mut(),
135 }
136 }
137
138 /// Gets an iterator over the keys of the dictionary.
139 #[inline]
140 pub fn keys(&self) -> Keys {
141 Keys {
142 iter: self.map.keys(),
143 }
144 }
145
146 /// Gets an iterator over the values of the dictionary.
147 #[inline]
148 pub fn values(&self) -> Values {
149 Values {
150 iter: self.map.values(),
151 }
152 }
153
154 /// Gets an iterator over mutable values of the dictionary.
155 #[inline]
156 pub fn values_mut(&mut self) -> ValuesMut {
157 ValuesMut {
158 iter: self.map.values_mut(),
159 }
160 }
161 }
162
163 impl Default for Dictionary {
164 #[inline]
165 fn default() -> Self {
166 Dictionary {
167 map: Default::default(),
168 }
169 }
170 }
171
172 impl Clone for Dictionary {
173 #[inline]
174 fn clone(&self) -> Self {
175 Dictionary {
176 map: self.map.clone(),
177 }
178 }
179 }
180
181 impl PartialEq for Dictionary {
182 #[inline]
183 fn eq(&self, other: &Self) -> bool {
184 self.map.eq(&other.map)
185 }
186 }
187
188 /// Access an element of this dictionary. Panics if the given key is not present in the dictionary.
189 ///
190 /// ```
191 /// # use plist::Value;
192 /// #
193 /// # let val = &Value::String("".to_owned());
194 /// # let _ =
195 /// match *val {
196 /// Value::Array(ref arr) => arr[0].as_string(),
197 /// Value::Dictionary(ref dict) => dict["type"].as_string(),
198 /// Value::String(ref s) => Some(s.as_str()),
199 /// _ => None,
200 /// }
201 /// # ;
202 /// ```
203 impl<'a> ops::Index<&'a str> for Dictionary {
204 type Output = Value;
205
206 fn index(&self, index: &str) -> &Value {
207 self.map.index(index)
208 }
209 }
210
211 /// Mutably access an element of this dictionary. Panics if the given key is not present in the
212 /// dictionary.
213 ///
214 /// ```
215 /// # let mut dict = plist::Dictionary::new();
216 /// # dict.insert("key".to_owned(), plist::Value::Boolean(false));
217 /// #
218 /// dict["key"] = "value".into();
219 /// ```
220 impl<'a> ops::IndexMut<&'a str> for Dictionary {
221 fn index_mut(&mut self, index: &str) -> &mut Value {
222 self.map.get_mut(index).expect("no entry found for key")
223 }
224 }
225
226 impl Debug for Dictionary {
227 #[inline]
228 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
229 self.map.fmt(formatter)
230 }
231 }
232
233 impl<K: Into<String>, V: Into<Value>> FromIterator<(K, V)> for Dictionary {
234 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
235 Dictionary {
236 map: iter
237 .into_iter()
238 .map(|(k, v)| (k.into(), v.into()))
239 .collect(),
240 }
241 }
242 }
243
244 impl Extend<(String, Value)> for Dictionary {
245 fn extend<T>(&mut self, iter: T)
246 where
247 T: IntoIterator<Item = (String, Value)>,
248 {
249 self.map.extend(iter);
250 }
251 }
252
253 macro_rules! delegate_iterator {
254 (($name:ident $($generics:tt)*) => $item:ty) => {
255 impl $($generics)* Iterator for $name $($generics)* {
256 type Item = $item;
257 #[inline]
258 fn next(&mut self) -> Option<Self::Item> {
259 self.iter.next()
260 }
261 #[inline]
262 fn size_hint(&self) -> (usize, Option<usize>) {
263 self.iter.size_hint()
264 }
265 }
266
267 /*impl $($generics)* DoubleEndedIterator for $name $($generics)* {
268 #[inline]
269 fn next_back(&mut self) -> Option<Self::Item> {
270 self.iter.next_back()
271 }
272 }*/
273
274 impl $($generics)* ExactSizeIterator for $name $($generics)* {
275 #[inline]
276 fn len(&self) -> usize {
277 self.iter.len()
278 }
279 }
280 }
281 }
282
283 //////////////////////////////////////////////////////////////////////////////
284
285 /// A view into a single entry in a dictionary, which may either be vacant or occupied.
286 /// This enum is constructed from the [`entry`] method on [`Dictionary`].
287 ///
288 /// [`entry`]: struct.Dictionary.html#method.entry
289 /// [`Dictionary`]: struct.Dictionary.html
290 #[cfg(any(
291 test,
292 feature = "enable_unstable_features_that_may_break_with_minor_version_bumps"
293 ))]
294 pub enum Entry<'a> {
295 /// A vacant Entry.
296 Vacant(VacantEntry<'a>),
297 /// An occupied Entry.
298 Occupied(OccupiedEntry<'a>),
299 }
300
301 /// A vacant Entry. It is part of the [`Entry`] enum.
302 ///
303 /// [`Entry`]: enum.Entry.html
304 #[cfg(any(
305 test,
306 feature = "enable_unstable_features_that_may_break_with_minor_version_bumps"
307 ))]
308 pub struct VacantEntry<'a> {
309 vacant: map::VacantEntry<'a, String, Value>,
310 }
311
312 /// An occupied Entry. It is part of the [`Entry`] enum.
313 ///
314 /// [`Entry`]: enum.Entry.html
315 #[cfg(any(
316 test,
317 feature = "enable_unstable_features_that_may_break_with_minor_version_bumps"
318 ))]
319 pub struct OccupiedEntry<'a> {
320 occupied: map::OccupiedEntry<'a, String, Value>,
321 }
322
323 #[cfg(any(
324 test,
325 feature = "enable_unstable_features_that_may_break_with_minor_version_bumps"
326 ))]
327 impl<'a> Entry<'a> {
328 /// Returns a reference to this entry's key.
329 ///
330 /// # Examples
331 ///
332 /// ```
333 /// let mut dict = plist::Dictionary::new();
334 /// assert_eq!(dict.entry("serde").key(), &"serde");
335 /// ```
336 pub fn key(&self) -> &String {
337 match *self {
338 Entry::Vacant(ref e) => e.key(),
339 Entry::Occupied(ref e) => e.key(),
340 }
341 }
342
343 /// Ensures a value is in the entry by inserting the default if empty, and returns a mutable
344 /// reference to the value in the entry.
345 ///
346 /// # Examples
347 ///
348 /// ```
349 /// let mut dict = plist::Dictionary::new();
350 /// dict.entry("serde").or_insert(12.into());
351 ///
352 /// assert_eq!(dict["serde"], 12.into());
353 /// ```
354 pub fn or_insert(self, default: Value) -> &'a mut Value {
355 match self {
356 Entry::Vacant(entry) => entry.insert(default),
357 Entry::Occupied(entry) => entry.into_mut(),
358 }
359 }
360
361 /// Ensures a value is in the entry by inserting the result of the default function if empty,
362 /// and returns a mutable reference to the value in the entry.
363 ///
364 /// # Examples
365 ///
366 /// ```
367 /// let mut dict = plist::Dictionary::new();
368 /// dict.entry("serde").or_insert_with(|| "hoho".into());
369 ///
370 /// assert_eq!(dict["serde"], "hoho".into());
371 /// ```
372 pub fn or_insert_with<F>(self, default: F) -> &'a mut Value
373 where
374 F: FnOnce() -> Value,
375 {
376 match self {
377 Entry::Vacant(entry) => entry.insert(default()),
378 Entry::Occupied(entry) => entry.into_mut(),
379 }
380 }
381 }
382
383 #[cfg(any(
384 test,
385 feature = "enable_unstable_features_that_may_break_with_minor_version_bumps"
386 ))]
387 impl<'a> VacantEntry<'a> {
388 /// Gets a reference to the key that would be used when inserting a value through the
389 /// VacantEntry.
390 ///
391 /// # Examples
392 ///
393 /// ```
394 /// use plist::dictionary::Entry;
395 ///
396 /// let mut dict = plist::Dictionary::new();
397 ///
398 /// match dict.entry("serde") {
399 /// Entry::Vacant(vacant) => assert_eq!(vacant.key(), &"serde"),
400 /// Entry::Occupied(_) => unimplemented!(),
401 /// }
402 /// ```
403 #[inline]
404 pub fn key(&self) -> &String {
405 self.vacant.key()
406 }
407
408 /// Sets the value of the entry with the VacantEntry's key, and returns a mutable reference
409 /// to it.
410 ///
411 /// # Examples
412 ///
413 /// ```
414 /// use plist::dictionary::Entry;
415 ///
416 /// let mut dict = plist::Dictionary::new();
417 ///
418 /// match dict.entry("serde") {
419 /// Entry::Vacant(vacant) => vacant.insert("hoho".into()),
420 /// Entry::Occupied(_) => unimplemented!(),
421 /// };
422 /// ```
423 #[inline]
424 pub fn insert(self, value: Value) -> &'a mut Value {
425 self.vacant.insert(value)
426 }
427 }
428
429 #[cfg(any(
430 test,
431 feature = "enable_unstable_features_that_may_break_with_minor_version_bumps"
432 ))]
433 impl<'a> OccupiedEntry<'a> {
434 /// Gets a reference to the key in the entry.
435 ///
436 /// # Examples
437 ///
438 /// ```
439 /// use plist::dictionary::Entry;
440 ///
441 /// let mut dict = plist::Dictionary::new();
442 /// dict.insert("serde".to_owned(), 12.into());
443 ///
444 /// match dict.entry("serde") {
445 /// Entry::Occupied(occupied) => assert_eq!(occupied.key(), &"serde"),
446 /// Entry::Vacant(_) => unimplemented!(),
447 /// }
448 /// ```
449 #[inline]
450 pub fn key(&self) -> &String {
451 self.occupied.key()
452 }
453
454 /// Gets a reference to the value in the entry.
455 ///
456 /// # Examples
457 ///
458 /// ```
459 /// use plist::Value;
460 /// use plist::dictionary::Entry;
461 ///
462 /// let mut dict = plist::Dictionary::new();
463 /// dict.insert("serde".to_owned(), 12.into());
464 ///
465 /// match dict.entry("serde") {
466 /// Entry::Occupied(occupied) => assert_eq!(occupied.get(), &Value::from(12)),
467 /// Entry::Vacant(_) => unimplemented!(),
468 /// }
469 /// ```
470 #[inline]
471 pub fn get(&self) -> &Value {
472 self.occupied.get()
473 }
474
475 /// Gets a mutable reference to the value in the entry.
476 ///
477 /// # Examples
478 ///
479 /// ```
480 /// use plist::Value;
481 /// use plist::dictionary::Entry;
482 ///
483 /// let mut dict = plist::Dictionary::new();
484 /// dict.insert("serde".to_owned(), Value::Array(vec![1.into(), 2.into(), 3.into()]));
485 ///
486 /// match dict.entry("serde") {
487 /// Entry::Occupied(mut occupied) => {
488 /// occupied.get_mut().as_array_mut().unwrap().push(4.into());
489 /// }
490 /// Entry::Vacant(_) => unimplemented!(),
491 /// }
492 ///
493 /// assert_eq!(dict["serde"].as_array().unwrap().len(), 4);
494 /// ```
495 #[inline]
496 pub fn get_mut(&mut self) -> &mut Value {
497 self.occupied.get_mut()
498 }
499
500 /// Converts the entry into a mutable reference to its value.
501 ///
502 /// # Examples
503 ///
504 /// ```
505 /// use plist::Value;
506 /// use plist::dictionary::Entry;
507 ///
508 /// let mut dict = plist::Dictionary::new();
509 /// dict.insert("serde".to_owned(), Value::Array(vec![1.into(), 2.into(), 3.into()]));
510 ///
511 /// match dict.entry("serde") {
512 /// Entry::Occupied(mut occupied) => {
513 /// occupied.into_mut().as_array_mut().unwrap().push(4.into());
514 /// }
515 /// Entry::Vacant(_) => unimplemented!(),
516 /// }
517 ///
518 /// assert_eq!(dict["serde"].as_array().unwrap().len(), 4);
519 /// ```
520 #[inline]
521 pub fn into_mut(self) -> &'a mut Value {
522 self.occupied.into_mut()
523 }
524
525 /// Sets the value of the entry with the `OccupiedEntry`'s key, and returns
526 /// the entry's old value.
527 ///
528 /// # Examples
529 ///
530 /// ```
531 /// use plist::Value;
532 /// use plist::dictionary::Entry;
533 ///
534 /// let mut dict = plist::Dictionary::new();
535 /// dict.insert("serde".to_owned(), 12.into());
536 ///
537 /// match dict.entry("serde") {
538 /// Entry::Occupied(mut occupied) => {
539 /// assert_eq!(occupied.insert(13.into()), 12.into());
540 /// assert_eq!(occupied.get(), &Value::from(13));
541 /// }
542 /// Entry::Vacant(_) => unimplemented!(),
543 /// }
544 /// ```
545 #[inline]
546 pub fn insert(&mut self, value: Value) -> Value {
547 self.occupied.insert(value)
548 }
549
550 /// Takes the value of the entry out of the dictionary, and returns it.
551 ///
552 /// # Examples
553 ///
554 /// ```
555 /// use plist::dictionary::Entry;
556 ///
557 /// let mut dict = plist::Dictionary::new();
558 /// dict.insert("serde".to_owned(), 12.into());
559 ///
560 /// match dict.entry("serde") {
561 /// Entry::Occupied(occupied) => assert_eq!(occupied.remove(), 12.into()),
562 /// Entry::Vacant(_) => unimplemented!(),
563 /// }
564 /// ```
565 #[inline]
566 pub fn remove(self) -> Value {
567 self.occupied.remove()
568 }
569 }
570
571 //////////////////////////////////////////////////////////////////////////////
572
573 impl<'a> IntoIterator for &'a Dictionary {
574 type Item = (&'a String, &'a Value);
575 type IntoIter = Iter<'a>;
576 #[inline]
577 fn into_iter(self) -> Self::IntoIter {
578 Iter {
579 iter: self.map.iter(),
580 }
581 }
582 }
583
584 /// An iterator over a plist::Dictionary's entries.
585 pub struct Iter<'a> {
586 iter: IterImpl<'a>,
587 }
588
589 type IterImpl<'a> = map::Iter<'a, String, Value>;
590
591 delegate_iterator!((Iter<'a>) => (&'a String, &'a Value));
592
593 //////////////////////////////////////////////////////////////////////////////
594
595 impl<'a> IntoIterator for &'a mut Dictionary {
596 type Item = (&'a String, &'a mut Value);
597 type IntoIter = IterMut<'a>;
598 #[inline]
599 fn into_iter(self) -> Self::IntoIter {
600 IterMut {
601 iter: self.map.iter_mut(),
602 }
603 }
604 }
605
606 /// A mutable iterator over a plist::Dictionary's entries.
607 pub struct IterMut<'a> {
608 iter: map::IterMut<'a, String, Value>,
609 }
610
611 delegate_iterator!((IterMut<'a>) => (&'a String, &'a mut Value));
612
613 //////////////////////////////////////////////////////////////////////////////
614
615 impl IntoIterator for Dictionary {
616 type Item = (String, Value);
617 type IntoIter = IntoIter;
618 #[inline]
619 fn into_iter(self) -> Self::IntoIter {
620 IntoIter {
621 iter: self.map.into_iter(),
622 }
623 }
624 }
625
626 /// An owning iterator over a plist::Dictionary's entries.
627 pub struct IntoIter {
628 iter: map::IntoIter<String, Value>,
629 }
630
631 delegate_iterator!((IntoIter) => (String, Value));
632
633 //////////////////////////////////////////////////////////////////////////////
634
635 /// An iterator over a plist::Dictionary's keys.
636 pub struct Keys<'a> {
637 iter: map::Keys<'a, String, Value>,
638 }
639
640 delegate_iterator!((Keys<'a>) => &'a String);
641
642 //////////////////////////////////////////////////////////////////////////////
643
644 /// An iterator over a plist::Dictionary's values.
645 pub struct Values<'a> {
646 iter: map::Values<'a, String, Value>,
647 }
648
649 delegate_iterator!((Values<'a>) => &'a Value);
650
651 //////////////////////////////////////////////////////////////////////////////
652
653 /// A mutable iterator over a plist::Dictionary's values.
654 pub struct ValuesMut<'a> {
655 iter: map::ValuesMut<'a, String, Value>,
656 }
657
658 delegate_iterator!((ValuesMut<'a>) => &'a mut Value);
659
660 #[cfg(feature = "serde")]
661 pub mod serde_impls {
662 use serde::{de, ser};
663 use std::fmt;
664
665 use crate::Dictionary;
666
667 impl ser::Serialize for Dictionary {
668 #[inline]
669 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
670 where
671 S: ser::Serializer,
672 {
673 use serde::ser::SerializeMap;
674 let mut map = serializer.serialize_map(Some(self.len()))?;
675 for (k, v) in self {
676 map.serialize_key(k)?;
677 map.serialize_value(v)?;
678 }
679 map.end()
680 }
681 }
682
683 impl<'de> de::Deserialize<'de> for Dictionary {
684 #[inline]
685 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
686 where
687 D: de::Deserializer<'de>,
688 {
689 struct Visitor;
690
691 impl<'de> de::Visitor<'de> for Visitor {
692 type Value = Dictionary;
693
694 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
695 formatter.write_str("a map")
696 }
697
698 #[inline]
699 fn visit_unit<E>(self) -> Result<Self::Value, E>
700 where
701 E: de::Error,
702 {
703 Ok(Dictionary::new())
704 }
705
706 #[inline]
707 fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
708 where
709 V: de::MapAccess<'de>,
710 {
711 let mut values = Dictionary::new();
712
713 while let Some((key, value)) = visitor.next_entry()? {
714 values.insert(key, value);
715 }
716
717 Ok(values)
718 }
719 }
720
721 deserializer.deserialize_map(Visitor)
722 }
723 }
724 }
725
726 #[cfg(test)]
727 mod tests {
728 use super::Dictionary;
729 use std::array::IntoIter;
730
731 #[test]
732 fn from_hash_map_to_dict() {
733 let dict: Dictionary = IntoIter::new([
734 ("Doge", "Shiba Inu"),
735 ("Cheems", "Shiba Inu"),
736 ("Walter", "Bull Terrier"),
737 ("Perro", "Golden Retriever"),
738 ])
739 .collect();
740 assert_eq!(
741 dict.get("Doge").and_then(|v| v.as_string()),
742 Some("Shiba Inu")
743 );
744 assert_eq!(
745 dict.get("Cheems").and_then(|v| v.as_string()),
746 Some("Shiba Inu")
747 );
748 assert_eq!(
749 dict.get("Walter").and_then(|v| v.as_string()),
750 Some("Bull Terrier")
751 );
752 assert_eq!(
753 dict.get("Perro").and_then(|v| v.as_string()),
754 Some("Golden Retriever")
755 );
756 }
757 }