Skip to main content

lean_ctx/core/
rooted_read_units.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! The unit read of a [`RootedUnitSource`]: the raw bytes of its descriptor
4//! are grouped into UNITS of complete records (lines), and every unit — and
5//! the SEAM between two units first — is admitted before any of its text
6//! leaves this module. A caller receives only admitted, storable text; the
7//! raw reads and the single admissions stay inside the crate.
8
9use super::RootedUnitSource;
10use crate::core::context_admission::cross_line::BOUNDED_REACH_BYTES;
11
12/// Size of one raw read from the descriptor.
13const READ_CHUNK_BYTES: usize = 64 * 1024;
14
15/// Bounds of [`RootedUnitSource::admit_records`].
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct UnitBounds {
18    /// Largest unit, and so the largest record: a record is never cut.
19    pub unit_bytes: usize,
20    /// How much of each unit next to a boundary is admitted once more as a
21    /// seam. Raised to at least the bounded cross-line reach
22    /// (`cross_line::BOUNDED_REACH_BYTES`) and capped at a quarter of
23    /// `unit_bytes`: a half is at most twice its side, so a whole seam is at
24    /// most one unit. A unit under four times the reach is refused
25    /// ([`UnitRefusal::UnitAdmissionUnsupported`]).
26    pub seam_side: usize,
27    /// Most bytes read from the descriptor before the source is refused.
28    pub max_total_bytes: u64,
29}
30
31/// Why [`RootedUnitSource::admit_records`] refused the source. Content-free.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum UnitRefusal {
34    /// More than `max_total_bytes` were read.
35    TooLarge,
36    /// One record alone is above `unit_bytes`.
37    RecordTooLarge,
38    /// Admission withheld a unit or a seam, or delivered it for a reader only.
39    Withheld,
40    /// The active rules cannot be applied unit by unit.
41    UnitAdmissionUnsupported,
42    /// A read failed, a unit is not UTF-8 text, or the caller's sink failed.
43    Unreadable,
44}
45
46impl RootedUnitSource {
47    /// Read this source to its end in units of complete records and hand the
48    /// admitted text of each unit, in file order, to `sink`.
49    ///
50    /// Each unit is admitted on its ORIGINAL bytes (`Self::admit_unit`),
51    /// after the seam with the unit before it (`Self::admit_seam`). Only
52    /// what may feed a derived store is handed out; any other outcome, of a
53    /// seam as of a unit, refuses the whole source. On `Err` the caller must
54    /// take over nothing `sink` has seen.
55    pub fn admit_records(
56        &mut self,
57        bounds: UnitBounds,
58        mut sink: impl FnMut(&str) -> Result<(), UnitRefusal>,
59    ) -> Result<(), UnitRefusal> {
60        let seam_side = seam_side(bounds)?;
61        let mut units = Units {
62            unit: Vec::new(),
63            tail: Vec::new(),
64            cap: bounds.unit_bytes,
65            seam_side,
66        };
67        // `units.unit`: complete records not yet admitted. `record`: the
68        // record being assembled. Both stay at or below the cap.
69        let mut record = Vec::new();
70        let mut chunk = vec![0_u8; READ_CHUNK_BYTES];
71        let mut total = 0_u64;
72        loop {
73            let read = self
74                .read_raw(&mut chunk)
75                .map_err(|_| UnitRefusal::Unreadable)?;
76            if read == 0 {
77                break;
78            }
79            total += read as u64;
80            if total > bounds.max_total_bytes {
81                return Err(UnitRefusal::TooLarge);
82            }
83            let mut rest = &chunk[..read];
84            // A record ends at a line feed. That byte never occurs inside a
85            // multi-byte UTF-8 character, so a unit never divides a character.
86            while let Some(newline) = rest.iter().position(|byte| *byte == b'\n') {
87                let (head, tail) = rest.split_at(newline + 1);
88                extend_record(&mut record, head, units.cap)?;
89                close_record(self, &mut units, &mut record, &mut sink)?;
90                rest = tail;
91            }
92            extend_record(&mut record, rest, units.cap)?;
93        }
94        // The last record may end without a line feed.
95        close_record(self, &mut units, &mut record, &mut sink)?;
96        admit_pending(self, &mut units, &mut sink)
97    }
98}
99
100/// The seam side actually used: at least what the built-in rules can match
101/// across a line end with a bound ([`BOUNDED_REACH_BYTES`]), at most a
102/// quarter of a unit. The caller cannot turn the seam off: when a unit is
103/// too small for a seam of that reach, unit admission does not apply.
104fn seam_side(bounds: UnitBounds) -> Result<usize, UnitRefusal> {
105    let most = bounds.unit_bytes / 4;
106    if most < BOUNDED_REACH_BYTES {
107        return Err(UnitRefusal::UnitAdmissionUnsupported);
108    }
109    Ok(bounds.seam_side.clamp(BOUNDED_REACH_BYTES, most))
110}
111
112/// The units being assembled.
113struct Units {
114    unit: Vec<u8>,
115    /// The end of the last admitted unit: the earlier half of the next seam.
116    tail: Vec<u8>,
117    cap: usize,
118    seam_side: usize,
119}
120
121fn extend_record(record: &mut Vec<u8>, bytes: &[u8], cap: usize) -> Result<(), UnitRefusal> {
122    if record.len() + bytes.len() > cap {
123        return Err(UnitRefusal::RecordTooLarge);
124    }
125    record.extend_from_slice(bytes);
126    Ok(())
127}
128
129/// Move the finished `record` into the unit, admitting the unit first when
130/// the record no longer fits into it.
131fn close_record(
132    reader: &RootedUnitSource,
133    units: &mut Units,
134    record: &mut Vec<u8>,
135    sink: &mut impl FnMut(&str) -> Result<(), UnitRefusal>,
136) -> Result<(), UnitRefusal> {
137    if units.unit.len() + record.len() > units.cap {
138        admit_pending(reader, units, sink)?;
139    }
140    units.unit.append(record);
141    Ok(())
142}
143
144/// Admit the pending unit — first the seam with the unit before it, then the
145/// unit — and hand the unit's admitted text to `sink`.
146fn admit_pending(
147    reader: &RootedUnitSource,
148    units: &mut Units,
149    sink: &mut impl FnMut(&str) -> Result<(), UnitRefusal>,
150) -> Result<(), UnitRefusal> {
151    if units.unit.is_empty() {
152        return Ok(());
153    }
154    let bytes = std::mem::take(&mut units.unit);
155    if !units.tail.is_empty() {
156        let mut seam = std::mem::take(&mut units.tail);
157        seam.extend_from_slice(seam_head(&bytes, units.seam_side));
158        let seam = reader.admit_seam(seam).map_err(|error| refusal(&error))?;
159        if !seam.storable {
160            return Err(UnitRefusal::Withheld);
161        }
162    }
163    units.tail = seam_tail(&bytes, units.seam_side).to_vec();
164    let unit = reader.admit_unit(bytes).map_err(|error| refusal(&error))?;
165    if !unit.storable {
166        return Err(UnitRefusal::Withheld);
167    }
168    sink(&unit.content)
169}
170
171/// The end of a unit for a seam: at least its last `side` bytes, extended
172/// back to the start of the record they begin in — complete records, so a
173/// line anchor sees what it sees in the file. When that would be more than
174/// twice `side` (one long record), the last `side` bytes instead, moved
175/// forward to a character boundary (at most three bytes less).
176fn seam_tail(unit: &[u8], side: usize) -> &[u8] {
177    if unit.len() <= side {
178        return unit;
179    }
180    let start = unit.len() - side;
181    let record = unit[..start]
182        .iter()
183        .rposition(|byte| *byte == b'\n')
184        .map_or(0, |newline| newline + 1);
185    if unit.len() - record <= 2 * side {
186        return &unit[record..];
187    }
188    let mut start = start;
189    while start < unit.len() && unit[start] & 0xC0 == 0x80 {
190        start += 1;
191    }
192    &unit[start..]
193}
194
195/// The start of a unit for a seam: at least its first `side` bytes, extended
196/// to the end of the record they end in. When that would be more than twice
197/// `side`, the first `side` bytes instead, moved back to a character boundary.
198fn seam_head(unit: &[u8], side: usize) -> &[u8] {
199    if unit.len() <= side {
200        return unit;
201    }
202    let record = unit[side - 1..]
203        .iter()
204        .position(|byte| *byte == b'\n')
205        .map_or(unit.len(), |newline| side + newline);
206    if record <= 2 * side {
207        return &unit[..record];
208    }
209    let mut end = side;
210    while end > 0 && unit[end] & 0xC0 == 0x80 {
211        end -= 1;
212    }
213    &unit[..end]
214}
215
216/// The typed refusal of an admission error: unit admission not applicable,
217/// withheld by a rule, or not readable.
218fn refusal(error: &std::io::Error) -> UnitRefusal {
219    match error.kind() {
220        std::io::ErrorKind::Unsupported => UnitRefusal::UnitAdmissionUnsupported,
221        std::io::ErrorKind::PermissionDenied => UnitRefusal::Withheld,
222        _ => UnitRefusal::Unreadable,
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::{BOUNDED_REACH_BYTES, UnitBounds, UnitRefusal, seam_head, seam_side, seam_tail};
229
230    fn bounds(unit_bytes: usize, seam_side: usize) -> UnitBounds {
231        UnitBounds {
232            unit_bytes,
233            seam_side,
234            max_total_bytes: u64::MAX,
235        }
236    }
237
238    #[test]
239    fn the_caller_cannot_shrink_or_disable_the_seam() {
240        let unit = 64 * BOUNDED_REACH_BYTES;
241        // Zero, or anything under the reach, is raised to the reach.
242        assert_eq!(seam_side(bounds(unit, 0)), Ok(BOUNDED_REACH_BYTES));
243        assert_eq!(seam_side(bounds(unit, 1)), Ok(BOUNDED_REACH_BYTES));
244        // Above a quarter of the unit it is capped there.
245        assert_eq!(seam_side(bounds(unit, usize::MAX)), Ok(unit / 4));
246        assert_eq!(
247            seam_side(bounds(unit, 2 * BOUNDED_REACH_BYTES)),
248            Ok(2 * BOUNDED_REACH_BYTES)
249        );
250        // Smallest read cap: a side is exactly the reach.
251        assert_eq!(
252            seam_side(bounds(4 * BOUNDED_REACH_BYTES, 0)),
253            Ok(BOUNDED_REACH_BYTES)
254        );
255    }
256
257    #[test]
258    fn a_unit_too_small_for_a_seam_is_refused() {
259        for unit in [0, 3, 4 * BOUNDED_REACH_BYTES - 1] {
260            assert_eq!(
261                seam_side(bounds(unit, BOUNDED_REACH_BYTES)),
262                Err(UnitRefusal::UnitAdmissionUnsupported),
263                "unit {unit}"
264            );
265        }
266    }
267
268    #[test]
269    fn seams_take_whole_records_up_to_twice_the_side() {
270        let unit = b"aaaa\nbbbb\ncccc\n";
271        assert_eq!(seam_tail(unit, 5), b"cccc\n");
272        assert_eq!(seam_head(unit, 5), b"aaaa\n");
273        assert_eq!(seam_tail(unit, 64), unit);
274        assert_eq!(seam_head(unit, 64), unit);
275    }
276
277    #[test]
278    fn a_long_record_is_cut_at_a_character_boundary() {
279        let unit = "x".repeat(10) + &"é".repeat(10);
280        let tail = seam_tail(unit.as_bytes(), 3);
281        assert!(std::str::from_utf8(tail).is_ok() && tail.len() <= 3);
282        let unit = "é".repeat(10) + "\n";
283        let head = seam_head(unit.as_bytes(), 3);
284        assert!(std::str::from_utf8(head).is_ok() && head.len() <= 3);
285    }
286}