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
//! Decides how scalars are written.
use std::borrow::Cow;
use std::fmt::Write;

use crate::resolve::{Version, is_plain_str, is_yaml11_implicit};

/// The longest simple (implicit) key the YAML specification allows.
pub(crate) const MAX_SIMPLE_KEY_LEN: usize = 1024;

/// Returns `true` if the character is printable in YAML.
fn is_printable(c: char) -> bool {
    matches!(c,
        '\t' | '\n' | '\r' | '\u{20}'..='\u{7e}' | '\u{85}' | '\u{a0}'..='\u{d7ff}'
        | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}')
}

/// Returns `true` if the character can only be written escaped in a
/// double-quoted scalar.
///
/// Besides non-printable characters these are line breaks (which fold in
/// plain and single-quoted scalars), tabs and the byte order mark.
fn needs_escape(c: char) -> bool {
    !is_printable(c)
        || matches!(
            c,
            '\n' | '\r' | '\t' | '\u{85}' | '\u{2028}' | '\u{2029}' | '\u{feff}'
        )
}

/// Returns `true` if the string can be written as literal block scalar.
fn is_block_safe(s: &str) -> bool {
    s.chars().all(|c| {
        is_printable(c) && !matches!(c, '\r' | '\u{85}' | '\u{2028}' | '\u{2029}' | '\u{feff}')
    })
}

/// Returns `true` if a string can be written as plain scalar.
///
/// It must not contain anything that has a meaning in YAML, and it must be
/// resolved as string by readers of YAML 1.2 and, if the compatibility
/// version is YAML 1.1, by readers of YAML 1.1.  In flow collections the
/// flow indicators are not allowed either.
pub(crate) fn is_plain_safe(s: &str, compat: Version, flow: bool) -> bool {
    let bytes = s.as_bytes();
    let (Some(&first), Some(&last)) = (bytes.first(), bytes.last()) else {
        return false;
    };
    if first == b' ' || last == b' ' {
        return false;
    }
    match first {
        // indicators, `-`, `?` and `:` are fine if followed by a character
        b'-' | b'?' | b':' => {
            if matches!(bytes.get(1), None | Some(b' ')) {
                return false;
            }
        }
        b',' | b'[' | b']' | b'{' | b'}' | b'#' | b'&' | b'*' | b'!' | b'|' | b'>' | b'\''
        | b'"' | b'%' | b'@' | b'`' => return false,
        _ => {}
    }
    if s.chars().any(needs_escape) {
        return false;
    }
    if flow && s.contains([',', '[', ']', '{', '}']) {
        return false;
    }
    // YAML 1.1 readers (like PyYAML) end plain scalars in flow collections
    // at `:` and `?`
    if flow && compat == Version::V1_1 && s.contains([':', '?']) {
        return false;
    }
    // mapping values and comments, `a:b` and `a#b` are fine
    if s.contains(": ") || s.ends_with(':') || s.contains(" #") {
        return false;
    }
    // document markers
    if (s.starts_with("---") || s.starts_with("...")) && matches!(bytes.get(3), None | Some(b' ')) {
        return false;
    }
    // merge keys
    if s == "<<" {
        return false;
    }
    if !is_plain_str(s, Version::V1_2) {
        return false;
    }
    if compat == Version::V1_1 && (!is_plain_str(s, Version::V1_1) || is_yaml11_implicit(s)) {
        return false;
    }
    true
}

/// Returns `true` if a string can be written single-quoted.
pub(crate) fn is_single_quote_safe(s: &str) -> bool {
    !s.chars().any(needs_escape)
}

/// Writes a single-quoted scalar.
pub(crate) fn write_single_quoted(out: &mut String, s: &str) {
    out.push('\'');
    for c in s.chars() {
        if c == '\'' {
            out.push_str("''");
        } else {
            out.push(c);
        }
    }
    out.push('\'');
}

