deser-yaml 0.10.1

YAML 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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
//! Writes serialization events as YAML.
//!
//! Collections are held back until their first item is known so that empty
//! collections can be written as `{}` and `[]` and the layout never needs to
//! be patched afterwards.  Collections are written in block style unless
//! they are compact (see [`Layout`]), the flow policy allows them to be
//! written in flow style or there is no indentation ([`Indent::None`]).
//! For the flow policy the events of a collection are recorded while it's
//! written in flow style.  If it turns out not to fit, the output is rolled
//! back and the recorded events are written in block style.
use std::borrow::Cow;
use std::fmt::{self, Write};

use deser_core::ext::{BigInt, Datetime, Decimal, ExtValue, Number, Timestamp};
use deser_core::hints::Layout;
use deser_core::ser::EventSink;
use deser_core::ser::SerializeRef;
use deser_core::{Atom, BytesFormat, Error, ErrorKind, Event, State};

use crate::quote::{
    BlockScalar, MAX_SIMPLE_KEY_LEN, PushSmall, is_plain_safe, is_single_quote_safe, push_indent,
    write_double_quoted, write_float, write_single_quoted, write_tag,
};
use crate::resolve::{Version, is_plain_str, writes_as_plain};
use crate::ser::{FlowPolicy, Indent, MultilineStyle, NullStyle, QuoteStyle, SerializerConfig};
use crate::style::{ScalarStyle, StyleHint};
use crate::tag::NodeTag;

/// The length of the lines of long `!!binary` values.
const BINARY_LINE_LEN: usize = 76;

/// The width folded scalars use if no width is configured.
const DEFAULT_FOLD_WIDTH: usize = 80;

/// Wraps base64 into a literal block of lines.
fn wrap_binary(encoded: &str) -> BlockScalar<'static> {
    let mut lines = String::with_capacity(encoded.len() + encoded.len() / BINARY_LINE_LEN + 1);
    for (idx, chunk) in encoded.as_bytes().chunks(BINARY_LINE_LEN).enumerate() {
        if idx > 0 {
            lines.push('\n');
        }
        // base64 is ASCII
        lines.push_str(std::str::from_utf8(chunk).unwrap());
    }
    BlockScalar::from_lines(lines)
}

/// The hints of an event.
#[derive(Debug, Clone, Default)]
struct Hints {
    tag: Option<String>,
    layout: Layout,
    style: Option<ScalarStyle>,
}

/// Where the next node is written.
#[derive(Debug, Clone, Copy)]
enum Pos {
    /// The root of the document.
    Root,
    /// After an indicator (`-`, `?` or the `:` of an explicit key), the
    /// content of the node starts at the given column.
    Inline(usize),
    /// The value of a simple key of a block mapping at the given column.
    Value(usize),
    /// Inside a flow collection.
    Flow,
}

/// Where a scalar is written, which restricts its styles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Context {
    /// Block scalars are allowed.
    Block,
    /// A key: on a single line.
    Key,
    /// In a flow collection: on a single line, no flow indicators.
    Flow,
}

/// An open collection.
struct Frame {
    is_map: bool,
    flow: bool,
    /// The column of the keys or dashes (block collections).
    indent: usize,
    /// For block collections `true` if the next entry continues the current
    /// line (the first entry of a collection that follows an indicator or
    /// starts the document).  For flow collections `true` for the first
    /// entry.
    first: bool,
    /// For maps: `true` if the next node is a value.
    value: bool,
    /// For maps: `true` if the key of the current entry is explicit (`?`).
    explicit: bool,
}

/// A collection whose first event was seen but that was not written yet.
#[derive(Clone)]
struct Pending {
    is_map: bool,
    hints: Hints,
    pos: Pos,
}

