deser-toml 0.10.1

TOML 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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
use std::borrow::Cow;
use std::fmt::Write;

use deser_core::ext::ExtValue;
use deser_core::hints::Layout;
use deser_core::ser::{self, SerializeDriver, SerializeRef};
use deser_core::{Atom, BytesFormat, Error, ErrorKind, Event, Serialize, State};

use crate::document::{Document, Entry, Item, Span, TableKind, Value};
use deser_core::ext::{Datetime, Number, Timestamp};

/// Configures how values are serialized to TOML.
///
/// The value has to serialize to a map (for instance a struct or a map
/// type) as TOML documents are tables.  As TOML has no null value, map
/// entries with null values (such as `None`) are skipped, null values in
/// sequences are an error.
///
/// Values that are maps are written as `[table]` sections and sequences of
/// maps as `[[array]]` sections unless they are nested in other sequences or
/// have the [`Layout::Compact`](deser_core::hints::Layout) hint (see
/// [`hints`](deser_core::hints)) which makes them inline.  Inline tables and
/// inline arrays of tables have that hint when deserialized, so they stay
/// inline when a value is deserialized and serialized again.
/// The output is compatible with TOML 1.0.
///
/// [`to_string`](Self::to_string) works like the
/// [`to_string`] function.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SerializerConfig {
    context: deser_core::Context,
}

impl SerializerConfig {
    /// Creates the default configuration.
    pub const fn new() -> SerializerConfig {
        SerializerConfig {
            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());
        }
    }

    /// Serializes the given value.
    pub fn to_string<T: Serialize + ?Sized>(&self, value: &T) -> Result<String, Error> {
        self.to_string_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_string_with<F, T: Serialize + ?Sized>(
        &self,
        value: &T,
        setup: F,
    ) -> Result<String, 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_string`](Self::to_string)).
    ///
    /// This is not generic: the code that exists for every type only
    /// erases it.
    fn to_string_ref(&self, value: SerializeRef<'_>) -> Result<String, Error> {
        let mut driver = SerializeDriver::from_ref(value);
        self.apply_context(&mut driver);
        self.serialize_driver(&mut driver)
    }

    /// Serializes the value of a driver.
    pub(crate) fn serialize_driver(
        &self,
        driver: &mut SerializeDriver<'_>,
    ) -> Result<String, Error> {
        let mut builder = Builder {
            doc: Document::default(),
            stack: Vec::new(),
            done: false,
            bytes: BytesFormat::of(driver.state()),
        };
        driver.drive(|event, state| builder.event(event, state))?;
        if !builder.done {
            return Err(Error::new(
                ErrorKind::InvalidState,
                "no value was serialized",
            ));
        }
        let mut writer = Writer {
            doc: &builder.doc,
            out: String::new(),
        };
        writer.write_document()?;
        Ok(writer.out)
    }
}

/// 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 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 TOML.
///
/// A TOML document holds a single value, writing a second one fails.
///
/// ```
/// use std::collections::BTreeMap;
/// use deser_toml::Serializer;
///
/// let mut serializer = Serializer::new();
/// serializer.serialize(&BTreeMap::from([("a", 1)])).unwrap();
/// assert!(serializer.serialize(&BTreeMap::from([("b", 2)])).is_err());
/// assert_eq!(serializer.finish(), "a = 1\n");
/// ```
///
/// The serializer is also the stream serializer of TOML (see
/// [`StreamSerializer`](ser::StreamSerializer)).  A TOML document cannot be
/// written in parts: the values of a table come before its subtables.  To
/// write to a [`Write`](std::io::Write) use [`SerializerConfig::writer`].
#[derive(Debug, Clone)]
pub struct Serializer {
    config: SerializerConfig,
    out: String,
    written: usize,
}

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

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: String::new(),
            written: 0,
        }
    }

    /// Serializes a value.
    ///
    /// If the value fails to serialize, nothing is written.
    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 configuration.
    pub fn config(&self) -> &SerializerConfig {
        &self.config
    }

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

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

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());
        }
        if self.written > 0 {
            return Err(Error::new(
                ErrorKind::InvalidState,
                "a TOML document holds a single value",
            ));
        }
        let toml = self.config.serialize_driver(driver)?;
        self.out.push_small(&toml);
        self.written += 1;
        Ok(())
    }
}

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

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

