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
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
//! Frontmatter and prefix-document splitting and parsing.
//!
//! Documentation tools, task trackers, and static site generators commonly embed a leading
//! YAML document delimited by `---` and `---` (or `...`) ahead of arbitrary non-YAML body text.
//! This module splits and parses that leading YAML header while preserving exact byte offsets
//! into the original input for [`LineIndex`](crate::LineIndex), [`Span`], and
//! [`SpannedTree`](crate::SpannedTree).

use crate::error::{Error, ErrorCode, ErrorKind};
use crate::limits::Limits;
use crate::options::ParseOptions;
use crate::span::{Location, Span};
use crate::value::Value;

const UTF8_BOM: &str = "\u{feff}";

/// The closing delimiter that terminated a frontmatter block.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FrontmatterDelimiter {
    /// Closed by a `---` document-start marker line.
    DocumentStart,
    /// Closed by a `...` document-end marker line.
    DocumentEnd,
}

/// A leading YAML frontmatter block split from the remaining non-YAML body.
///
/// [`yaml`](Self::yaml) always starts at byte offset `0` of the original input (preserving any
/// leading UTF-8 BOM and opening `---` line), so every [`Span`] produced when parsing it with
/// [`parse_events`](crate::parse_events), [`SpannedTree::parse`](crate::SpannedTree::parse), or
/// any error aligns directly with [`LineIndex::new(input)`](crate::LineIndex::new).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Frontmatter<'a> {
    yaml: &'a str,
    yaml_span: Span,
    closing_delimiter: FrontmatterDelimiter,
    delimiter_span: Span,
    body: &'a str,
    body_offset: usize,
}

impl<'a> Frontmatter<'a> {
    /// The leading YAML frontmatter slice (`&input[..yaml_span.end()]`), starting at byte `0`
    /// of the original input and ending immediately before the closing delimiter line.
    #[must_use]
    pub const fn yaml(&self) -> &'a str {
        self.yaml
    }

    /// The byte span of [`yaml`](Self::yaml) in the original input (`0..closing_start`).
    #[must_use]
    pub const fn yaml_span(&self) -> Span {
        self.yaml_span
    }

    /// Which delimiter (`---` or `...`) closed the frontmatter block.
    #[must_use]
    pub const fn closing_delimiter(&self) -> FrontmatterDelimiter {
        self.closing_delimiter
    }

    /// The 3-byte span of the closing `---` or `...` delimiter in the original input.
    #[must_use]
    pub const fn delimiter_span(&self) -> Span {
        self.delimiter_span
    }

    /// The remaining non-YAML body slice immediately after the closing delimiter line.
    #[must_use]
    pub const fn body(&self) -> &'a str {
        self.body
    }

    /// Exact byte offset of [`body`](Self::body) in the original input.
    ///
    /// `&input[frontmatter.body_offset()..]` is always identical to `frontmatter.body()`.
    #[must_use]
    pub const fn body_offset(&self) -> usize {
        self.body_offset
    }
}

/// A decoded leading YAML frontmatter value paired with the remaining non-YAML body slice.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct ParsedFrontmatter<'a, T> {
    /// The decoded frontmatter value.
    pub frontmatter: T,
    /// The remaining non-YAML body slice after the closing delimiter line.
    pub body: &'a str,
    /// Exact byte offset of `body` in the original input.
    pub body_offset: usize,
    /// Byte span of the YAML frontmatter slice (`0..closing_start`) in the original input.
    pub yaml_span: Span,
    /// Which delimiter (`---` or `...`) closed the frontmatter block.
    pub closing_delimiter: FrontmatterDelimiter,
    /// The 3-byte span of the closing `---` or `...` delimiter in the original input.
    pub delimiter_span: Span,
}

