Skip to main content

hol_cigar/
chunking.rs

1//! Exact source partitioning at caller-supplied syntax boundaries. No parser or I/O is implicit.
2
3use crate::{ContextError, Document};
4
5impl Document {
6    /// Partition exact source bytes at explicit one-based, absolute line starts.
7    ///
8    /// The first chunk begins at `self.start_line`; `starts` contains only later starts,
9    /// strictly increasing. Every chunk must contain non-whitespace text. Nothing is omitted,
10    /// normalized or overlapped; LF and CRLF are preserved. IDs use `original_id:L<start>`.
11    /// At most 4096 chunks and 16 MiB of input are accepted. Memory for locating boundaries
12    /// is proportional to the number of chunks, not the number of lines.
13    ///
14    /// A caller-owned parser chooses complete syntax units. This function checks source ranges,
15    /// not language syntax, execution safety, source authority or semantic dependencies. Replace
16    /// the whole source after edits so obsolete chunks are withdrawn; repair hard edges explicitly.
17    pub fn chunks_at_lines(&self, starts: &[usize]) -> Result<Vec<Self>, ContextError> {
18        if self.text.len() > 16_777_216 || starts.len() >= 4096 {
19            return Err(ContextError::LimitExceeded);
20        }
21        if self.id.len() > 100
22            || !crate::graph::valid_id(&self.id)
23            || self.start_line == 0
24            || self.source.is_empty()
25            || self.source.len() > 2048
26            || self.source.chars().any(char::is_control)
27            || self.text.trim().is_empty()
28            || starts.first().is_some_and(|line| *line <= self.start_line)
29            || starts.windows(2).any(|pair| pair.first() >= pair.get(1))
30        {
31            return Err(ContextError::InvalidInput);
32        }
33        let mut offsets = Vec::with_capacity(starts.len() + 1);
34        offsets.push((self.start_line, 0_usize));
35        let mut line = self.start_line;
36        let mut offset = 0;
37        let mut next = 0;
38        for text in self.text.split_inclusive('\n') {
39            if starts.get(next) == Some(&line) {
40                offsets.push((line, offset));
41                next += 1;
42            }
43            offset += text.len();
44            if offset < self.text.len() {
45                line = line.checked_add(1).ok_or(ContextError::LimitExceeded)?;
46            }
47        }
48        if next != starts.len() {
49            return Err(ContextError::InvalidInput);
50        }
51        let mut chunks = Vec::with_capacity(offsets.len());
52        for (index, (start_line, start)) in offsets.iter().copied().enumerate() {
53            let end = offsets
54                .get(index + 1)
55                .map_or(self.text.len(), |(_, offset)| *offset);
56            let text = self.text.get(start..end).ok_or(ContextError::Integrity)?;
57            if text.trim().is_empty() {
58                return Err(ContextError::InvalidInput);
59            }
60            chunks.push(Self {
61                id: format!("{}:L{start_line}", self.id),
62                source: self.source.clone(),
63                start_line,
64                text: text.to_owned(),
65            });
66        }
67        Ok(chunks)
68    }
69}