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
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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
//! Bounded on-demand logical-line and token window for single-pass streaming parsing.
//!
//! Instead of buffering every `Token` and `Line` for an entire YAML document upfront,
//! [`LineWindow`] scans small bounded batches of logical lines (`<= 128` lines and `<= 384`
//! tokens, ~12 KiB) on demand from [`Scanner`]. Batching keeps the scanner and parser hot in
//! instruction cache with plain contiguous `Vec<Line>` indexing, while flushing and reusing
//! consumed batches in O(1) keeps transient parser memory bounded by O(batch + active line)
//! rather than O(document size).

use std::panic::AssertUnwindSafe;

use crate::error::Error;
use crate::event::ScalarStyle;
use crate::limits::Limits;
use crate::position::column_on_line;
#[cfg(test)]
use crate::position::lines_at_most;
use crate::scanner::{Scanner, Token, TokenKind, UNMATCHED_FLOW};
use crate::span::Span;

use super::{Run, fit_u32, matched_flow_end, to_u32};

/// A logical line's token range in the parser's token buffer.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Line {
    pub(super) start: u32,
    pub(super) end: u32,
    pub(super) indent: u32,
}

impl Line {
    /// The line of `tokens[start..end]`, from `input`. Its indent is its first token's column,
    /// less any tab before that token and what follows the tab: YAML indents with spaces alone
    /// (production 63), so a tab there separates and `k:\n\tv` holds `v` at indent 0.
    pub(super) fn new(
        tokens: &[Token],
        start: usize,
        end: usize,
        input: &str,
        compat: bool,
    ) -> Result<Self, Box<Error>> {
        let first_span = tokens.get(start).map_or_else(|| Span::empty(0), |t| t.span);
        let indent = tokens.get(start).map_or(0, |token| {
            let offset = token.span.start();
            let bytes = input.as_bytes();
            let mut i = offset;
            let mut first_tab: Option<usize> = None;
            while i > 0 {
                match bytes[i - 1] {
                    b' ' => i -= 1,
                    b'\t' => {
                        i -= 1;
                        first_tab = Some(i);
                    }
                    _ => break,
                }
            }
            if i == 0 || matches!(bytes[i - 1], b'\n' | b'\r') {
                first_tab.map_or(offset - i, |tab| tab - i)
            } else {
                let column = column_on_line(input, offset, compat).saturating_sub(1);
                match first_tab {
                    Some(tab) => column.saturating_sub(offset - tab),
                    None => column,
                }
            }
        });
        Ok(Self {
            start: to_u32(start, first_span, input, compat)?,
            end: to_u32(end, first_span, input, compat)?,
            indent: to_u32(indent, first_span, input, compat)?,
        })
    }

    #[inline]
    pub(super) fn start(self) -> usize {
        self.start as usize
    }

    #[inline]
    pub(super) fn end(self) -> usize {
        self.end as usize
    }

    #[inline]
    pub(super) fn indent(self) -> usize {
        self.indent as usize
    }

    #[inline]
    pub(super) fn len(self) -> usize {
        (self.end - self.start) as usize
    }

    #[inline]
    pub(super) fn is_empty(self) -> bool {
        self.start == self.end
    }

    #[inline]
    pub(super) fn advance(&mut self, count: usize) {
        self.start = self.start.saturating_add(fit_u32(count)).min(self.end);
    }
}

/// Compact summary of a retired line for compatibility-mode indentation diagnostics (`compat` only).
#[derive(Clone, Copy, Debug)]
pub(crate) struct CompatParent {
    indent: u32,
    /// Byte offset of the line's first surviving token when retired, or `None` if empty.
    first_offset: Option<usize>,
    is_block_entry: bool,
}

/// Reusable `'static` line-window and scanner scratch checked out from [`crate::ParserBuf`].
#[derive(Debug, Default)]
pub(crate) struct WindowScratch {
    pub(crate) lines: Vec<Line>,
    pub(crate) tokens: Vec<Token>,
    pub(crate) flow_link_stack: Vec<usize>,
    pub(crate) compat_parents: Vec<CompatParent>,
    pub(crate) scanner: crate::scanner::ScannerScratch,
}

impl WindowScratch {
    pub(crate) fn clear_and_clamp(&mut self) {
        self.lines.clear();
        if self.lines.capacity() > 256 {
            self.lines = Vec::new();
        }
        self.tokens.clear();
        if self.tokens.capacity() > WINDOW_SHRINK_CAP {
            self.tokens = Vec::new();
        }
        self.flow_link_stack.clear();
        if self.flow_link_stack.capacity() > 256 {
            self.flow_link_stack = Vec::new();
        }
        self.compat_parents.clear();
        if self.compat_parents.capacity() > 256 {
            self.compat_parents = Vec::new();
        }
        self.scanner.clear_and_clamp();
    }

    pub(crate) fn release_all(&mut self) {
        self.lines = Vec::new();
        self.tokens = Vec::new();
        self.flow_link_stack = Vec::new();
        self.compat_parents = Vec::new();
        self.scanner.release_all();
    }
}

