ayaml 1.0.0

A safe, pure-Rust YAML parser, event stream, value model, Serde layer, and emitter
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
//! Scalar resolution for the YAML 1.2.2 default profile.
//!
//! Parser events retain raw scalar text, style, tag, anchor, and span; this
//! module resolves one scalar to a `Value`, and the event keeps the rest of
//! its metadata.

use std::borrow::Cow;

use crate::error::{Error, ErrorCode, ErrorKind};
use crate::event::ScalarStyle;
use crate::number::Number;
use crate::tag::{Tag, TaggedValue};
use crate::value::Value;

/// Resolve a scalar under the active parsing profile.
pub(crate) fn resolve_scalar(
    text: &str,
    style: ScalarStyle,
    tag: Option<&Tag>,
) -> Result<Value, Error> {
    resolve_scalar_cow(Cow::Borrowed(text), style, tag)
}

/// Resolve a scalar under the active parsing profile, moving an owned decoded string directly
/// into `Value::String` without an extra copy.
pub(crate) fn resolve_scalar_cow(
    text: Cow<'_, str>,
    style: ScalarStyle,
    tag: Option<&Tag>,
) -> Result<Value, Error> {
    if let Some(tag) = tag {
        if tag.is_core() {
            return resolve_explicit_core_cow(text, tag.suffix(), tag);
        }
        // A custom tag keeps its payload resolved as if untagged:
        // `!Flag true` holds a bool. The non-specific
        // tag `!` makes a scalar a string (YAML 1.2.2 section 6.9.1).
        let payload = if tag.is_non_specific() {
            Value::String(text.into_owned())
        } else {
            resolve_scalar_cow(text, style, None)?
        };
        return Ok(Value::from(TaggedValue::new(tag.clone(), payload)));
    }

    if style != ScalarStyle::Plain {
        return Ok(Value::String(text.into_owned()));
    }
    if let Some(value) = resolve_plain(&text) {
        return Ok(value);
    }
    Ok(Value::String(text.into_owned()))
}

/// Whether an untagged plain scalar with this text resolves to a string.
/// Unlike [`resolve_scalar`], this does not allocate.
pub(crate) fn plain_resolves_to_string(text: &str) -> bool {
    resolve_plain(text).is_none()
}

/// Resolve untagged plain text to a null, bool or number, or `None` when it
/// is a string. Integers are exact up to 128 bits. A wider decimal
/// integer is a float, and a wider `0x`/`0o`/`0b` integer is a string.
pub(crate) fn resolve_plain(text: &str) -> Option<Value> {
    match text.as_bytes().first().copied() {
        None => Some(Value::Null),
        Some(b'~') => (text.len() == 1).then_some(Value::Null),
        Some(b'n' | b'N') => is_null(text).then_some(Value::Null),
        Some(b't' | b'T' | b'f' | b'F') => parse_bool(text).map(Value::Bool),
        Some(b'0'..=b'9' | b'+' | b'-' | b'.') => {
            if let Some(number) = parse_int(text) {
                return Some(Value::Number(number));
            }
            parse_float(text).map(Value::Number)
        }
        _ => None,
    }
}

pub(crate) fn resolve_explicit_core(text: &str, suffix: &str, tag: &Tag) -> Result<Value, Error> {
    resolve_explicit_core_cow(Cow::Borrowed(text), suffix, tag)
}