/// A collection that is tentatively written in flow style.
struct Attempt {
    /// The collection, to write it in block style instead.
    pending: Pending,
    /// The state before the collection was written.
    out_len: usize,
    depth: usize,
    space: bool,
    line_done: bool,
    /// The events of the collection after its start.
    events: Vec<(Event<'static>, Hints)>,
    /// The column the collection has to end before.
    width: usize,
}

/// A scalar that was rendered for a position.
enum Scalar<'a> {
    /// Text that is written as is.
    Text(Cow<'a, str>),
    /// Short text that is written as is (numbers), without allocating.
    Short(ShortText),
    /// A block scalar.
    Block(BlockScalar<'a>),
    /// Nothing (a null with [`NullStyle::Empty`]).
    Empty,
}

impl Scalar<'_> {
    /// Detaches a scalar from the data it borrows.
    fn into_owned(self) -> Scalar<'static> {
        match self {
            Scalar::Text(text) => Scalar::Text(Cow::Owned(text.into_owned())),
            Scalar::Short(text) => Scalar::Short(text),
            Scalar::Empty => Scalar::Empty,
            // long `!!binary` values of fallbacks
            Scalar::Block(block) => Scalar::Block(block.into_owned()),
        }
    }
}

/// A short text held inline.
struct ShortText {
    buf: [u8; 48],
    len: usize,
}

impl ShortText {
    fn new() -> ShortText {
        ShortText {
            buf: [0; 48],
            len: 0,
        }
    }

    fn as_str(&self) -> &str {
        // SAFETY: only complete strings are written into the buffer (see
        // `write_str`), so it holds valid UTF-8 up to `len`.
        unsafe { std::str::from_utf8_unchecked(&self.buf[..self.len]) }
    }
}

impl fmt::Write for ShortText {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let end = self.len + s.len();
        let dst = self.buf.get_mut(self.len..end).ok_or(fmt::Error)?;
        // SAFETY: the destination has the length of the string.  Most texts
        // are short (like numbers), these are copied inline.
        unsafe { crate::copy::copy_small(s.as_ptr(), dst.as_mut_ptr(), s.len()) };
        self.len = end;
        Ok(())
    }
}

impl<'a> Scalar<'a> {
    /// Returns the text of a scalar that is written inline.
    fn text(&self) -> Option<&str> {
        match self {
            Scalar::Text(text) => Some(text),
            Scalar::Short(text) => Some(text.as_str()),
            _ => None,
        }
    }

    /// Renders a short text.
    fn short_text(value: &str) -> Scalar<'a> {
        let mut text = ShortText::new();
        text.write_str(value).expect("short text");
        Scalar::Short(text)
    }

    /// Renders a number (or other short text) with its `Display`.
    fn short(value: impl fmt::Display) -> Scalar<'a> {
        let mut text = ShortText::new();
        write!(text, "{}", value).expect("short text");
        Scalar::Short(text)
    }
}

pub(crate) struct Emitter {
    config: SerializerConfig,
    /// How bytes are written (from the state).
    bytes: BytesFormat,
    pub(crate) out: String,
    stack: Vec<Frame>,
    pending: Option<Pending>,
    attempt: Option<Attempt>,
    /// `true` if a space has to be written before the next inline content
    /// (after an indicator).
    space: bool,
    /// `true` once the root value was written.
    done: bool,
    /// `true` if the current line was already terminated (after block
    /// scalars).
    line_done: bool,
    /// The column at `column_offset` in the output.  The column is only
    /// needed for the flow policy, it's updated from the output written
    /// since it was last computed.
    column: usize,
    column_offset: usize,
    /// The column at the start of the output (the output before it was
    /// passed on, see `take_output`).
    base_column: usize,
    /// The buffer for the events of the next attempt (reused to not
    /// allocate for every attempt).
    spare_events: Vec<(Event<'static>, Hints)>,
    /// The driver is paused once the output is this long (see
    /// `EventSink`).
    pub(crate) limit: usize,
}

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

    fn pause(&mut self) -> bool {
        // the output of a collection that is written in flow style
        // tentatively can still change
        self.attempt.is_none() && self.out.len() >= self.limit
    }
}

