deser-plist 0.10.1

Property list (plist) support for deser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use deser_core::State;
use deser_core::ext::{BigInt, Datetime, ExtValue, Number, Timestamp};
use deser_core::ser::SerializeRef;
use deser_core::ser::{self, SerializeDriver};
use deser_core::{Atom, Error, ErrorKind, Event, Serialize};

use crate::common::{timestamp_from_plist, timestamp_to_plist};
use crate::format::Format;
use crate::uid::Uid;
use crate::write_binary;
use crate::write_text::TextWriter;

/// Configures how values are serialized to property lists.
///
/// The [`set_format`](Self::set_format) selects the encoding, by default XML is
/// written.
///
/// ```
/// use deser_plist::{Format, SerializerConfig};
///
/// const BINARY: SerializerConfig = SerializerConfig::builder().format(Format::Binary).build();
/// let bytes = BINARY.to_vec(&vec![1, 2, 3]).unwrap();
/// assert!(bytes.starts_with(b"bplist00"));
///
/// const ASCII: SerializerConfig = SerializerConfig::builder().format(Format::Ascii).build();
/// assert_eq!(ASCII.to_string(&vec![1, 2, 3]).unwrap(), "(\n\t1,\n\t2,\n\t3,\n)\n");
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SerializerConfig {
    format: Format,
    context: deser_core::Context,
}

impl SerializerConfig {
    /// Creates the default configuration.
    pub const fn new() -> SerializerConfig {
        SerializerConfig {
            format: Format::Xml,
            context: deser_core::Context::new(),
        }
    }

    /// Returns a builder for the configuration (see [`SerializerConfigBuilder`]).
    pub const fn builder() -> SerializerConfigBuilder {
        SerializerConfigBuilder::new()
    }

    /// Returns a builder that starts with this configuration.
    pub const fn into_builder(self) -> SerializerConfigBuilder {
        SerializerConfigBuilder { value: self }
    }

    /// Sets the context the values are serialized in.
    ///
    /// The values of the context are the defaults of the extension values
    /// of the state (see [`Context`](deser_core::Context)), for instance
    /// the [`BytesFormat`](deser_core::BytesFormat).  The serializers and
    /// writers created with the configuration use this context.  A context set on
    /// the driver takes precedence.
    pub fn set_context(&mut self, context: deser_core::Context) {
        self.context = context;
    }

    /// Returns the context the values are serialized in.
    pub fn context(&self) -> &deser_core::Context {
        &self.context
    }

    /// Gives the context to a driver which has none.
    #[inline]
    fn apply_context(&self, driver: &mut SerializeDriver<'_>) {
        if !self.context.is_empty() {
            driver.set_default_context(self.context.clone());
        }
    }

    /// Sets the format to write.
    pub const fn set_format(&mut self, format: Format) {
        self.format = format;
    }

    /// Serializes the given value.
    pub fn to_vec<T: Serialize + ?Sized>(&self, value: &T) -> Result<Vec<u8>, Error> {
        self.to_vec_ref(SerializeRef::new(&value))
    }