#[allow(
    clippy::match_same_arms,
    reason = "the arms stay separate to document each representation or state"
)]
fn resolve_explicit_core_cow(text: Cow<'_, str>, suffix: &str, tag: &Tag) -> Result<Value, Error> {
    match suffix {
        "str" => Ok(Value::String(text.into_owned())),
        "int" => parse_int_with(&text, true)
            .map(Value::Number)
            .ok_or_else(|| resolution_error(ErrorCode::InvalidIntScalar, "invalid !!int scalar")),
        // The core schema reads `!!float 01` as 1.0. Untagged, `01` stays a
        // string.
        "float" => parse_float_with(&text, true)
            .map(Value::Number)
            .ok_or_else(|| {
                resolution_error(ErrorCode::InvalidFloatScalar, "invalid !!float scalar")
            }),
        "bool" => parse_bool(&text)
            .map(Value::Bool)
            .ok_or_else(|| resolution_error(ErrorCode::InvalidBoolScalar, "invalid !!bool scalar")),
        "null" if is_null(&text) => Ok(Value::Null),
        "null" => Err(resolution_error(
            ErrorCode::InvalidNullScalar,
            "invalid !!null scalar",
        )),
        // A core name this schema doesn't define is left for the application, like a custom tag.
        _ => Ok(Value::from(TaggedValue::new(
            tag.clone(),
            Value::String(text.into_owned()),
        ))),
    }
}

fn resolution_error(code: ErrorCode, message: &str) -> Error {
    Error::coded(ErrorKind::Resolution, code, message)
}

pub(crate) fn is_null(text: &str) -> bool {
    matches!(text, "" | "~" | "null" | "Null" | "NULL")
}

pub(crate) fn is_radix_int(text: &str) -> bool {
    let digits = text.strip_prefix(['+', '-']).unwrap_or(text);
    digits.starts_with("0x") || digits.starts_with("0o") || digits.starts_with("0b")
}

pub(crate) fn parse_bool(text: &str) -> Option<bool> {
    match text {
        "true" | "True" | "TRUE" => Some(true),
        "false" | "False" | "FALSE" => Some(false),
        _ => None,
    }
}

pub(crate) fn parse_int(text: &str) -> Option<Number> {
    parse_int_with(text, false)
}

pub(crate) fn parse_int_with(text: &str, allow_leading_zero: bool) -> Option<Number> {
    let (negative, rest_str) = match text.as_bytes().first() {
        Some(b'-') => (true, &text[1..]),
        Some(b'+') => (false, &text[1..]),
        _ => (false, text),
    };
    let rest = rest_str.as_bytes();
    if rest.is_empty() {
        return None;
    }
    // Fast path: 1..=18 decimal ASCII digits fit in both `u64` and `i64` without overflow,
    // avoiding 128-bit division/multiplication and `from_str_radix` overhead.
    if rest.len() <= 18 {
        let first = rest[0];
        if first.is_ascii_digit() {
            if rest.len() == 1 {
                let digit = u64::from(first - b'0');
                return Some(if negative {
                    Number::from_i64(-i64::from(first - b'0'))
                } else {
                    Number::from_u64(digit)
                });
            }
            let try_decimal_fast = if first == b'0' {
                allow_leading_zero && !matches!(rest[1], b'b' | b'o' | b'x')
            } else {
                true
            };
            if try_decimal_fast {
                let mut acc = u64::from(first - b'0');
                for &byte in &rest[1..] {
                    let digit = byte.wrapping_sub(b'0');
                    if digit > 9 {
                        return None;
                    }
                    acc = acc * 10 + u64::from(digit);
                }
                return Some(if negative {
                    // `acc <= 999_999_999_999_999_999 < i64::MAX`, so negation cannot overflow.
                    #[allow(
                        clippy::cast_possible_wrap,
                        reason = "18 decimal digits are strictly below i64::MAX"
                    )]
                    let signed = -(acc as i64);
                    Number::from_i64(signed)
                } else {
                    Number::from_u64(acc)
                });
            }
        }
    }
    let digits = rest_str;
    if digits.starts_with(['+', '-']) {
        return None;
    }
    let (radix, digits) = if let Some(rest) = digits.strip_prefix("0b") {
        (2, rest)
    } else if let Some(rest) = digits.strip_prefix("0o") {
        (8, rest)
    } else if let Some(rest) = digits.strip_prefix("0x") {
        (16, rest)
    } else {
        (10, digits)
    };
    if digits.is_empty() || digits.starts_with(['+', '-']) {
        return None;
    }
    if !allow_leading_zero && radix == 10 && digits.starts_with('0') {
        // 1-digit `"0"` already returned above; multi-digit `"0123"` stays a string under Core Schema.
        return None;
    }
    let magnitude = u128::from_str_radix(digits, radix).ok()?;
    if negative {
        return 0_i128
            .checked_sub_unsigned(magnitude)
            .map(Number::from_i128);
    }
    Some(Number::from_u128(magnitude))
}

