1use std::fmt;
8
9use indexmap::IndexMap;
10
11use crate::etree::{self, Element};
12use crate::py;
13use crate::xml_reader::{self, Content};
14
15pub type Dict = IndexMap<String, Value>;
17
18#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
20pub enum PlistError {
21 #[error("{0}")]
23 Value(String),
24 #[error("{0}")]
26 Overflow(String),
27 #[error("{0}")]
29 Base64(String),
30 #[error("{0}")]
32 Xml(String),
33}
34
35type Result<T> = std::result::Result<T, PlistError>;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
39pub struct Date {
40 pub year: u16,
42 pub month: u8,
44 pub day: u8,
46 pub hour: u8,
48 pub minute: u8,
50 pub second: u8,
52}
53
54#[derive(Debug, Clone)]
56pub enum Value {
57 Bool(bool),
59 Integer(i128),
61 Real(f64),
63 String(String),
65 Data(Vec<u8>),
67 Date(Date),
69 Array(Vec<Value>),
71 Dict(Dict),
73}
74
75impl Value {
76 pub fn as_dict(&self) -> Option<&Dict> {
78 match self {
79 Value::Dict(d) => Some(d),
80 _ => None,
81 }
82 }
83
84 pub fn as_str(&self) -> Option<&str> {
86 match self {
87 Value::String(s) => Some(s),
88 _ => None,
89 }
90 }
91
92 fn as_number(&self) -> Option<Number> {
94 match *self {
95 Value::Bool(b) => Some(Number::Int(i128::from(b))),
96 Value::Integer(i) => Some(Number::Int(i)),
97 Value::Real(f) => Some(Number::Float(f)),
98 _ => None,
99 }
100 }
101}
102
103#[derive(Clone, Copy)]
104enum Number {
105 Int(i128),
106 Float(f64),
107}
108
109impl PartialEq for Number {
110 fn eq(&self, other: &Self) -> bool {
111 match (*self, *other) {
112 (Number::Int(a), Number::Int(b)) => a == b,
113 (Number::Float(a), Number::Float(b)) => a == b,
114 (Number::Int(i), Number::Float(f)) | (Number::Float(f), Number::Int(i)) => {
115 f.fract() == 0.0 && f.is_finite() && (i as f64) == f && i == f as i128
116 }
117 }
118 }
119}
120
121impl PartialEq for Value {
124 fn eq(&self, other: &Self) -> bool {
125 if let (Some(a), Some(b)) = (self.as_number(), other.as_number()) {
126 return a == b;
127 }
128 match (self, other) {
129 (Value::String(a), Value::String(b)) => a == b,
130 (Value::Data(a), Value::Data(b)) => a == b,
131 (Value::Date(a), Value::Date(b)) => a == b,
132 (Value::Array(a), Value::Array(b)) => a == b,
133 (Value::Dict(a), Value::Dict(b)) => a == b,
134 _ => false,
135 }
136 }
137}
138
139impl From<bool> for Value {
140 fn from(v: bool) -> Self {
141 Value::Bool(v)
142 }
143}
144
145impl From<i64> for Value {
146 fn from(v: i64) -> Self {
147 Value::Integer(i128::from(v))
148 }
149}
150
151impl From<i32> for Value {
152 fn from(v: i32) -> Self {
153 Value::Integer(i128::from(v))
154 }
155}
156
157impl From<f64> for Value {
158 fn from(v: f64) -> Self {
159 Value::Real(v)
160 }
161}
162
163impl From<&str> for Value {
164 fn from(v: &str) -> Self {
165 Value::String(v.to_owned())
166 }
167}
168
169impl From<String> for Value {
170 fn from(v: String) -> Self {
171 Value::String(v)
172 }
173}
174
175impl From<Vec<Value>> for Value {
176 fn from(v: Vec<Value>) -> Self {
177 Value::Array(v)
178 }
179}
180
181impl From<Dict> for Value {
182 fn from(v: Dict) -> Self {
183 Value::Dict(v)
184 }
185}
186
187impl fmt::Display for Date {
188 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190 write!(
191 f,
192 "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
193 self.year, self.month, self.day, self.hour, self.minute, self.second
194 )
195 }
196}
197
198fn days_in_month(year: u16, month: u8) -> u8 {
199 match month {
200 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
201 4 | 6 | 9 | 11 => 30,
202 _ => {
203 if (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400) {
204 29
205 } else {
206 28
207 }
208 }
209 }
210}
211
212pub fn date_from_string(s: &str) -> Result<Date> {
215 let bytes = s.as_bytes();
216 let mut pos = 0;
217 let mut fields: Vec<u16> = Vec::new();
218 let digits = |pos: usize, n: usize| -> Option<u16> {
219 let part = bytes.get(pos..pos + n)?;
220 if part.iter().all(u8::is_ascii_digit) {
221 Some(
222 part.iter()
223 .fold(0u16, |acc, &d| acc * 10 + u16::from(d - b'0')),
224 )
225 } else {
226 None
227 }
228 };
229 let bad = || PlistError::Value(format!("Expected ISO 8601 date string, but got {s:?}."));
230 fields.push(digits(0, 4).ok_or_else(bad)?);
231 pos += 4;
232 for sep in *b"--T::" {
233 if bytes.get(pos) == Some(&sep)
234 && let Some(v) = digits(pos + 1, 2)
235 {
236 fields.push(v);
237 pos += 3;
238 } else {
239 break;
240 }
241 }
242 if bytes.get(pos) != Some(&b'Z') {
243 return Err(bad());
244 }
245 if fields.len() < 3 {
246 return Err(PlistError::Value(format!(
247 "function missing required argument '{}'",
248 ["month", "day"][fields.len() - 1]
249 )));
250 }
251 fields.resize(6, 0);
252 let year = fields[0];
253 let [month, day, hour, minute, second] =
254 [fields[1], fields[2], fields[3], fields[4], fields[5]].map(|v| v as u8);
255 if year == 0 {
256 return Err(PlistError::Value(format!("year {year} is out of range")));
257 }
258 if !(1..=12).contains(&month) {
259 return Err(PlistError::Value("month must be in 1..12".into()));
260 }
261 if day == 0 || day > days_in_month(year, month) {
262 return Err(PlistError::Value("day is out of range for month".into()));
263 }
264 if hour > 23 {
265 return Err(PlistError::Value("hour must be in 0..23".into()));
266 }
267 if minute > 59 {
268 return Err(PlistError::Value("minute must be in 0..59".into()));
269 }
270 if second > 59 {
271 return Err(PlistError::Value("second must be in 0..59".into()));
272 }
273 Ok(Date {
274 year,
275 month,
276 day,
277 hour,
278 minute,
279 second,
280 })
281}
282
283const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
284
285fn b64encode(data: &[u8]) -> String {
287 let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
288 for chunk in data.chunks(3) {
289 let b = [
290 chunk[0],
291 *chunk.get(1).unwrap_or(&0),
292 *chunk.get(2).unwrap_or(&0),
293 ];
294 let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
295 for i in 0..4 {
296 if i <= chunk.len() {
297 out.push(B64[((n >> (18 - 6 * i)) & 63) as usize] as char);
298 } else {
299 out.push('=');
300 }
301 }
302 }
303 out
304}
305
306pub fn b64decode(text: &str) -> Result<Vec<u8>> {
310 let mut out = Vec::new();
311 let mut quad_pos = 0;
312 let mut left: u32 = 0;
313 let mut pads = 0;
314 let mut padded = false;
315 let mut data_chars = 0usize;
316 for c in text.bytes() {
317 if c == b'=' {
318 if quad_pos >= 2 {
319 pads += 1;
320 if quad_pos + pads >= 4 {
321 padded = true;
322 }
323 }
324 continue;
325 }
326 let Some(v) = B64.iter().position(|&b| b == c) else {
327 continue;
328 };
329 let v = v as u32;
330 pads = 0;
331 padded = false;
332 data_chars += 1;
333 match quad_pos {
334 0 => {
335 left = v;
336 quad_pos = 1;
337 }
338 1 => {
339 out.push(((left << 2) | (v >> 4)) as u8);
340 left = v & 0x0f;
341 quad_pos = 2;
342 }
343 2 => {
344 out.push(((left << 4) | (v >> 2)) as u8);
345 left = v & 0x03;
346 quad_pos = 3;
347 }
348 _ => {
349 out.push(((left << 6) | v) as u8);
350 left = 0;
351 quad_pos = 0;
352 }
353 }
354 }
355 match quad_pos {
356 _ if padded => Ok(out),
357 0 => Ok(out),
358 1 => Err(PlistError::Base64(format!(
359 "Invalid base64-encoded string: number of data characters ({data_chars}) cannot be 1 more than a multiple of 4"
360 ))),
361 _ => Err(PlistError::Base64("Incorrect padding".into())),
362 }
363}
364
365fn encode_base64(data: &[u8], maxlinelength: Option<usize>, indent_level: usize) -> String {
368 let encoded = b64encode(data);
369 match maxlinelength {
370 Some(maxlinelength) if !encoded.is_empty() && maxlinelength > 0 => {
371 let indent = format!("\n{}", " ".repeat(indent_level));
372 let max_length = 16.max(maxlinelength.saturating_sub(indent.len()));
373 let mut out = String::new();
374 for chunk in encoded.as_bytes().chunks(max_length) {
375 out.push_str(&indent);
376 out.push_str(std::str::from_utf8(chunk).unwrap_or_default());
377 }
378 out.push_str(&indent);
379 out
380 }
381 _ => encoded,
382 }
383}
384
385#[derive(Debug, Clone, Copy)]
387pub struct TreeOptions {
388 pub sort_keys: bool,
390 pub pretty_print: bool,
392 pub indent_level: usize,
394}
395
396impl Default for TreeOptions {
397 fn default() -> Self {
398 TreeOptions {
399 sort_keys: true,
400 pretty_print: true,
401 indent_level: 1,
402 }
403 }
404}
405
406fn text_element(tag: &str, text: String) -> Element {
407 let mut el = Element::new(tag);
408 el.text = Some(text);
409 el
410}
411
412fn make_element(value: &Value, ctx: &mut TreeOptions) -> Result<Element> {
413 Ok(match value {
414 Value::String(s) => text_element("string", s.clone()),
415 Value::Bool(b) => Element::new(if *b { "true" } else { "false" }),
416 Value::Integer(i) => {
417 if -(1i128 << 63) <= *i && *i < (1i128 << 64) {
418 text_element("integer", i.to_string())
419 } else {
420 return Err(PlistError::Overflow(i.to_string()));
421 }
422 }
423 Value::Real(f) => text_element("real", py::float_repr(*f)),
424 Value::Dict(d) => {
425 let mut el = Element::new("dict");
426 let mut items: Vec<(&String, &Value)> = d.iter().collect();
427 if ctx.sort_keys {
428 items.sort_by(|a, b| a.0.cmp(b.0));
429 }
430 ctx.indent_level += 1;
431 for (key, value) in items {
432 el.append(text_element("key", key.clone()));
433 el.append(make_element(value, ctx)?);
434 }
435 ctx.indent_level -= 1;
436 el
437 }
438 Value::Array(a) => {
439 let mut el = Element::new("array");
440 if a.is_empty() {
441 return Ok(el);
442 }
443 ctx.indent_level += 1;
444 for value in a {
445 el.append(make_element(value, ctx)?);
446 }
447 ctx.indent_level -= 1;
448 el
449 }
450 Value::Date(d) => text_element("date", d.to_string()),
451 Value::Data(data) => text_element(
452 "data",
453 encode_base64(
454 data,
455 if ctx.pretty_print { Some(76) } else { None },
456 ctx.indent_level,
457 ),
458 ),
459 })
460}
461
462pub fn totree(value: &Value, options: TreeOptions) -> Result<Element> {
464 let mut ctx = options;
465 make_element(value, &mut ctx)
466}
467
468struct PlistTarget {
470 stack: Vec<Value>,
471 keys: Vec<Option<String>>,
473 current_key: Option<String>,
474 root: Option<Value>,
475 data: Vec<String>,
476}
477
478impl PlistTarget {
479 fn start(&mut self, tag: &str) -> Result<()> {
480 self.data.clear();
481 match tag {
482 "dict" => self.start_container(Value::Dict(Dict::new())),
483 "array" => self.start_container(Value::Array(Vec::new())),
484 _ => Ok(()),
485 }
486 }
487
488 fn start_container(&mut self, value: Value) -> Result<()> {
491 let key = if self.current_key.is_some() {
492 match self.stack.last() {
493 Some(Value::Dict(_)) => {}
494 Some(top) => return Err(unexpected(top)),
495 None => return Err(PlistError::Value("unexpected element".into())),
496 }
497 self.current_key.take()
498 } else {
499 if let Some(top) = self.stack.last()
500 && !matches!(top, Value::Array(_))
501 {
502 return Err(unexpected(top));
503 }
504 None
505 };
506 self.stack.push(value);
507 self.keys.push(key);
508 Ok(())
509 }
510
511 fn end(&mut self, tag: &str) -> Result<()> {
512 match tag {
513 "dict" => {
514 if let Some(key) = &self.current_key
515 && !key.is_empty()
516 {
517 return Err(PlistError::Value(format!("missing value for key '{key}'")));
518 }
519 self.end_container()
520 }
521 "array" => self.end_container(),
522 "key" => {
523 let is_dict = matches!(self.stack.last(), Some(Value::Dict(_)));
524 if self.current_key.as_ref().is_some_and(|k| !k.is_empty()) || !is_dict {
525 return Err(PlistError::Value("unexpected key".into()));
526 }
527 self.current_key = Some(self.get_data());
528 Ok(())
529 }
530 "true" => self.add_object(Value::Bool(true)),
531 "false" => self.add_object(Value::Bool(false)),
532 "integer" => {
533 let data = self.get_data();
534 let v = py::parse_int(&data).ok_or_else(|| {
535 PlistError::Value(format!(
536 "invalid literal for int() with base 10: {}",
537 py::str_repr(&data)
538 ))
539 })?;
540 self.add_object(Value::Integer(v))
541 }
542 "real" => {
543 let data = self.get_data();
544 let v = py::parse_float(&data).ok_or_else(|| {
545 PlistError::Value(format!(
546 "could not convert string to float: {}",
547 py::str_repr(&data)
548 ))
549 })?;
550 self.add_object(Value::Real(v))
551 }
552 "string" => {
553 let data = self.get_data();
554 self.add_object(Value::String(data))
555 }
556 "data" => {
557 let data = self.get_data();
558 self.add_object(Value::Data(b64decode(&data)?))
559 }
560 "date" => {
561 let data = self.get_data();
562 self.add_object(Value::Date(date_from_string(&data)?))
563 }
564 _ => Ok(()),
565 }
566 }
567
568 fn end_container(&mut self) -> Result<()> {
569 let (Some(value), Some(key)) = (self.stack.pop(), self.keys.pop()) else {
571 return Err(PlistError::Value("pop from empty list".into()));
572 };
573 match (self.stack.last_mut(), key) {
574 (Some(Value::Dict(d)), Some(key)) => {
575 d.insert(key, value);
576 }
577 (Some(Value::Array(a)), None) => a.push(value),
578 (None, _) => self.root = Some(value),
579 _ => return Err(PlistError::Value("unexpected element".into())),
580 }
581 Ok(())
582 }
583
584 fn add_object(&mut self, value: Value) -> Result<()> {
585 if self.current_key.is_some() {
586 match self.stack.last_mut() {
587 Some(Value::Dict(d)) => {
588 let key = self.current_key.take().unwrap_or_default();
589 d.insert(key, value);
590 }
591 Some(top) => return Err(unexpected(top)),
592 None => return Err(PlistError::Value("unexpected element".into())),
593 }
594 } else if self.stack.is_empty() {
595 self.root = Some(value);
596 } else {
597 match self.stack.last_mut() {
598 Some(Value::Array(a)) => a.push(value),
599 Some(top) => return Err(unexpected(top)),
600 None => {}
601 }
602 }
603 Ok(())
604 }
605
606 fn get_data(&mut self) -> String {
607 let data = self.data.concat();
608 self.data.clear();
609 data
610 }
611}
612
613fn unexpected(top: &Value) -> PlistError {
614 PlistError::Value(format!("unexpected element: {top:?}"))
615}
616
617pub fn element_text(element: &xml_reader::Element) -> Option<String> {
619 let mut text: Option<String> = None;
620 for content in &element.content {
621 match content {
622 Content::Text(t) => text.get_or_insert_with(String::new).push_str(t),
623 Content::Element(_) => break,
624 }
625 }
626 text
627}
628
629fn walk(target: &mut PlistTarget, element: &xml_reader::Element) -> Result<()> {
630 target.start(&element.name)?;
631 let mut has_children = false;
632 for child in element.elements() {
633 has_children = true;
634 walk(target, child)?;
635 }
636 if !has_children {
637 target.data.push(element_text(element).unwrap_or_default());
638 }
639 target.end(&element.name)
640}
641
642pub fn fromtree(tree: &xml_reader::Element) -> Result<Value> {
644 let mut target = PlistTarget {
645 stack: Vec::new(),
646 keys: Vec::new(),
647 current_key: None,
648 root: None,
649 data: Vec::new(),
650 };
651 walk(&mut target, tree)?;
652 target
653 .root
654 .ok_or_else(|| PlistError::Value("No root set.".into()))
655}
656
657pub fn loads(text: &str) -> Result<Value> {
659 let root = xml_reader::parse(text.strip_prefix('\u{feff}').unwrap_or(text))
660 .map_err(|e| PlistError::Xml(e.0))?;
661 fromtree(&root)
662}
663
664pub fn loads_bytes(data: &[u8]) -> Result<Value> {
667 loads(&decode_xml(data)?)
668}
669
670fn decode_utf16(data: &[u8], big_endian: bool) -> Result<String> {
671 let (pairs, rest) = data.as_chunks::<2>();
672 if !rest.is_empty() {
673 return Err(PlistError::Xml("truncated UTF-16 data".into()));
674 }
675 let units = pairs.iter().map(|&c| {
676 if big_endian {
677 u16::from_be_bytes(c)
678 } else {
679 u16::from_le_bytes(c)
680 }
681 });
682 char::decode_utf16(units)
683 .collect::<std::result::Result<String, _>>()
684 .map_err(|e| PlistError::Xml(e.to_string()))
685}
686
687fn declared_encoding(data: &[u8]) -> Option<String> {
690 let head = data.get(..data.len().min(200))?;
691 if !head.starts_with(b"<?xml") {
692 return None;
693 }
694 let end = head.windows(2).position(|w| w == b"?>")?;
695 let decl = std::str::from_utf8(&head[..end]).ok()?;
696 let rest = &decl[decl.find("encoding")? + "encoding".len()..];
697 let rest = rest.trim_start().strip_prefix('=')?.trim_start();
698 let quote = rest.chars().next()?;
699 let value = rest.get(1..)?;
700 Some(value[..value.find(quote)?].to_ascii_lowercase())
701}
702
703pub fn decode_xml(data: &[u8]) -> Result<String> {
707 if let Some(rest) = data.strip_prefix(b"\xef\xbb\xbf") {
708 return String::from_utf8(rest.to_vec()).map_err(|e| PlistError::Xml(e.to_string()));
709 }
710 if let Some(rest) = data.strip_prefix(b"\xff\xfe") {
711 return decode_utf16(rest, false);
712 }
713 if let Some(rest) = data.strip_prefix(b"\xfe\xff") {
714 return decode_utf16(rest, true);
715 }
716 if data.starts_with(b"<\0?\0") {
717 return decode_utf16(data, false);
718 }
719 if data.starts_with(b"\0<\0?") {
720 return decode_utf16(data, true);
721 }
722 match declared_encoding(data).as_deref() {
723 Some("latin-1" | "latin1" | "iso-8859-1" | "iso8859-1") => Ok(py::latin1_decode(data)),
724 _ => String::from_utf8(data.to_vec()).map_err(|e| PlistError::Xml(e.to_string())),
725 }
726}
727
728pub fn dumps(value: &Value, sort_keys: bool, pretty_print: bool) -> Result<String> {
730 let mut root = Element::new("plist");
731 root.set("version", "1.0");
732 root.append(totree(
733 value,
734 TreeOptions {
735 sort_keys,
736 pretty_print,
737 indent_level: 1,
738 },
739 )?);
740 let mut out = String::from("<?xml version='1.0' encoding='UTF-8'?>");
741 if pretty_print {
742 out.push('\n');
743 }
744 out.push_str(
745 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">",
746 );
747 if pretty_print {
748 out.push('\n');
749 }
750 out.push_str(&etree::tostring(&root, pretty_print, false).map_err(|e| PlistError::Xml(e.0))?);
751 Ok(out)
752}
753
754#[cfg(test)]
755mod tests {
756 use super::*;
757
758 fn dict(items: Vec<(&str, Value)>) -> Value {
759 Value::Dict(items.into_iter().map(|(k, v)| (k.to_owned(), v)).collect())
760 }
761
762 #[test]
763 fn target_doctest() -> Result<()> {
764 let v = loads("<dict> <key>something</key> <string>blah</string></dict>")?;
765 assert_eq!(v, dict(vec![("something", "blah".into())]));
766 Ok(())
767 }
768
769 #[test]
770 fn roundtrip() -> Result<()> {
771 let value = dict(vec![
772 ("b", Value::Array(vec![1.into(), 2.5.into(), true.into()])),
773 ("a", Value::Data(b"<binary gunk>".to_vec())),
774 ("c", Value::Date(date_from_string("2020-01-02T03:04:05Z")?)),
775 ("d", dict(vec![("x", Value::Array(vec![]))])),
776 ]);
777 let text = dumps(&value, true, true)?;
778 assert_eq!(
780 text,
781 "<?xml version='1.0' encoding='UTF-8'?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n <dict>\n <key>a</key>\n <data>\n PGJpbmFyeSBndW5rPg==\n </data>\n <key>b</key>\n <array>\n <integer>1</integer>\n <real>2.5</real>\n <true/>\n </array>\n <key>c</key>\n <date>2020-01-02T03:04:05Z</date>\n <key>d</key>\n <dict>\n <key>x</key>\n <array/>\n </dict>\n </dict>\n</plist>\n"
782 );
783 assert_eq!(loads(&text)?, value);
784 Ok(())
785 }
786
787 #[test]
788 fn numbers_compare_like_python() {
789 assert_eq!(Value::Bool(true), Value::Integer(1));
790 assert_eq!(Value::Integer(2), Value::Real(2.0));
791 assert_ne!(Value::Integer(2), Value::String("2".into()));
792 }
793
794 #[test]
795 fn base64_decode() -> Result<()> {
796 assert_eq!(
797 b64decode("\n PGJp\n bmFyeSBndW5rPg==\n ")?,
798 b"<binary gunk>"
799 );
800 assert!(b64decode("YQ").is_err());
801 assert_eq!(b64decode("YQ==YQ==")?, b"a\x06\x10");
803 assert_eq!(b64decode("YWI=Y")?, b"ab\x18");
804 assert_eq!(b64decode("YQ===")?, b"a");
805 assert!(b64decode("YQ==Y").is_err());
806 assert!(b64decode("YQ=a").is_err());
807 assert!(b64decode("YQ==YWI").is_err());
808 Ok(())
809 }
810}