    /// Serializes the given value with a configured driver.
    ///
    /// The callback is invoked with the driver before the serialization
    /// starts, for instance to add [`Layer`](deser_core::ser::Layer)s.
    pub fn to_vec_with<F, T: Serialize + ?Sized>(
        &self,
        value: &T,
        setup: F,
    ) -> Result<Vec<u8>, Error>
    where
        F: FnOnce(&mut SerializeDriver<'_>),
    {
        let mut driver = SerializeDriver::new(&value);
        setup(&mut driver);
        self.apply_context(&mut driver);
        self.serialize_driver(&mut driver)
    }

    /// Serializes a value whose type is erased (see
    /// [`to_vec`](Self::to_vec)).
    ///
    /// This is not generic: the code that exists for every type only
    /// erases it.
    fn to_vec_ref(&self, value: SerializeRef<'_>) -> Result<Vec<u8>, Error> {
        let mut driver = SerializeDriver::from_ref(value);
        self.apply_context(&mut driver);
        self.serialize_driver(&mut driver)
    }

    /// Serializes the given value into a string.
    ///
    /// This fails for the binary format.
    pub fn to_string<T: Serialize + ?Sized>(&self, value: &T) -> Result<String, Error> {
        if !self.format.is_text() {
            return Err(Error::new(
                ErrorKind::UnsupportedType,
                "binary property lists cannot be written to strings",
            ));
        }
        let bytes = self.to_vec(value)?;
        // the text writers only write UTF-8
        Ok(String::from_utf8(bytes).unwrap())
    }

    /// Serializes the value of a driver.
    pub(crate) fn serialize_driver(
        &self,
        driver: &mut SerializeDriver<'_>,
    ) -> Result<Vec<u8>, Error> {
        if self.format.is_text() {
            let mut writer = TextWriter::new(self.format, String::with_capacity(256));
            driver.drive_sink(&mut writer)?;
            writer.finish()?;
            return Ok(writer.out.into_bytes());
        }
        let mut builder = Builder::default();
        driver.drive_sink(&mut builder)?;
        let tree = builder.finish()?;
        Ok(write_binary::write(&tree))
    }

    /// Returns `true` if the output can be written in parts.
    pub(crate) fn is_text(&self) -> bool {
        self.format.is_text()
    }

    /// Serializes (a part of) the value of a driver as text property list
    /// and appends it to the output.
    ///
    /// The progress of the value is kept in `value` (see
    /// `StreamSerializer::drive_partial`), `true` is returned once the
    /// value is complete.  If this fails, what was appended by the call is
    /// removed from the output.
    pub(crate) fn serialize_part(
        &self,
        value: &mut Option<Box<TextWriter>>,
        driver: &mut SerializeDriver<'_>,
        out: &mut Vec<u8>,
        limit: usize,
    ) -> Result<bool, Error> {
        let len = out.len();
        // the writer writes into an empty output directly, otherwise its
        // output is appended
        let adopt = out.is_empty();
        let buffer = match adopt {
            // the output only holds text if it's not empty
            true => String::new(),
            false => String::with_capacity(256),
        };
        let mut local;
        let writer: &mut TextWriter = match value {
            Some(writer) => {
                writer.out = buffer;
                writer
            }
            // a value that is written at once does not box the writer
            None if limit == usize::MAX => {
                local = TextWriter::new(self.format, buffer);
                &mut local
            }
            None => value.insert(Box::new(TextWriter::new(self.format, buffer))),
        };
        let rv = if limit == usize::MAX {
            driver.drive_sink(writer).map(|()| true)
        } else {
            writer.limit = limit;
            driver.drive_until(writer)
        };
        let rv = rv.and_then(|done| {
            if done {
                writer.finish()?;
            }
            Ok(done)
        });
        let output = core::mem::take(&mut writer.out).into_bytes();
        match rv {
            Ok(done) => {
                if adopt {
                    *out = output;
                } else {
                    out.extend_from_slice(&output);
                }
                if done {
                    *value = None;
                }
                Ok(done)
            }
            Err(err) => {
                // the value is abandoned
                *value = None;
                out.truncate(len);
                Err(err)
            }
        }
    }
}

/// Builds a [`SerializerConfig`].
///
/// The methods have the names of the setters of [`SerializerConfig`] (without `set_`).
#[derive(Debug, Clone)]
#[must_use]
pub struct SerializerConfigBuilder {
    value: SerializerConfig,
}

impl SerializerConfigBuilder {
    /// Creates a builder that starts with the default.
    pub const fn new() -> SerializerConfigBuilder {
        SerializerConfigBuilder {
            value: SerializerConfig::new(),
        }
    }

    /// Sets the format to write.
    ///
    /// See [`SerializerConfig::set_format`].
    pub const fn format(mut self, format: Format) -> SerializerConfigBuilder {
        self.value.set_format(format);
        self
    }

    /// Sets the context the values are serialized in.
    ///
    /// See [`SerializerConfig::set_context`].
    pub fn context(mut self, context: deser_core::Context) -> SerializerConfigBuilder {
        self.value.set_context(context);
        self
    }