fn decimal_integer_like(text: &str) -> bool {
    let digits = text.strip_prefix(['+', '-']).unwrap_or(text);
    !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
}

fn parse_float(text: &str) -> Option<Number> {
    parse_float_with(text, false)
}

/// The finite float that a core-schema number spelling stands for, a leading zero allowed, as in
/// `01` or `01.5`, which resolve to strings. Other text, such as `inf`, gives `None`, and so does a
/// spelling too large for a float, such as `1e999`.
pub(crate) fn float_from_text(text: &str) -> Option<f64> {
    parse_float_with(text, true).and_then(|number| number.as_f64())
}

pub(crate) fn parse_float_with(text: &str, allow_leading_zero: bool) -> Option<Number> {
    match text {
        ".inf" | ".Inf" | ".INF" | "+.inf" | "+.Inf" | "+.INF" => {
            return Some(Number::from_f64(f64::INFINITY));
        }
        "-.inf" | "-.Inf" | "-.INF" => {
            return Some(Number::from_f64(f64::NEG_INFINITY));
        }
        ".nan" | ".NaN" | ".NAN" => return Some(Number::from_f64(f64::NAN)),
        _ => {}
    }
    if decimal_integer_like(text) {
        let digits = text.strip_prefix(['+', '-']).unwrap_or(text);
        if !allow_leading_zero && digits.len() > 1 && digits.starts_with('0') {
            return None;
        }
    } else if !text.contains(['.', 'e', 'E']) {
        return None;
    }
    let value = text.parse::<f64>().ok()?;
    value.is_finite().then(|| Number::from_f64(value))
}

#[cfg(test)]
mod tests {
    use super::resolve_scalar;
    use crate::event::ScalarStyle;
    use crate::tag::Tag;
    use crate::value::Value;

    fn plain(text: &str) -> Value {
        resolve_scalar(text, ScalarStyle::Plain, None).expect("resolve")
    }

    #[test]
    fn compatibility_scalars() {
        assert_eq!(plain("yes"), Value::from("yes"));
        assert_eq!(plain("0123"), Value::from("0123"));
        assert_eq!(plain("2026-10-19"), Value::from("2026-10-19"));
        assert_eq!(plain("0b11").as_u64(), Some(3));
        assert_eq!(plain("0x1f").as_u64(), Some(31));
        assert_eq!(plain("0o17").as_u64(), Some(15));
        assert_eq!(plain("-0b11").as_i64(), Some(-3));
        assert_eq!(plain("-0x1f").as_i64(), Some(-31));
        assert_eq!(plain("--9"), Value::from("--9"));
        assert_eq!(plain("++9"), Value::from("++9"));
        assert_eq!(plain("0x+3"), Value::from("0x+3"));
        assert_eq!(plain("0x-3"), Value::from("0x-3"));
        assert!(
            plain("99999999999999999999999999999999999999999999")
                .as_f64()
                .is_some_and(|value| value > 1e43)
        );
        assert_eq!(plain("1e400"), Value::from("1e400"));
        let wide = |text| plain(text).as_number().copied().expect("number");
        assert_eq!(
            wide("18446744073709551616").as_u128(),
            Some(u128::from(u64::MAX) + 1)
        );
        assert_eq!(
            wide("-9223372036854775809").as_i128(),
            Some(i128::from(i64::MIN) - 1)
        );
        assert_eq!(
            wide("340282366920938463463374607431768211455").as_u128(),
            Some(u128::MAX)
        );
        assert_eq!(
            wide("-170141183460469231731687303715884105728").as_i128(),
            Some(i128::MIN)
        );
        assert!(wide("-170141183460469231731687303715884105729").is_f64());
        assert!(
            plain("340282366920938463463374607431768211456")
                .as_f64()
                .is_some_and(f64::is_finite)
        );
        assert_eq!(wide("0x10000000000000000").as_u128(), Some(1 << 64));
        assert_eq!(wide("-0x10000000000000000").as_i128(), Some(-(1 << 64)));
        // Past 128 bits a radix integer is a string.
        assert_eq!(
            plain("0x100000000000000000000000000000000"),
            Value::from("0x100000000000000000000000000000000")
        );
        assert_eq!(
            plain("-0x80000000000000000000000000000001"),
            Value::from("-0x80000000000000000000000000000001")
        );
        assert_eq!(plain("-1e400"), Value::from("-1e400"));
        assert_eq!(
            plain("012345678901234567890123456789012345678901"),
            Value::from("012345678901234567890123456789012345678901")
        );
        assert_eq!(plain("1e3").as_f64(), Some(1000.0));
        assert!(plain("~").is_null());
        assert_eq!(plain(".inf").as_f64(), Some(f64::INFINITY));
        assert!(plain(".nan").as_f64().is_some_and(f64::is_nan));
        assert!(plain(".NAN").as_f64().is_some_and(f64::is_nan));
        assert_eq!(plain(".INF").as_f64(), Some(f64::INFINITY));
        assert_eq!(plain("+.nan"), Value::from("+.nan"));
        assert_eq!(plain("-.nan"), Value::from("-.nan"));
        assert_eq!(plain(".nAn"), Value::from(".nAn"));
        assert_eq!(plain(".iNf"), Value::from(".iNf"));
    }