#[cfg(feature = "io")]
impl SerializerConfig {
    /// Creates a writer of a TOML document (see
    /// [`deser::io::Writer`](deser_core::io::Writer)).
    ///
    /// A stream holds a single document, writing a second value fails.  The
    /// document is written with a single write once it's complete.
    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.
///
/// The document is written with a single write once it's complete: TOML
/// documents cannot be written while the value is serialized as the values
/// of a table come before its subtables.
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut out = Vec::new();
/// deser_toml::to_writer(&mut out, &BTreeMap::from([("a", 1)])).unwrap();
/// assert_eq!(out, b"a = 1\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 TOML.
///
/// This uses the default [`SerializerConfig`], see there for more
/// information.
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut value = BTreeMap::new();
/// value.insert("name", vec!["a", "b"]);
/// assert_eq!(
///     deser_toml::to_string(&value).unwrap(),
///     "name = [\"a\", \"b\"]\n"
/// );
/// ```
pub fn to_string<T: Serialize + ?Sized>(value: &T) -> Result<String, Error> {
    SerializerConfig::new().to_string(value)
}

/// A map or sequence that is being built.
enum Frame {
    /// A table with the pending key if the next event is a value.
    Table(usize, Option<String>),
    Array(usize),
}

/// Builds a document from serialization events.
struct Builder {
    doc: Document<'static>,
    stack: Vec<Frame>,
    done: bool,
    bytes: BytesFormat,
}

/// A value converted from an atom.
enum Converted {
    Value(Value<'static>),
    Null,
}

impl Builder {
    fn event(&mut self, event: Event, state: &State) -> Result<(), Error> {
        let Some(frame) = self.stack.last_mut() else {
            if self.done {
                return Err(Error::new(ErrorKind::InvalidState, "unexpected event"));
            }
            return match event {
                Event::MapStart(_) => {
                    let id = self.doc.new_table(TableKind::Header, Span::default());
                    self.stack.push(Frame::Table(id, None));
                    Ok(())
                }
                _ => Err(Error::new(
                    ErrorKind::UnsupportedType,
                    "TOML documents must be tables",
                )),
            };
        };

        match *frame {
            Frame::Table(_, ref mut key @ None) => match event {
                Event::Atom(atom) => {
                    *key = Some(key_to_string(atom, self.bytes)?);
                    Ok(())
                }
                Event::MapEnd => {
                    self.stack.pop();
                    self.done = self.stack.is_empty();
                    Ok(())
                }
                _ => Err(unsupported_key()),
            },
            Frame::Table(id, ref mut key @ Some(_)) => {
                let key = key.take().unwrap();
                let value = match self.value(event, state)? {
                    Converted::Value(value) => value,
                    // map entries with null values are skipped
                    Converted::Null => return Ok(()),
                };
                let entry = Entry {
                    key: Cow::Owned(key),
                    key_span: Span::default(),
                    item: Item {
                        value,
                        span: Span::default(),
                    },
                };
                match self.doc.insert_new(id, entry) {
                    Ok(()) => Ok(()),
                    Err(entry) => Err(Error::new(
                        ErrorKind::DuplicateKey,
                        format!("duplicate key `{}`", entry.key),
                    )),
                }
            }
            Frame::Array(id) => {
                if event == Event::SeqEnd {
                    self.stack.pop();
                    return Ok(());
                }
                match self.value(event, state)? {
                    Converted::Value(value) => {
                        self.doc.arrays[id].items.push(Item {
                            value,
                            span: Span::default(),
                        });
                        Ok(())
                    }
                    Converted::Null => Err(Error::new(
                        ErrorKind::UnsupportedType,
                        "TOML does not support null values in arrays",
                    )),
                }
            }
        }
    }

    /// Converts the first event of a value.  Maps and sequences are pushed
    /// to the stack.
    fn value(&mut self, event: Event, state: &State) -> Result<Converted, Error> {
        match event {
            Event::Atom(Atom::Bytes(ref bytes)) => Ok(Converted::Value(
                self.bytes_value(bytes, bytes.fallback.copied().unwrap_or(self.bytes)),
            )),
            Event::Atom(atom) => convert_atom(atom, self.bytes),
            Event::MapStart(_) => {
                // compact tables are inline tables, others sections
                let kind = match Layout::of(state) {
                    Layout::Compact => TableKind::Inline,
                    _ => TableKind::Header,
                };
                let id = self.doc.new_table(kind, Span::default());
                self.stack.push(Frame::Table(id, None));
                Ok(Converted::Value(Value::Table(id)))
            }
            Event::SeqStart(_) => {
                // arrays of tables are `[[array]]` sections unless compact
                let of_tables = Layout::of(state) != Layout::Compact;
                let id = self.doc.new_array(of_tables, Span::default());
                self.stack.push(Frame::Array(id));
                Ok(Converted::Value(Value::Array(id)))
            }
            Event::MapEnd | Event::SeqEnd => {
                Err(Error::new(ErrorKind::InvalidState, "unexpected end event"))
            }
        }
    }