    /// Returns the built [`SerializerConfig`].
    pub const fn build(self) -> SerializerConfig {
        // the value cannot be moved out of the builder in a const fn as the
        // builder needs dropping (the context has a destructor)
        // SAFETY: the value is read once and the builder is forgotten
        let value = unsafe { core::ptr::read(&self.value) };
        core::mem::forget(self);
        value
    }
}

impl Default for SerializerConfigBuilder {
    fn default() -> SerializerConfigBuilder {
        SerializerConfigBuilder::new()
    }
}

/// Serializes values into property lists.
///
/// A property list holds a single value.
///
/// ```
/// use deser_plist::Serializer;
///
/// let mut serializer = Serializer::new();
/// serializer.serialize(&true).unwrap();
/// assert!(serializer.output().ends_with(b"<plist version=\"1.0\">\n<true/>\n</plist>\n"));
/// ```
///
/// The serializer is also the stream serializer of property lists (see
/// [`StreamSerializer`](ser::StreamSerializer)).  XML and OpenStep
/// property lists can be written in parts, binary property lists are
/// written once the value is complete as the object table needs all
/// objects.  To write to a [`Write`](std::io::Write) use
/// [`SerializerConfig::writer`].
#[derive(Default)]
pub struct Serializer {
    config: SerializerConfig,
    out: Vec<u8>,
    written: bool,
    // the value that is written in parts
    value: Option<Box<TextWriter>>,
    // a value was started with `drive_partial` and is not complete
    in_progress: bool,
}

impl Clone for Serializer {
    /// Clones the serializer.
    ///
    /// The clone of a serializer that writes a value in parts cannot write
    /// more values (see
    /// [`StreamSerializer::in_progress`](ser::StreamSerializer::in_progress)).
    fn clone(&self) -> Serializer {
        Serializer {
            config: self.config.clone(),
            out: self.out.clone(),
            written: self.written,
            value: None,
            in_progress: self.in_progress,
        }
    }
}

impl core::fmt::Debug for Serializer {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Serializer")
            .field("config", &self.config)
            .field("output", &self.out)
            .field("written", &self.written)
            .field("in_progress", &self.in_progress)
            .finish()
    }
}

impl Serializer {
    /// Creates a serializer.
    pub fn new() -> Serializer {
        Serializer::with_config(SerializerConfig::new())
    }

    /// Creates a serializer with the given configuration.
    pub fn with_config(config: SerializerConfig) -> Serializer {
        Serializer {
            config,
            out: Vec::new(),
            written: false,
            value: None,
            in_progress: false,
        }
    }

    /// Returns the configuration.
    pub fn config(&self) -> &SerializerConfig {
        &self.config
    }

    /// Returns `true` once the value was written.
    pub fn written(&self) -> bool {
        self.written
    }

    /// Serializes a value.
    ///
    /// A property list holds a single value, serializing a second value
    /// fails.
    pub fn serialize<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
        ser::Serializer::serialize(self, value)
    }

    /// Serializes a value with a configured driver.
    ///
    /// The callback is invoked with the driver before the value is
    /// serialized, for instance to add [`Layer`](deser_core::ser::Layer)s.
    pub fn serialize_with<F, T: Serialize + ?Sized>(
        &mut self,
        value: &T,
        setup: F,
    ) -> Result<(), Error>
    where
        F: FnOnce(&mut SerializeDriver<'_>),
    {
        ser::Serializer::serialize_with(self, value, setup)
    }

    /// Returns the output written so far (that was not cleared).
    pub fn output(&self) -> &[u8] {
        &self.out
    }

    /// Returns the output.
    pub fn finish(self) -> Vec<u8> {
        self.out
    }

    /// Fails if a value was written or is being written.
    fn check_single(&self) -> Result<(), Error> {
        if self.in_progress {
            return Err(Error::in_progress());
        }
        if self.written {
            return Err(Error::new(
                ErrorKind::InvalidState,
                "a property list holds a single value",
            ));
        }
        Ok(())
    }
}

impl ser::Serializer for Serializer {
    fn drive(&mut self, driver: &mut SerializeDriver<'_>) -> Result<(), Error> {
        if !self.config.context.is_empty() {
            driver.set_default_context(self.config.context.clone());
        }
        self.check_single()?;
        if self.config.is_text() {
            self.config
                .serialize_part(&mut self.value, driver, &mut self.out, usize::MAX)?;
        } else {
            let bytes = self.config.serialize_driver(driver)?;
            self.out.extend_from_slice(&bytes);
        }
        self.written = true;
        Ok(())
    }
}