impl Emitter {
    pub(crate) fn new(config: &SerializerConfig, out: String, bytes: BytesFormat) -> Emitter {
        Emitter {
            config: config.clone(),
            bytes,
            out,
            stack: Vec::new(),
            pending: None,
            attempt: None,
            space: false,
            done: false,
            line_done: false,
            column: 0,
            column_offset: 0,
            base_column: 0,
            spare_events: Vec::new(),
            limit: usize::MAX,
        }
    }

    /// Finishes the document, the output is complete afterwards.
    pub(crate) fn finish(&mut self) -> Result<(), Error> {
        if !self.done || !self.stack.is_empty() || self.pending.is_some() {
            return Err(Error::new(ErrorKind::InvalidState, "incomplete document"));
        }
        if !self.line_done {
            self.out.push('\n');
        }
        Ok(())
    }

    /// Returns the output written so far and continues with an empty
    /// output.
    ///
    /// This is only done while no collection is written in flow style
    /// tentatively (see `pause`), the offsets of the attempt are not moved.
    pub(crate) fn take_output(&mut self) -> String {
        debug_assert!(self.attempt.is_none());
        self.base_column = self.column();
        self.column_offset = 0;
        std::mem::take(&mut self.out)
    }

    pub(crate) fn event(&mut self, event: Event, state: &State) -> Result<(), Error> {
        let hints = Hints {
            tag: state.event::<NodeTag>().and_then(|x| x.0.clone()),
            layout: Layout::of(state),
            style: state.event::<StyleHint>().and_then(|x| x.0),
        };
        self.emit(event, hints)
    }

    fn emit(&mut self, event: Event, hints: Hints) -> Result<(), Error> {
        if let Some(ref mut attempt) = self.attempt {
            attempt.events.push((event.to_static(), hints.clone()));
            // only collections of scalars are written in flow style
            if matches!(event, Event::MapStart(_) | Event::SeqStart(_)) {
                return self.abort_attempt();
            }
        }
        if let Some(pending) = self.pending.take() {
            match event {
                Event::MapEnd if pending.is_map => return self.write_empty(pending),
                Event::SeqEnd if !pending.is_map => return self.write_empty(pending),
                ref event => {
                    let is_start = matches!(event, Event::MapStart(_) | Event::SeqStart(_));
                    if !is_start && self.may_attempt(&pending) {
                        self.start_attempt(pending, event, &hints);
                    } else {
                        self.open(pending);
                    }
                }
            }
        }
        match event {
            Event::Atom(atom) => self.atom(atom, hints)?,
            Event::MapStart(_) => self.start(true, hints)?,
            Event::SeqStart(_) => self.start(false, hints)?,
            Event::MapEnd => self.end(true)?,
            Event::SeqEnd => self.end(false)?,
        }
        if let Some(ref attempt) = self.attempt {
            let width = attempt.width;
            if self.stack.len() <= attempt.depth {
                // the collection ended and fits
                let mut events = self.attempt.take().unwrap().events;
                events.clear();
                self.spare_events = events;
            } else if self.column() > width {
                return self.abort_attempt();
            }
        }
        Ok(())
    }

    /// Returns `true` if the collection may be written in flow style if it
    /// fits.
    fn may_attempt(&self, pending: &Pending) -> bool {
        matches!(self.config.flow, FlowPolicy::LeafIfFits(_))
            && self.config.indent != Indent::None
            && pending.hints.layout == Layout::Auto
            && !matches!(pending.pos, Pos::Flow)
    }

    /// Starts writing a collection in flow style tentatively.
    fn start_attempt(&mut self, pending: Pending, event: &Event, hints: &Hints) {
        let FlowPolicy::LeafIfFits(width) = self.config.flow else {
            unreachable!();
        };
        self.attempt = Some(Attempt {
            pending: pending.clone(),
            out_len: self.out.len(),
            depth: self.stack.len(),
            space: self.space,
            line_done: self.line_done,
            events: {
                let mut events = std::mem::take(&mut self.spare_events);
                events.push((event.to_static(), hints.clone()));
                events
            },
            width,
        });
        self.open_flow(pending);
    }