/// Split a leading YAML frontmatter block from `input` under the given limits.
///
/// Returns `Ok(None)` when `input` does not begin with a standalone `---` opening line
/// (optionally preceded by a UTF-8 BOM). Returns `Err` when `limits` is invalid, when the
/// frontmatter exceeds `limits.max_input_bytes`, or when an opening `---` line has no matching
/// closing `---` or `...` line before end of input.
pub(crate) fn split_frontmatter_with_limits<'a>(
    input: &'a str,
    limits: &Limits,
) -> Result<Option<Frontmatter<'a>>, Error> {
    limits.validate()?;

    let bom_len = if input.starts_with(UTF8_BOM) {
        UTF8_BOM.len()
    } else {
        0
    };
    let after_bom = &input[bom_len..];

    let max_bytes = limits.max_input_bytes;
    let Some(open_line) =
        match_delimiter_line(after_bom, true, Some(max_bytes.saturating_sub(bom_len)))
    else {
        return Ok(None);
    };
    if open_line.exceeded_limit {
        return Err(input_limit_error(limits, max_bytes.saturating_add(1)));
    }
    let open_span = Span::new(bom_len, bom_len + 3);
    let mut pos = bom_len + open_line.next_offset;

    if !open_line.has_newline {
        // An opening `---` at EOF with no closing delimiter is unclosed frontmatter.
        limits.check_input(input.len()).map_err(limit_at_start)?;
        return Err(missing_closing_delimiter(input, open_span));
    }

    while pos <= input.len() {
        limits.check_input(pos).map_err(limit_at_start)?;
        if pos == input.len() {
            break;
        }
        let rest = &input[pos..];
        let remaining = max_bytes - pos;
        if let Some(close) = match_delimiter_line(rest, false, Some(remaining)) {
            if close.exceeded_limit {
                return Err(input_limit_error(
                    limits,
                    pos.saturating_add(close.next_offset),
                ));
            }
            let body_offset = pos + close.next_offset;
            return Ok(Some(Frontmatter {
                yaml: &input[..pos],
                yaml_span: Span::new(0, pos),
                closing_delimiter: close.kind,
                delimiter_span: Span::new(pos, pos + 3),
                body: &input[body_offset..],
                body_offset,
            }));
        }
        let Some(step) = next_line_len_bounded(rest, remaining) else {
            return Err(input_limit_error(
                limits,
                pos.saturating_add(remaining).saturating_add(1),
            ));
        };
        pos += step;
    }

    Err(missing_closing_delimiter(input, open_span))
}

/// Parse a leading YAML frontmatter block into a typed Serde value.
pub(crate) fn parse_frontmatter_with<'de, T: serde::Deserialize<'de>>(
    input: &'de str,
    options: &ParseOptions,
) -> Result<Option<ParsedFrontmatter<'de, T>>, Error> {
    let Some(split) = split_frontmatter_with_limits(input, &options.limits)? else {
        return Ok(None);
    };
    let frontmatter = crate::from_str_with(split.yaml(), options)?;
    Ok(Some(ParsedFrontmatter {
        frontmatter,
        body: split.body(),
        body_offset: split.body_offset(),
        yaml_span: split.yaml_span(),
        closing_delimiter: split.closing_delimiter(),
        delimiter_span: split.delimiter_span(),
    }))
}

/// Parse a leading YAML frontmatter block into a generic [`Value`].
pub(crate) fn parse_frontmatter_value_with<'a>(
    input: &'a str,
    options: &ParseOptions,
) -> Result<Option<ParsedFrontmatter<'a, Value>>, Error> {
    let Some(split) = split_frontmatter_with_limits(input, &options.limits)? else {
        return Ok(None);
    };
    let frontmatter = crate::parse_value_with(split.yaml(), options)?;
    Ok(Some(ParsedFrontmatter {
        frontmatter,
        body: split.body(),
        body_offset: split.body_offset(),
        yaml_span: split.yaml_span(),
        closing_delimiter: split.closing_delimiter(),
        delimiter_span: split.delimiter_span(),
    }))
}

struct MatchedDelimiter {
    kind: FrontmatterDelimiter,
    next_offset: usize,
    has_newline: bool,
    exceeded_limit: bool,
}