impl ser::StreamSerializer for Serializer {
    fn output(&self) -> &[u8] {
        &self.out
    }

    fn clear_output(&mut self) {
        self.out.clear();
    }

    /// XML and OpenStep property lists are written in parts.
    fn supports_partial(&self) -> bool {
        self.config.is_text()
    }

    fn drive_partial(
        &mut self,
        driver: &mut SerializeDriver<'_>,
        limit: usize,
    ) -> Result<bool, Error> {
        if !self.config.context.is_empty() {
            driver.set_default_context(self.config.context.clone());
        }
        if self.value.is_none() {
            if limit == usize::MAX || !self.config.is_text() {
                ser::Serializer::drive(self, driver)?;
                return Ok(true);
            }
            self.check_single()?;
        }
        // the parts of a value that failed stay written (see
        // `in_progress`)
        if !self
            .config
            .serialize_part(&mut self.value, driver, &mut self.out, limit)?
        {
            self.in_progress = true;
            return Ok(false);
        }
        self.in_progress = false;
        self.written = true;
        Ok(true)
    }

    fn in_progress(&self) -> bool {
        self.in_progress
    }
}

#[cfg(feature = "io")]
impl SerializerConfig {
    /// Creates a writer of a property list (see
    /// [`deser::io::Writer`](deser_core::io::Writer)).
    ///
    /// A stream holds a single property list, writing a second value fails.
    /// XML and OpenStep property lists are written in parts while the value
    /// is serialized.  Binary property lists are written once the value is
    /// complete as the object table needs all objects.
    pub fn writer<W: std::io::Write>(&self, writer: W) -> deser_core::io::Writer<W, Serializer> {
        deser_core::io::Writer::new(writer, Serializer::with_config(self.clone()))
    }

    /// Serializes a value to a writer.
    ///
    /// See [`to_writer`].
    pub fn to_writer<W: std::io::Write, T: Serialize + ?Sized>(
        &self,
        writer: W,
        value: &T,
    ) -> Result<(), Error> {
        self.writer(writer).write(value)
    }
}

/// Serializes a value to a writer as XML property list.
///
/// To write other formats use [`SerializerConfig::to_writer`].
///
/// ```
/// let mut out = Vec::new();
/// deser_plist::to_writer(&mut out, &true).unwrap();
/// assert!(out.ends_with(b"<true/>\n</plist>\n"));
/// ```
#[cfg(feature = "io")]
pub fn to_writer<W: std::io::Write, T: Serialize + ?Sized>(
    writer: W,
    value: &T,
) -> Result<(), Error> {
    SerializerConfig::new().to_writer(writer, value)
}

/// Serializes a value to an XML property list.
///
/// This uses the default [`SerializerConfig`].
///
/// ```
/// let bytes = deser_plist::to_vec(&vec!["a", "b"]).unwrap();
/// assert!(bytes.ends_with(b"<array>\n\t<string>a</string>\n\t<string>b</string>\n</array>\n</plist>\n"));
/// ```
pub fn to_vec<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>, Error> {
    SerializerConfig::new().to_vec(value)
}

/// Serializes a value to an XML property list in a string.
///
/// This uses the default [`SerializerConfig`].
pub fn to_string<T: Serialize + ?Sized>(value: &T) -> Result<String, Error> {
    SerializerConfig::new().to_string(value)
}

/// A value of a property list.
pub(crate) enum Node {
    Bool(bool),
    Int(i128),
    Real(f64),
    Real32(f32),
    Str(String),
    Data(Vec<u8>),
    Date(Timestamp),
    Uid(u64),
    Array(Vec<usize>),
    Dict(Vec<(String, usize)>),
}

/// The values of a property list, the first one is the top value.
pub(crate) struct Tree {
    pub(crate) nodes: Vec<Node>,
}

/// An open container of the builder.
enum Open {
    Array(usize, Vec<usize>),
    Dict(usize, Vec<(String, usize)>, Option<String>),
}

/// Builds the tree from serialization events.
#[derive(Default)]
struct Builder {
    nodes: Vec<Node>,
    stack: Vec<Open>,
}