    /// Rolls back a collection written in flow style and writes it in block
    /// style.
    #[cold]
    fn abort_attempt(&mut self) -> Result<(), Error> {
        let attempt = self.attempt.take().unwrap();
        self.out.truncate(attempt.out_len);
        if self.column_offset > attempt.out_len {
            // the column was computed for output that is gone, count the
            // line again
            match self.out.rfind('\n') {
                Some(idx) => {
                    self.column = 0;
                    self.column_offset = idx + 1;
                }
                None => {
                    self.column = self.base_column;
                    self.column_offset = 0;
                }
            }
        }
        self.stack.truncate(attempt.depth);
        self.space = attempt.space;
        self.line_done = attempt.line_done;
        self.pending = None;
        self.open_block(attempt.pending);
        let mut events = attempt.events;
        for (event, hints) in events.drain(..) {
            self.emit(event, hints)?;
        }
        if events.capacity() > self.spare_events.capacity() {
            self.spare_events = events;
        }
        Ok(())
    }

    /// Returns the current column.
    fn column(&mut self) -> usize {
        let new = &self.out[self.column_offset..];
        match new.rfind('\n') {
            Some(idx) => self.column = new[idx + 1..].chars().count(),
            None => self.column += new.chars().count(),
        }
        self.column_offset = self.out.len();
        self.column
    }

    /// Returns `true` if the current node is in a flow collection.
    fn in_flow(&self) -> bool {
        self.stack.last().is_some_and(|x| x.flow)
    }

    /// Starts a map or sequence, it's written once the next event is known.
    fn start(&mut self, is_map: bool, hints: Hints) -> Result<(), Error> {
        let pos = match self.begin_node()? {
            Some(pos) => pos,
            // collections as keys are explicit
            None => self.begin_explicit_key(),
        };
        self.pending = Some(Pending { is_map, hints, pos });
        Ok(())
    }

    fn end(&mut self, is_map: bool) -> Result<(), Error> {
        match self.stack.pop() {
            Some(frame) if frame.is_map == is_map && (!is_map || !frame.value) => {
                if frame.flow {
                    self.out.push(if is_map { '}' } else { ']' });
                }
            }
            _ => return Err(Error::new(ErrorKind::InvalidState, "unexpected end event")),
        }
        self.complete();
        Ok(())
    }

    /// Writes an empty collection.
    fn write_empty(&mut self, pending: Pending) -> Result<(), Error> {
        self.write_inline_start(pending.hints.tag.as_deref());
        self.out
            .push_small(if pending.is_map { "{}" } else { "[]" });
        self.complete();
        Ok(())
    }

    /// Writes the start of a non-empty collection.
    fn open(&mut self, pending: Pending) {
        if matches!(pending.pos, Pos::Flow)
            || pending.hints.layout == Layout::Compact
            || self.config.indent == Indent::None
        {
            self.open_flow(pending);
        } else {
            self.open_block(pending);
        }
    }

    fn open_flow(&mut self, pending: Pending) {
        self.write_inline_start(pending.hints.tag.as_deref());
        self.out.push(if pending.is_map { '{' } else { '[' });
        self.stack.push(Frame {
            is_map: pending.is_map,
            flow: true,
            indent: 0,
            first: true,
            value: false,
            explicit: false,
        });
    }

