1use std::{
2 borrow::Cow,
3 fs::File,
4 io::{BufReader, BufWriter, Read, Seek, Write},
5 path::Path,
6};
7
8use crate::{
9 error::{self, Error, ErrorKind, EventKind},
10 stream::{
11 private, AsciiReader, BinaryWriter, Event, Events, Reader, Writer, XmlReader,
12 XmlWriteOptions, XmlWriter,
13 },
14 u64_to_usize, Date, Dictionary, Integer, Uid,
15};
16
17#[derive(Clone, Debug, PartialEq)]
19#[non_exhaustive]
20pub enum Value {
21 Array(Vec<Value>),
22 Dictionary(Dictionary),
23 Boolean(bool),
24 Data(Vec<u8>),
25 Date(Date),
26 Real(f64),
27 Integer(Integer),
28 String(String),
29 Uid(Uid),
30}
31
32impl Value {
33 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Value, Error> {
35 let file = File::open(path).map_err(error::from_io_without_position)?;
36 Value::from_reader(BufReader::new(file))
37 }
38
39 pub fn from_reader<R: Read + Seek>(reader: R) -> Result<Value, Error> {
41 let reader = Reader::new(reader);
42 Value::from_events(reader)
43 }
44
45 pub fn from_reader_ascii<R: Read>(reader: R) -> Result<Value, Error> {
47 let reader = AsciiReader::new(reader);
48 Value::from_events(reader)
49 }
50
51 pub fn from_reader_xml<R: Read>(reader: R) -> Result<Value, Error> {
53 let reader = XmlReader::new(BufReader::new(reader));
54 Value::from_events(reader)
55 }
56
57 pub fn to_file_binary<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> {
59 let mut file = File::create(path).map_err(error::from_io_without_position)?;
60 self.to_writer_binary(BufWriter::new(&mut file))?;
61 file.sync_all().map_err(error::from_io_without_position)?;
62 Ok(())
63 }
64
65 pub fn to_file_xml<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> {
67 let mut file = File::create(path).map_err(error::from_io_without_position)?;
68 self.to_writer_xml(BufWriter::new(&mut file))?;
69 file.sync_all().map_err(error::from_io_without_position)?;
70 Ok(())
71 }
72
73 pub fn to_writer_binary<W: Write>(&self, writer: W) -> Result<(), Error> {
75 let mut writer = BinaryWriter::new(writer);
76 self.to_writer_inner(&mut writer)
77 }
78
79 pub fn to_writer_xml<W: Write>(&self, writer: W) -> Result<(), Error> {
81 self.to_writer_xml_with_options(writer, &XmlWriteOptions::default())
82 }
83
84 pub fn to_writer_xml_with_options<W: Write>(
104 &self,
105 writer: W,
106 options: &XmlWriteOptions,
107 ) -> Result<(), Error> {
108 let mut writer = XmlWriter::new_with_options(writer, options);
109 self.to_writer_inner(&mut writer)
110 }
111
112 fn to_writer_inner(&self, writer: &mut dyn Writer) -> Result<(), Error> {
113 let events = self.events();
114 for event in events {
115 writer.write(event)?;
116 }
117 Ok(())
118 }
119
120 #[cfg(feature = "enable_unstable_features_that_may_break_with_minor_version_bumps")]
123 pub fn from_events<'event, T>(events: T) -> Result<Value, Error>
124 where
125 T: IntoIterator<Item = Result<Event<'event>, Error>>,
126 {
127 Builder::build(events.into_iter())
128 }
129
130 #[cfg(not(feature = "enable_unstable_features_that_may_break_with_minor_version_bumps"))]
133 pub(crate) fn from_events<'event, T>(events: T) -> Result<Value, Error>
134 where
135 T: IntoIterator<Item = Result<Event<'event>, Error>>,
136 {
137 Builder::build(events.into_iter())
138 }
139
140 #[cfg(feature = "enable_unstable_features_that_may_break_with_minor_version_bumps")]
142 #[doc(hidden)]
143 #[deprecated(since = "1.2.0", note = "use Value::events instead")]
144 pub fn into_events(&self) -> Events {
145 self.events()
146 }
147
148 #[cfg(not(feature = "enable_unstable_features_that_may_break_with_minor_version_bumps"))]
150 pub(crate) fn events(&self) -> Events {
151 Events::new(self)
152 }
153
154 #[cfg(feature = "enable_unstable_features_that_may_break_with_minor_version_bumps")]
156 pub fn events(&self) -> Events {
157 Events::new(self)
158 }
159
160 pub fn into_array(self) -> Option<Vec<Value>> {
167 match self {
168 Value::Array(dict) => Some(dict),
169 _ => None,
170 }
171 }
172
173 pub fn as_array(&self) -> Option<&Vec<Value>> {
177 match *self {
178 Value::Array(ref array) => Some(array),
179 _ => None,
180 }
181 }
182
183 pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
187 match *self {
188 Value::Array(ref mut array) => Some(array),
189 _ => None,
190 }
191 }
192
193 pub fn into_dictionary(self) -> Option<Dictionary> {
200 match self {
201 Value::Dictionary(dict) => Some(dict),
202 _ => None,
203 }
204 }
205
206 pub fn as_dictionary(&self) -> Option<&Dictionary> {
210 match *self {
211 Value::Dictionary(ref dict) => Some(dict),
212 _ => None,
213 }
214 }
215
216 pub fn as_dictionary_mut(&mut self) -> Option<&mut Dictionary> {
220 match *self {
221 Value::Dictionary(ref mut dict) => Some(dict),
222 _ => None,
223 }
224 }
225
226 pub fn as_boolean(&self) -> Option<bool> {
230 match *self {
231 Value::Boolean(v) => Some(v),
232 _ => None,
233 }
234 }
235
236 pub fn into_data(self) -> Option<Vec<u8>> {
243 match self {
244 Value::Data(data) => Some(data),
245 _ => None,
246 }
247 }
248
249 pub fn as_data(&self) -> Option<&[u8]> {
253 match *self {
254 Value::Data(ref data) => Some(data),
255 _ => None,
256 }
257 }
258
259 pub fn as_date(&self) -> Option<Date> {
263 match *self {
264 Value::Date(date) => Some(date),
265 _ => None,
266 }
267 }
268
269 pub fn as_real(&self) -> Option<f64> {
273 match *self {
274 Value::Real(v) => Some(v),
275 _ => None,
276 }
277 }
278
279 pub fn as_signed_integer(&self) -> Option<i64> {
283 match *self {
284 Value::Integer(v) => v.as_signed(),
285 _ => None,
286 }
287 }
288
289 pub fn as_unsigned_integer(&self) -> Option<u64> {
293 match *self {
294 Value::Integer(v) => v.as_unsigned(),
295 _ => None,
296 }
297 }
298
299 pub fn into_string(self) -> Option<String> {
306 match self {
307 Value::String(v) => Some(v),
308 _ => None,
309 }
310 }
311
312 pub fn as_string(&self) -> Option<&str> {
316 match *self {
317 Value::String(ref v) => Some(v),
318 _ => None,
319 }
320 }
321
322 pub fn into_uid(self) -> Option<Uid> {
329 match self {
330 Value::Uid(u) => Some(u),
331 _ => None,
332 }
333 }
334
335 pub fn as_uid(&self) -> Option<&Uid> {
339 match *self {
340 Value::Uid(ref u) => Some(u),
341 _ => None,
342 }
343 }
344}
345
346#[cfg(feature = "serde")]
347pub mod serde_impls {
348 use serde::{
349 de,
350 de::{EnumAccess, MapAccess, SeqAccess, VariantAccess, Visitor},
351 ser,
352 };
353
354 use crate::{
355 date::serde_impls::DATE_NEWTYPE_STRUCT_NAME, uid::serde_impls::UID_NEWTYPE_STRUCT_NAME,
356 Dictionary, Value,
357 };
358
359 pub const VALUE_NEWTYPE_STRUCT_NAME: &str = "PLIST-VALUE";
360
361 impl ser::Serialize for Value {
362 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
363 where
364 S: serde::Serializer,
365 {
366 match *self {
367 Value::Array(ref v) => v.serialize(serializer),
368 Value::Dictionary(ref m) => m.serialize(serializer),
369 Value::Boolean(b) => serializer.serialize_bool(b),
370 Value::Data(ref v) => serializer.serialize_bytes(v),
371 Value::Date(d) => d.serialize(serializer),
372 Value::Real(n) => serializer.serialize_f64(n),
373 Value::Integer(n) => n.serialize(serializer),
374 Value::String(ref s) => serializer.serialize_str(s),
375 Value::Uid(ref u) => u.serialize(serializer),
376 }
377 }
378 }
379
380 impl<'de> de::Deserialize<'de> for Value {
381 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
382 where
383 D: serde::Deserializer<'de>,
384 {
385 struct ValueVisitor;
386
387 impl<'de> Visitor<'de> for ValueVisitor {
388 type Value = Value;
389
390 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
391 formatter.write_str("any supported plist value")
392 }
393
394 fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
395 Ok(Value::Boolean(value))
396 }
397
398 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Value, E> {
399 Ok(Value::Data(v))
400 }
401
402 fn visit_bytes<E>(self, v: &[u8]) -> Result<Value, E> {
403 Ok(Value::Data(v.to_vec()))
404 }
405
406 fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
407 Ok(Value::Integer(value.into()))
408 }
409
410 fn visit_u64<E>(self, value: u64) -> Result<Value, E> {
411 Ok(Value::Integer(value.into()))
412 }
413
414 fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
415 Ok(Value::Real(value))
416 }
417
418 fn visit_map<V>(self, mut map: V) -> Result<Value, V::Error>
419 where
420 V: MapAccess<'de>,
421 {
422 let mut values = Dictionary::new();
423 while let Some((k, v)) = map.next_entry()? {
424 values.insert(k, v);
425 }
426 Ok(Value::Dictionary(values))
427 }
428
429 fn visit_str<E>(self, value: &str) -> Result<Value, E> {
430 Ok(Value::String(value.to_owned()))
431 }
432
433 fn visit_string<E>(self, value: String) -> Result<Value, E> {
434 Ok(Value::String(value))
435 }
436
437 fn visit_newtype_struct<T>(self, deserializer: T) -> Result<Value, T::Error>
438 where
439 T: de::Deserializer<'de>,
440 {
441 deserializer.deserialize_any(self)
442 }
443
444 fn visit_seq<A>(self, mut seq: A) -> Result<Value, A::Error>
445 where
446 A: SeqAccess<'de>,
447 {
448 let mut vec = Vec::with_capacity(seq.size_hint().unwrap_or(0));
449 while let Some(elem) = seq.next_element()? {
450 vec.push(elem);
451 }
452 Ok(Value::Array(vec))
453 }
454
455 fn visit_enum<A>(self, data: A) -> Result<Value, A::Error>
456 where
457 A: EnumAccess<'de>,
458 {
459 let (name, variant) = data.variant::<String>()?;
460 match &*name {
461 DATE_NEWTYPE_STRUCT_NAME => Ok(Value::Date(variant.newtype_variant()?)),
462 UID_NEWTYPE_STRUCT_NAME => Ok(Value::Uid(variant.newtype_variant()?)),
463 _ => Err(de::Error::unknown_variant(
464 &name,
465 &[DATE_NEWTYPE_STRUCT_NAME, UID_NEWTYPE_STRUCT_NAME],
466 )),
467 }
468 }
469 }
470
471 deserializer.deserialize_newtype_struct(VALUE_NEWTYPE_STRUCT_NAME, ValueVisitor)
476 }
477 }
478}
479
480impl From<Vec<Value>> for Value {
481 fn from(from: Vec<Value>) -> Value {
482 Value::Array(from)
483 }
484}
485
486impl From<Dictionary> for Value {
487 fn from(from: Dictionary) -> Value {
488 Value::Dictionary(from)
489 }
490}
491
492impl From<bool> for Value {
493 fn from(from: bool) -> Value {
494 Value::Boolean(from)
495 }
496}
497
498impl<'a> From<&'a bool> for Value {
499 fn from(from: &'a bool) -> Value {
500 Value::Boolean(*from)
501 }
502}
503
504impl From<Date> for Value {
505 fn from(from: Date) -> Value {
506 Value::Date(from)
507 }
508}
509
510impl<'a> From<&'a Date> for Value {
511 fn from(from: &'a Date) -> Value {
512 Value::Date(*from)
513 }
514}
515
516impl From<f64> for Value {
517 fn from(from: f64) -> Value {
518 Value::Real(from)
519 }
520}
521
522impl From<f32> for Value {
523 fn from(from: f32) -> Value {
524 Value::Real(from.into())
525 }
526}
527
528impl From<i64> for Value {
529 fn from(from: i64) -> Value {
530 Value::Integer(Integer::from(from))
531 }
532}
533
534impl From<i32> for Value {
535 fn from(from: i32) -> Value {
536 Value::Integer(Integer::from(from))
537 }
538}
539
540impl From<i16> for Value {
541 fn from(from: i16) -> Value {
542 Value::Integer(Integer::from(from))
543 }
544}
545
546impl From<i8> for Value {
547 fn from(from: i8) -> Value {
548 Value::Integer(Integer::from(from))
549 }
550}
551
552impl From<u64> for Value {
553 fn from(from: u64) -> Value {
554 Value::Integer(Integer::from(from))
555 }
556}
557
558impl From<u32> for Value {
559 fn from(from: u32) -> Value {
560 Value::Integer(Integer::from(from))
561 }
562}
563
564impl From<u16> for Value {
565 fn from(from: u16) -> Value {
566 Value::Integer(Integer::from(from))
567 }
568}
569
570impl From<u8> for Value {
571 fn from(from: u8) -> Value {
572 Value::Integer(Integer::from(from))
573 }
574}
575
576impl<'a> From<&'a f64> for Value {
577 fn from(from: &'a f64) -> Value {
578 Value::Real(*from)
579 }
580}
581
582impl<'a> From<&'a f32> for Value {
583 fn from(from: &'a f32) -> Value {
584 Value::Real((*from).into())
585 }
586}
587
588impl<'a> From<&'a i64> for Value {
589 fn from(from: &'a i64) -> Value {
590 Value::Integer(Integer::from(*from))
591 }
592}
593
594impl<'a> From<&'a i32> for Value {
595 fn from(from: &'a i32) -> Value {
596 Value::Integer(Integer::from(*from))
597 }
598}
599
600impl<'a> From<&'a i16> for Value {
601 fn from(from: &'a i16) -> Value {
602 Value::Integer(Integer::from(*from))
603 }
604}
605
606impl<'a> From<&'a i8> for Value {
607 fn from(from: &'a i8) -> Value {
608 Value::Integer(Integer::from(*from))
609 }
610}
611
612impl<'a> From<&'a u64> for Value {
613 fn from(from: &'a u64) -> Value {
614 Value::Integer(Integer::from(*from))
615 }
616}
617
618impl<'a> From<&'a u32> for Value {
619 fn from(from: &'a u32) -> Value {
620 Value::Integer(Integer::from(*from))
621 }
622}
623
624impl<'a> From<&'a u16> for Value {
625 fn from(from: &'a u16) -> Value {
626 Value::Integer((*from).into())
627 }
628}
629
630impl<'a> From<&'a u8> for Value {
631 fn from(from: &'a u8) -> Value {
632 Value::Integer((*from).into())
633 }
634}
635
636impl From<String> for Value {
637 fn from(from: String) -> Value {
638 Value::String(from)
639 }
640}
641
642impl<'a> From<&'a str> for Value {
643 fn from(from: &'a str) -> Value {
644 Value::String(from.into())
645 }
646}
647
648enum StackItem {
649 Root(Value),
650 Array(Vec<Value>),
651 Dict(Dictionary),
652 DictAndKey(Dictionary, String),
653}
654
655#[derive(Default)]
656pub struct Builder {
657 stack: Vec<StackItem>,
658}
659
660impl Builder {
661 fn build<'event, T>(stream: T) -> Result<Value, Error>
662 where
663 T: Iterator<Item = Result<Event<'event>, Error>>,
664 {
665 let mut builder = Self::default();
666 for event in stream {
667 builder.write(event?)?;
668 }
669 builder.finish()
670 }
671
672 fn write_value(&mut self, value: Value) -> Result<(), Error> {
673 match (self.stack.pop(), value) {
674 (None, value) => self.stack.push(StackItem::Root(value)),
675 (Some(StackItem::Root(_)), value) => {
676 return Err(ErrorKind::ExpectedEndOfEventStream {
677 found: EventKind::of_value(&value),
678 }
679 .without_position())
680 }
681 (Some(StackItem::Array(mut array)), value) => {
682 array.push(value);
683 self.stack.push(StackItem::Array(array));
684 }
685 (Some(StackItem::Dict(dict)), Value::String(key)) => {
686 self.stack.push(StackItem::DictAndKey(dict, key))
687 }
688 (Some(StackItem::Dict(_)), value) => {
689 return Err(ErrorKind::UnexpectedEventType {
690 expected: EventKind::DictionaryKeyOrEndCollection,
691 found: EventKind::of_value(&value),
692 }
693 .without_position())
694 }
695 (Some(StackItem::DictAndKey(mut dict, key)), value) => {
696 dict.insert(key, value);
697 self.stack.push(StackItem::Dict(dict));
698 }
699 }
700 Ok(())
701 }
702
703 pub fn finish(&mut self) -> Result<Value, Error> {
704 match self.stack.pop() {
705 Some(StackItem::Root(value)) => Ok(value),
706 _ => Err(ErrorKind::UnexpectedEndOfEventStream.without_position()),
707 }
708 }
709}
710
711impl Writer for Builder {
712 fn write_start_array(&mut self, len: Option<u64>) -> Result<(), Error> {
713 let len = len.and_then(u64_to_usize).unwrap_or(0);
714 self.stack.push(StackItem::Array(Vec::with_capacity(len)));
715 Ok(())
716 }
717
718 fn write_start_dictionary(&mut self, _: Option<u64>) -> Result<(), Error> {
719 self.stack.push(StackItem::Dict(Dictionary::new()));
720 Ok(())
721 }
722
723 fn write_end_collection(&mut self) -> Result<(), Error> {
724 let value = match self.stack.pop() {
725 Some(StackItem::Root(_)) => {
726 return Err(ErrorKind::ExpectedEndOfEventStream {
727 found: EventKind::EndCollection,
728 }
729 .without_position())
730 }
731 Some(StackItem::Array(array)) => Value::Array(array),
732 Some(StackItem::Dict(dict)) => Value::Dictionary(dict),
733 Some(StackItem::DictAndKey(_, _)) | None => {
734 return Err(ErrorKind::UnexpectedEventType {
735 expected: EventKind::ValueOrStartCollection,
736 found: EventKind::EndCollection,
737 }
738 .without_position())
739 }
740 };
741 self.write_value(value)
742 }
743
744 fn write_boolean(&mut self, value: bool) -> Result<(), Error> {
745 self.write_value(Value::Boolean(value))
746 }
747
748 fn write_data(&mut self, value: Cow<[u8]>) -> Result<(), Error> {
749 self.write_value(Value::Data(value.into_owned()))
750 }
751
752 fn write_date(&mut self, value: Date) -> Result<(), Error> {
753 self.write_value(Value::Date(value))
754 }
755
756 fn write_integer(&mut self, value: Integer) -> Result<(), Error> {
757 self.write_value(Value::Integer(value))
758 }
759
760 fn write_real(&mut self, value: f64) -> Result<(), Error> {
761 self.write_value(Value::Real(value))
762 }
763
764 fn write_string(&mut self, value: Cow<str>) -> Result<(), Error> {
765 self.write_value(Value::String(value.into_owned()))
766 }
767
768 fn write_uid(&mut self, value: Uid) -> Result<(), Error> {
769 self.write_value(Value::Uid(value))
770 }
771}
772
773impl private::Sealed for Builder {}
774
775#[cfg(test)]
776mod tests {
777 use std::time::SystemTime;
778
779 use super::*;
780 use crate::{stream::Event::*, Date};
781
782 #[test]
783 fn value_accessors() {
784 let vec = vec![Value::Real(0.0)];
785 let mut array = Value::Array(vec.clone());
786 assert_eq!(array.as_array(), Some(&vec.clone()));
787 assert_eq!(array.as_array_mut(), Some(&mut vec.clone()));
788
789 let mut map = Dictionary::new();
790 map.insert("key1".to_owned(), Value::String("value1".to_owned()));
791 let mut dict = Value::Dictionary(map.clone());
792 assert_eq!(dict.as_dictionary(), Some(&map.clone()));
793 assert_eq!(dict.as_dictionary_mut(), Some(&mut map.clone()));
794
795 assert_eq!(Value::Boolean(true).as_boolean(), Some(true));
796
797 let slice: &[u8] = &[1, 2, 3];
798 assert_eq!(Value::Data(slice.to_vec()).as_data(), Some(slice));
799 assert_eq!(
800 Value::Data(slice.to_vec()).into_data(),
801 Some(slice.to_vec())
802 );
803
804 let date: Date = SystemTime::now().into();
805 assert_eq!(Value::Date(date).as_date(), Some(date));
806
807 assert_eq!(Value::Real(0.0).as_real(), Some(0.0));
808 assert_eq!(Value::Integer(1.into()).as_signed_integer(), Some(1));
809 assert_eq!(Value::Integer(1.into()).as_unsigned_integer(), Some(1));
810 assert_eq!(Value::Integer((-1).into()).as_unsigned_integer(), None);
811 assert_eq!(
812 Value::Integer((i64::max_value() as u64 + 1).into()).as_signed_integer(),
813 None
814 );
815 assert_eq!(Value::String("2".to_owned()).as_string(), Some("2"));
816 assert_eq!(
817 Value::String("t".to_owned()).into_string(),
818 Some("t".to_owned())
819 );
820 }
821
822 #[test]
823 fn builder() {
824 let events = vec![
826 StartDictionary(None),
827 String("Author".into()),
828 String("William Shakespeare".into()),
829 String("Lines".into()),
830 StartArray(None),
831 String("It is a tale told by an idiot,".into()),
832 String("Full of sound and fury, signifying nothing.".into()),
833 EndCollection,
834 String("Birthdate".into()),
835 Integer(1564.into()),
836 String("Height".into()),
837 Real(1.60),
838 EndCollection,
839 ];
840
841 let value = Builder::build(events.into_iter().map(Ok));
842
843 let lines = vec![
845 Value::String("It is a tale told by an idiot,".to_owned()),
846 Value::String("Full of sound and fury, signifying nothing.".to_owned()),
847 ];
848
849 let mut dict = Dictionary::new();
850 dict.insert(
851 "Author".to_owned(),
852 Value::String("William Shakespeare".to_owned()),
853 );
854 dict.insert("Lines".to_owned(), Value::Array(lines));
855 dict.insert("Birthdate".to_owned(), Value::Integer(1564.into()));
856 dict.insert("Height".to_owned(), Value::Real(1.60));
857
858 assert_eq!(value.unwrap(), Value::Dictionary(dict));
859 }
860}