impl ser::EventSink for Builder {
    fn event(
        &mut self,
        event: Event,
        _value: SerializeRef<'_>,
        _state: &mut State,
    ) -> Result<(), Error> {
        Builder::event(self, event)
    }
}

impl Builder {
    fn finish(self) -> Result<Tree, Error> {
        if self.nodes.is_empty() || !self.stack.is_empty() {
            return Err(Error::new(ErrorKind::InvalidState, "incomplete value"));
        }
        Ok(Tree { nodes: self.nodes })
    }

    fn event(&mut self, event: Event) -> Result<(), Error> {
        let Some(open) = self.stack.last_mut() else {
            if !self.nodes.is_empty() {
                return Err(Error::new(ErrorKind::InvalidState, "unexpected event"));
            }
            return match self.value(event)? {
                Some(_) => Ok(()),
                None => Err(Error::new(
                    ErrorKind::UnsupportedType,
                    "property lists cannot hold null values",
                )),
            };
        };
        match open {
            Open::Dict(_, _, key @ None) => match event {
                Event::Atom(atom) => {
                    *key = Some(key_to_string(atom)?);
                    Ok(())
                }
                Event::MapEnd => self.close(),
                _ => Err(unsupported_key()),
            },
            Open::Dict(_, _, key @ Some(_)) => {
                let key = key.take().unwrap();
                // map entries with null values are skipped
                if let Some(value) = self.value(event)? {
                    self.add_entry(key, value);
                }
                Ok(())
            }
            Open::Array(..) => {
                if event == Event::SeqEnd {
                    return self.close();
                }
                match self.value(event)? {
                    Some(value) => {
                        self.add_item(value);
                        Ok(())
                    }
                    None => Err(Error::new(
                        ErrorKind::UnsupportedType,
                        "property lists cannot hold null values in arrays",
                    )),
                }
            }
        }
    }

    /// Returns the open container a value was added to.
    ///
    /// If the value opened a container, it's on top of the stack and the
    /// parent is below it.
    fn parent(&mut self, value: usize) -> &mut Open {
        let len = self.stack.len();
        let opened = match self.stack[len - 1] {
            Open::Array(id, _) | Open::Dict(id, _, _) => id == value,
        };
        &mut self.stack[if opened { len - 2 } else { len - 1 }]
    }

    fn add_entry(&mut self, key: String, value: usize) {
        match self.parent(value) {
            Open::Dict(_, entries, _) => entries.push((key, value)),
            Open::Array(..) => unreachable!(),
        }
    }

    fn add_item(&mut self, value: usize) {
        match self.parent(value) {
            Open::Array(_, items) => items.push(value),
            Open::Dict(..) => unreachable!(),
        }
    }

    /// Closes the innermost container.
    fn close(&mut self) -> Result<(), Error> {
        match self.stack.pop() {
            Some(Open::Array(id, items)) => self.nodes[id] = Node::Array(items),
            Some(Open::Dict(id, entries, None)) => self.nodes[id] = Node::Dict(entries),
            Some(Open::Dict(_, _, Some(_))) => {
                return Err(Error::new(ErrorKind::InvalidState, "map without value"));
            }
            None => return Err(Error::new(ErrorKind::InvalidState, "unexpected end")),
        }
        Ok(())
    }

    /// Adds the value of the first event of a value.  Maps and sequences
    /// are pushed to the stack.  Returns `None` for null.
    fn value(&mut self, event: Event) -> Result<Option<usize>, Error> {
        let id = self.nodes.len();
        let node = match event {
            Event::Atom(atom) => match convert_atom(atom)? {
                // binary property lists store dates as seconds in a float
                Some(Node::Date(value))
                    if timestamp_from_plist(timestamp_to_plist(&value)).is_none() =>
                {
                    return Err(Error::new(
                        ErrorKind::OutOfRange,
                        "date out of range for binary property lists",
                    ));
                }
                Some(node) => node,
                None => return Ok(None),
            },
            Event::MapStart(_) => {
                self.stack.push(Open::Dict(id, Vec::new(), None));
                Node::Dict(Vec::new())
            }
            Event::SeqStart(_) => {
                self.stack.push(Open::Array(id, Vec::new()));
                Node::Array(Vec::new())
            }
            Event::MapEnd | Event::SeqEnd => {
                return Err(Error::new(ErrorKind::InvalidState, "unexpected end event"));
            }
        };
        self.nodes.push(node);
        Ok(Some(id))
    }
}