    /// Converts bytes into a string or an array of integers.
    fn bytes_value(&mut self, bytes: &[u8], format: BytesFormat) -> Value<'static> {
        match format.encode(bytes) {
            Some(encoded) => Value::Str(Cow::Owned(encoded)),
            None => {
                let id = self.doc.new_array(false, Span::default());
                self.doc.arrays[id]
                    .items
                    .extend(bytes.iter().map(|&byte| Item {
                        value: Value::Int(byte.into()),
                        span: Span::default(),
                    }));
                Value::Array(id)
            }
        }
    }
}

fn convert_atom(atom: Atom, bytes: BytesFormat) -> Result<Converted, Error> {
    Ok(Converted::Value(match atom {
        Atom::Null => return Ok(Converted::Null),
        Atom::Bool(value) => Value::Bool(value),
        Atom::Str(value) | Atom::Lexical(value) => Value::Str(Cow::Owned(value.into_owned())),
        Atom::Char(value) => Value::Str(Cow::Owned(value.to_string())),
        Atom::U64(value) => match i64::try_from(value) {
            Ok(value) => Value::Int(value),
            Err(_) => Value::UInt(value),
        },
        Atom::I64(value) => Value::Int(value),
        Atom::F64(value) => Value::Float(value),
        Atom::F32(value) => Value::Float32(value),
        // bytes are converted by the builder, this is reached for the
        // fallbacks of extension values which cannot be arrays.
        Atom::Bytes(value) => Value::Str(Cow::Owned(encode_str(&value, value.fallback, bytes))),
        Atom::Ext(ref ext) => return convert_ext(ext, bytes),
        // values whose type was inferred from text are written as value
        Atom::Implicit(value) => return convert_atom(value.value().to_atom(), bytes),
        _ => return Err(Error::new(ErrorKind::UnsupportedType, "unknown atom")),
    }))
}

#[cold]
fn convert_ext(ext: &ExtValue, bytes: BytesFormat) -> Result<Converted, Error> {
    if let Some(value) = ext.downcast_ref::<Datetime>() {
        if !value.is_valid() {
            return Err(Error::new(ErrorKind::InvalidValue, "invalid datetime"));
        }
        return Ok(Converted::Value(Value::Datetime(*value)));
    }
    // numbers from text formats keep their text if it's a float, the syntax
    // of JSON floats is valid in TOML
    if let Some(value) = ext.downcast_value_ref::<Number>() {
        return Ok(Converted::Value(if value.is_integer() {
            Value::Float(value.value())
        } else {
            Value::FloatText(Cow::Owned(value.as_str().to_string()))
        }));
    }
    // instants are written as offset date-times in UTC if possible
    if let Some(value) = ext
        .downcast_ref::<Timestamp>()
        .and_then(|x| x.to_datetime())
    {
        return Ok(Converted::Value(Value::Datetime(value)));
    }
    let out_of_range = || Error::new(ErrorKind::OutOfRange, "integer out of range for TOML");
    if let Some(&value) = ext.downcast_ref::<u128>() {
        let value = u64::try_from(value).map_err(|_| out_of_range())?;
        return convert_atom(Atom::U64(value), bytes);
    }
    if let Some(&value) = ext.downcast_ref::<i128>() {
        return if let Ok(value) = i64::try_from(value) {
            convert_atom(Atom::I64(value), bytes)
        } else {
            let value = u64::try_from(value).map_err(|_| out_of_range())?;
            convert_atom(Atom::U64(value), bytes)
        };
    }
    match ext.fallback() {
        Atom::Ext(_) => Err(Error::new(
            ErrorKind::UnsupportedType,
            format!("TOML does not support {}", ext.name()),
        )),
        fallback => convert_atom(fallback, bytes),
    }
}

/// Encodes bytes as string.
///
/// Strings are required (for keys), so bytes that would be arrays are base64.
fn encode_str(value: &[u8], fallback: Option<&BytesFormat>, bytes: BytesFormat) -> String {
    fallback
        .copied()
        .unwrap_or(bytes)
        .encode(value)
        .or_else(|| BytesFormat::BASE64.encode(value))
        .unwrap_or_default()
}

fn key_to_string(atom: Atom, bytes: BytesFormat) -> Result<String, Error> {
    Ok(match atom {
        Atom::Implicit(value) => return key_to_string(value.value().to_atom(), bytes),
        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::Bytes(value) => encode_str(&value, value.fallback, bytes),
        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, bytes),
                }
            }
        }
        _ => return Err(unsupported_key()),
    })
}