    #[test]
    fn quoted_scalars_stay_strings() {
        assert_eq!(
            resolve_scalar("123", ScalarStyle::DoubleQuoted, None).unwrap(),
            Value::from("123")
        );
        assert_eq!(
            resolve_scalar("true", ScalarStyle::SingleQuoted, None).unwrap(),
            Value::from("true")
        );
    }

    #[test]
    fn core_tags_override_style() {
        assert_eq!(
            resolve_scalar("123", ScalarStyle::DoubleQuoted, Some(&Tag::core("str"))).unwrap(),
            Value::from("123")
        );
        assert_eq!(
            resolve_scalar("0123", ScalarStyle::Plain, Some(&Tag::core("int")))
                .unwrap()
                .as_u64(),
            Some(123)
        );
        assert_eq!(
            resolve_scalar("x", ScalarStyle::Plain, Some(&Tag::core("int")))
                .unwrap_err()
                .kind(),
            crate::error::ErrorKind::Resolution
        );
    }

    #[test]
    fn custom_tags_remain_tagged() {
        let value =
            resolve_scalar("hello", ScalarStyle::Plain, Some(&Tag::local("Custom"))).unwrap();
        assert!(value.is_tagged());
        assert_eq!(value.as_tagged().unwrap().tag.to_string(), "!Custom");
        assert_eq!(value.as_tagged().unwrap().value.as_str(), Some("hello"));
    }

    #[test]
    fn booleans_and_numbers() {
        assert_eq!(plain("true"), Value::from(true));
        assert_eq!(plain("False"), Value::from(false));
        assert_eq!(plain("-42").as_i64(), Some(-42));
        assert_eq!(plain("+42").as_i64(), Some(42));
        assert_eq!(plain("1.5").as_f64(), Some(1.5));
    }

    #[test]
    fn plain_first_byte_dispatch_matches_every_scalar_class() {
        assert!(plain("").is_null());
        assert!(plain("~").is_null());
        assert_eq!(plain("~tilde"), Value::from("~tilde"));
        assert!(plain("null").is_null());
        assert!(plain("Null").is_null());
        assert!(plain("NULL").is_null());
        assert_eq!(plain("nullable"), Value::from("nullable"));
        assert_eq!(plain("TRUE"), Value::from(true));
        assert_eq!(plain("FALSE"), Value::from(false));
        assert_eq!(plain("truth"), Value::from("truth"));
        assert_eq!(plain("falsehood"), Value::from("falsehood"));
        assert_eq!(plain("service-a"), Value::from("service-a"));
        assert_eq!(plain("/etc/hosts"), Value::from("/etc/hosts"));
        assert_eq!(plain("café"), Value::from("café"));
        assert_eq!(plain("-.INF").as_f64(), Some(f64::NEG_INFINITY));
        assert_eq!(plain("+.Inf").as_f64(), Some(f64::INFINITY));
    }