/// Converts an atom into a node.  Returns `None` for null.
pub(crate) fn convert_atom(atom: Atom) -> Result<Option<Node>, Error> {
    Ok(Some(match atom {
        Atom::Null => return Ok(None),
        Atom::Bool(value) => Node::Bool(value),
        Atom::Str(value) | Atom::Lexical(value) => Node::Str(value.into_owned()),
        Atom::Char(value) => Node::Str(value.to_string()),
        Atom::U64(value) => Node::Int(value.into()),
        Atom::I64(value) => Node::Int(value.into()),
        Atom::F64(value) => Node::Real(value),
        Atom::F32(value) => Node::Real32(value),
        // property lists have binary data, bytes are never encoded
        Atom::Bytes(value) => Node::Data(value.into_owned()),
        Atom::Ext(ref ext) => return convert_ext(ext),
        // values whose type was inferred from text are written as value
        Atom::Implicit(value) => return convert_atom(value.value().to_atom()),
        _ => return Err(Error::new(ErrorKind::UnsupportedType, "unknown atom")),
    }))
}

#[cold]
fn convert_ext(ext: &ExtValue) -> Result<Option<Node>, Error> {
    if let Some(value) = ext.downcast_ref::<Uid>() {
        return Ok(Some(Node::Uid(value.get())));
    }
    if let Some(&value) = ext.downcast_ref::<Timestamp>() {
        return Ok(Some(Node::Date(value)));
    }
    // offset date-times are instants, other date-times are strings
    if let Some(&value) = ext.downcast_ref::<Datetime>()
        && value.offset.is_some()
        && let Ok(value) = Timestamp::try_from(value)
    {
        return Ok(Some(Node::Date(value)));
    }
    let out_of_range = || Error::new(ErrorKind::OutOfRange, "integer out of range for plist");
    if let Some(&value) = ext.downcast_ref::<u128>() {
        return Ok(Some(Node::Int(
            i128::try_from(value).map_err(|_| out_of_range())?,
        )));
    }
    if let Some(&value) = ext.downcast_ref::<i128>() {
        return Ok(Some(Node::Int(value)));
    }
    if let Some(value) = ext.downcast_ref::<BigInt>().and_then(|x| x.to_i128()) {
        return Ok(Some(Node::Int(value)));
    }
    // numbers from text formats are integers if their text is one
    if let Some(value) = ext.downcast_value_ref::<Number>()
        && let Ok(value) = value.as_str().parse::<i128>()
    {
        return Ok(Some(Node::Int(value)));
    }
    match ext.fallback() {
        Atom::Ext(_) => Err(Error::new(
            ErrorKind::UnsupportedType,
            format!("property lists do not support {}", ext.name()),
        )),
        fallback => convert_atom(fallback),
    }
}

/// Converts a key into a string.
pub(crate) fn key_to_string(atom: Atom) -> Result<String, Error> {
    Ok(match atom {
        Atom::Implicit(value) => return key_to_string(value.value().to_atom()),
        Atom::Str(value) | Atom::Lexical(value) => value.into_owned(),
        Atom::Char(value) => value.to_string(),
        Atom::U64(value) => value.to_string(),
        Atom::I64(value) => value.to_string(),
        Atom::Bool(value) => value.to_string(),
        Atom::Ext(ref ext) => {
            if let Some(value) = ext.downcast_ref::<u128>() {
                value.to_string()
            } else if let Some(value) = ext.downcast_ref::<i128>() {
                value.to_string()
            } else {
                match ext.fallback() {
                    Atom::Ext(_) => return Err(unsupported_key()),
                    fallback => return key_to_string(fallback),
                }
            }
        }
        _ => return Err(unsupported_key()),
    })
}

#[cold]
pub(crate) fn unsupported_key() -> Error {
    Error::new(
        ErrorKind::UnsupportedType,
        "dictionary keys of property lists must be strings",
    )
}