#[cold]
fn unsupported_key() -> Error {
    Error::new(
        ErrorKind::UnsupportedType,
        "TOML only supports strings, integers and booleans as keys",
    )
}

/// How a table is introduced.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Header {
    /// The root table.
    None,
    /// `[table]`
    Table,
    /// `[[table]]`
    ArrayTable,
}

/// A table section to write.
struct Section<'d> {
    id: usize,
    path: Vec<&'d str>,
    header: Header,
}

/// An inline array or table that is being written.
enum InlineFrame {
    Table(usize, usize),
    Array(usize, usize),
}

struct Writer<'d> {
    doc: &'d Document<'static>,
    out: String,
}

impl<'d> Writer<'d> {
    /// Returns `true` if the value is written as section rather than inline.
    fn is_section(&self, value: &Value) -> bool {
        match *value {
            Value::Table(id) => self.doc.tables[id].kind != TableKind::Inline,
            Value::Array(id) => self.is_array_of_tables(id),
            _ => false,
        }
    }

    fn is_array_of_tables(&self, id: usize) -> bool {
        let array = &self.doc.arrays[id];
        array.of_tables
            && !array.items.is_empty()
            && array
                .items
                .iter()
                .all(|x| matches!(x.value, Value::Table(_)))
    }

    fn write_document(&mut self) -> Result<(), Error> {
        let doc = self.doc;
        let mut sections = vec![Section {
            id: 0,
            path: Vec::new(),
            header: Header::None,
        }];

        while let Some(section) = sections.pop() {
            let table = &doc.tables[section.id];
            let has_values = table
                .entries
                .iter()
                .any(|x| !self.is_section(&x.item.value));

            // tables which only contain other tables do not need a header,
            // they are created implicitly by the headers of their children.
            let header = match section.header {
                Header::Table if !has_values && !table.entries.is_empty() => None,
                Header::Table => Some(("[", "]")),
                Header::ArrayTable => Some(("[[", "]]")),
                Header::None => None,
            };
            if let Some((open, close)) = header {
                if !self.out.is_empty() {
                    self.out.push('\n');
                }
                self.out.push_small(open);
                for (idx, key) in section.path.iter().enumerate() {
                    if idx > 0 {
                        self.out.push('.');
                    }
                    write_key(&mut self.out, key);
                }
                self.out.push_small(close);
                self.out.push('\n');
            }

            for entry in &table.entries {
                if !self.is_section(&entry.item.value) {
                    write_key(&mut self.out, &entry.key);
                    self.out.push_small(" = ");
                    self.write_value(&entry.item.value)?;
                    self.out.push('\n');
                }
            }

            // the sections are processed from the end of the stack
            let first_child = sections.len();
            for entry in &table.entries {
                let child_path = || {
                    let mut path = section.path.clone();
                    path.push(&*entry.key);
                    path
                };
                match entry.item.value {
                    Value::Table(id) if self.is_section(&entry.item.value) => {
                        sections.push(Section {
                            id,
                            path: child_path(),
                            header: Header::Table,
                        })
                    }
                    Value::Array(id) if self.is_array_of_tables(id) => {
                        for item in &doc.arrays[id].items {
                            if let Value::Table(id) = item.value {
                                sections.push(Section {
                                    id,
                                    path: child_path(),
                                    header: Header::ArrayTable,
                                });
                            }
                        }
                    }
                    _ => {}
                }
            }
            sections[first_child..].reverse();
        }

        Ok(())
    }

    /// Writes a value inline.
    fn write_value(&mut self, value: &Value) -> Result<(), Error> {
        let doc = self.doc;
        let mut stack = Vec::new();
        self.write_value_start(value, &mut stack);

        while let Some(frame) = stack.last_mut() {
            let value = match *frame {
                InlineFrame::Table(id, ref mut index) => {
                    let table = &doc.tables[id];
                    match table.entries.get(*index) {
                        Some(entry) => {
                            self.out.push_small(if *index == 0 { " " } else { ", " });
                            *index += 1;
                            write_key(&mut self.out, &entry.key);
                            self.out.push_small(" = ");
                            &entry.item.value
                        }
                        None => {
                            self.out
                                .push_small(if table.entries.is_empty() { "}" } else { " }" });
                            stack.pop();
                            continue;
                        }
                    }
                }
                InlineFrame::Array(id, ref mut index) => match doc.arrays[id].items.get(*index) {
                    Some(item) => {
                        if *index > 0 {
                            self.out.push_small(", ");
                        }
                        *index += 1;
                        &item.value
                    }
                    None => {
                        self.out.push(']');
                        stack.pop();
                        continue;
                    }
                },
            };
            self.write_value_start(value, &mut stack);
        }

        Ok(())
    }