/// Writes a double-quoted scalar.
pub(crate) fn write_double_quoted(out: &mut String, s: &str) {
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\0' => out.push_str("\\0"),
            '\u{7}' => out.push_str("\\a"),
            '\u{8}' => out.push_str("\\b"),
            '\t' => out.push_str("\\t"),
            '\n' => out.push_str("\\n"),
            '\u{b}' => out.push_str("\\v"),
            '\u{c}' => out.push_str("\\f"),
            '\r' => out.push_str("\\r"),
            '\u{1b}' => out.push_str("\\e"),
            '\u{85}' => out.push_str("\\N"),
            '\u{a0}' => out.push_str("\\_"),
            '\u{2028}' => out.push_str("\\L"),
            '\u{2029}' => out.push_str("\\P"),
            c if needs_escape(c) => match c as u32 {
                n @ 0..=0xff => write!(out, "\\x{:02x}", n).unwrap(),
                n @ 0x100..=0xffff => write!(out, "\\u{:04x}", n).unwrap(),
                n => write!(out, "\\U{:08x}", n).unwrap(),
            },
            c => out.push(c),
        }
    }
    out.push('"');
}

/// The smallest width that folded lines are wrapped to, regardless of the
/// indentation.
const MIN_FOLD_WIDTH: usize = 20;

/// A block scalar (literal `|` or folded `>`).
pub(crate) struct BlockScalar<'a> {
    /// The content without the trailing line breaks.
    content: Cow<'a, str>,
    /// The number of trailing line breaks.
    trailing: usize,
    /// `true` if an indentation indicator is required.
    needs_indicator: bool,
    /// The width to fold lines at, `None` for literal block scalars.
    fold: Option<usize>,
}

impl<'a> BlockScalar<'a> {
    /// Returns a literal block scalar for a string if it can be written as
    /// one.
    pub(crate) fn literal(s: &'a str) -> Option<BlockScalar<'a>> {
        if s.is_empty() || !is_block_safe(s) {
            return None;
        }
        let content = s.trim_end_matches('\n');
        // the indentation is detected from the first line with content,
        // leading spaces (or lines of spaces) need an explicit indicator
        let needs_indicator = content
            .split('\n')
            .find(|line| !line.is_empty())
            .is_some_and(|line| line.starts_with(' '));
        Some(BlockScalar {
            content: Cow::Borrowed(content),
            trailing: s.len() - content.len(),
            needs_indicator,
            fold: None,
        })
    }

    /// Returns a folded block scalar for a string if it can be written as
    /// one.
    ///
    /// Folding only changes the layout if the reader restores the string
    /// exactly: lines are only broken at single spaces between other
    /// characters, lines must not start or end with whitespace (these are not
    /// folded by readers) and the string must not start with a line break.
    pub(crate) fn folded(s: &'a str, width: usize) -> Option<BlockScalar<'a>> {
        let mut rv = BlockScalar::literal(s)?;
        let foldable = !s.starts_with('\n')
            && rv
                .content
                .split('\n')
                .all(|line| !line.starts_with([' ', '\t']) && !line.ends_with([' ', '\t']));
        if !foldable {
            return None;
        }
        rv.fold = Some(width);
        Some(rv)
    }

    /// Returns `true` if a single-line string is worth folding at the width.
    pub(crate) fn should_fold(s: &str, width: usize) -> bool {
        s.len() > width && fold_points(s).next().is_some()
    }

    /// Detaches the block scalar from the data it borrows.
    pub(crate) fn into_owned(self) -> BlockScalar<'static> {
        BlockScalar {
            content: Cow::Owned(self.content.into_owned()),
            trailing: self.trailing,
            needs_indicator: self.needs_indicator,
            fold: self.fold,
        }
    }

    /// Creates a literal block from lines without leading spaces.
    pub(crate) fn from_lines(lines: String) -> BlockScalar<'static> {
        BlockScalar {
            content: Cow::Owned(lines),
            trailing: 1,
            needs_indicator: false,
            fold: None,
        }
    }

    /// Writes the header (`|` or `>` with indicators).
    ///
    /// `indicator` is the indentation of the content relative to the parent
    /// node, it's only written if required.
    pub(crate) fn write_header(&self, out: &mut String, indicator: usize) {
        out.push(if self.fold.is_some() { '>' } else { '|' });
        if self.needs_indicator {
            write!(out, "{}", indicator).unwrap();
        }
        match self.trailing {
            0 => out.push('-'),
            // clipping keeps one line break but empty content has none
            1 if !self.content.is_empty() => {}
            _ => out.push('+'),
        }
    }

