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