    #[test]
    fn decimal_int_fast_path_matches_boundaries_and_fallbacks() {
        let int_tag = Tag::core("int");
        let resolve_int =
            |s: &str| resolve_scalar(s, ScalarStyle::Plain, Some(&int_tag)).expect("explicit int");

        // 0, -0, +0, single digits (including negative single digit), and 18-digit fast-path max/min.
        assert_eq!(plain("0"), Value::from(0_i64));
        assert_eq!(plain("-0"), Value::from(0_i64));
        assert_eq!(plain("+0"), Value::from(0_i64));
        assert_eq!(plain("-7"), Value::from(-7_i64));
        assert_eq!(plain("+7"), Value::from(7_i64));
        assert_eq!(
            plain("999999999999999999"),
            Value::from(999_999_999_999_999_999_i64)
        );
        assert_eq!(
            plain("-999999999999999999"),
            Value::from(-999_999_999_999_999_999_i64)
        );
        assert_eq!(
            plain("+999999999999999999"),
            Value::from(999_999_999_999_999_999_i64)
        );

        // 19-digit fallback to i64::MAX / i64::MIN / u64::MAX / u128 / > u128::MAX.
        assert_eq!(plain("9223372036854775807"), Value::from(i64::MAX));
        assert_eq!(plain("-9223372036854775808"), Value::from(i64::MIN));
        assert_eq!(plain("18446744073709551615"), Value::from(u64::MAX));
        assert_eq!(
            plain("18446744073709551616"),
            Value::Number(crate::Number::from_u128(18_446_744_073_709_551_616))
        );
        assert_eq!(
            plain("-170141183460469231731687303715884105728"),
            Value::Number(crate::Number::from_i128(i128::MIN))
        );
        assert_eq!(
            plain("340282366920938463463374607431768211456").as_f64(),
            Some(340_282_366_920_938_463_463_374_607_431_768_211_456.0)
        );

        // Leading zeros: rejected for plain Core Schema, allowed for explicit !!int.
        assert_eq!(plain("0123"), Value::from("0123"));
        assert_eq!(plain("-0123"), Value::from("-0123"));
        assert_eq!(resolve_int("0123"), Value::from(123_i64));
        assert_eq!(resolve_int("-0123"), Value::from(-123_i64));
        assert_eq!(resolve_int("0000000000000000012"), Value::from(12_i64));

        // Non-decimal radices and non-digit rejections (both plain and explicit `!!int`).
        assert_eq!(plain("0x1f"), Value::from(0x1f_i64));
        assert_eq!(plain("0o17"), Value::from(0o17_i64));
        assert_eq!(resolve_int("0x1f"), Value::from(0x1f_i64));
        assert_eq!(resolve_int("0o17"), Value::from(0o17_i64));
        assert_eq!(resolve_int("0b101"), Value::from(5_i64));
        assert_eq!(resolve_int("+0x1f"), Value::from(0x1f_i64));
        assert_eq!(plain("123a"), Value::from("123a"));
        assert_eq!(plain("-"), Value::from("-"));
        assert_eq!(plain("+"), Value::from("+"));

        // `parse_float_with(..., false)` accepts single-digit `"0"`/`"-0"` while rejecting leading zeros.
        assert_eq!(
            super::parse_float_with("0", false).and_then(|n| n.as_f64()),
            Some(0.0)
        );
        assert_eq!(
            super::parse_float_with("-0", false).and_then(|n| n.as_f64()),
            Some(-0.0)
        );
        assert_eq!(super::parse_float_with("01", false), None);
    }
}