tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

389 lignes · 13159 octetsBrut · Historique
1//! Standard input as lines and bytes (`std/io`, ADR 0086): what is read
2//! ahead and not taken yet, cut into lines or chunks on demand. Both back
3//! ends feed it from their own reader (the native runtime's `louise-stdin`
4//! thread, the interpreter's source) and take from it the same way.
5//!
6//! - **Lines** end at `\n`, which is dropped with a `\r` just before it. A
7//! last line without `\n` is still a line.
8//! - **A line longer than its maximum** is an error for that line: what was
9//! read of it is dropped, and so is the rest, up to its `\n`, whatever
10//! reads next.
11//! - **Bounded.** The reader reads ahead while less than [`BUDGET`] bytes
12//! wait, or while a line reader waits for the end of a line that has
13//! none yet, up to [`MAX_LINE`]: a line is never cut because the budget
14//! is full, and a program that stops reading stops the reader.
15//! - **A read error** is reported once, after the data read before it;
16//! input then ends.
17
18/// Bytes read ahead and not taken before the reader stops reading (unless
19/// a line reader waits for the end of a longer line): as much as a
20/// default Linux pipe holds.
21pub const BUDGET: usize = 64 * 1024;
22
23/// The longest line a reader can take, and the default maximum: 16 MiB.
24pub const MAX_LINE: usize = 16 * 1024 * 1024;
25
26/// What one take found.
27#[derive(Debug, PartialEq, Eq)]
28pub enum Taken {
29 /// A line (without its `\n` or `\r\n`), or a chunk of bytes.
30 Data(Vec<u8>),
31 /// Input ended: nothing more will come.
32 End,
33 /// The line was longer than the maximum; its rest is skipped.
34 TooLong,
35 /// The system refused to read (its message); input ends after it.
36 Failed(String),
37 /// Nothing to take yet: wait for the reader.
38 Wait,
39}
40
41impl Taken {
42 /// The kind `tl_io_read_line` and `tl_io_read_bytes` return with the
43 /// data or the message (`std/io`'s `read_raw` results).
44 pub fn kind(&self) -> i64 {
45 match self {
46 Taken::Data(_) => 0,
47 Taken::End | Taken::Wait => 1,
48 Taken::TooLong => 2,
49 Taken::Failed(_) => 3,
50 }
51 }
52
53 /// The data or the message, as bytes.
54 pub fn into_bytes(self) -> Vec<u8> {
55 match self {
56 Taken::Data(data) => data,
57 Taken::Failed(message) => message.into_bytes(),
58 Taken::End | Taken::Wait | Taken::TooLong => Vec::new(),
59 }
60 }
61}
62
63/// How input ended, once the reader saw it end.
64#[derive(Debug, PartialEq, Eq)]
65enum End {
66 Eof,
67 Failed(String),
68}
69
70/// Input read ahead and not taken yet.
71#[derive(Debug, Default)]
72pub struct Input {
73 /// What was read; `data[start..]` is not taken yet.
74 data: Vec<u8>,
75 start: usize,
76 /// How many bytes from `start` are known to hold no `\n`, so a line
77 /// growing chunk by chunk is scanned once.
78 no_newline: usize,
79 /// The reader saw input end (or fail): nothing more is read.
80 end: Option<End>,
81 /// The rest of a line too long is skipped, up to its `\n`.
82 skipping: bool,
83 /// A line reader waits for the end of a line longer than the budget.
84 line_wanted: bool,
85}
86
87impl Input {
88 /// Bytes read and not taken.
89 pub fn pending(&self) -> usize {
90 self.data.len() - self.start
91 }
92
93 /// Whether the reader should read more now.
94 pub fn wants_more(&self) -> bool {
95 self.end.is_none()
96 && (self.pending() < BUDGET || (self.line_wanted && self.pending() <= MAX_LINE))
97 }
98
99 /// Whether input ended (the reader stops).
100 pub fn ended(&self) -> bool {
101 self.end.is_some()
102 }
103
104 /// The reader read `bytes`.
105 pub fn push(&mut self, bytes: &[u8]) {
106 if bytes.contains(&b'\n') {
107 self.line_wanted = false;
108 }
109 self.data.extend_from_slice(bytes);
110 }
111
112 /// The reader reached the end of input.
113 pub fn finish(&mut self) {
114 self.end.get_or_insert(End::Eof);
115 }
116
117 /// The reader failed with `message`: reported once, after what was
118 /// read before; input then ends.
119 pub fn fail(&mut self, message: String) {
120 self.end.get_or_insert(End::Failed(message));
121 }
122
123 /// The next line, of at most `max` bytes (without its `\n`).
124 pub fn take_line(&mut self, max: usize) -> Taken {
125 let max = max.min(MAX_LINE);
126 if !self.skip() {
127 return self.at_end();
128 }
129 let pending = &self.data[self.start..];
130 let limit = pending.len().min(max.saturating_add(1));
131 let found = pending[self.no_newline.min(limit)..limit]
132 .iter()
133 .position(|&b| b == b'\n')
134 .map(|i| i + self.no_newline.min(limit));
135 if let Some(i) = found {
136 let mut line = pending[..i].to_vec();
137 if line.last() == Some(&b'\r') {
138 line.pop();
139 }
140 self.advance(i + 1);
141 return Taken::Data(line);
142 }
143 self.no_newline = limit;
144 if pending.len() > max {
145 self.skipping = true;
146 self.advance(limit);
147 self.skip();
148 return Taken::TooLong;
149 }
150 if self.end.is_some() {
151 if pending.is_empty() {
152 return self.at_end();
153 }
154 let line = pending.to_vec();
155 self.advance(line.len());
156 return Taken::Data(line);
157 }
158 self.line_wanted = true;
159 Taken::Wait
160 }
161
162 /// Up to `max` bytes (at least one) of what was read.
163 pub fn take_bytes(&mut self, max: usize) -> Taken {
164 if !self.skip() {
165 return self.at_end();
166 }
167 let n = self.pending().min(max.max(1));
168 if n == 0 {
169 return self.at_end();
170 }
171 let chunk = self.data[self.start..self.start + n].to_vec();
172 self.advance(n);
173 Taken::Data(chunk)
174 }
175
176 /// Drop the rest of a line too long, as far as it was read. Returns
177 /// whether something may be taken: false while skipping, with nothing
178 /// left after the skip.
179 fn skip(&mut self) -> bool {
180 if !self.skipping {
181 return true;
182 }
183 let pending = &self.data[self.start..];
184 match pending.iter().position(|&b| b == b'\n') {
185 Some(i) => {
186 self.skipping = false;
187 self.advance(i + 1);
188 true
189 }
190 None => {
191 self.advance(pending.len());
192 false
193 }
194 }
195 }
196
197 /// Nothing pending: the end, the error (once), or wait for more.
198 fn at_end(&mut self) -> Taken {
199 match &self.end {
200 None => Taken::Wait,
201 Some(End::Eof) => Taken::End,
202 Some(End::Failed(_)) => match self.end.replace(End::Eof) {
203 Some(End::Failed(message)) => Taken::Failed(message),
204 _ => Taken::End,
205 },
206 }
207 }
208
209 /// `n` bytes were taken (or skipped).
210 fn advance(&mut self, n: usize) {
211 self.start += n;
212 self.no_newline = 0;
213 self.line_wanted = false;
214 if self.start == self.data.len() {
215 // Keep the buffer for the next reads, unless a long line grew it.
216 if self.data.capacity() > 4 * BUDGET {
217 self.data = Vec::new();
218 } else {
219 self.data.clear();
220 }
221 self.start = 0;
222 } else if self.start >= BUDGET && self.start * 2 >= self.data.len() {
223 self.data.drain(..self.start);
224 self.start = 0;
225 }
226 }
227}
228
229#[cfg(test)]
230mod tests {
231 use super::*;
232
233 fn line(s: &str) -> Taken {
234 Taken::Data(s.as_bytes().to_vec())
235 }
236
237 fn input(s: &str) -> Input {
238 let mut input = Input::default();
239 input.push(s.as_bytes());
240 input
241 }
242
243 #[test]
244 fn lines_drop_their_newline_and_a_carriage_return_before_it() {
245 let mut i = input("one\ntwo\r\n\r\nthree\rx\n");
246 assert_eq!(i.take_line(MAX_LINE), line("one"));
247 assert_eq!(i.take_line(MAX_LINE), line("two"));
248 assert_eq!(i.take_line(MAX_LINE), line(""));
249 assert_eq!(i.take_line(MAX_LINE), line("three\rx"));
250 assert_eq!(i.take_line(MAX_LINE), Taken::Wait);
251 }
252
253 #[test]
254 fn a_last_line_without_newline_is_a_line_then_input_ends() {
255 let mut i = input("a\nlast");
256 assert_eq!(i.take_line(MAX_LINE), line("a"));
257 assert_eq!(i.take_line(MAX_LINE), Taken::Wait, "it may go on");
258 i.finish();
259 assert_eq!(i.take_line(MAX_LINE), line("last"));
260 assert_eq!(i.take_line(MAX_LINE), Taken::End);
261 assert_eq!(i.take_line(MAX_LINE), Taken::End, "for every later read");
262 assert_eq!(i.take_bytes(10), Taken::End);
263 }
264
265 #[test]
266 fn empty_input_ends_at_once() {
267 let mut i = Input::default();
268 i.finish();
269 assert_eq!(i.take_line(MAX_LINE), Taken::End);
270 assert!(!i.wants_more());
271 }
272
273 #[test]
274 fn a_line_split_across_reads_is_one_line() {
275 let mut i = input("hel");
276 assert_eq!(i.take_line(MAX_LINE), Taken::Wait);
277 i.push(b"lo\nwo");
278 assert_eq!(i.take_line(MAX_LINE), line("hello"));
279 i.push(b"rld\n");
280 assert_eq!(i.take_line(MAX_LINE), line("world"));
281 }
282
283 #[test]
284 fn a_line_too_long_is_skipped_to_its_newline() {
285 let mut i = input("0123456789\nok\n");
286 assert_eq!(i.take_line(5), Taken::TooLong);
287 assert_eq!(i.take_line(5), line("ok"));
288 // Exactly the maximum fits.
289 let mut i = input("12345\n");
290 assert_eq!(i.take_line(5), line("12345"));
291 }
292
293 #[test]
294 fn the_rest_of_a_line_too_long_is_skipped_as_it_comes() {
295 let mut i = input("0123456789");
296 assert_eq!(i.take_line(5), Taken::TooLong);
297 assert_eq!(i.pending(), 0);
298 i.push(b"still the same line");
299 assert_eq!(i.take_line(5), Taken::Wait);
300 assert_eq!(i.pending(), 0);
301 i.push(b" end\nnext\n");
302 assert_eq!(i.take_line(5), line("next"));
303 // Bytes skip it too.
304 let mut i = input("0123456789");
305 assert_eq!(i.take_line(5), Taken::TooLong);
306 i.push(b"xx\nab");
307 assert_eq!(i.take_bytes(10), Taken::Data(b"ab".to_vec()));
308 }
309
310 #[test]
311 fn a_line_too_long_at_the_end_of_input_is_skipped_then_input_ends() {
312 let mut i = input("0123456789");
313 i.finish();
314 assert_eq!(i.take_line(5), Taken::TooLong);
315 assert_eq!(i.take_line(5), Taken::End);
316 }
317
318 #[test]
319 fn bytes_are_taken_as_they_were_read() {
320 let mut i = input("ab\ncd");
321 assert_eq!(i.take_bytes(2), Taken::Data(b"ab".to_vec()));
322 assert_eq!(i.take_bytes(100), Taken::Data(b"\ncd".to_vec()));
323 assert_eq!(i.take_bytes(100), Taken::Wait);
324 assert_eq!(i.take_bytes(0), Taken::Wait, "at least one byte");
325 i.push(b"z");
326 assert_eq!(i.take_bytes(0), Taken::Data(b"z".to_vec()));
327 i.finish();
328 assert_eq!(i.take_bytes(100), Taken::End);
329 }
330
331 #[test]
332 fn a_read_error_comes_once_after_the_data_then_input_ends() {
333 let mut i = input("a\n");
334 i.fail("Input/output error".into());
335 assert!(!i.wants_more());
336 assert_eq!(i.take_line(MAX_LINE), line("a"));
337 assert_eq!(
338 i.take_line(MAX_LINE),
339 Taken::Failed("Input/output error".into())
340 );
341 assert_eq!(i.take_line(MAX_LINE), Taken::End);
342 }
343
344 #[test]
345 fn the_reader_stops_at_the_budget_unless_a_line_needs_more() {
346 let mut i = Input::default();
347 assert!(i.wants_more());
348 i.push(&vec![b'x'; BUDGET]);
349 assert!(!i.wants_more(), "a full budget");
350 // A line reader waits for the end of this line: read on.
351 assert_eq!(i.take_line(MAX_LINE), Taken::Wait);
352 assert!(i.wants_more());
353 i.push(b"x\n");
354 assert!(!i.wants_more(), "the line is complete");
355 assert_eq!(i.take_line(MAX_LINE), Taken::Data(vec![b'x'; BUDGET + 1]));
356 assert!(i.wants_more());
357 // Never past the longest line.
358 let mut i = Input::default();
359 i.push(&vec![b'x'; MAX_LINE + 1]);
360 i.line_wanted = true;
361 assert!(!i.wants_more());
362 assert_eq!(i.take_line(MAX_LINE), Taken::TooLong);
363 }
364
365 #[test]
366 fn many_short_lines_compact_the_buffer() {
367 let mut i = Input::default();
368 let text = "line\n".repeat(BUDGET);
369 i.push(text.as_bytes());
370 for _ in 0..BUDGET {
371 assert_eq!(i.take_line(MAX_LINE), line("line"));
372 assert!(
373 i.start < BUDGET || i.start * 2 < i.data.len(),
374 "taken bytes are dropped once they are half the buffer"
375 );
376 }
377 assert_eq!(i.pending(), 0);
378 assert_eq!(i.data.capacity(), 0, "a buffer grown large is released");
379 }
380
381 #[test]
382 fn kinds_and_bytes_are_what_std_io_reads() {
383 assert_eq!(line("a").kind(), 0);
384 assert_eq!(Taken::End.kind(), 1);
385 assert_eq!(Taken::TooLong.kind(), 2);
386 assert_eq!(Taken::Failed("no".into()).kind(), 3);
387 assert_eq!(Taken::Failed("no".into()).into_bytes(), b"no");
388 }
389}