//! Standard input as lines and bytes (`std/io`, ADR 0086): what is read //! ahead and not taken yet, cut into lines or chunks on demand. Both back //! ends feed it from their own reader (the native runtime's `louise-stdin` //! thread, the interpreter's source) and take from it the same way. //! //! - **Lines** end at `\n`, which is dropped with a `\r` just before it. A //! last line without `\n` is still a line. //! - **A line longer than its maximum** is an error for that line: what was //! read of it is dropped, and so is the rest, up to its `\n`, whatever //! reads next. //! - **Bounded.** The reader reads ahead while less than [`BUDGET`] bytes //! wait, or while a line reader waits for the end of a line that has //! none yet, up to [`MAX_LINE`]: a line is never cut because the budget //! is full, and a program that stops reading stops the reader. //! - **A read error** is reported once, after the data read before it; //! input then ends. /// Bytes read ahead and not taken before the reader stops reading (unless /// a line reader waits for the end of a longer line): as much as a /// default Linux pipe holds. pub const BUDGET: usize = 64 * 1024; /// The longest line a reader can take, and the default maximum: 16 MiB. pub const MAX_LINE: usize = 16 * 1024 * 1024; /// What one take found. #[derive(Debug, PartialEq, Eq)] pub enum Taken { /// A line (without its `\n` or `\r\n`), or a chunk of bytes. Data(Vec), /// Input ended: nothing more will come. End, /// The line was longer than the maximum; its rest is skipped. TooLong, /// The system refused to read (its message); input ends after it. Failed(String), /// Nothing to take yet: wait for the reader. Wait, } impl Taken { /// The kind `tl_io_read_line` and `tl_io_read_bytes` return with the /// data or the message (`std/io`'s `read_raw` results). pub fn kind(&self) -> i64 { match self { Taken::Data(_) => 0, Taken::End | Taken::Wait => 1, Taken::TooLong => 2, Taken::Failed(_) => 3, } } /// The data or the message, as bytes. pub fn into_bytes(self) -> Vec { match self { Taken::Data(data) => data, Taken::Failed(message) => message.into_bytes(), Taken::End | Taken::Wait | Taken::TooLong => Vec::new(), } } } /// How input ended, once the reader saw it end. #[derive(Debug, PartialEq, Eq)] enum End { Eof, Failed(String), } /// Input read ahead and not taken yet. #[derive(Debug, Default)] pub struct Input { /// What was read; `data[start..]` is not taken yet. data: Vec, start: usize, /// How many bytes from `start` are known to hold no `\n`, so a line /// growing chunk by chunk is scanned once. no_newline: usize, /// The reader saw input end (or fail): nothing more is read. end: Option, /// The rest of a line too long is skipped, up to its `\n`. skipping: bool, /// A line reader waits for the end of a line longer than the budget. line_wanted: bool, } impl Input { /// Bytes read and not taken. pub fn pending(&self) -> usize { self.data.len() - self.start } /// Whether the reader should read more now. pub fn wants_more(&self) -> bool { self.end.is_none() && (self.pending() < BUDGET || (self.line_wanted && self.pending() <= MAX_LINE)) } /// Whether input ended (the reader stops). pub fn ended(&self) -> bool { self.end.is_some() } /// The reader read `bytes`. pub fn push(&mut self, bytes: &[u8]) { if bytes.contains(&b'\n') { self.line_wanted = false; } self.data.extend_from_slice(bytes); } /// The reader reached the end of input. pub fn finish(&mut self) { self.end.get_or_insert(End::Eof); } /// The reader failed with `message`: reported once, after what was /// read before; input then ends. pub fn fail(&mut self, message: String) { self.end.get_or_insert(End::Failed(message)); } /// The next line, of at most `max` bytes (without its `\n`). pub fn take_line(&mut self, max: usize) -> Taken { let max = max.min(MAX_LINE); if !self.skip() { return self.at_end(); } let pending = &self.data[self.start..]; let limit = pending.len().min(max.saturating_add(1)); let found = pending[self.no_newline.min(limit)..limit] .iter() .position(|&b| b == b'\n') .map(|i| i + self.no_newline.min(limit)); if let Some(i) = found { let mut line = pending[..i].to_vec(); if line.last() == Some(&b'\r') { line.pop(); } self.advance(i + 1); return Taken::Data(line); } self.no_newline = limit; if pending.len() > max { self.skipping = true; self.advance(limit); self.skip(); return Taken::TooLong; } if self.end.is_some() { if pending.is_empty() { return self.at_end(); } let line = pending.to_vec(); self.advance(line.len()); return Taken::Data(line); } self.line_wanted = true; Taken::Wait } /// Up to `max` bytes (at least one) of what was read. pub fn take_bytes(&mut self, max: usize) -> Taken { if !self.skip() { return self.at_end(); } let n = self.pending().min(max.max(1)); if n == 0 { return self.at_end(); } let chunk = self.data[self.start..self.start + n].to_vec(); self.advance(n); Taken::Data(chunk) } /// Drop the rest of a line too long, as far as it was read. Returns /// whether something may be taken: false while skipping, with nothing /// left after the skip. fn skip(&mut self) -> bool { if !self.skipping { return true; } let pending = &self.data[self.start..]; match pending.iter().position(|&b| b == b'\n') { Some(i) => { self.skipping = false; self.advance(i + 1); true } None => { self.advance(pending.len()); false } } } /// Nothing pending: the end, the error (once), or wait for more. fn at_end(&mut self) -> Taken { match &self.end { None => Taken::Wait, Some(End::Eof) => Taken::End, Some(End::Failed(_)) => match self.end.replace(End::Eof) { Some(End::Failed(message)) => Taken::Failed(message), _ => Taken::End, }, } } /// `n` bytes were taken (or skipped). fn advance(&mut self, n: usize) { self.start += n; self.no_newline = 0; self.line_wanted = false; if self.start == self.data.len() { // Keep the buffer for the next reads, unless a long line grew it. if self.data.capacity() > 4 * BUDGET { self.data = Vec::new(); } else { self.data.clear(); } self.start = 0; } else if self.start >= BUDGET && self.start * 2 >= self.data.len() { self.data.drain(..self.start); self.start = 0; } } } #[cfg(test)] mod tests { use super::*; fn line(s: &str) -> Taken { Taken::Data(s.as_bytes().to_vec()) } fn input(s: &str) -> Input { let mut input = Input::default(); input.push(s.as_bytes()); input } #[test] fn lines_drop_their_newline_and_a_carriage_return_before_it() { let mut i = input("one\ntwo\r\n\r\nthree\rx\n"); assert_eq!(i.take_line(MAX_LINE), line("one")); assert_eq!(i.take_line(MAX_LINE), line("two")); assert_eq!(i.take_line(MAX_LINE), line("")); assert_eq!(i.take_line(MAX_LINE), line("three\rx")); assert_eq!(i.take_line(MAX_LINE), Taken::Wait); } #[test] fn a_last_line_without_newline_is_a_line_then_input_ends() { let mut i = input("a\nlast"); assert_eq!(i.take_line(MAX_LINE), line("a")); assert_eq!(i.take_line(MAX_LINE), Taken::Wait, "it may go on"); i.finish(); assert_eq!(i.take_line(MAX_LINE), line("last")); assert_eq!(i.take_line(MAX_LINE), Taken::End); assert_eq!(i.take_line(MAX_LINE), Taken::End, "for every later read"); assert_eq!(i.take_bytes(10), Taken::End); } #[test] fn empty_input_ends_at_once() { let mut i = Input::default(); i.finish(); assert_eq!(i.take_line(MAX_LINE), Taken::End); assert!(!i.wants_more()); } #[test] fn a_line_split_across_reads_is_one_line() { let mut i = input("hel"); assert_eq!(i.take_line(MAX_LINE), Taken::Wait); i.push(b"lo\nwo"); assert_eq!(i.take_line(MAX_LINE), line("hello")); i.push(b"rld\n"); assert_eq!(i.take_line(MAX_LINE), line("world")); } #[test] fn a_line_too_long_is_skipped_to_its_newline() { let mut i = input("0123456789\nok\n"); assert_eq!(i.take_line(5), Taken::TooLong); assert_eq!(i.take_line(5), line("ok")); // Exactly the maximum fits. let mut i = input("12345\n"); assert_eq!(i.take_line(5), line("12345")); } #[test] fn the_rest_of_a_line_too_long_is_skipped_as_it_comes() { let mut i = input("0123456789"); assert_eq!(i.take_line(5), Taken::TooLong); assert_eq!(i.pending(), 0); i.push(b"still the same line"); assert_eq!(i.take_line(5), Taken::Wait); assert_eq!(i.pending(), 0); i.push(b" end\nnext\n"); assert_eq!(i.take_line(5), line("next")); // Bytes skip it too. let mut i = input("0123456789"); assert_eq!(i.take_line(5), Taken::TooLong); i.push(b"xx\nab"); assert_eq!(i.take_bytes(10), Taken::Data(b"ab".to_vec())); } #[test] fn a_line_too_long_at_the_end_of_input_is_skipped_then_input_ends() { let mut i = input("0123456789"); i.finish(); assert_eq!(i.take_line(5), Taken::TooLong); assert_eq!(i.take_line(5), Taken::End); } #[test] fn bytes_are_taken_as_they_were_read() { let mut i = input("ab\ncd"); assert_eq!(i.take_bytes(2), Taken::Data(b"ab".to_vec())); assert_eq!(i.take_bytes(100), Taken::Data(b"\ncd".to_vec())); assert_eq!(i.take_bytes(100), Taken::Wait); assert_eq!(i.take_bytes(0), Taken::Wait, "at least one byte"); i.push(b"z"); assert_eq!(i.take_bytes(0), Taken::Data(b"z".to_vec())); i.finish(); assert_eq!(i.take_bytes(100), Taken::End); } #[test] fn a_read_error_comes_once_after_the_data_then_input_ends() { let mut i = input("a\n"); i.fail("Input/output error".into()); assert!(!i.wants_more()); assert_eq!(i.take_line(MAX_LINE), line("a")); assert_eq!( i.take_line(MAX_LINE), Taken::Failed("Input/output error".into()) ); assert_eq!(i.take_line(MAX_LINE), Taken::End); } #[test] fn the_reader_stops_at_the_budget_unless_a_line_needs_more() { let mut i = Input::default(); assert!(i.wants_more()); i.push(&vec![b'x'; BUDGET]); assert!(!i.wants_more(), "a full budget"); // A line reader waits for the end of this line: read on. assert_eq!(i.take_line(MAX_LINE), Taken::Wait); assert!(i.wants_more()); i.push(b"x\n"); assert!(!i.wants_more(), "the line is complete"); assert_eq!(i.take_line(MAX_LINE), Taken::Data(vec![b'x'; BUDGET + 1])); assert!(i.wants_more()); // Never past the longest line. let mut i = Input::default(); i.push(&vec![b'x'; MAX_LINE + 1]); i.line_wanted = true; assert!(!i.wants_more()); assert_eq!(i.take_line(MAX_LINE), Taken::TooLong); } #[test] fn many_short_lines_compact_the_buffer() { let mut i = Input::default(); let text = "line\n".repeat(BUDGET); i.push(text.as_bytes()); for _ in 0..BUDGET { assert_eq!(i.take_line(MAX_LINE), line("line")); assert!( i.start < BUDGET || i.start * 2 < i.data.len(), "taken bytes are dropped once they are half the buffer" ); } assert_eq!(i.pending(), 0); assert_eq!(i.data.capacity(), 0, "a buffer grown large is released"); } #[test] fn kinds_and_bytes_are_what_std_io_reads() { assert_eq!(line("a").kind(), 0); assert_eq!(Taken::End.kind(), 1); assert_eq!(Taken::TooLong.kind(), 2); assert_eq!(Taken::Failed("no".into()).kind(), 3); assert_eq!(Taken::Failed("no".into()).into_bytes(), b"no"); } }