    fn open_block(&mut self, pending: Pending) {
        let (indent, first) = match pending.pos {
            Pos::Root => {
                if let Some(ref tag) = pending.hints.tag {
                    write_tag(&mut self.out, tag);
                    self.out.push('\n');
                }
                (0, true)
            }
            Pos::Inline(column) => match pending.hints.tag {
                Some(ref tag) => {
                    self.flush_space();
                    write_tag(&mut self.out, tag);
                    (column, false)
                }
                None => (column, true),
            },
            Pos::Value(key_column) => {
                if let Some(ref tag) = pending.hints.tag {
                    self.flush_space();
                    write_tag(&mut self.out, tag);
                }
                self.space = false;
                let indent = if pending.is_map || self.config.indent_sequences {
                    key_column + self.config.indent_width()
                } else {
                    key_column
                };
                (indent, false)
            }
            Pos::Flow => unreachable!("collections in flow collections are flow"),
        };
        self.stack.push(Frame {
            is_map: pending.is_map,
            flow: false,
            indent,
            first,
            value: false,
            explicit: false,
        });
    }

    /// Writes what precedes a node in its parent and returns the position
    /// of the node.  Returns `None` for keys, they are written by the caller.
    fn begin_node(&mut self) -> Result<Option<Pos>, Error> {
        let Some(frame) = self.stack.last_mut() else {
            if self.done {
                return Err(Error::new(
                    ErrorKind::InvalidState,
                    "a document can only contain one value",
                ));
            }
            return Ok(Some(Pos::Root));
        };
        if frame.flow {
            if frame.is_map && frame.value {
                if frame.explicit {
                    self.out.push(':');
                    self.space = true;
                }
                return Ok(Some(Pos::Flow));
            }
            if !std::mem::replace(&mut frame.first, false) {
                self.out.push(',');
                self.space = true;
            }
            return Ok(if frame.is_map { None } else { Some(Pos::Flow) });
        }
        let indent = frame.indent;
        if !frame.is_map {
            self.begin_entry();
            self.out.push('-');
            self.space = true;
            return Ok(Some(Pos::Inline(indent + 2)));
        }
        if !frame.value {
            return Ok(None);
        }
        if frame.explicit {
            self.newline(indent);
            self.out.push(':');
            self.space = true;
            Ok(Some(Pos::Inline(indent + 2)))
        } else {
            Ok(Some(Pos::Value(indent)))
        }
    }

    /// Moves to the start of the next entry of the current block collection.
    fn begin_entry(&mut self) {
        let frame = self.stack.last_mut().unwrap();
        if frame.flow {
            // the separator was written by `begin_node`
            self.flush_space();
            return;
        }
        let indent = frame.indent;
        if std::mem::replace(&mut frame.first, false) {
            self.flush_space();
        } else {
            self.newline(indent);
        }
    }

    /// Writes the `?` of an explicit key and returns the position of the key.
    fn begin_explicit_key(&mut self) -> Pos {
        self.begin_entry();
        let frame = self.stack.last_mut().unwrap();
        frame.explicit = true;
        let pos = if frame.flow {
            Pos::Flow
        } else {
            Pos::Inline(frame.indent + 2)
        };
        self.out.push('?');
        self.space = true;
        pos
    }

    /// Records that a node was completed.
    fn complete(&mut self) {
        match self.stack.last_mut() {
            Some(frame) if frame.is_map => {
                if frame.value {
                    frame.explicit = false;
                }
                frame.value = !frame.value;
            }
            Some(_) => {}
            None => self.done = true,
        }
    }

    fn newline(&mut self, indent: usize) {
        if !std::mem::take(&mut self.line_done) {
            self.out.push('\n');
        }
        push_indent(&mut self.out, indent);
        self.space = false;
    }

    fn flush_space(&mut self) {
        if self.space {
            self.out.push(' ');
            self.space = false;
        }
    }

    /// Writes the separator and the tag before inline content.
    fn write_inline_start(&mut self, tag: Option<&str>) {
        self.flush_space();
        if let Some(tag) = tag {
            write_tag(&mut self.out, tag);
            self.out.push(' ');
        }
    }