/// Match a standalone `---` (or `...` when `opening_only` is false) line at the start of `s`.
///
/// Only optional horizontal whitespace (`' '` or `'\t'`) and an optional `# ...` comment (when
/// preceded by whitespace) are permitted before `\r\n`, `\n`, or EOF. When `max_len` is `Some`,
/// scanning stops once the line length exceeds `max_len` bytes and reports `exceeded_limit`.
fn match_delimiter_line(
    s: &str,
    opening_only: bool,
    max_len: Option<usize>,
) -> Option<MatchedDelimiter> {
    let bytes = s.as_bytes();
    let kind = if bytes.starts_with(b"---") {
        FrontmatterDelimiter::DocumentStart
    } else if !opening_only && bytes.starts_with(b"...") {
        FrontmatterDelimiter::DocumentEnd
    } else {
        return None;
    };
    if let Some(&next) = bytes.get(3)
        && !matches!(next, b' ' | b'\t' | b'\n' | b'\r')
    {
        return None;
    }

    let limit = max_len.unwrap_or(bytes.len()).min(bytes.len());
    let mut i = 3;
    let mut saw_comment = false;
    while i < bytes.len() {
        if max_len.is_some() && i > limit {
            return Some(MatchedDelimiter {
                kind,
                next_offset: i,
                has_newline: false,
                exceeded_limit: true,
            });
        }
        match bytes[i] {
            b' ' | b'\t' => {
                i += 1;
            }
            // `bytes[3]` was already validated as whitespace or line break above, so reaching `#`
            // here implies at least one preceding space or tab after the delimiter.
            b'#' => {
                saw_comment = true;
                break;
            }
            b'\n' | b'\r' => break,
            _ => return None,
        }
    }
    if saw_comment {
        // Skip comment through end of line (bounded when max_len is set).
        while i < bytes.len() && bytes[i] != b'\n' && bytes[i] != b'\r' {
            if max_len.is_some() && i > limit {
                // Advance past at most 3 UTF-8 continuation bytes so `next_offset` is
                // always a valid UTF-8 character boundary into `s`.
                if (bytes[i] & 0b1100_0000) == 0b1000_0000 {
                    i += 1;
                }
                if i < bytes.len() && (bytes[i] & 0b1100_0000) == 0b1000_0000 {
                    i += 1;
                }
                if i < bytes.len() && (bytes[i] & 0b1100_0000) == 0b1000_0000 {
                    i += 1;
                }
                return Some(MatchedDelimiter {
                    kind,
                    next_offset: i,
                    has_newline: false,
                    exceeded_limit: true,
                });
            }
            i += 1;
        }
    }

    if i == bytes.len() {
        let exceeded_limit = max_len.is_some_and(|max| i > max);
        return Some(MatchedDelimiter {
            kind,
            next_offset: i,
            has_newline: false,
            exceeded_limit,
        });
    }
    if bytes[i] == b'\n' {
        let next_offset = i + 1;
        let exceeded_limit = max_len.is_some_and(|max| next_offset > max);
        return Some(MatchedDelimiter {
            kind,
            next_offset,
            has_newline: true,
            exceeded_limit,
        });
    }
    if bytes[i] == b'\r' {
        let step = if bytes.get(i + 1) == Some(&b'\n') {
            2
        } else {
            1
        };
        let next_offset = i + step;
        let exceeded_limit = max_len.is_some_and(|max| next_offset > max);
        return Some(MatchedDelimiter {
            kind,
            next_offset,
            has_newline: true,
            exceeded_limit,
        });
    }
    None
}

fn limit_at_start(error: crate::limits::LimitExceeded) -> Error {
    Error::from(error)
        .with_span(Span::empty(0))
        .with_location(Location::new(1, 1))
}

fn input_limit_error(limits: &Limits, actual: usize) -> Error {
    match limits.check_input(actual) {
        Err(error) => limit_at_start(error),
        Ok(()) => Error::coded(
            ErrorKind::Limit,
            ErrorCode::InputSizeLimit,
            "input exceeds max_input_bytes",
        )
        .with_span(Span::empty(0))
        .with_location(Location::new(1, 1)),
    }
}

/// Byte length of the first line of `s` (including its `\r\n`, `\n`, or `\r`), bounded to at most
/// `max_len` bytes.
///
/// Returns `None` if the line exceeds `max_len` bytes without reaching a line break or EOF.
fn next_line_len_bounded(s: &str, max_len: usize) -> Option<usize> {
    let bytes = s.as_bytes();
    let limit = bytes.len().min(max_len);
    let mut i = 0;
    while i < limit {
        if bytes[i] == b'\n' {
            return Some(i + 1);
        }
        if bytes[i] == b'\r' {
            if bytes.get(i + 1) == Some(&b'\n') {
                return (i + 2 <= max_len).then_some(i + 2);
            }
            return Some(i + 1);
        }
        i += 1;
    }
    if bytes.len() <= max_len {
        Some(bytes.len())
    } else {
        None
    }
}