/// Token-arena growth chunks used when a single logical line (e.g., a large flow collection)
/// grows past the bounded streaming batch window.
pub(super) const TOKEN_ARENA_CHUNK: usize = 8 * 1024;
#[cfg(test)]
pub(super) const TOKEN_ARENA_WIDE_CHUNK: usize = 16 * 1024;
pub(super) const TOKEN_ARENA_SMALL_CHUNK: usize = 64;
#[cfg(any(test, kani))]
pub(super) const TOKEN_ARENA_MID_CHUNK: usize = 256;

/// Maximum logical lines scanned per bounded refill batch for large documents (128 * 12 B = 1.5 KiB).
const WINDOW_BATCH_LINES: usize = 128;
/// Soft token target per bounded refill batch for large documents (384 * 32 B = 12 KiB).
const WINDOW_BATCH_TOKENS: usize = 384;
/// Smaller bounded batch caps for tiny (`<= 512 B`) and small-to-medium (`<= 8 KiB`) documents so
/// transient token and line windows scale smoothly down to sub-KiB footprints on small inputs.
const SMALL_BATCH_LINES: usize = 16;
const SMALL_BATCH_TOKENS: usize = 20;
const SMALL_TOKEN_CAP: usize = 24;
const MEDIUM_BATCH_LINES: usize = 32;
const MEDIUM_BATCH_TOKENS: usize = 96;
const MEDIUM_TOKEN_CAP: usize = 112;
/// Initial token buffer capacity for tiny/single-scalar inputs (512 B).
const WINDOW_INIT_CHUNK: usize = 16;
/// Capacity above which an emptied token buffer (e.g. after a large single-line flow collection
/// retires) is released immediately rather than kept warm across subsequent block lines.
const WINDOW_SHRINK_CAP: usize = 1_024;

#[inline]
const fn batch_limits(input_len: usize) -> (usize, usize) {
    if input_len <= 512 {
        (SMALL_BATCH_LINES, SMALL_BATCH_TOKENS)
    } else if input_len <= 8_192 {
        (MEDIUM_BATCH_LINES, MEDIUM_BATCH_TOKENS)
    } else {
        (WINDOW_BATCH_LINES, WINDOW_BATCH_TOKENS)
    }
}

pub(super) fn reserve_tokens(
    tokens: &mut Vec<Token>,
    additional: usize,
    most: usize,
    span: Span,
    input: &str,
    compat: bool,
) -> Result<(), Box<Error>> {
    tokens.try_reserve_exact(additional).map_err(|_| {
        let observed = u64::try_from(tokens.len().saturating_add(additional)).unwrap_or(u64::MAX);
        let limit = u64::try_from(most).unwrap_or(u64::MAX);
        Box::new(
            Error::from(crate::limits::LimitExceeded::new(
                crate::limits::LimitKind::Events,
                limit,
                observed,
            ))
            .with_span(span)
            .with_input_location(input, compat),
        )
    })
}

#[cfg(test)]
pub(super) fn push_token(
    tokens: &mut Vec<Token>,
    token: Token,
    chunk: usize,
    most: usize,
    input: &str,
) -> Result<(), Box<Error>> {
    if tokens.len() == tokens.capacity() {
        let room = most.saturating_sub(tokens.len()).max(1);
        let additional = arena_growth(tokens.len(), chunk).min(room);
        reserve_tokens(tokens, additional, most, token.span, input, false)?;
    }
    tokens.push(token);
    Ok(())
}

/// How many tokens a full arena of `len` grows by before any estimate: its first chunk, and
/// then as many tokens as it holds.
pub(super) const fn arena_growth(len: usize, chunk: usize) -> usize {
    if len <= chunk { chunk } else { len }
}

/// The token arena capacity to reserve before scanning a mid-sized document, or `None` to grow
/// as tokens arrive.
#[cfg(any(test, kani))]
pub(super) fn mid_input_token_capacity(
    input_len: usize,
    line_count: usize,
    most: usize,
) -> Option<usize> {
    if (4097..=32768).contains(&input_len) && line_count > 0 && input_len / line_count <= 80 {
        Some((input_len / 10).min(most))
    } else {
        None
    }
}

/// How far one reservation may run ahead of the tokens already scanned.
pub(super) const TOKEN_ARENA_AHEAD: usize = 8;

/// How many tokens a full arena of `len` grows by once estimates have begun.
pub(super) const fn estimated_growth(
    len: usize,
    estimate: usize,
    chunk: usize,
    most: usize,
) -> usize {
    let sixteenth = len / 16;
    let least = if sixteenth > chunk { sixteenth } else { chunk };
    let wanted = estimate.saturating_sub(len);
    let growth = if wanted > least { wanted } else { least };
    let room = most.saturating_sub(len);
    let room = if room == 0 { 1 } else { room };
    if growth < room { growth } else { room }
}