    /// Writes the lines of the content, each ending with a line break.
    pub(crate) fn write_body(&self, out: &mut String, indent: usize) {
        if self.content.is_empty() {
            // only line breaks (kept with the `+` indicator)
            for _ in 0..self.trailing {
                out.push('\n');
            }
            return;
        }
        let mut prev_empty = true;
        for (idx, line) in self.content.split('\n').enumerate() {
            // in folded scalars a line break between two lines is folded
            // into a space, a line break needs an additional empty line.
            if idx > 0 && self.fold.is_some() && !prev_empty {
                out.push('\n');
            }
            prev_empty = line.is_empty();
            if !line.is_empty() {
                push_indent(out, indent);
                match self.fold {
                    Some(width) => write_folded_line(out, line, indent, width),
                    None => out.push_str(line),
                }
            }
            out.push('\n');
        }
        for _ in 1..self.trailing {
            out.push('\n');
        }
    }
}

/// Returns the positions of the spaces a line can be folded at: single
/// spaces between other characters.
fn fold_points(line: &str) -> impl Iterator<Item = usize> + '_ {
    let bytes = line.as_bytes();
    (1..bytes.len().saturating_sub(1)).filter(move |&idx| {
        bytes[idx] == b' '
            && !bytes[idx - 1].is_ascii_whitespace()
            && !bytes[idx + 1].is_ascii_whitespace()
    })
}

/// Writes a line of a folded scalar, broken at spaces so that the lines do
/// not exceed the width if possible.
fn write_folded_line(out: &mut String, line: &str, indent: usize, width: usize) {
    let available = width.saturating_sub(indent).max(MIN_FOLD_WIDTH);
    let mut start = 0;
    let mut last_point = None;
    for point in fold_points(line) {
        if point - start > available
            && let Some(last) = last_point
        {
            out.push_str(&line[start..last]);
            out.push('\n');
            push_indent(out, indent);
            start = last + 1;
        }
        last_point = Some(point);
    }
    if line.len() - start > available
        && let Some(last) = last_point
        && last > start
    {
        out.push_str(&line[start..last]);
        out.push('\n');
        push_indent(out, indent);
        start = last + 1;
    }
    out.push_str(&line[start..]);
}

/// Writes spaces for an indentation.
pub(crate) fn push_indent(out: &mut String, indent: usize) {
    const SPACES: &str = "                                                                ";
    match SPACES.get(..indent) {
        Some(spaces) => out.push_small(spaces),
        None => out.extend(std::iter::repeat_n(' ', indent)),
    }
}

/// Writes a float so that readers of YAML 1.1 and 1.2 read it as float.
///
/// YAML 1.1 requires a `.` in floats and a sign in exponents.  The text is
/// the shortest that reads back as the same value of its type (`f32` or
/// `f64`).
pub(crate) fn write_float<W: Write, F: zmij::Float + Into<f64>>(out: &mut W, value: F) {
    let wide: f64 = value.into();
    if wide.is_nan() {
        out.write_str(".nan").unwrap();
    } else if wide.is_infinite() {
        out.write_str(if wide > 0.0 { ".inf" } else { "-.inf" })
            .unwrap();
    } else {
        let mut buffer = zmij::Buffer::new();
        let formatted = buffer.format_finite(value);
        // the exponent always has a sign, the mantissa needs a `.`.  The
        // exponent is at most `e-324`, so only the last five bytes can be
        // the `e`.
        let bytes = formatted.as_bytes();
        let tail = bytes.len().saturating_sub(5);
        match bytes[tail..].iter().rposition(|&b| b == b'e') {
            Some(e) if !bytes[..tail + e].contains(&b'.') => {
                let e = tail + e;
                out.write_str(&formatted[..e]).unwrap();
                out.write_str(".0e").unwrap();
                out.write_str(&formatted[e + 1..]).unwrap();
            }
            _ => out.write_str(formatted).unwrap(),
        }
    }
}

/// Returns `true` if the character can be part of a tag shorthand suffix.
fn is_tag_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || "-#;/?:@&=+$_.~*'()".contains(c)
}