fn missing_closing_delimiter(input: &str, open_span: Span) -> Error {
    let prefix = &input[..open_span.end()];
    Error::coded(
        ErrorKind::Parser,
        ErrorCode::UnexpectedToken,
        "unterminated frontmatter: expected closing `---` or `...` delimiter",
    )
    .with_span(open_span)
    .with_input_location(prefix, false)
}

#[cfg(kani)]
mod kani_proofs {
    use super::{FrontmatterDelimiter, match_delimiter_line, next_line_len_bounded};

    #[kani::proof]
    #[kani::unwind(9)]
    fn verify_next_line_len_bounded_invariants() {
        // Constant-offset symbolic fill (<= 7 bytes to stay below `from_utf8`'s 8-byte SWAR
        // loop) with optional 2-, 3-, or 4-byte UTF-8 scalars (`'é'`, `'€'`, `'🚀'`) at any valid
        // interior position so `is_char_boundary` is checked across every UTF-8 sequence width.
        let mut buf = [0_u8; 7];
        for slot in &mut buf {
            *slot = match kani::any::<u8>() & 3 {
                0 => b'a',
                1 => b'\n',
                2 => b'\r',
                _ => b'-',
            };
        }
        let len: usize = kani::any();
        kani::assume(len <= buf.len());
        match kani::any::<u8>() & 3 {
            1 if len >= 2 => {
                let mb_pos: usize = kani::any();
                kani::assume(mb_pos <= len - 2);
                buf[mb_pos..mb_pos + 2].copy_from_slice(&[0xC3, 0xA9]); // 'é'
            }
            2 if len >= 3 => {
                let mb_pos: usize = kani::any();
                kani::assume(mb_pos <= len - 3);
                buf[mb_pos..mb_pos + 3].copy_from_slice(&[0xE2, 0x82, 0xAC]); // '€'
            }
            3 if len >= 4 => {
                let mb_pos: usize = kani::any();
                kani::assume(mb_pos <= len - 4);
                buf[mb_pos..mb_pos + 4].copy_from_slice(&[0xF0, 0x9F, 0x9A, 0x80]); // '🚀'
            }
            _ => {}
        }
        let max_len: usize = kani::any();
        let Ok(s) = std::str::from_utf8(&buf[..len]) else {
            return;
        };

        match next_line_len_bounded(s, max_len) {
            Some(step) => {
                assert!(step <= len);
                assert!(step <= max_len);
                assert!(s.is_char_boundary(step));
                if len > 0 {
                    assert!(step > 0);
                }
                // Never split a `\r\n` line ending.
                if step > 0 && step < len {
                    assert!(!(buf[step - 1] == b'\r' && buf[step] == b'\n'));
                }
            }
            None => {
                assert!(len > max_len);
                // No complete line ending can finish within `max_len` bytes.
                let mut i = 0;
                while i < max_len && i < len {
                    assert!(buf[i] != b'\n');
                    if buf[i] == b'\r' {
                        assert!(i + 1 < len && buf[i + 1] == b'\n' && i + 2 > max_len);
                    }
                    i += 1;
                }
            }
        }
    }

