Debian Codegraph @

third_party/rust/plist/src/value.rs

raw
1 use std::{
2 fs::File,
3 io::{BufReader, BufWriter, Read, Seek, Write},
4 path::Path,
5 };
6
7 use crate::{
8 error::{self, Error, ErrorKind, EventKind},
9 stream::{
10 BinaryWriter, Event, Events, OwnedEvent, Reader, Writer, XmlReader, XmlWriteOptions,
11 XmlWriter,
12 },
13 u64_to_usize, Date, Dictionary, Integer, Uid,
14 };
15
16 /// Represents any plist value.
17 #[derive(Clone, Debug, PartialEq)]
18 #[non_exhaustive]
19 pub enum Value {
20 Array(Vec<Value>),
21 Dictionary(Dictionary),
22 Boolean(bool),
23 Data(Vec<u8>),
24 Date(Date),
25 Real(f64),
26 Integer(Integer),
27 String(String),
28 Uid(Uid),
29 }
30
31 impl Value {
32 /// Reads a `Value` from a plist file of any encoding.
33 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Value, Error> {
34 let file = File::open(path).map_err(error::from_io_without_position)?;
35 Value::from_reader(BufReader::new(file))
36 }
37
38 /// Reads a `Value` from a seekable byte stream containing a plist of any encoding.
39 pub fn from_reader<R: Read + Seek>(reader: R) -> Result<Value, Error> {
40 let reader = Reader::new(reader);
41 Value::from_events(reader)
42 }
43
44 /// Reads a `Value` from a seekable byte stream containing an XML encoded plist.
45 pub fn from_reader_xml<R: Read>(reader: R) -> Result<Value, Error> {
46 let reader = XmlReader::new(reader);
47 Value::from_events(reader)
48 }
49
50 /// Serializes a `Value` to a file as a binary encoded plist.
51 pub fn to_file_binary<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> {
52 let mut file = File::create(path).map_err(error::from_io_without_position)?;
53 self.to_writer_binary(BufWriter::new(&mut file))?;
54 file.sync_all().map_err(error::from_io_without_position)?;
55 Ok(())
56 }
57
58 /// Serializes a `Value` to a file as an XML encoded plist.
59 pub fn to_file_xml<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> {
60 let mut file = File::create(path).map_err(error::from_io_without_position)?;
61 self.to_writer_xml(BufWriter::new(&mut file))?;
62 file.sync_all().map_err(error::from_io_without_position)?;
63 Ok(())
64 }
65
66 /// Serializes a `Value` to a byte stream as a binary encoded plist.
67 pub fn to_writer_binary<W: Write>(&self, writer: W) -> Result<(), Error> {
68 let mut writer = BinaryWriter::new(writer);
69 self.to_writer_inner(&mut writer)
70 }
71
72 /// Serializes a `Value` to a byte stream as an XML encoded plist.
73 pub fn to_writer_xml<W: Write>(&self, writer: W) -> Result<(), Error> {
74 self.to_writer_xml_with_options(writer, &XmlWriteOptions::default())
75 }
76
77 /// Serializes a `Value` to a stream, using custom [`XmlWriteOptions`].
78 ///
79 /// If you need to serialize to a file, you must acquire an appropriate
80 /// `Write` handle yourself.
81 ///
82 /// # Examples
83 ///
84 /// ```no_run
85 /// use std::io::{BufWriter, Write};
86 /// use std::fs::File;
87 /// use plist::{Dictionary, Value, XmlWriteOptions};
88 ///
89 /// let value: Value = Dictionary::new().into();
90 /// // .. add some keys & values
91 /// let mut file = File::create("com.example.myPlist.plist").unwrap();
92 /// let options = XmlWriteOptions::default().indent_string(" ");
93 /// value.to_writer_xml_with_options(BufWriter::new(&mut file), &options).unwrap();
94 /// file.sync_all().unwrap();
95 /// ```
96 pub fn to_writer_xml_with_options<W: Write>(
97 &self,
98 writer: W,
99 options: &XmlWriteOptions,
100 ) -> Result<(), Error> {
101 let mut writer = XmlWriter::new_with_options(writer, options);
102 self.to_writer_inner(&mut writer)
103 }
104
105 fn to_writer_inner(&self, writer: &mut dyn Writer) -> Result<(), Error> {
106 let events = self.events();
107 for event in events {
108 writer.write(&event)?;
109 }
110 Ok(())
111 }
112
113 /// Builds a single `Value` from an `Event` iterator.
114 /// On success any excess `Event`s will remain in the iterator.
115 #[cfg(feature = "enable_unstable_features_that_may_break_with_minor_version_bumps")]
116 pub fn from_events<T>(events: T) -> Result<Value, Error>
117 where
118 T: IntoIterator<Item = Result<OwnedEvent, Error>>,
119 {
120 Builder::new(events.into_iter()).build()
121 }
122
123 /// Builds a single `Value` from an `Event` iterator.
124 /// On success any excess `Event`s will remain in the iterator.
125 #[cfg(not(feature = "enable_unstable_features_that_may_break_with_minor_version_bumps"))]
126 pub(crate) fn from_events<T>(events: T) -> Result<Value, Error>
127 where
128 T: IntoIterator<Item = Result<OwnedEvent, Error>>,
129 {
130 Builder::new(events.into_iter()).build()
131 }
132
133 /// Converts a `Value` into an `Event` iterator.
134 #[cfg(feature = "enable_unstable_features_that_may_break_with_minor_version_bumps")]
135 #[doc(hidden)]
136 #[deprecated(since = "1.2.0", note = "use Value::events instead")]
137 pub fn into_events(&self) -> Events {
138 self.events()
139 }
140
141 /// Creates an `Event` iterator for this `Value`.
142 #[cfg(not(feature = "enable_unstable_features_that_may_break_with_minor_version_bumps"))]
143 pub(crate) fn events(&self) -> Events {
144 Events::new(self)
145 }
146
147 /// Creates an `Event` iterator for this `Value`.
148 #[cfg(feature = "enable_unstable_features_that_may_break_with_minor_version_bumps")]
149 pub fn events(&self) -> Events {
150 Events::new(self)
151 }
152
153 /// If the `Value` is a Array, returns the underlying `Vec`.
154 ///
155 /// Returns `None` otherwise.
156 ///
157 /// This method consumes the `Value`. To get a reference instead, use
158 /// `as_array`.
159 pub fn into_array(self) -> Option<Vec<Value>> {
160 match self {
161 Value::Array(dict) => Some(dict),
162 _ => None,
163 }
164 }
165
166 /// If the `Value` is an Array, returns the associated `Vec`.
167 ///
168 /// Returns `None` otherwise.
169 pub fn as_array(&self) -> Option<&Vec<Value>> {
170 match *self {
171 Value::Array(ref array) => Some(array),
172 _ => None,
173 }
174 }
175
176 /// If the `Value` is an Array, returns the associated mutable `Vec`.
177 ///
178 /// Returns `None` otherwise.
179 pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
180 match *self {
181 Value::Array(ref mut array) => Some(array),
182 _ => None,
183 }
184 }
185
186 /// If the `Value` is a Dictionary, returns the associated `BTreeMap`.
187 ///
188 /// Returns `None` otherwise.
189 ///
190 /// This method consumes the `Value`. To get a reference instead, use
191 /// `as_dictionary`.
192 pub fn into_dictionary(self) -> Option<Dictionary> {
193 match self {
194 Value::Dictionary(dict) => Some(dict),
195 _ => None,
196 }
197 }
198
199 /// If the `Value` is a Dictionary, returns the associated `BTreeMap`.
200 ///
201 /// Returns `None` otherwise.
202 pub fn as_dictionary(&self) -> Option<&Dictionary> {
203 match *self {
204 Value::Dictionary(ref dict) => Some(dict),
205 _ => None,
206 }
207 }
208
209 /// If the `Value` is a Dictionary, returns the associated mutable `BTreeMap`.
210 ///
211 /// Returns `None` otherwise.
212 pub fn as_dictionary_mut(&mut self) -> Option<&mut Dictionary> {
213 match *self {
214 Value::Dictionary(ref mut dict) => Some(dict),
215 _ => None,
216 }
217 }
218
219 /// If the `Value` is a Boolean, returns the associated `bool`.
220 ///
221 /// Returns `None` otherwise.
222 pub fn as_boolean(&self) -> Option<bool> {
223 match *self {
224 Value::Boolean(v) => Some(v),
225 _ => None,
226 }
227 }
228
229 /// If the `Value` is a Data, returns the underlying `Vec`.
230 ///
231 /// Returns `None` otherwise.
232 ///
233 /// This method consumes the `Value`. If this is not desired, please use
234 /// `as_data` method.
235 pub fn into_data(self) -> Option<Vec<u8>> {
236 match self {
237 Value::Data(data) => Some(data),
238 _ => None,
239 }
240 }
241
242 /// If the `Value` is a Data, returns the associated `Vec`.
243 ///
244 /// Returns `None` otherwise.
245 pub fn as_data(&self) -> Option<&[u8]> {
246 match *self {
247 Value::Data(ref data) => Some(data),
248 _ => None,
249 }
250 }
251
252 /// If the `Value` is a Date, returns the associated `Date`.
253 ///
254 /// Returns `None` otherwise.
255 pub fn as_date(&self) -> Option<Date> {
256 match *self {
257 Value::Date(date) => Some(date),
258 _ => None,
259 }
260 }
261
262 /// If the `Value` is a Real, returns the associated `f64`.
263 ///
264 /// Returns `None` otherwise.
265 pub fn as_real(&self) -> Option<f64> {
266 match *self {
267 Value::Real(v) => Some(v),
268 _ => None,
269 }
270 }
271
272 /// If the `Value` is a signed Integer, returns the associated `i64`.
273 ///
274 /// Returns `None` otherwise.
275 pub fn as_signed_integer(&self) -> Option<i64> {
276 match *self {
277 Value::Integer(v) => v.as_signed(),
278 _ => None,
279 }
280 }
281
282 /// If the `Value` is an unsigned Integer, returns the associated `u64`.
283 ///
284 /// Returns `None` otherwise.
285 pub fn as_unsigned_integer(&self) -> Option<u64> {
286 match *self {
287 Value::Integer(v) => v.as_unsigned(),
288 _ => None,
289 }
290 }
291
292 /// If the `Value` is a String, returns the underlying `String`.
293 ///
294 /// Returns `None` otherwise.
295 ///
296 /// This method consumes the `Value`. If this is not desired, please use
297 /// `as_string` method.
298 pub fn into_string(self) -> Option<String> {
299 match self {
300 Value::String(v) => Some(v),
301 _ => None,
302 }
303 }
304
305 /// If the `Value` is a String, returns the associated `str`.
306 ///
307 /// Returns `None` otherwise.
308 pub fn as_string(&self) -> Option<&str> {
309 match *self {
310 Value::String(ref v) => Some(v),
311 _ => None,
312 }
313 }
314
315 /// If the `Value` is a Uid, returns the underlying `Uid`.
316 ///
317 /// Returns `None` otherwise.
318 ///
319 /// This method consumes the `Value`. If this is not desired, please use
320 /// `as_uid` method.
321 pub fn into_uid(self) -> Option<Uid> {
322 match self {
323 Value::Uid(u) => Some(u),
324 _ => None,
325 }
326 }
327
328 /// If the `Value` is a Uid, returns the associated `Uid`.
329 ///
330 /// Returns `None` otherwise.
331 pub fn as_uid(&self) -> Option<&Uid> {
332 match *self {
333 Value::Uid(ref u) => Some(u),
334 _ => None,
335 }
336 }
337 }
338
339 #[cfg(feature = "serde")]
340 pub mod serde_impls {
341 use serde::{
342 de,
343 de::{EnumAccess, MapAccess, SeqAccess, VariantAccess, Visitor},
344 ser,
345 };
346
347 use crate::{
348 date::serde_impls::DATE_NEWTYPE_STRUCT_NAME, uid::serde_impls::UID_NEWTYPE_STRUCT_NAME,
349 Dictionary, Value,
350 };
351
352 pub const VALUE_NEWTYPE_STRUCT_NAME: &str = "PLIST-VALUE";
353
354 impl ser::Serialize for Value {
355 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
356 where
357 S: serde::Serializer,
358 {
359 match *self {
360 Value::Array(ref v) => v.serialize(serializer),
361 Value::Dictionary(ref m) => m.serialize(serializer),
362 Value::Boolean(b) => serializer.serialize_bool(b),
363 Value::Data(ref v) => serializer.serialize_bytes(v),
364 Value::Date(d) => d.serialize(serializer),
365 Value::Real(n) => serializer.serialize_f64(n),
366 Value::Integer(n) => n.serialize(serializer),
367 Value::String(ref s) => serializer.serialize_str(s),
368 Value::Uid(ref u) => u.serialize(serializer),
369 }
370 }
371 }
372
373 impl<'de> de::Deserialize<'de> for Value {
374 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
375 where
376 D: serde::Deserializer<'de>,
377 {
378 struct ValueVisitor;
379
380 impl<'de> Visitor<'de> for ValueVisitor {
381 type Value = Value;
382
383 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
384 formatter.write_str("any supported plist value")
385 }
386
387 fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
388 Ok(Value::Boolean(value))
389 }
390
391 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Value, E> {
392 Ok(Value::Data(v))
393 }
394
395 fn visit_bytes<E>(self, v: &[u8]) -> Result<Value, E> {
396 Ok(Value::Data(v.to_vec()))
397 }
398
399 fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
400 Ok(Value::Integer(value.into()))
401 }
402
403 fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
404 Ok(Value::Integer(value.into()))
405 }
406
407 fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
408 Ok(Value::Real(value))
409 }
410
411 fn visit_map<V>(self, mut map: V) -> Result<Value, V::Error>
412 where
413 V: MapAccess<'de>,
414 {
415 let mut values = Dictionary::new();
416 while let Some((k, v)) = map.next_entry()? {
417 values.insert(k, v);
418 }
419 Ok(Value::Dictionary(values))
420 }
421
422 fn visit_str<E>(self, value: &str) -> Result<Value, E> {
423 Ok(Value::String(value.to_owned()))
424 }
425
426 fn visit_string<E>(self, value: String) -> Result<Value, E> {
427 Ok(Value::String(value))
428 }
429
430 fn visit_newtype_struct<T>(self, deserializer: T) -> Result<Value, T::Error>
431 where
432 T: de::Deserializer<'de>,
433 {
434 deserializer.deserialize_any(self)
435 }
436
437 fn visit_seq<A>(self, mut seq: A) -> Result<Value, A::Error>
438 where
439 A: SeqAccess<'de>,
440 {
441 let mut vec = Vec::with_capacity(seq.size_hint().unwrap_or(0));
442 while let Some(elem) = seq.next_element()? {
443 vec.push(elem);
444 }
445 Ok(Value::Array(vec))
446 }
447
448 fn visit_enum<A>(self, data: A) -> Result<Value, A::Error>
449 where
450 A: EnumAccess<'de>,
451 {
452 let (name, variant) = data.variant::<String>()?;
453 match &*name {
454 DATE_NEWTYPE_STRUCT_NAME => Ok(Value::Date(variant.newtype_variant()?)),
455 UID_NEWTYPE_STRUCT_NAME => Ok(Value::Uid(variant.newtype_variant()?)),
456 _ => Err(de::Error::unknown_variant(
457 &name,
458 &[DATE_NEWTYPE_STRUCT_NAME, UID_NEWTYPE_STRUCT_NAME],
459 )),
460 }
461 }
462 }
463
464 // Serde serialisers are encouraged to treat newtype structs as insignificant
465 // wrappers around the data they contain. That means not parsing anything other
466 // than the contained value. Therefore, this should not prevent using `Value`
467 // with other `Serializer`s.
468 deserializer.deserialize_newtype_struct(VALUE_NEWTYPE_STRUCT_NAME, ValueVisitor)
469 }
470 }
471 }
472
473 impl From<Vec<Value>> for Value {
474 fn from(from: Vec<Value>) -> Value {
475 Value::Array(from)
476 }
477 }
478
479 impl From<Dictionary> for Value {
480 fn from(from: Dictionary) -> Value {
481 Value::Dictionary(from)
482 }
483 }
484
485 impl From<bool> for Value {
486 fn from(from: bool) -> Value {
487 Value::Boolean(from)
488 }
489 }
490
491 impl<'a> From<&'a bool> for Value {
492 fn from(from: &'a bool) -> Value {
493 Value::Boolean(*from)
494 }
495 }
496
497 impl From<Date> for Value {
498 fn from(from: Date) -> Value {
499 Value::Date(from)
500 }
501 }
502
503 impl<'a> From<&'a Date> for Value {
504 fn from(from: &'a Date) -> Value {
505 Value::Date(*from)
506 }
507 }
508
509 impl From<f64> for Value {
510 fn from(from: f64) -> Value {
511 Value::Real(from)
512 }
513 }
514
515 impl From<f32> for Value {
516 fn from(from: f32) -> Value {
517 Value::Real(from.into())
518 }
519 }
520
521 impl From<i64> for Value {
522 fn from(from: i64) -> Value {
523 Value::Integer(Integer::from(from))
524 }
525 }
526
527 impl From<i32> for Value {
528 fn from(from: i32) -> Value {
529 Value::Integer(Integer::from(from))
530 }
531 }
532
533 impl From<i16> for Value {
534 fn from(from: i16) -> Value {
535 Value::Integer(Integer::from(from))
536 }
537 }
538
539 impl From<i8> for Value {
540 fn from(from: i8) -> Value {
541 Value::Integer(Integer::from(from))
542 }
543 }
544
545 impl From<u64> for Value {
546 fn from(from: u64) -> Value {
547 Value::Integer(Integer::from(from))
548 }
549 }
550
551 impl From<u32> for Value {
552 fn from(from: u32) -> Value {
553 Value::Integer(Integer::from(from))
554 }
555 }
556
557 impl From<u16> for Value {
558 fn from(from: u16) -> Value {
559 Value::Integer(Integer::from(from))
560 }
561 }
562
563 impl From<u8> for Value {
564 fn from(from: u8) -> Value {
565 Value::Integer(Integer::from(from))
566 }
567 }
568
569 impl<'a> From<&'a f64> for Value {
570 fn from(from: &'a f64) -> Value {
571 Value::Real(*from)
572 }
573 }
574
575 impl<'a> From<&'a f32> for Value {
576 fn from(from: &'a f32) -> Value {
577 Value::Real((*from).into())
578 }
579 }
580
581 impl<'a> From<&'a i64> for Value {
582 fn from(from: &'a i64) -> Value {
583 Value::Integer(Integer::from(*from))
584 }
585 }
586
587 impl<'a> From<&'a i32> for Value {
588 fn from(from: &'a i32) -> Value {
589 Value::Integer(Integer::from(*from))
590 }
591 }
592
593 impl<'a> From<&'a i16> for Value {
594 fn from(from: &'a i16) -> Value {
595 Value::Integer(Integer::from(*from))
596 }
597 }
598
599 impl<'a> From<&'a i8> for Value {
600 fn from(from: &'a i8) -> Value {
601 Value::Integer(Integer::from(*from))
602 }
603 }
604
605 impl<'a> From<&'a u64> for Value {
606 fn from(from: &'a u64) -> Value {
607 Value::Integer(Integer::from(*from))
608 }
609 }
610
611 impl<'a> From<&'a u32> for Value {
612 fn from(from: &'a u32) -> Value {
613 Value::Integer(Integer::from(*from))
614 }
615 }
616
617 impl<'a> From<&'a u16> for Value {
618 fn from(from: &'a u16) -> Value {
619 Value::Integer((*from).into())
620 }
621 }
622
623 impl<'a> From<&'a u8> for Value {
624 fn from(from: &'a u8) -> Value {
625 Value::Integer((*from).into())
626 }
627 }
628
629 impl From<String> for Value {
630 fn from(from: String) -> Value {
631 Value::String(from)
632 }
633 }
634
635 impl<'a> From<&'a str> for Value {
636 fn from(from: &'a str) -> Value {
637 Value::String(from.into())
638 }
639 }
640
641 struct Builder<T> {
642 stream: T,
643 token: Option<OwnedEvent>,
644 }
645
646 impl<T: Iterator<Item = Result<OwnedEvent, Error>>> Builder<T> {
647 fn new(stream: T) -> Builder<T> {
648 Builder {
649 stream,
650 token: None,
651 }
652 }
653
654 fn build(mut self) -> Result<Value, Error> {
655 self.bump()?;
656 self.build_value()
657 }
658
659 fn bump(&mut self) -> Result<(), Error> {
660 self.token = match self.stream.next() {
661 Some(Ok(token)) => Some(token),
662 Some(Err(err)) => return Err(err),
663 None => None,
664 };
665 Ok(())
666 }
667
668 fn build_value(&mut self) -> Result<Value, Error> {
669 match self.token.take() {
670 Some(Event::StartArray(len)) => Ok(Value::Array(self.build_array(len)?)),
671 Some(Event::StartDictionary(len)) => Ok(Value::Dictionary(self.build_dict(len)?)),
672
673 Some(Event::Boolean(b)) => Ok(Value::Boolean(b)),
674 Some(Event::Data(d)) => Ok(Value::Data(d.into_owned())),
675 Some(Event::Date(d)) => Ok(Value::Date(d)),
676 Some(Event::Integer(i)) => Ok(Value::Integer(i)),
677 Some(Event::Real(f)) => Ok(Value::Real(f)),
678 Some(Event::String(s)) => Ok(Value::String(s.into_owned())),
679 Some(Event::Uid(u)) => Ok(Value::Uid(u)),
680
681 Some(event @ Event::EndCollection) => Err(error::unexpected_event_type(
682 EventKind::ValueOrStartCollection,
683 &event,
684 )),
685
686 None => Err(ErrorKind::UnexpectedEndOfEventStream.without_position()),
687 }
688 }
689
690 fn build_array(&mut self, len: Option<u64>) -> Result<Vec<Value>, Error> {
691 let mut values = match len.and_then(u64_to_usize) {
692 Some(len) => Vec::with_capacity(len),
693 None => Vec::new(),
694 };
695
696 loop {
697 self.bump()?;
698 if let Some(Event::EndCollection) = self.token {
699 self.token.take();
700 return Ok(values);
701 }
702 values.push(self.build_value()?);
703 }
704 }
705
706 fn build_dict(&mut self, _len: Option<u64>) -> Result<Dictionary, Error> {
707 let mut dict = Dictionary::new();
708
709 loop {
710 self.bump()?;
711 match self.token.take() {
712 Some(Event::EndCollection) => return Ok(dict),
713 Some(Event::String(s)) => {
714 self.bump()?;
715 dict.insert(s.into_owned(), self.build_value()?);
716 }
717 Some(event) => {
718 return Err(error::unexpected_event_type(
719 EventKind::DictionaryKeyOrEndCollection,
720 &event,
721 ))
722 }
723 None => return Err(ErrorKind::UnexpectedEndOfEventStream.without_position()),
724 }
725 }
726 }
727 }
728
729 #[cfg(test)]
730 mod tests {
731 use std::time::SystemTime;
732
733 use super::*;
734 use crate::{stream::Event::*, Date, Dictionary, Value};
735
736 #[test]
737 fn value_accessors() {
738 let vec = vec![Value::Real(0.0)];
739 let mut array = Value::Array(vec.clone());
740 assert_eq!(array.as_array(), Some(&vec.clone()));
741 assert_eq!(array.as_array_mut(), Some(&mut vec.clone()));
742
743 let mut map = Dictionary::new();
744 map.insert("key1".to_owned(), Value::String("value1".to_owned()));
745 let mut dict = Value::Dictionary(map.clone());
746 assert_eq!(dict.as_dictionary(), Some(&map.clone()));
747 assert_eq!(dict.as_dictionary_mut(), Some(&mut map.clone()));
748
749 assert_eq!(Value::Boolean(true).as_boolean(), Some(true));
750
751 let slice: &[u8] = &[1, 2, 3];
752 assert_eq!(Value::Data(slice.to_vec()).as_data(), Some(slice));
753 assert_eq!(
754 Value::Data(slice.to_vec()).into_data(),
755 Some(slice.to_vec())
756 );
757
758 let date: Date = SystemTime::now().into();
759 assert_eq!(Value::Date(date.clone()).as_date(), Some(date));
760
761 assert_eq!(Value::Real(0.0).as_real(), Some(0.0));
762 assert_eq!(Value::Integer(1.into()).as_signed_integer(), Some(1));
763 assert_eq!(Value::Integer(1.into()).as_unsigned_integer(), Some(1));
764 assert_eq!(Value::Integer((-1).into()).as_unsigned_integer(), None);
765 assert_eq!(
766 Value::Integer((i64::max_value() as u64 + 1).into()).as_signed_integer(),
767 None
768 );
769 assert_eq!(Value::String("2".to_owned()).as_string(), Some("2"));
770 assert_eq!(
771 Value::String("t".to_owned()).into_string(),
772 Some("t".to_owned())
773 );
774 }
775
776 #[test]
777 fn builder() {
778 // Input
779 let events = vec![
780 StartDictionary(None),
781 String("Author".into()),
782 String("William Shakespeare".into()),
783 String("Lines".into()),
784 StartArray(None),
785 String("It is a tale told by an idiot,".into()),
786 String("Full of sound and fury, signifying nothing.".into()),
787 EndCollection,
788 String("Birthdate".into()),
789 Integer(1564.into()),
790 String("Height".into()),
791 Real(1.60),
792 EndCollection,
793 ];
794
795 let builder = Builder::new(events.into_iter().map(|e| Ok(e)));
796 let plist = builder.build();
797
798 // Expected output
799 let mut lines = Vec::new();
800 lines.push(Value::String("It is a tale told by an idiot,".to_owned()));
801 lines.push(Value::String(
802 "Full of sound and fury, signifying nothing.".to_owned(),
803 ));
804
805 let mut dict = Dictionary::new();
806 dict.insert(
807 "Author".to_owned(),
808 Value::String("William Shakespeare".to_owned()),
809 );
810 dict.insert("Lines".to_owned(), Value::Array(lines));
811 dict.insert("Birthdate".to_owned(), Value::Integer(1564.into()));
812 dict.insert("Height".to_owned(), Value::Real(1.60));
813
814 assert_eq!(plist.unwrap(), Value::Dictionary(dict));
815 }
816 }