Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_core/
sexpr_projection.rs

1//! Allocation-bounded structural selection over KiCad S-expression source.
2
3mod scanner;
4
5use crate::sexpr::{
6    Error, ErrorKind, ErrorPhase, Lexer, Position, Sexp, Token, TokenKind, decode_quoted,
7    is_teardrop_numeric_key, parse,
8};
9use scanner::scan_form_spans_unsorted;
10use std::borrow::Cow;
11use std::collections::BTreeSet;
12use std::io::{Read, Seek, SeekFrom};
13use std::ops::Range;
14#[cfg(feature = "measurement")]
15use std::time::Instant;
16
17/// A source-form selector. Empty optional sets mean no restriction.
18#[derive(Clone, Debug, Default, Eq, PartialEq)]
19pub struct Selector {
20    pub heads: Option<BTreeSet<String>>,
21    pub paths: Option<BTreeSet<Vec<String>>>,
22    pub min_depth: Option<usize>,
23    pub max_depth: Option<usize>,
24    pub prune_heads: BTreeSet<String>,
25}
26
27impl Selector {
28    /// Validate depth bounds before scanning untrusted input.
29    pub fn validate(&self) -> Result<(), Error> {
30        if self
31            .min_depth
32            .zip(self.max_depth)
33            .is_some_and(|(minimum, maximum)| minimum > maximum)
34        {
35            return Err(Error::at(
36                ErrorPhase::Tree,
37                ErrorKind::InvalidSelector,
38                "Selector min_depth cannot exceed max_depth",
39                Position::START,
40            ));
41        }
42        Ok(())
43    }
44
45    fn matches(&self, span: &FormSpan) -> bool {
46        if self
47            .heads
48            .as_ref()
49            .is_some_and(|heads| span.head.as_ref().is_none_or(|head| !heads.contains(head)))
50        {
51            return false;
52        }
53        if self
54            .paths
55            .as_ref()
56            .is_some_and(|paths| !paths.contains(&span.path))
57        {
58            return false;
59        }
60        if self.min_depth.is_some_and(|minimum| span.depth < minimum) {
61            return false;
62        }
63        if self.max_depth.is_some_and(|maximum| span.depth > maximum) {
64            return false;
65        }
66        true
67    }
68
69    fn matches_parts<'path, I>(&self, head: Option<&str>, path: I, depth: usize) -> bool
70    where
71        I: Clone + Iterator<Item = &'path str>,
72    {
73        if self
74            .heads
75            .as_ref()
76            .is_some_and(|heads| head.is_none_or(|value| !heads.contains(value)))
77        {
78            return false;
79        }
80        if self.paths.as_ref().is_some_and(|paths| {
81            !paths
82                .iter()
83                .any(|target| target.iter().map(String::as_str).eq(path.clone()))
84        }) {
85            return false;
86        }
87        if self.min_depth.is_some_and(|minimum| depth < minimum) {
88            return false;
89        }
90        if self.max_depth.is_some_and(|maximum| depth > maximum) {
91            return false;
92        }
93        true
94    }
95
96    fn should_scan_children<'path, I>(&self, head: Option<&str>, path: I, depth: usize) -> bool
97    where
98        I: Clone + Iterator<Item = &'path str>,
99    {
100        if head.is_some_and(|value| self.prune_heads.contains(value)) {
101            return false;
102        }
103        if self.max_depth.is_some_and(|maximum| depth >= maximum) {
104            return false;
105        }
106        self.paths.as_ref().is_none_or(|paths| {
107            paths.iter().any(|target| {
108                let mut active = path.clone();
109                let prefix_matches = target
110                    .iter()
111                    .map(String::as_str)
112                    .zip(active.by_ref())
113                    .all(|(expected, actual)| expected == actual);
114                prefix_matches && active.next().is_none() && target.len() > path.clone().count()
115            })
116        })
117    }
118}
119
120/// Exact byte and line/column range for one complete list form.
121#[derive(Clone, Debug, Eq, PartialEq)]
122pub struct FormSpan {
123    pub head: Option<String>,
124    pub path: Vec<String>,
125    pub depth: usize,
126    pub range: Range<usize>,
127    pub start: Position,
128    pub end: Position,
129}
130
131impl FormSpan {
132    /// Borrow this form from the original source.
133    pub fn text<'a>(&self, source: &'a str) -> Result<&'a str, Error> {
134        source.get(self.range.clone()).ok_or_else(|| {
135            Error::at(
136                ErrorPhase::Tree,
137                ErrorKind::InvalidSpan,
138                "Form span is not a valid range for this source",
139                self.start,
140            )
141        })
142    }
143}
144
145/// Reusable structural form index. It owns metadata, never source text.
146#[derive(Clone, Debug, Eq, PartialEq)]
147pub struct StructuralIndex {
148    source_len: usize,
149    forms: Vec<FormSpan>,
150}
151
152impl StructuralIndex {
153    /// Scan all visible forms once for repeated selectors.
154    pub fn new(source: &str) -> Result<Self, Error> {
155        Ok(Self {
156            source_len: source.len(),
157            forms: scan_form_spans(source, &Selector::default())?,
158        })
159    }
160
161    pub fn source_len(&self) -> usize {
162        self.source_len
163    }
164
165    pub fn forms(&self) -> &[FormSpan] {
166        &self.forms
167    }
168
169    /// Select indexed forms without rescanning the source.
170    pub fn select<'a>(&'a self, selector: &'a Selector) -> Result<Vec<&'a FormSpan>, Error> {
171        selector.validate()?;
172        Ok(self
173            .forms
174            .iter()
175            .filter(|span| selector.matches(span) && !is_pruned(span, selector))
176            .collect())
177    }
178}
179
180fn is_pruned(span: &FormSpan, selector: &Selector) -> bool {
181    let ancestor_count = span
182        .path
183        .len()
184        .saturating_sub(usize::from(span.head.is_some()));
185    span.path[..ancestor_count]
186        .iter()
187        .any(|head| selector.prune_heads.contains(head))
188}
189
190#[derive(Debug)]
191struct Frame<Head> {
192    head: Option<Head>,
193    depth: usize,
194    start: Position,
195    visible: bool,
196    scan_children: bool,
197    awaiting_head: bool,
198    teardrop_bare_field: TeardropBareField,
199}
200
201#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
202enum TeardropBareField {
203    #[default]
204    None,
205    AwaitingValue,
206    AwaitingClose,
207}
208
209/// Select complete list forms without materializing a token vector or tree.
210pub fn scan_form_spans(source: &str, selector: &Selector) -> Result<Vec<FormSpan>, Error> {
211    let mut spans = scan_form_spans_unsorted(source, selector)?;
212    spans.sort_by_key(|span| span.range.start);
213    Ok(spans)
214}
215
216/// Test-only timing split for select-all scan and source-order sorting.
217#[cfg(feature = "measurement")]
218#[doc(hidden)]
219pub fn measure_form_span_sort(
220    source: &str,
221    selector: &Selector,
222) -> Result<(Vec<FormSpan>, u128, u128), Error> {
223    let scan_started = Instant::now();
224    let mut spans = scan_form_spans_unsorted(source, selector)?;
225    let scan_ns = scan_started.elapsed().as_nanos();
226    let sort_started = Instant::now();
227    spans.sort_by_key(|span| span.range.start);
228    let sort_ns = sort_started.elapsed().as_nanos();
229    Ok((spans, scan_ns, sort_ns))
230}
231
232/// Materialize only one previously selected form.
233pub fn parse_form(source: &str, span: &FormSpan) -> Result<Sexp, Error> {
234    parse(span.text(source)?)
235}
236
237fn token_head<'source>(token: &Token<'source>) -> Cow<'source, str> {
238    match token.kind {
239        TokenKind::QuotedString => Cow::Owned(decode_quoted(token.lexeme)),
240        _ => Cow::Borrowed(token.lexeme),
241    }
242}
243
244fn resource_error(message: &'static str, position: Position) -> Error {
245    Error::at(
246        ErrorPhase::Tree,
247        ErrorKind::ResourceLimit,
248        message,
249        position,
250    )
251}
252
253#[derive(Clone, Copy, Debug, Eq, PartialEq)]
254enum StreamLexState {
255    Normal,
256    Atom,
257    Unicode { in_atom: bool },
258    Quoted { escaped: bool },
259    Comment,
260}
261
262struct Utf8Validator {
263    remaining: u8,
264    next_min: u8,
265    next_max: u8,
266    sequence_start: Position,
267}
268
269impl Utf8Validator {
270    fn new() -> Self {
271        Self {
272            remaining: 0,
273            next_min: 0x80,
274            next_max: 0xbf,
275            sequence_start: Position::START,
276        }
277    }
278
279    fn accept(&mut self, byte: u8, position: Position) -> Result<(), Error> {
280        if self.remaining != 0 {
281            if !(self.next_min..=self.next_max).contains(&byte) {
282                return Err(invalid_utf8(position));
283            }
284            self.remaining -= 1;
285            self.next_min = 0x80;
286            self.next_max = 0xbf;
287            return Ok(());
288        }
289        if byte <= 0x7f {
290            return Ok(());
291        }
292        self.sequence_start = position;
293        match byte {
294            0xc2..=0xdf => self.remaining = 1,
295            0xe0 => {
296                self.remaining = 2;
297                self.next_min = 0xa0;
298            }
299            0xe1..=0xec | 0xee..=0xef => self.remaining = 2,
300            0xed => {
301                self.remaining = 2;
302                self.next_max = 0x9f;
303            }
304            0xf0 => {
305                self.remaining = 3;
306                self.next_min = 0x90;
307            }
308            0xf1..=0xf3 => self.remaining = 3,
309            0xf4 => {
310                self.remaining = 3;
311                self.next_max = 0x8f;
312            }
313            _ => return Err(invalid_utf8(position)),
314        }
315        Ok(())
316    }
317
318    fn finish(&self) -> Result<(), Error> {
319        if self.remaining == 0 {
320            Ok(())
321        } else {
322            Err(invalid_utf8(self.sequence_start))
323        }
324    }
325}
326
327fn invalid_utf8(position: Position) -> Error {
328    Error::at(
329        ErrorPhase::Lex,
330        ErrorKind::InvalidUtf8,
331        "KiCad S-expression input is not valid UTF-8",
332        position,
333    )
334}
335
336struct StreamingProjection<'a> {
337    selector: &'a Selector,
338    stack: Vec<Frame<String>>,
339    spans: Vec<FormSpan>,
340    state: StreamLexState,
341    position: Position,
342    token_start: Position,
343    head_bytes: Vec<u8>,
344    unicode_bytes: Vec<u8>,
345    collect_head: bool,
346    collect_teardrop_scalar: bool,
347    saw_root: bool,
348    line_has_content: bool,
349    last_was_cr: bool,
350    utf8: Utf8Validator,
351}
352
353impl<'a> StreamingProjection<'a> {
354    fn new(selector: &'a Selector) -> Self {
355        Self {
356            selector,
357            stack: Vec::new(),
358            spans: Vec::new(),
359            state: StreamLexState::Normal,
360            position: Position::START,
361            token_start: Position::START,
362            head_bytes: Vec::new(),
363            unicode_bytes: Vec::new(),
364            collect_head: false,
365            collect_teardrop_scalar: false,
366            saw_root: false,
367            line_has_content: false,
368            last_was_cr: false,
369            utf8: Utf8Validator::new(),
370        }
371    }
372
373    #[allow(
374        clippy::too_many_lines,
375        reason = "pre-standard byte-state transition retained under the structural ratchet"
376    )]
377    fn feed(&mut self, byte: u8) -> Result<(), Error> {
378        self.utf8.accept(byte, self.position)?;
379        let mut reprocess = true;
380        while reprocess {
381            reprocess = false;
382            match self.state {
383                StreamLexState::Comment => {
384                    if matches!(byte, b'\r' | b'\n') {
385                        self.state = StreamLexState::Normal;
386                        reprocess = true;
387                    } else {
388                        self.advance(byte);
389                    }
390                }
391                StreamLexState::Atom => {
392                    if is_ascii_separator(byte) {
393                        self.finish_head(false)?;
394                        self.state = StreamLexState::Normal;
395                        reprocess = true;
396                    } else if !byte.is_ascii() {
397                        self.unicode_bytes.clear();
398                        self.unicode_bytes.push(byte);
399                        self.state = StreamLexState::Unicode { in_atom: true };
400                        self.advance(byte);
401                    } else {
402                        self.push_head_byte(byte)?;
403                        self.advance(byte);
404                    }
405                }
406                StreamLexState::Unicode { in_atom } => {
407                    self.unicode_bytes.push(byte);
408                    self.advance(byte);
409                    if self.utf8.remaining == 0 {
410                        self.finish_unicode_scalar(in_atom)?;
411                    }
412                }
413                StreamLexState::Quoted { escaped } => {
414                    self.push_head_byte(byte)?;
415                    self.advance(byte);
416                    if escaped {
417                        self.state = StreamLexState::Quoted { escaped: false };
418                    } else if byte == b'\\' {
419                        self.state = StreamLexState::Quoted { escaped: true };
420                    } else if byte == b'"' {
421                        self.finish_head(true)?;
422                        self.state = StreamLexState::Normal;
423                        self.line_has_content = true;
424                    }
425                }
426                StreamLexState::Normal => match byte {
427                    b if is_ascii_space(b) => self.advance(b),
428                    b'#' if !self.line_has_content => {
429                        self.state = StreamLexState::Comment;
430                        self.advance(byte);
431                    }
432                    b'(' => {
433                        self.open_form()?;
434                        self.line_has_content = true;
435                        self.advance(byte);
436                    }
437                    b')' => {
438                        let close = self.position;
439                        self.line_has_content = true;
440                        self.advance(byte);
441                        self.close_form(close)?;
442                    }
443                    b'"' => {
444                        self.begin_head();
445                        self.push_head_byte(byte)?;
446                        self.state = StreamLexState::Quoted { escaped: false };
447                        self.line_has_content = true;
448                        self.advance(byte);
449                    }
450                    non_ascii if !non_ascii.is_ascii() => {
451                        self.begin_head();
452                        self.unicode_bytes.clear();
453                        self.unicode_bytes.push(non_ascii);
454                        self.state = StreamLexState::Unicode { in_atom: false };
455                        self.advance(non_ascii);
456                    }
457                    _ => {
458                        if self.stack.is_empty() {
459                            return Err(Error::at(
460                                ErrorPhase::Tree,
461                                ErrorKind::MissingOpeningParenthesis,
462                                "Missing initial opening parenthesis",
463                                self.position,
464                            ));
465                        }
466                        self.begin_head();
467                        self.push_head_byte(byte)?;
468                        self.state = StreamLexState::Atom;
469                        self.line_has_content = true;
470                        self.advance(byte);
471                    }
472                },
473            }
474        }
475        Ok(())
476    }
477
478    fn finish(mut self) -> Result<Vec<FormSpan>, Error> {
479        if self.state == StreamLexState::Atom {
480            self.finish_head(false)?;
481        } else if matches!(self.state, StreamLexState::Quoted { .. }) {
482            return Err(Error::at(
483                ErrorPhase::Lex,
484                ErrorKind::UnterminatedString,
485                "Unterminated delimited string",
486                self.token_start,
487            ));
488        }
489        self.utf8.finish()?;
490        if matches!(self.state, StreamLexState::Unicode { .. }) {
491            return Err(invalid_utf8(self.token_start));
492        }
493        if let Some(frame) = self.stack.last() {
494            return Err(Error::at(
495                ErrorPhase::Tree,
496                ErrorKind::UnbalancedOpeningParenthesis,
497                "Unbalanced opening parenthesis",
498                frame.start,
499            ));
500        }
501        if !self.saw_root {
502            return Err(Error::at(
503                ErrorPhase::Tree,
504                ErrorKind::EmptyExpression,
505                "No or empty expression",
506                Position::START,
507            ));
508        }
509        Ok(self.spans)
510    }
511
512    fn open_form(&mut self) -> Result<(), Error> {
513        // The scanner keeps an explicit stack, so nesting has no ceiling.
514        if self.stack.last().is_some_and(|parent| parent.awaiting_head) {
515            let (visible, depth) = {
516                let parent = self.stack.last_mut().expect("checked above");
517                parent.awaiting_head = false;
518                (parent.visible, parent.depth)
519            };
520            let scan_children = visible
521                && self.selector.should_scan_children(
522                    None,
523                    self.stack.iter().filter_map(|frame| frame.head.as_deref()),
524                    depth,
525                );
526            self.stack.last_mut().expect("checked above").scan_children = scan_children;
527        }
528        let visible = self.stack.last().is_none_or(|parent| parent.scan_children);
529        self.stack.push(Frame {
530            head: None,
531            depth: self.stack.len(),
532            start: self.position,
533            visible,
534            scan_children: visible,
535            awaiting_head: true,
536            teardrop_bare_field: TeardropBareField::None,
537        });
538        self.saw_root = true;
539        Ok(())
540    }
541
542    fn close_form(&mut self, close: Position) -> Result<(), Error> {
543        if self.stack.last().is_some_and(|frame| {
544            frame.head.as_deref() == Some("teardrops")
545                && frame.teardrop_bare_field == TeardropBareField::AwaitingClose
546        }) {
547            self.stack
548                .last_mut()
549                .expect("checked above")
550                .teardrop_bare_field = TeardropBareField::None;
551            return Ok(());
552        }
553        let Some(frame) = self.stack.last() else {
554            return Err(Error::at(
555                ErrorPhase::Tree,
556                ErrorKind::UnbalancedClosingParenthesis,
557                "Unbalanced closing parenthesis",
558                close,
559            ));
560        };
561        let selected = frame.visible
562            && self.selector.matches_parts(
563                frame.head.as_deref(),
564                self.stack.iter().filter_map(|item| item.head.as_deref()),
565                frame.depth,
566            );
567        let frame = self.stack.pop().expect("checked above");
568        if selected {
569            let mut path = self
570                .stack
571                .iter()
572                .filter_map(|item| item.head.clone())
573                .collect::<Vec<_>>();
574            if let Some(head) = frame.head.as_ref() {
575                path.push(head.clone());
576            }
577            let span = FormSpan {
578                head: frame.head,
579                path,
580                depth: frame.depth,
581                range: frame.start.offset..self.position.offset,
582                start: frame.start,
583                end: self.position,
584            };
585            self.spans.push(span);
586        }
587        Ok(())
588    }
589
590    fn begin_head(&mut self) {
591        self.token_start = self.position;
592        self.collect_head = self.stack.last().is_some_and(|frame| frame.awaiting_head);
593        self.collect_teardrop_scalar = self.stack.last().is_some_and(|frame| {
594            frame.head.as_deref() == Some("teardrops")
595                && frame.teardrop_bare_field != TeardropBareField::AwaitingClose
596        });
597        self.head_bytes.clear();
598    }
599
600    fn push_head_byte(&mut self, byte: u8) -> Result<(), Error> {
601        if self.collect_head || self.collect_teardrop_scalar {
602            self.head_bytes.push(byte);
603        }
604        Ok(())
605    }
606
607    fn finish_head(&mut self, quoted: bool) -> Result<(), Error> {
608        if !self.collect_head && !self.collect_teardrop_scalar {
609            return Ok(());
610        }
611        let text =
612            std::str::from_utf8(&self.head_bytes).map_err(|_| invalid_utf8(self.token_start))?;
613        let head = if quoted {
614            decode_quoted(text)
615        } else {
616            text.to_owned()
617        };
618        if !self.collect_head {
619            let frame = self.stack.last_mut().ok_or_else(|| {
620                Error::at(
621                    ErrorPhase::Tree,
622                    ErrorKind::MissingOpeningParenthesis,
623                    "Missing initial opening parenthesis",
624                    self.token_start,
625                )
626            })?;
627            frame.teardrop_bare_field = match frame.teardrop_bare_field {
628                TeardropBareField::None if is_teardrop_numeric_key(&head) => {
629                    TeardropBareField::AwaitingValue
630                }
631                TeardropBareField::AwaitingValue => TeardropBareField::AwaitingClose,
632                state => state,
633            };
634            self.collect_teardrop_scalar = false;
635            return Ok(());
636        }
637        let Some(frame) = self.stack.last_mut() else {
638            return Err(Error::at(
639                ErrorPhase::Tree,
640                ErrorKind::MissingOpeningParenthesis,
641                "Missing initial opening parenthesis",
642                self.token_start,
643            ));
644        };
645        frame.head = Some(head);
646        frame.awaiting_head = false;
647        let (visible, depth) = (frame.visible, frame.depth);
648        let scan_children = visible
649            && self.selector.should_scan_children(
650                self.stack.last().and_then(|item| item.head.as_deref()),
651                self.stack.iter().filter_map(|item| item.head.as_deref()),
652                depth,
653            );
654        self.stack
655            .last_mut()
656            .expect("head belongs to an active frame")
657            .scan_children = scan_children;
658        self.collect_head = false;
659        self.collect_teardrop_scalar = false;
660        Ok(())
661    }
662
663    fn finish_unicode_scalar(&mut self, in_atom: bool) -> Result<(), Error> {
664        let text =
665            std::str::from_utf8(&self.unicode_bytes).map_err(|_| invalid_utf8(self.token_start))?;
666        let Some(character) = text.chars().next() else {
667            return Err(invalid_utf8(self.token_start));
668        };
669        if character.is_whitespace() {
670            if in_atom {
671                self.finish_head(false)?;
672            } else {
673                self.collect_head = false;
674                self.head_bytes.clear();
675            }
676            self.state = StreamLexState::Normal;
677            return Ok(());
678        }
679        if !in_atom && self.stack.is_empty() {
680            return Err(Error::at(
681                ErrorPhase::Tree,
682                ErrorKind::MissingOpeningParenthesis,
683                "Missing initial opening parenthesis",
684                self.token_start,
685            ));
686        }
687        let bytes = std::mem::take(&mut self.unicode_bytes);
688        for byte in bytes {
689            self.push_head_byte(byte)?;
690        }
691        self.line_has_content = true;
692        self.state = StreamLexState::Atom;
693        Ok(())
694    }
695
696    fn advance(&mut self, byte: u8) {
697        self.position.offset = self.position.offset.saturating_add(1);
698        match byte {
699            b'\r' => {
700                self.position.line = self.position.line.saturating_add(1);
701                self.position.column = 1;
702                self.line_has_content = false;
703                self.last_was_cr = true;
704            }
705            b'\n' => {
706                if !self.last_was_cr {
707                    self.position.line = self.position.line.saturating_add(1);
708                }
709                self.position.column = 1;
710                self.line_has_content = false;
711                self.last_was_cr = false;
712            }
713            continuation if continuation & 0xc0 == 0x80 => {
714                self.last_was_cr = false;
715            }
716            _ => {
717                self.position.column = self.position.column.saturating_add(1);
718                self.last_was_cr = false;
719            }
720        }
721    }
722}
723
724fn is_ascii_space(byte: u8) -> bool {
725    matches!(byte, b' ' | b'\t' | b'\r' | b'\n' | 0x0b | 0x0c)
726}
727
728fn is_ascii_separator(byte: u8) -> bool {
729    is_ascii_space(byte) || matches!(byte, b'(' | b')')
730}
731
732/// Scan selected metadata from a native byte stream without retaining the file.
733pub fn scan_reader_form_spans<R: Read>(
734    mut reader: R,
735    selector: &Selector,
736) -> Result<Vec<FormSpan>, Error> {
737    selector.validate()?;
738    let mut scanner = StreamingProjection::new(selector);
739    let mut buffer = [0_u8; 64 * 1024];
740    loop {
741        let count = reader.read(&mut buffer).map_err(|_| {
742            Error::at(
743                ErrorPhase::Lex,
744                ErrorKind::Io,
745                "Failed to read S-expression source",
746                scanner.position,
747            )
748        })?;
749        if count == 0 {
750            break;
751        }
752        for byte in &buffer[..count] {
753            scanner.feed(*byte)?;
754        }
755    }
756    let mut spans = scanner.finish()?;
757    spans.sort_by_key(|span| span.range.start);
758    Ok(spans)
759}
760
761/// Test-only timing split for streaming select-all scan and source-order sort.
762#[cfg(feature = "measurement")]
763#[doc(hidden)]
764pub fn measure_reader_form_span_sort<R: Read>(
765    mut reader: R,
766    selector: &Selector,
767) -> Result<(Vec<FormSpan>, u128, u128), Error> {
768    selector.validate()?;
769    let scan_started = Instant::now();
770    let mut scanner = StreamingProjection::new(selector);
771    let mut buffer = [0_u8; 64 * 1024];
772    loop {
773        let count = reader.read(&mut buffer).map_err(|_| {
774            Error::at(
775                ErrorPhase::Lex,
776                ErrorKind::Io,
777                "Failed to read S-expression source",
778                scanner.position,
779            )
780        })?;
781        if count == 0 {
782            break;
783        }
784        for byte in &buffer[..count] {
785            scanner.feed(*byte)?;
786        }
787    }
788    let mut spans = scanner.finish()?;
789    let scan_ns = scan_started.elapsed().as_nanos();
790    let sort_started = Instant::now();
791    spans.sort_by_key(|span| span.range.start);
792    let sort_ns = sort_started.elapsed().as_nanos();
793    Ok((spans, scan_ns, sort_ns))
794}
795
796/// Seek and read only one selected form from an indexed native source.
797pub fn read_form_bytes<R: Read + Seek>(
798    reader: &mut R,
799    span: &FormSpan,
800    max_form_bytes: usize,
801) -> Result<Vec<u8>, Error> {
802    let Some(length) = span.range.end.checked_sub(span.range.start) else {
803        return Err(Error::at(
804            ErrorPhase::Tree,
805            ErrorKind::InvalidSpan,
806            "Selected form has an inverted byte range",
807            span.start,
808        ));
809    };
810    if length > max_form_bytes {
811        return Err(resource_error(
812            "Selected form exceeds max_form_bytes",
813            span.start,
814        ));
815    }
816    let offset = u64::try_from(span.range.start).map_err(|_| {
817        Error::at(
818            ErrorPhase::Lex,
819            ErrorKind::Io,
820            "Selected form offset cannot be represented by native I/O",
821            span.start,
822        )
823    })?;
824    reader.seek(SeekFrom::Start(offset)).map_err(|_| {
825        Error::at(
826            ErrorPhase::Lex,
827            ErrorKind::Io,
828            "Failed to seek to selected form",
829            span.start,
830        )
831    })?;
832    let mut output = vec![0_u8; length];
833    reader.read_exact(&mut output).map_err(|_| {
834        Error::at(
835            ErrorPhase::Lex,
836            ErrorKind::Io,
837            "Failed to read complete selected form",
838            span.start,
839        )
840    })?;
841    Ok(output)
842}