    #[kani::proof]
    #[kani::unwind(9)]
    fn verify_match_delimiter_line_bounds() {
        // Constant-offset symbolic buffer up to 7 bytes (staying below `from_utf8`'s 8-byte SWAR
        // loop while covering arbitrary prefixes, whitespace, comments, line endings, and
        // multi-byte UTF-8 sequences `'é'`/`'€'`/`'🚀'`).
        let mut buf = [0_u8; 7];
        match kani::any::<u8>() & 3 {
            0 => buf[0..3].copy_from_slice(b"---"),
            1 => buf[0..3].copy_from_slice(b"..."),
            2 => buf[0..3].copy_from_slice(b"--x"),
            _ => buf[0..3].copy_from_slice(b"xyz"),
        }
        for slot in &mut buf[3..] {
            *slot = match kani::any::<u8>() & 7 {
                0 => b'-',
                1 => b'.',
                2 => b' ',
                3 => b'\t',
                4 => b'#',
                5 => b'\r',
                6 => b'\n',
                _ => b'x',
            };
        }
        let len: usize = kani::any();
        kani::assume(len <= buf.len());
        match kani::any::<u8>() & 3 {
            1 if len >= 5 => {
                let mb_pos: usize = kani::any();
                kani::assume((3..=len - 2).contains(&mb_pos));
                buf[mb_pos..mb_pos + 2].copy_from_slice(&[0xC3, 0xA9]); // 'é'
            }
            2 if len >= 6 => {
                let mb_pos: usize = kani::any();
                kani::assume((3..=len - 3).contains(&mb_pos));
                buf[mb_pos..mb_pos + 3].copy_from_slice(&[0xE2, 0x82, 0xAC]); // '€'
            }
            3 if len >= 7 => {
                let mb_pos: usize = kani::any();
                kani::assume((3..=len - 4).contains(&mb_pos));
                buf[mb_pos..mb_pos + 4].copy_from_slice(&[0xF0, 0x9F, 0x9A, 0x80]); // '🚀'
            }
            _ => {}
        }
        let opening_only: bool = kani::any();
        let max_len: Option<usize> = if kani::any() {
            let max: usize = kani::any();
            kani::assume(max <= buf.len() + 2 || max == usize::MAX);
            Some(max)
        } else {
            None
        };
        if let Ok(s) = std::str::from_utf8(&buf[..len]) {
            check_match_delimiter_invariants(s, opening_only, max_len);
        }
    }

    #[kani::proof]
    #[kani::unwind(12)]
    fn verify_match_delimiter_line_multibyte_comments() {
        // Static 2-, 3-, and 4-byte UTF-8 comment lines (no `from_utf8` SWAR loop) with symbolic
        // `max_len` spanning every interior continuation byte of `'é'`, `'€'`, and `'🚀'`,
        // directly proving the comment-truncation continuation-skip loop keeps UTF-8 boundaries.
        let opening_only: bool = kani::any();
        let comment_limit: usize = kani::any();
        kani::assume(comment_limit <= 12);
        for sample in [
            "--- #é\n",
            "... #é\n",
            "--- #€\n",
            "... #€\n",
            "--- #🚀\n",
            "... #🚀\n",
        ] {
            check_match_delimiter_invariants(sample, opening_only, Some(comment_limit));
        }
    }