/// Tokens to hold after scanning a prefix of a large logical line, or `None` before enough tokens
/// show the density.
pub(super) fn prefix_token_capacity(
    tokens: usize,
    consumed: usize,
    last_tokens: usize,
    last_consumed: usize,
    input_len: usize,
    most: usize,
) -> Option<usize> {
    const THRESHOLD: usize = 1_024;
    if tokens < THRESHOLD || consumed == 0 {
        return None;
    }
    let overall = tokens as u128 * input_len as u128 / consumed as u128;
    let remaining = input_len.saturating_sub(consumed) as u128;
    let recent_tokens = tokens.saturating_sub(last_tokens) as u128;
    let recent_bytes = consumed.saturating_sub(last_consumed) as u128;
    let recent = if recent_tokens > 0 && recent_bytes > 0 {
        (tokens as u128).saturating_add(recent_tokens * remaining / recent_bytes)
    } else {
        0
    };
    let estimate = overall.max(recent);
    let estimate = usize::try_from(estimate.saturating_add(estimate / 64)).unwrap_or(usize::MAX);
    let cap = input_len
        .min(most)
        .min(tokens.saturating_mul(TOKEN_ARENA_AHEAD));
    Some(estimate.min(cap).max(tokens))
}

/// Pair every flow collection's opening token with the relative token distance to its matching
/// closing token (`close - open`), making links invariant under both window compaction and
/// leading token advancement (`line.advance(1)`), reusing `stack` to avoid per-line allocations.
pub(super) fn link_flow_ends_with_stack(tokens: &mut [Token], stack: &mut Vec<usize>) {
    stack.clear();
    for index in 0..tokens.len() {
        match tokens[index].kind {
            TokenKind::FlowSequenceStart { .. } | TokenKind::FlowMappingStart { .. } => {
                stack.push(index);
            }
            TokenKind::FlowSequenceEnd | TokenKind::FlowMappingEnd => {
                if let Some(open) = stack.pop()
                    && let Ok(delta) = u32::try_from(index - open)
                    && delta != UNMATCHED_FLOW
                {
                    match &mut tokens[open].kind {
                        TokenKind::FlowSequenceStart { end }
                        | TokenKind::FlowMappingStart { end } => *end = delta,
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }
}

/// Compute the compaction cut for shifting live lines when a batch retires partially.
/// Pure helper verified symbolically by Kani.
#[inline]
pub(super) fn compact_shift(
    dead_prefix: usize,
    tokens_len: usize,
    first_live_start: Option<usize>,
) -> usize {
    let bound = first_live_start.map_or(tokens_len, |start| start.min(tokens_len));
    dead_prefix.min(bound)
}

/// Bounded on-demand logical-line and token window fed in small cache-friendly batches from
/// [`Scanner`].
#[derive(Debug)]
#[allow(
    clippy::struct_excessive_bools,
    reason = "the flags represent independent stream boundary, truncation, and compat-lookback states"
)]
pub(super) struct LineWindow<'a> {
    scanner: Scanner<'a>,
    input: &'a str,
    compat: bool,
    /// Global logical line index of `lines[0]` (total lines already flushed/retired).
    base_line: usize,
    /// Cached `base_line + lines.len()` so `ensure_line`'s hot path is a single comparison.
    loaded_end: usize,
    /// Highest line index retired by the parser (flushed lazily at batch refill boundaries).
    retire_mark: usize,
    /// Active logical lines in the current batch (`base_line .. base_line + lines.len()`).
    lines: Vec<Line>,
    /// Token storage for the current batch (cleared/reused in O(1) at batch boundaries).
    tokens: Vec<Token>,
    /// Reusable stack for per-line flow partner linking (zero allocs on block-only docs).
    flow_link_stack: Vec<usize>,
    /// Recent density state for large single-line flow collections.
    last_tokens: usize,
    last_consumed: usize,
    chunk: usize,
    stream_start: Option<Span>,
    stream_end: Option<Span>,
    started: bool,
    eof: bool,
    /// Deferred scanner failure recorded after a flow opener (surfaced at truncated EOF / run end).
    ///
    /// Scanner errors hold only owned metadata (no dynamic `source`), so wrapping in
    /// `AssertUnwindSafe` preserves `EventStream` and `Deserializer`'s `UnwindSafe` auto-trait.
    scanner_error: Option<AssertUnwindSafe<Box<Error>>>,
    /// Non-flow scanner failure encountered speculatively during batch lookahead past the
    /// demanded line; surfaced only if the parser actually advances to `loaded_end()`.
    prefetch_error: Option<AssertUnwindSafe<Box<Error>>>,
    /// Whether the last scanned line was truncated mid-line by `scanner_error`.
    truncated_last_line: bool,
    /// End byte offset of the last surviving token on line `base_line - 1`, if any.
    last_retired_end: Option<usize>,
    /// Whether line `base_line - 1` contained a `TokenKind::Anchor` (`compat` mode only).
    last_retired_had_anchor: bool,
    /// Monotonic indentation stack of retired lines for `compat_indentation_message` (`compat` only).
    compat_parents: Vec<CompatParent>,
    #[cfg(test)]
    peak_tokens_len: usize,
    #[cfg(test)]
    peak_tokens_cap: usize,
}

impl<'a> LineWindow<'a> {
    pub(super) fn new(scanner: Scanner<'a>, input: &'a str, compat: bool) -> Self {
        Self::with_scratch(scanner, input, compat, WindowScratch::default())
    }

    pub(super) fn with_scratch(
        scanner: Scanner<'a>,
        input: &'a str,
        compat: bool,
        mut scratch: WindowScratch,
    ) -> Self {
        scratch.lines.clear();
        scratch.tokens.clear();
        scratch.flow_link_stack.clear();
        scratch.compat_parents.clear();
        let chunk = if input.len() <= 4096 {
            TOKEN_ARENA_SMALL_CHUNK
        } else {
            TOKEN_ARENA_CHUNK
        };
        Self {
            scanner,
            input,
            compat,
            base_line: 0,
            loaded_end: 0,
            retire_mark: 0,
            lines: scratch.lines,
            tokens: scratch.tokens,
            flow_link_stack: scratch.flow_link_stack,
            last_tokens: 0,
            last_consumed: 0,
            chunk,
            stream_start: None,
            stream_end: None,
            started: false,
            eof: false,
            scanner_error: None,
            prefetch_error: None,
            truncated_last_line: false,
            last_retired_end: None,
            last_retired_had_anchor: false,
            compat_parents: scratch.compat_parents,
            #[cfg(test)]
            peak_tokens_len: 0,
            #[cfg(test)]
            peak_tokens_cap: 0,
        }
    }

    pub(super) fn take_scratch(&mut self) -> WindowScratch {
        let mut scratch = WindowScratch {
            lines: std::mem::take(&mut self.lines),
            tokens: std::mem::take(&mut self.tokens),
            flow_link_stack: std::mem::take(&mut self.flow_link_stack),
            compat_parents: std::mem::take(&mut self.compat_parents),
            scanner: self.scanner.take_scratch(),
        };
        scratch.clear_and_clamp();
        scratch
    }

    #[inline]
    pub(super) fn loaded_end(&self) -> usize {
        self.loaded_end
    }

    #[inline]
    pub(super) fn stream_end(&self) -> Option<Span> {
        self.stream_end
    }

    #[inline]
    pub(super) fn end_offset(&self) -> usize {
        self.stream_end.map_or(self.input.len(), Span::start)
    }

    #[inline]
    pub(super) fn has_scanner_error(&self) -> bool {
        self.scanner_error.is_some()
    }

    #[inline]
    pub(super) fn truncated_last_line(&self) -> bool {
        self.truncated_last_line
    }

    #[cold]
    #[inline(never)]
    pub(super) fn take_scanner_error(&mut self) -> Result<(), Box<Error>> {
        if let Some(error) = self.scanner_error.take() {
            return Err(error.0);
        }
        Ok(())
    }

    /// Consume the scanner's `StreamStart` token once and return its span (preserving BOM offset).
    pub(super) fn ensure_started(&mut self, limits: &Limits) -> Result<Span, Box<Error>> {
        if self.started {
            return Ok(self.stream_start.unwrap_or_else(|| Span::empty(0)));
        }
        self.started = true;
        match self.scanner.next_token(limits)? {
            Some(token) if matches!(token.kind, TokenKind::StreamStart) => {
                self.stream_start = Some(token.span);
                Ok(token.span)
            }
            Some(token) if matches!(token.kind, TokenKind::StreamEnd) => {
                self.stream_end = Some(token.span);
                self.eof = true;
                Ok(Span::empty(0))
            }
            None => {
                self.eof = true;
                Ok(Span::empty(0))
            }
            Some(_) => Ok(Span::empty(0)),
        }
    }

    /// Ensure logical line `index` is scanned into the active batch, returning `true` if it exists
    /// or `false` if EOF/deferred flow error occurred before `index`.
    #[inline]
    pub(super) fn ensure_line(
        &mut self,
        index: usize,
        limits: &Limits,
    ) -> Result<bool, Box<Error>> {
        if index < self.loaded_end() {
            return Ok(true);
        }
        if self.eof && self.prefetch_error.is_none() {
            return Ok(false);
        }
        self.fill_to(index, limits)
    }

    /// Mark every logical line `< target` as retired. Actual reclamation happens once per batch
    /// inside [`Self::fill_to`], keeping the per-line hot path to a single integer max.
    #[inline]
    pub(super) fn retire_before(&mut self, target: usize) {
        if target > self.retire_mark {
            self.retire_mark = target;
        }
    }

    #[cold]
    #[inline(never)]
    fn fill_to(&mut self, target: usize, limits: &Limits) -> Result<bool, Box<Error>> {
        if let Some(error) = self.prefetch_error.take() {
            return Err(error.0);
        }
        if self.eof {
            return Ok(false);
        }
        if !self.started {
            self.ensure_started(limits)?;
        }
        self.flush_retired();

        let most = limits.max_events;
        let input = self.input;
        let input_len = self.scanner.input_len();
        let compat = self.compat;

        // Scan at least through `target`, then fill up to one bounded cache-friendly batch
        // sized to the input class in a tight scanner loop.
        let (max_batch_lines, max_batch_tokens) = batch_limits(input_len);
        let mut batch_lines = 0_usize;
        let batch_token_start = self.tokens.len();
        while !self.eof {
            let demanded = self.loaded_end <= target;
            if !demanded
                && (batch_lines >= max_batch_lines
                    || self.tokens.len().saturating_sub(batch_token_start) >= max_batch_tokens)
            {
                break;
            }
            let line_start = self.tokens.len();
            let mut saw_flow_on_line = false;
            let mut stop_batch = false;

            loop {
                let token = match self.scanner.next_token(limits) {
                    Ok(Some(token)) => token,
                    Ok(None) => {
                        self.eof = true;
                        break;
                    }
                    Err(error) => {
                        // Only defer *non-limit* scanner errors mid-line after a flow opener.
                        // Returning a scanner *limit* error on the demanded line (and parking it
                        // in `prefetch_error` when prefetched) preserves strict limit monotonicity:
                        // keeping partial tokens of a limit-truncated line can hide a later `:` or
                        // line break and swap `Ok` or one non-limit error into a different non-limit
                        // error.
                        if error.kind() != crate::error::ErrorKind::Limit
                            && self.scanner.saw_flow_start()
                        {
                            self.eof = true;
                            self.truncated_last_line = self.tokens.len() > line_start;
                            self.scanner_error = Some(AssertUnwindSafe(error));
                            break;
                        }
                        if demanded {
                            return Err(error);
                        }
                        // Speculative prefetch hit a scanner or limit error on a future line:
                        // discard partial tokens for this line and park the error until the parser
                        // actually demands `loaded_end()`.
                        self.tokens.truncate(line_start);
                        self.eof = true;
                        self.prefetch_error = Some(AssertUnwindSafe(error));
                        return Ok(target < self.loaded_end());
                    }
                };
                match token.kind {
                    TokenKind::StreamStart => {
                        self.stream_start = Some(token.span);
                    }
                    TokenKind::StreamEnd => {
                        self.stream_end = Some(token.span);
                        self.eof = true;
                        break;
                    }
                    TokenKind::LineBreak => {
                        if self.tokens.len() > line_start {
                            break;
                        }
                    }
                    TokenKind::FlowSequenceStart { .. } | TokenKind::FlowMappingStart { .. } => {
                        saw_flow_on_line = true;
                        self.push_token_into_window(token, most, input_len)?;
                    }
                    TokenKind::Scalar(ref scalar)
                        if matches!(scalar.style, ScalarStyle::Literal | ScalarStyle::Folded) =>
                    {
                        self.push_token_into_window(token, most, input_len)?;
                        break;
                    }
                    _ => {
                        self.push_token_into_window(token, most, input_len)?;
                    }
                }
            }

            if self.tokens.len() > line_start {
                if saw_flow_on_line {
                    link_flow_ends_with_stack(
                        &mut self.tokens[line_start..],
                        &mut self.flow_link_stack,
                    );
                }
                let first_kind = &self.tokens[line_start].kind;
                if matches!(first_kind, TokenKind::DocumentEnd)
                    || (self.loaded_end > 0
                        && matches!(first_kind, TokenKind::DocumentStart { .. }))
                {
                    stop_batch = true;
                }
                let line = Line::new(&self.tokens, line_start, self.tokens.len(), input, compat)?;
                if self.lines.capacity() == 0 {
                    let line_cap = if input_len <= 64 { 4 } else { max_batch_lines };
                    self.lines.reserve_exact(line_cap);
                }
                self.lines.push(line);
                self.loaded_end += 1;
                batch_lines += 1;
                if stop_batch && self.loaded_end > target {
                    break;
                }
            }
        }
        Ok(target < self.loaded_end)
    }

    fn flush_retired(&mut self) {
        let retire_to = self.retire_mark.min(self.loaded_end());
        if retire_to <= self.base_line {
            return;
        }
        let count = retire_to - self.base_line;
        if self.compat {
            for &line in &self.lines[..count] {
                if line.is_empty() {
                    push_compat_parent(
                        &mut self.compat_parents,
                        CompatParent {
                            indent: line.indent,
                            first_offset: None,
                            is_block_entry: false,
                        },
                    );
                } else {
                    let first = &self.tokens[line.start()];
                    push_compat_parent(
                        &mut self.compat_parents,
                        CompatParent {
                            indent: line.indent,
                            first_offset: Some(first.span.start()),
                            is_block_entry: matches!(first.kind, TokenKind::BlockEntry),
                        },
                    );
                }
            }
        }
        let last_retired = self.lines[count - 1];
        if last_retired.is_empty() {
            self.last_retired_end = None;
            self.last_retired_had_anchor = false;
        } else {
            self.last_retired_end = Some(self.tokens[last_retired.end() - 1].span.end());
            if self.compat {
                self.last_retired_had_anchor = self.tokens
                    [last_retired.start()..last_retired.end()]
                    .iter()
                    .any(|token| matches!(token.kind, TokenKind::Anchor));
            }
        }
        if count == self.lines.len() {
            self.lines.clear();
            self.last_tokens = 0;
            self.last_consumed = 0;
            if self.tokens.capacity() > WINDOW_SHRINK_CAP {
                self.tokens = Vec::new();
            } else {
                self.tokens.clear();
            }
        } else {
            let cut = compact_shift(
                last_retired.end(),
                self.tokens.len(),
                Some(self.lines[count].start()),
            );
            self.lines.drain(..count);
            if cut > 0 {
                self.tokens.drain(..cut);
                self.last_tokens = 0;
                self.last_consumed = 0;
                if self.tokens.capacity() > WINDOW_SHRINK_CAP
                    && self.tokens.len() <= WINDOW_BATCH_TOKENS
                {
                    self.tokens.shrink_to(WINDOW_BATCH_TOKENS);
                }
                let cut_u32 = fit_u32(cut);
                for line in &mut self.lines {
                    line.start -= cut_u32;
                    line.end -= cut_u32;
                }
            }
        }
        self.base_line = retire_to;
        self.loaded_end = self.base_line + self.lines.len();
    }

    #[inline]
    fn push_token_into_window(
        &mut self,
        token: Token,
        most: usize,
        input_len: usize,
    ) -> Result<(), Box<Error>> {
        if self.tokens.len() == self.tokens.capacity() {
            self.grow_tokens(token.span, most, input_len)?;
        }
        self.tokens.push(token);
        #[cfg(test)]
        {
            self.peak_tokens_len = self.peak_tokens_len.max(self.tokens.len());
            self.peak_tokens_cap = self.peak_tokens_cap.max(self.tokens.capacity());
        }
        Ok(())
    }

    #[cold]
    #[inline(never)]
    fn grow_tokens(&mut self, span: Span, most: usize, input_len: usize) -> Result<(), Box<Error>> {
        let len = self.tokens.len();
        let room = most.saturating_sub(len).max(1);
        let additional = if len == 0 {
            let init = if (65..=512).contains(&input_len) {
                SMALL_TOKEN_CAP
            } else {
                WINDOW_INIT_CHUNK
            };
            init.min(room)
        } else if len < WINDOW_BATCH_TOKENS {
            let target = if input_len <= 512 && len < SMALL_TOKEN_CAP {
                SMALL_TOKEN_CAP
            } else if input_len <= 512 && len < TOKEN_ARENA_SMALL_CHUNK {
                TOKEN_ARENA_SMALL_CHUNK
            } else if input_len <= 8_192 && len < MEDIUM_TOKEN_CAP {
                MEDIUM_TOKEN_CAP
            } else {
                WINDOW_BATCH_TOKENS + 64
            };
            target.saturating_sub(len).max(1).min(room)
        } else if len < WINDOW_SHRINK_CAP {
            // Stay at or below `WINDOW_SHRINK_CAP` for medium-width lines (`448..1024` tokens) so
            // the token buffer is reused across batches instead of jumping to `TOKEN_ARENA_CHUNK`
            // and immediately freeing on retirement.
            WINDOW_SHRINK_CAP.saturating_sub(len).max(1).min(room)
        } else if let Some(capacity) = prefix_token_capacity(
            len + 1,
            span.end(),
            self.last_tokens,
            if self.last_tokens == 0 {
                self.tokens.first().map_or(0, |t| t.span.start())
            } else {
                self.last_consumed
            },
            input_len,
            most,
        ) {
            self.last_tokens = len + 1;
            self.last_consumed = span.end();
            estimated_growth(len, capacity, self.chunk, most)
        } else {
            arena_growth(len, self.chunk).min(room)
        };
        reserve_tokens(
            &mut self.tokens,
            additional,
            most,
            span,
            self.input,
            self.compat,
        )
    }

    /// Nearest preceding line `< index` whose indent is strictly less than `indent`, returning its
    /// `(first_token_offset, is_block_entry)` if `indent == parent.indent + 1` and non-empty.
    #[cold]
    pub(super) fn compat_parent(&self, index: usize, indent: usize) -> Option<(usize, bool)> {
        let active_end = index.saturating_sub(self.base_line).min(self.lines.len());
        for &line in self.lines[..active_end].iter().rev() {
            if line.indent() < indent {
                if indent != line.indent() + 1 || line.is_empty() {
                    return None;
                }
                let token = &self.tokens[line.start()];
                return Some((
                    token.span.start(),
                    matches!(token.kind, TokenKind::BlockEntry),
                ));
            }
        }
        let parent = self
            .compat_parents
            .iter()
            .rev()
            .find(|parent| (parent.indent as usize) < indent)?;
        if indent != (parent.indent as usize) + 1 {
            return None;
        }
        parent
            .first_offset
            .map(|offset| (offset, parent.is_block_entry))
    }

    #[inline]
    pub(super) fn get_line(&self, index: usize) -> Option<Line> {
        let offset = index.checked_sub(self.base_line)?;
        self.lines.get(offset).copied()
    }

    #[inline]
    pub(super) fn line(&self, index: usize) -> Line {
        debug_assert!(
            index >= self.base_line && index < self.loaded_end(),
            "line {index} outside active window {}..{}",
            self.base_line,
            self.loaded_end()
        );
        self.lines[index - self.base_line]
    }

    #[inline]
    pub(super) fn line_slice(&self, line: Line) -> &[Token] {
        &self.tokens[line.start()..line.end()]
    }

    #[inline]
    pub(super) fn line_tokens(&self, index: usize) -> &[Token] {
        self.line_slice(self.line(index))
    }

    #[inline]
    pub(super) fn line_first(&self, index: usize) -> Option<&Token> {
        let line = self.get_line(index)?;
        if line.is_empty() {
            return None;
        }
        self.tokens.get(line.start())
    }

    pub(super) fn take_line_first_span(&mut self, index: usize) -> Option<Span> {
        let offset = index.checked_sub(self.base_line)?;
        let line = self.lines.get_mut(offset)?;
        if line.is_empty() {
            return None;
        }
        let span = self.tokens[line.start()].span;
        line.advance(1);
        Some(span)
    }

    #[inline]
    pub(super) fn run_tokens(&self, run: Run) -> &[Token] {
        let line = self.line(run.line());
        &self.tokens[line.start() + run.start()..line.start() + run.end()]
    }

    #[inline]
    pub(super) fn token_mut(&mut self, run: Run, offset: usize) -> &mut Token {
        let abs = self.line(run.line()).start() + run.start() + offset;
        &mut self.tokens[abs]
    }

    /// End byte offset of line `index`'s last surviving token, supporting both active lines and the
    /// immediately retired line `base_line - 1`.
    #[inline]
    pub(super) fn line_last_end(&self, index: usize) -> Option<usize> {
        if let Some(offset) = index.checked_sub(self.base_line) {
            let line = self.lines.get(offset)?;
            if line.is_empty() {
                return None;
            }
            return line
                .end()
                .checked_sub(1)
                .and_then(|end| self.tokens.get(end))
                .map(|token| token.span.end());
        }
        if index + 1 == self.base_line {
            return self.last_retired_end;
        }
        debug_assert!(
            false,
            "line_last_end requested for retired line {index} (base_line = {})",
            self.base_line
        );
        None
    }

    /// Whether line `index` contained a `TokenKind::Anchor` token (`compat` `&a::\n|` check).
    #[cold]
    pub(super) fn line_had_anchor(&self, index: usize) -> bool {
        if index >= self.base_line {
            return self
                .line_tokens(index)
                .iter()
                .any(|token| matches!(token.kind, TokenKind::Anchor));
        }
        if index + 1 == self.base_line {
            return self.last_retired_had_anchor;
        }
        false
    }

    /// Release all buffered lines, tokens, and auxiliary tables immediately.
    pub(super) fn release(&mut self) {
        self.lines = Vec::new();
        self.loaded_end = self.base_line;
        self.tokens = Vec::new();
        self.flow_link_stack = Vec::new();
        self.compat_parents = Vec::new();
    }

    /// Current tokens held in the active batch window.
    #[inline]
    pub(super) fn tokens_len(&self) -> usize {
        self.tokens.len()
    }

    #[cfg(test)]
    pub(super) fn tokens_cap(&self) -> usize {
        self.tokens.capacity()
    }

    #[cfg(test)]
    pub(super) fn peak_tokens_len(&self) -> usize {
        self.peak_tokens_len
    }

    #[cfg(test)]
    pub(super) fn peak_tokens_cap(&self) -> usize {
        self.peak_tokens_cap
    }

    /// Whether the currently buffered logical line(s) hold a large single-line flow shape that
    /// benefits from building the root tree whole and releasing the token buffer before the Serde
    /// target reads.
    ///
    /// Multi-line block documents only keep one bounded batch (`<= ~448` tokens, ~14 KiB) in the
    /// window at any time, so this returns `false` immediately without scanning.
    pub(super) fn should_build_whole(&self, drop_global_tags: bool) -> bool {
        if self.tokens.len() < 1_024 {
            return false;
        }
        let large_span = self.tokens.len() / 4;
        let mut anchors = 0_usize;
        for &line in &self.lines {
            let line_tokens = &self.tokens[line.start()..line.end()];
            for (index, token) in line_tokens.iter().enumerate() {
                match &token.kind {
                    TokenKind::Anchor => {
                        anchors += 1;
                        if next_node_is_large(line_tokens, index + 1, large_span) {
                            return true;
                        }
                    }
                    TokenKind::Tag(tag)
                        if !(tag.is_core_collection()
                            || tag.is_core_scalar()
                            || (drop_global_tags && tag.is_non_core_global())) =>
                    {
                        if next_node_is_large(line_tokens, index + 1, large_span) {
                            return true;
                        }
                    }
                    TokenKind::Key => {
                        if next_node_is_large(line_tokens, index + 1, large_span) {
                            return true;
                        }
                    }
                    TokenKind::FlowSequenceStart { end } | TokenKind::FlowMappingStart { end } => {
                        if let Some(delta) = matched_flow_end(*end)
                            && delta >= large_span
                            && index
                                .checked_add(delta)
                                .and_then(|close| close.checked_add(1))
                                .and_then(|next| line_tokens.get(next))
                                .is_some_and(|t| matches!(t.kind, TokenKind::Value))
                        {
                            return true;
                        }
                    }
                    _ => {}
                }
            }
        }
        anchors >= 16 && anchors.saturating_mul(32) >= self.tokens.len()
    }
}

#[cold]
fn push_compat_parent(parents: &mut Vec<CompatParent>, parent: CompatParent) {
    while parents
        .last()
        .is_some_and(|top| top.indent >= parent.indent)
    {
        parents.pop();
    }
    parents.push(parent);
}

fn next_node_is_large(line_tokens: &[Token], mut index: usize, large_span: usize) -> bool {
    while matches!(
        line_tokens.get(index).map(|t| &t.kind),
        Some(TokenKind::Anchor | TokenKind::Tag(_))
    ) {
        index += 1;
    }
    if let Some(TokenKind::FlowSequenceStart { end } | TokenKind::FlowMappingStart { end }) =
        line_tokens.get(index).map(|t| &t.kind)
    {
        return matched_flow_end(*end).is_some_and(|delta| delta >= large_span);
    }
    false
}

/// Whole-document logical-line reader retained for arena-growth unit tests.
#[cfg(test)]
pub(super) struct Lines {
    pub(super) tokens: Vec<Token>,
    pub(super) growths: usize,
}

#[cfg(test)]
pub(super) fn read_lines(scanner: &mut Scanner<'_>, limits: &Limits) -> Result<Lines, Box<Error>> {
    let input = scanner.input();
    let input_len = scanner.input_len();
    let compat = scanner.is_compat();
    let most = limits.max_events;
    let mut mid_capacity = None;
    let (initial_chunk, chunk) = match input_len {
        0..=4096 => (TOKEN_ARENA_SMALL_CHUNK, TOKEN_ARENA_SMALL_CHUNK),
        4097..=32768 => {
            let line_count = lines_at_most(input.as_bytes());
            mid_capacity = mid_input_token_capacity(input_len, line_count, most);
            (TOKEN_ARENA_MID_CHUNK, TOKEN_ARENA_MID_CHUNK)
        }
        _ => {
            let sample = &input.as_bytes()[..4096];
            let sample_lines = lines_at_most(sample);
            if sample_lines == 0 || sample.len() / sample_lines > 80 {
                (TOKEN_ARENA_SMALL_CHUNK, TOKEN_ARENA_CHUNK)
            } else if sample.len() / sample_lines <= 10 {
                (TOKEN_ARENA_WIDE_CHUNK, TOKEN_ARENA_WIDE_CHUNK)
            } else {
                (TOKEN_ARENA_CHUNK, TOKEN_ARENA_CHUNK)
            }
        }
    };
    let mut tokens = Vec::new();
    let mut flow_stack = Vec::new();
    if let Some(capacity) = mid_capacity {
        reserve_tokens(&mut tokens, capacity, most, Span::empty(0), input, compat)?;
    }
    let mut last_tokens = 0_usize;
    let mut last_consumed = 0_usize;
    let mut line_start = 0;
    let mut saw_flow_on_line = false;
    let mut growths = 0;
    loop {
        let token = match scanner.next_token(limits) {
            Ok(Some(token)) => token,
            Ok(None) => break,
            Err(error) => {
                if !scanner.saw_flow_start() {
                    return Err(error);
                }
                break;
            }
        };
        match token.kind {
            TokenKind::StreamStart => {}
            TokenKind::StreamEnd => break,
            TokenKind::LineBreak => {
                if tokens.len() > line_start {
                    if saw_flow_on_line {
                        link_flow_ends_with_stack(&mut tokens[line_start..], &mut flow_stack);
                        saw_flow_on_line = false;
                    }
                    let _ = Line::new(&tokens, line_start, tokens.len(), input, compat)?;
                    line_start = tokens.len();
                }
            }
            _ => {
                let block_scalar = token.kind.scalar_style().is_some_and(|style| {
                    matches!(style, ScalarStyle::Literal | ScalarStyle::Folded)
                });
                saw_flow_on_line |= matches!(
                    token.kind,
                    TokenKind::FlowSequenceStart { .. } | TokenKind::FlowMappingStart { .. }
                );
                let consumed = token.span.end();
                if tokens.is_empty() {
                    last_consumed = token.span.start();
                }
                let capacity_before = tokens.capacity();
                if tokens.len() == tokens.capacity() {
                    let room = most.saturating_sub(tokens.len()).max(1);
                    let step_chunk = if tokens.is_empty() {
                        initial_chunk
                    } else {
                        chunk
                    };
                    let additional = if let Some(capacity) = prefix_token_capacity(
                        tokens.len() + 1,
                        consumed,
                        last_tokens,
                        last_consumed,
                        input_len,
                        most,
                    ) {
                        last_tokens = tokens.len() + 1;
                        last_consumed = consumed;
                        estimated_growth(tokens.len(), capacity, step_chunk, most)
                    } else {
                        arena_growth(tokens.len(), step_chunk).min(room)
                    };
                    reserve_tokens(&mut tokens, additional, most, token.span, input, compat)?;
                }
                tokens.push(token);
                growths += usize::from(tokens.capacity() != capacity_before);
                if block_scalar {
                    if saw_flow_on_line {
                        link_flow_ends_with_stack(&mut tokens[line_start..], &mut flow_stack);
                        saw_flow_on_line = false;
                    }
                    let _ = Line::new(&tokens, line_start, tokens.len(), input, compat)?;
                    line_start = tokens.len();
                }
            }
        }
    }
    if tokens.len() > line_start {
        if saw_flow_on_line {
            link_flow_ends_with_stack(&mut tokens[line_start..], &mut flow_stack);
        }
        let _ = Line::new(&tokens, line_start, tokens.len(), input, compat)?;
    }
    if tokens.len() <= 8192 {
        tokens.shrink_to_fit();
    }
    Ok(Lines { tokens, growths })
}