1use super::RootedUnitSource;
10use crate::core::context_admission::cross_line::BOUNDED_REACH_BYTES;
11
12const READ_CHUNK_BYTES: usize = 64 * 1024;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct UnitBounds {
18 pub unit_bytes: usize,
20 pub seam_side: usize,
27 pub max_total_bytes: u64,
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum UnitRefusal {
34 TooLarge,
36 RecordTooLarge,
38 Withheld,
40 UnitAdmissionUnsupported,
42 Unreadable,
44}
45
46impl RootedUnitSource {
47 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 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 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 close_record(self, &mut units, &mut record, &mut sink)?;
96 admit_pending(self, &mut units, &mut sink)
97 }
98}
99
100fn 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
112struct Units {
114 unit: Vec<u8>,
115 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
129fn 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
144fn 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
171fn 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
195fn 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
216fn 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 assert_eq!(seam_side(bounds(unit, 0)), Ok(BOUNDED_REACH_BYTES));
243 assert_eq!(seam_side(bounds(unit, 1)), Ok(BOUNDED_REACH_BYTES));
244 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 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}