/// Returns `true` if the character can be part of a verbatim tag.
fn is_uri_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || "-#;/?:@&=+$,_.!~*'()[]".contains(c)
}

const YAML_TAG_PREFIX: &str = "tag:yaml.org,2002:";

/// Writes a tag, using the `!!` shorthand for tags of yaml.org, the tag
/// itself for local tags and the verbatim form for all others.
pub(crate) fn write_tag(out: &mut String, tag: &str) {
    if let Some(suffix) = tag.strip_prefix(YAML_TAG_PREFIX)
        && !suffix.is_empty()
        && suffix.chars().all(is_tag_char)
    {
        out.push_str("!!");
        out.push_str(suffix);
    } else if tag == "!" {
        out.push('!');
    } else if let Some(suffix) = tag.strip_prefix('!')
        && !suffix.is_empty()
        && suffix.chars().all(is_tag_char)
    {
        out.push_str(tag);
    } else {
        out.push_str("!<");
        for c in tag.chars() {
            if is_uri_char(c) || (c == '%') {
                out.push(c);
            } else {
                let mut buf = [0; 4];
                for byte in c.encode_utf8(&mut buf).bytes() {
                    write!(out, "%{:02X}", byte).unwrap();
                }
            }
        }
        out.push('>');
    }
}

/// Appends short strings without calling into `memcpy`.
pub(crate) 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);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_plain() {
        for s in [
            "hello", "a b", "-a", "?a", "::1", "a:b", "a#b", "a,b", "yes!", "2001-1",
        ] {
            assert!(is_plain_safe(s, Version::V1_2, false), "{}", s);
        }
        for s in [
            "", " a", "a ", "- a", "-", "a: b", "a:", "a #b", "#a", "---", "...", "--- a", "<<",
            "true", "null", "~", "1", "1.5", "0x10", ".inf", "a\nb", "a\tb", "'a", "!a", "&a",
            "*a", "%a", "@a", "`a", "|", ">",
        ] {
            assert!(!is_plain_safe(s, Version::V1_2, false), "{:?}", s);
        }
        // strings that are only special in YAML 1.1
        for s in [
            "yes",
            "on",
            "Off",
            "y",
            "0b10",
            "1:30",
            "1_000",
            "2001-12-14",
            "=",
        ] {
            assert!(is_plain_safe(s, Version::V1_2, false), "{}", s);
            assert!(!is_plain_safe(s, Version::V1_1, false), "{}", s);
        }
    }

    #[test]
    fn test_plain_in_flow() {
        for s in ["a,b", "a[b", "a]", "a{", "a}"] {
            assert!(is_plain_safe(s, Version::V1_2, false), "{}", s);
            assert!(!is_plain_safe(s, Version::V1_2, true), "{}", s);
        }
        for s in [":a", "?a", "a?", "a:b"] {
            assert!(is_plain_safe(s, Version::V1_2, true), "{}", s);
            assert!(!is_plain_safe(s, Version::V1_1, true), "{}", s);
        }
    }

    #[test]
    fn test_float() {
        let f = |value: f64| {
            let mut out = String::new();
            write_float(&mut out, value);
            out
        };
        assert_eq!(f(1.0), "1.0");
        assert_eq!(f(1e20), "1.0e+20");
        assert_eq!(f(1.5e-7), "1.5e-7");
        // the longest exponents
        assert_eq!(f(5e-324), "5.0e-324");
        assert_eq!(f(-1e300), "-1.0e+300");
        assert_eq!(f(1.7976931348623157e308), "1.7976931348623157e+308");
        assert_eq!(f(-0.0), "-0.0");
        assert_eq!(f(f64::NAN), ".nan");
        assert_eq!(f(f64::NEG_INFINITY), "-.inf");
    }

    #[test]
    fn test_tags() {
        let t = |tag: &str| {
            let mut out = String::new();
            write_tag(&mut out, tag);
            out
        };
        assert_eq!(t("tag:yaml.org,2002:set"), "!!set");
        assert_eq!(t("!color"), "!color");
        assert_eq!(t("!"), "!");
        assert_eq!(
            t("tag:example.com,2000:app/foo"),
            "!<tag:example.com,2000:app/foo>"
        );
        assert_eq!(t("!a b"), "!<!a%20b>");
    }
}