    fn check_match_delimiter_invariants(s: &str, opening_only: bool, max_len: Option<usize>) {
        let bytes = s.as_bytes();
        let len = bytes.len();
        if let Some(matched) = match_delimiter_line(s, opening_only, max_len) {
            if opening_only {
                assert_eq!(matched.kind, FrontmatterDelimiter::DocumentStart);
            }
            assert!(matched.next_offset <= len);
            assert!(s.is_char_boundary(matched.next_offset));
            if len > 3 {
                assert!(matches!(bytes[3], b' ' | b'\t' | b'\n' | b'\r'));
            }
            if !matched.exceeded_limit {
                assert!(matched.next_offset >= 3);
                if let Some(max) = max_len {
                    assert!(matched.next_offset <= max);
                }
                if matched.has_newline {
                    assert!(matched.next_offset >= 4);
                    if matched.next_offset < len {
                        assert!(
                            !(bytes[matched.next_offset - 1] == b'\r'
                                && bytes[matched.next_offset] == b'\n')
                        );
                    }
                } else {
                    assert_eq!(matched.next_offset, len);
                }
            } else {
                assert!(max_len.is_some());
            }
        }
    }
}

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

    #[test]
    fn match_delimiter_line_keeps_utf8_char_boundary_on_over_limit_comment() {
        let input = "--- #é\n";
        let matched = match_delimiter_line(input, true, Some(5)).expect("delimiter match");
        assert!(matched.exceeded_limit);
        assert!(input.is_char_boundary(matched.next_offset));
        assert_eq!(matched.next_offset, 7);

        // 4-byte UTF-8 character (`🦀`) at every interior continuation offset.
        let emoji = "--- #🦀\n";
        for max in [5, 6, 7] {
            let m = match_delimiter_line(emoji, true, Some(max)).expect("delimiter match");
            assert!(m.exceeded_limit);
            assert!(emoji.is_char_boundary(m.next_offset), "max={max}");
            assert_eq!(m.next_offset, 9, "max={max}");
        }
    }

    #[test]
    fn match_delimiter_line_rejects_four_hyphens_even_under_tiny_limit() {
        assert!(match_delimiter_line("----\nbody\n", true, Some(2)).is_none());
        assert!(match_delimiter_line("...x\nbody\n", false, Some(2)).is_none());
        assert!(match_delimiter_line("---#comment\n", true, Some(2)).is_none());
    }

    #[test]
    fn bare_cr_crlf_and_closing_delimiter_limits_stay_bounded() {
        use super::{FrontmatterDelimiter, next_line_len_bounded};

        assert_eq!(next_line_len_bounded("a: 1\rbody", 10), Some(5));
        assert_eq!(next_line_len_bounded("a: 1\r\nbody", 10), Some(6));
        assert_eq!(next_line_len_bounded("a: 1\r\nbody", 5), None);

        let cr_open = match_delimiter_line("---\ra: 1\r", true, Some(10)).expect("cr open");
        assert_eq!(cr_open.kind, FrontmatterDelimiter::DocumentStart);
        assert_eq!(cr_open.next_offset, 4);
        assert!(cr_open.has_newline);
        assert!(!cr_open.exceeded_limit);

        let cr_close = match_delimiter_line("...\rbody", false, Some(10)).expect("cr close");
        assert_eq!(cr_close.kind, FrontmatterDelimiter::DocumentEnd);
        assert_eq!(cr_close.next_offset, 4);
        assert!(!cr_close.exceeded_limit);

        let over_close =
            match_delimiter_line("--- #long comment\n", false, Some(8)).expect("over close");
        assert!(over_close.exceeded_limit);
        assert!("--- #long comment\n".is_char_boundary(over_close.next_offset));

        // Exact-fit (`== max`) vs 1-byte-over (`> max`) boundaries for EOF, LF, CR, and CRLF.
        for (line, expected_len) in [("---", 3), ("---\n", 4), ("---\r", 4), ("---\r\n", 5)] {
            let exact = match_delimiter_line(line, false, Some(expected_len)).expect(line);
            assert_eq!(exact.next_offset, expected_len, "{line:?}");
            assert!(!exact.exceeded_limit, "exact fit must not exceed: {line:?}");
            let over = match_delimiter_line(line, false, Some(expected_len - 1)).expect(line);
            assert!(over.exceeded_limit, "1 byte over must exceed: {line:?}");
        }
        // `i == limit` in trailing whitespace loop still inspects byte `limit` (catching `>` -> `==`/`>=`).
        assert!(match_delimiter_line("---  x\n", true, Some(5)).is_none());
        let eq_nl = match_delimiter_line("---  \n", true, Some(5)).expect("delimiter at limit");
        assert!(eq_nl.has_newline && eq_nl.next_offset == 6 && eq_nl.exceeded_limit);
        let past_ws = match_delimiter_line("---     \n", true, Some(4)).expect("past ws limit");
        assert!(!past_ws.has_newline && past_ws.next_offset == 5 && past_ws.exceeded_limit);
        let eof_comment = match_delimiter_line("--- #comment", false, Some(20)).expect("eof");
        assert_eq!(eof_comment.next_offset, 12);
        assert!(!eof_comment.has_newline && !eof_comment.exceeded_limit);

        // Over-limit multi-byte UTF-8 comment right at EOF (no trailing newline) hits continuation
        // bounds checks (`i < bytes.len()`) without panicking out-of-bounds.
        let eof_2b = match_delimiter_line("--- #é", true, Some(5)).expect("eof 2-byte");
        assert!(eof_2b.exceeded_limit && eof_2b.next_offset == 7);
        let eof_3b = match_delimiter_line("--- #€", true, Some(5)).expect("eof 3-byte");
        assert!(eof_3b.exceeded_limit && eof_3b.next_offset == 8);
    }
}