    fn atom(&mut self, atom: Atom, hints: Hints) -> Result<(), Error> {
        // bytes that are sequences are written as sequences of integers
        if let Atom::Bytes(ref bytes) = atom
            && !self.config.binary
            && bytes.fallback.copied().unwrap_or(self.bytes) == BytesFormat::SEQ
        {
            self.emit(
                Event::seq_start(),
                Hints {
                    layout: hints.layout,
                    tag: hints.tag,
                    style: None,
                },
            )?;
            for &byte in bytes.iter() {
                self.emit(Event::Atom(Atom::U64(byte.into())), Hints::default())?;
            }
            return self.emit(Event::SeqEnd, Hints::default());
        }

        let pos = match self.begin_node()? {
            Some(pos) => pos,
            None => return self.key(atom, hints),
        };
        let context = match pos {
            Pos::Flow => Context::Flow,
            // without indentation a scalar document is on a single line
            _ if self.config.indent == Indent::None => Context::Key,
            _ => Context::Block,
        };
        let (scalar, implicit_tag) = self.render(&atom, context, hints.style)?;
        let tag = hints.tag.as_deref().or(implicit_tag);
        match scalar {
            // nothing to write, the indicator or key stands on its own
            Scalar::Empty if !matches!(pos, Pos::Root) && tag.is_none() => {
                self.space = false;
            }
            Scalar::Empty => {
                self.write_inline_start(tag);
                self.out.push_small("null");
            }
            Scalar::Text(_) | Scalar::Short(_) => {
                self.write_inline_start(tag);
                self.out.push_small(scalar.text().unwrap());
            }
            Scalar::Block(block) => {
                self.write_inline_start(tag);
                // the indentation indicator is relative to the parent node
                let (column, parent) = match pos {
                    // the document is at indentation 0 for indicators
                    Pos::Root => (self.config.indent_width(), 0),
                    Pos::Inline(column) => (column, column - 2),
                    Pos::Value(key_column) => (key_column + self.config.indent_width(), key_column),
                    Pos::Flow => unreachable!("no block scalars in flow collections"),
                };
                block.write_header(&mut self.out, column - parent);
                self.out.push('\n');
                block.write_body(&mut self.out, column);
                self.line_done = true;
            }
        }
        self.complete();
        Ok(())
    }

    /// Writes a scalar key.
    fn key(&mut self, atom: Atom, hints: Hints) -> Result<(), Error> {
        let context = if self.in_flow() {
            Context::Flow
        } else {
            Context::Key
        };
        let (scalar, implicit_tag) = self.render(&atom, context, hints.style)?;
        let tag = hints.tag.as_deref().or(implicit_tag);
        let text = match scalar {
            Scalar::Empty => "null",
            Scalar::Block(_) => unreachable!("keys are never block scalars"),
            ref scalar => scalar.text().unwrap(),
        };
        if text.len() > MAX_SIMPLE_KEY_LEN {
            self.begin_explicit_key();
            self.write_inline_start(tag);
            self.out.push_small(text);
        } else {
            self.begin_entry();
            self.write_inline_start(tag);
            self.out.push_small(text);
            self.out.push(':');
            self.space = true;
        }
        self.complete();
        Ok(())
    }

