From 031c033745060fc2c83db5a2bf63fd1942ad3176 Mon Sep 17 00:00:00 2001 From: Irene Knapp Date: Fri, 15 Jan 2021 22:51:46 -0800 Subject: Add some rudimentary terminal stuff, which breaks the previously existing functionality --- src/main.rs | 2 ++ src/terminal.rs | 93 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 src/terminal.rs (limited to 'src') diff --git a/src/main.rs b/src/main.rs index d1a25a6..3199528 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,6 +13,7 @@ pub mod error; pub mod path; pub mod prelude; pub mod result; +pub mod terminal; pub enum Input { @@ -38,6 +39,7 @@ fn repl() -> Result<()> { loop { prompt()?; + terminal::handle_input(io::stdin())?; let input = read()?; match input { Input::String(string) => execute(&string)?, diff --git a/src/terminal.rs b/src/terminal.rs new file mode 100644 index 0000000..6d65c82 --- /dev/null +++ b/src/terminal.rs @@ -0,0 +1,93 @@ +use std::io::{self, BufRead, BufReader, Read}; +use std::str; + + +struct CharBufReader { + reader: BufReader, + char_buffer: String, +} + + +impl CharBufReader { + pub fn new(reader: BufReader) -> CharBufReader { + CharBufReader { + reader: reader, + char_buffer: String::new(), + } + } + + pub fn fill_buf(&mut self) + -> std::result::Result<&str, io::Error> + { + loop { + let byte_buffer = self.reader.fill_buf()?; + + match str::from_utf8(byte_buffer) { + Err(error) => { + let n_valid = error.valid_up_to(); + if n_valid == 0 { + self.reader.consume(1); + } else { + match str::from_utf8(&byte_buffer[..n_valid]) { + Err(_) => { + self.reader.consume(1); + }, + Ok(chars) => { + self.char_buffer.push_str(chars); + + self.reader.consume(n_valid); + + break; + }, + } + } + }, + Ok(chars) => { + self.char_buffer.push_str(chars); + + let n_to_consume = byte_buffer.len(); + self.reader.consume(n_to_consume); + + break; + } + } + } + + return Ok(&self.char_buffer); + } + + pub fn consume(&mut self, amount: usize) { + self.char_buffer.replace_range(..amount, ""); + println!("consume {:?}", self.char_buffer); + } +} + + +pub fn handle_input(input_stream: impl Read) + -> std::result::Result<(), io::Error> +{ + let reader = BufReader::new(input_stream); + let mut reader = CharBufReader::new(reader); + + let string = reader.fill_buf()?; + println!("top level {:?}", string); + + let n_to_consume = string.len(); + reader.consume(n_to_consume); + + Ok(()) +} + + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn test_empty_input() { + let buffer = Cursor::new(vec![]); + let result = handle_input(buffer); + assert!(result.is_ok()); + } +} -- cgit 1.4.1