    /// Writes a scalar or the start of an inline table or array.
    fn write_value_start(&mut self, value: &Value, stack: &mut Vec<InlineFrame>) {
        match *value {
            Value::Str(ref value) => write_string(&mut self.out, value),
            Value::Int(value) => self.out.push_small(itoa::Buffer::new().format(value)),
            Value::UInt(value) => self.out.push_small(itoa::Buffer::new().format(value)),
            Value::Float(value) => write_float(&mut self.out, value),
            Value::Float32(value) => write_float(&mut self.out, value),
            Value::FloatText(ref value) => self.out.push_small(value),
            Value::Bool(value) => self.out.push_small(if value { "true" } else { "false" }),
            Value::Datetime(ref value) => write!(self.out, "{}", value).unwrap(),
            Value::Table(id) => {
                self.out.push('{');
                stack.push(InlineFrame::Table(id, 0));
            }
            Value::Array(id) => {
                self.out.push('[');
                stack.push(InlineFrame::Array(id, 0));
            }
        }
    }
}

/// Writes a float with the shortest text that reads back as the same value
/// of its type (`f32` or `f64`).  The text always has a fractional part or
/// an exponent.
fn write_float<F: zmij::Float + Into<f64>>(out: &mut String, value: F) {
    let wide: f64 = value.into();
    if wide.is_nan() {
        out.push_small("nan");
    } else if wide.is_infinite() {
        out.push_small(if wide > 0.0 { "inf" } else { "-inf" });
    } else {
        out.push_small(zmij::Buffer::new().format_finite(value));
    }
}

fn is_bare_key(key: &str) -> bool {
    !key.is_empty()
        && key
            .bytes()
            .all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-')
}

fn write_key(out: &mut String, key: &str) {
    if is_bare_key(key) {
        out.push_small(key);
    } else {
        write_basic_string(out, key);
    }
}

/// Writes a string as basic, literal or multi-line basic string.
fn write_string(out: &mut String, value: &str) {
    if value.contains('\n') {
        write_multiline_string(out, value);
    } else if value.contains(['"', '\\'])
        && !value
            .chars()
            .any(|c| c == '\'' || (c.is_control() && c != '\t'))
    {
        // literal strings do not need escaping for quotes and backslashes
        out.push('\'');
        out.push_small(value);
        out.push('\'');
    } else {
        write_basic_string(out, value);
    }
}

/// Writes an escape for a control character.
///
/// Only escapes that exist in TOML 1.0 are used.
fn write_control_escape(out: &mut String, c: char) {
    match c {
        '\x08' => out.push_small("\\b"),
        '\t' => out.push_small("\\t"),
        '\n' => out.push_small("\\n"),
        '\x0c' => out.push_small("\\f"),
        '\r' => out.push_small("\\r"),
        c => write!(out, "\\u{:04X}", c as u32).unwrap(),
    }
}

fn is_escaped_control(c: char) -> bool {
    matches!(c, '\0'..='\x1f' | '\x7f')
}

fn write_basic_string(out: &mut String, value: &str) {
    out.push('"');
    for c in value.chars() {
        match c {
            '"' => out.push_small("\\\""),
            '\\' => out.push_small("\\\\"),
            c if is_escaped_control(c) => write_control_escape(out, c),
            c => out.push(c),
        }
    }
    out.push('"');
}

fn write_multiline_string(out: &mut String, value: &str) {
    // the newline after the opening delimiter is trimmed by parsers
    out.push_small("\"\"\"\n");
    let mut quotes = 0;
    for c in value.chars() {
        match c {
            // three quotes in a row would end the string
            '"' if quotes == 2 => {
                out.push_small("\\\"");
                quotes = 0;
                continue;
            }
            '"' => out.push('"'),
            '\\' => out.push_small("\\\\"),
            '\n' | '\t' => out.push(c),
            c if is_escaped_control(c) => write_control_escape(out, c),
            c => out.push(c),
        }
        quotes = if c == '"' { quotes + 1 } else { 0 };
    }
    out.push_small("\"\"\"");
}

/// Appends short strings without calling into `memcpy`.
trait PushSmall {
    fn push_small(&mut self, s: &str);
}

impl PushSmall for String {
    #[inline(always)]
    fn push_small(&mut self, s: &str) {
        crate::copy::push_str(self, s);
    }
}