    /// Renders an atom as scalar.
    ///
    /// Returns the scalar and a tag that is implied by the value (such as
    /// `!!binary`).
    fn render<'a>(
        &self,
        atom: &'a Atom,
        context: Context,
        style: Option<ScalarStyle>,
    ) -> Result<(Scalar<'a>, Option<&'static str>), Error> {
        Ok(match *atom {
            Atom::Null => match (self.config.null_style, context) {
                (NullStyle::Tilde, _) => (Scalar::Text("~".into()), None),
                (NullStyle::Empty, Context::Block) => (Scalar::Empty, None),
                _ => (Scalar::Text("null".into()), None),
            },
            Atom::Bool(value) => (
                Scalar::Text(if value { "true" } else { "false" }.into()),
                None,
            ),
            Atom::U64(value) => (Scalar::short_text(itoa::Buffer::new().format(value)), None),
            Atom::I64(value) => (Scalar::short_text(itoa::Buffer::new().format(value)), None),
            Atom::F64(value) => {
                let mut text = ShortText::new();
                write_float(&mut text, value);
                (Scalar::Short(text), None)
            }
            Atom::F32(value) => {
                let mut text = ShortText::new();
                write_float(&mut text, value);
                (Scalar::Short(text), None)
            }
            Atom::Char(value) => (
                self.render_owned_str(value.to_string(), context, style),
                None,
            ),
            // lexical atoms are strings, they are quoted where YAML would
            // read them as another type
            Atom::Str(ref value) | Atom::Lexical(ref value) => {
                (self.render_str(value, context, style), None)
            }
            Atom::Bytes(ref bytes) => {
                let format = if self.config.binary {
                    BytesFormat::BASE64
                } else {
                    bytes.fallback.copied().unwrap_or(self.bytes)
                };
                // sequences are handled before, keys are always strings
                let encoded = format
                    .encode(bytes)
                    .or_else(|| BytesFormat::BASE64.encode(bytes))
                    .unwrap_or_default();
                if self.config.binary {
                    let tag = Some("tag:yaml.org,2002:binary");
                    if encoded.is_empty() {
                        (Scalar::Text("\"\"".into()), tag)
                    } else if encoded.len() > BINARY_LINE_LEN && context == Context::Block {
                        (Scalar::Block(wrap_binary(&encoded)), tag)
                    } else {
                        (Scalar::Text(encoded.into()), tag)
                    }
                } else {
                    (self.render_owned_str(encoded, context, style), None)
                }
            }
            Atom::Ext(ref ext) => return self.render_ext(ext, context, style),
            // values whose type was inferred from text keep their text if
            // it's read as the same value, otherwise they are written as
            // their value
            Atom::Implicit(ref value) if writes_as_plain(value, self.config.compat) => {
                (Scalar::Text(Cow::Borrowed(value.text().as_str())), None)
            }
            Atom::Implicit(ref value) => {
                let value = value.value().to_atom();
                let (scalar, tag) = self.render(&value, context, style)?;
                (scalar.into_owned(), tag)
            }
            _ => return Err(Error::new(ErrorKind::UnsupportedType, "unknown atom")),
        })
    }

    #[cold]
    fn render_ext<'a>(
        &self,
        ext: &'a ExtValue,
        context: Context,
        style: Option<ScalarStyle>,
    ) -> Result<(Scalar<'a>, Option<&'static str>), Error> {
        if let Some(value) = ext.downcast_ref::<u128>() {
            return Ok((Scalar::short(value), None));
        }
        if let Some(value) = ext.downcast_ref::<i128>() {
            return Ok((Scalar::short(value), None));
        }
        if let Some(value) = ext.downcast_ref::<BigInt>() {
            return Ok((Scalar::Text(value.to_string().into()), None));
        }
        // number literals keep their text if YAML reads it as number
        if let Some(value) = ext.downcast_value_ref::<Number>()
            && self.is_number(value.as_str())
        {
            return Ok((Scalar::Text(value.as_str().into()), None));
        }
        if let Some(value) = ext.downcast_ref::<Decimal>()
            && self.is_number(value.as_str())
        {
            return Ok((Scalar::Text(value.as_str().into()), None));
        }
        let datetime = ext.downcast_ref::<Datetime>().copied().or_else(|| {
            ext.downcast_ref::<Timestamp>()
                .and_then(|x| x.to_datetime())
        });
        if let Some(value) = datetime {
            return Ok(self.render_datetime(value, context, style));
        }
        match ext.fallback() {
            Atom::Ext(_) => Err(Error::new(
                ErrorKind::UnsupportedType,
                format!("YAML does not support {}", ext.name()),
            )),
            // strings of fallbacks are always on a single line as they do
            // not outlive this call
            Atom::Str(value) | Atom::Lexical(value) => Ok((
                self.render_owned_str(value.into_owned(), context, style),
                None,
            )),
            fallback => {
                let (scalar, tag) = self.render(&fallback, context, style)?;
                Ok((scalar.into_owned(), tag))
            }
        }
    }

    /// Renders a date / time.
    ///
    /// Timestamps (dates and date-times with offset) are written plain (or
    /// tagged), other values (local date-times and times) as strings as YAML
    /// has no representation for them.
    fn render_datetime<'a>(
        &self,
        value: Datetime,
        context: Context,
        style: Option<ScalarStyle>,
    ) -> (Scalar<'a>, Option<&'static str>) {
        let text = value.to_string();
        let is_timestamp = value.date.is_some() && (value.time.is_none() || value.offset.is_some());
        if !is_timestamp {
            return (self.render_owned_str(text, context, style), None);
        }
        let tag = self
            .config
            .timestamp_tag
            .then_some("tag:yaml.org,2002:timestamp");
        (Scalar::Text(text.into()), tag)
    }

    /// Returns `true` if text is read as number in all versions.
    fn is_number(&self, s: &str) -> bool {
        !is_plain_str(s, Version::V1_2)
            && (self.config.compat == Version::V1_2 || !is_plain_str(s, Version::V1_1))
            && s.parse::<f64>().is_ok()
    }

    /// Renders an owned string, never as block scalar.
    fn render_owned_str<'a>(
        &self,
        value: String,
        context: Context,
        style: Option<ScalarStyle>,
    ) -> Scalar<'a> {
        let context = match context {
            Context::Block => Context::Key,
            other => other,
        };
        match self.render_str(&value, context, style) {
            Scalar::Text(text) => Scalar::Text(Cow::Owned(text.into_owned())),
            _ => unreachable!("strings outside of blocks are text"),
        }
    }

    /// Renders a string.
    ///
    /// The requested style is used if the string can be written in it,
    /// otherwise the style that the configuration asks for (if possible).
    fn render_str<'a>(
        &self,
        value: &'a str,
        context: Context,
        style: Option<ScalarStyle>,
    ) -> Scalar<'a> {
        let block = context == Context::Block;
        let flow = context == Context::Flow;
        let fold_width = self.config.fold_width.unwrap_or(DEFAULT_FOLD_WIDTH);
        match style {
            Some(ScalarStyle::Plain) if is_plain_safe(value, self.config.compat, flow) => {
                return Scalar::Text(value.into());
            }
            Some(ScalarStyle::SingleQuoted) if is_single_quote_safe(value) => {
                let mut out = String::with_capacity(value.len() + 2);
                write_single_quoted(&mut out, value);
                return Scalar::Text(out.into());
            }
            Some(ScalarStyle::DoubleQuoted) => {
                let mut out = String::with_capacity(value.len() + 2);
                write_double_quoted(&mut out, value);
                return Scalar::Text(out.into());
            }
            Some(ScalarStyle::Literal) if block => {
                if let Some(block) = BlockScalar::literal(value) {
                    return Scalar::Block(block);
                }
            }
            Some(ScalarStyle::Folded) if block => {
                if let Some(block) =
                    BlockScalar::folded(value, fold_width).or_else(|| BlockScalar::literal(value))
                {
                    return Scalar::Block(block);
                }
            }
            _ => {}
        }

        if block && !self.config.quote_all {
            if value.contains('\n') {
                if self.config.multiline == MultilineStyle::Literal
                    && let Some(block) = BlockScalar::literal(value)
                {
                    return Scalar::Block(block);
                }
            } else if let Some(width) = self.config.fold_width
                && BlockScalar::should_fold(value, width)
                && let Some(block) = BlockScalar::folded(value, width)
            {
                return Scalar::Block(block);
            }
        }
        if !self.config.quote_all && is_plain_safe(value, self.config.compat, flow) {
            return Scalar::Text(Cow::Borrowed(value));
        }
        let mut out = String::with_capacity(value.len() + 2);
        if self.config.quote_style == QuoteStyle::Single && is_single_quote_safe(value) {
            write_single_quoted(&mut out, value);
        } else {
            write_double_quoted(&mut out, value);
        }
        Scalar::Text(out.into())
    }
}