diff --git a/src/inputfile.rs b/src/inputfile.rs index d4e2e52e..feec9857 100644 --- a/src/inputfile.rs +++ b/src/inputfile.rs @@ -7,17 +7,31 @@ const THEME_PREVIEW_FILE: &[u8] = include_bytes!("../assets/theme_preview.rs"); pub struct InputFileReader<'a> { inner: Box, + buffer: Vec, } impl<'a> InputFileReader<'a> { fn new(reader: R) -> InputFileReader<'a> { InputFileReader { inner: Box::new(reader), + buffer: vec![], } } + pub fn get_first_line(&mut self) -> io::Result> { + assert!(self.buffer.is_empty()); + + self.inner.read_until(b'\n', &mut self.buffer)?; + Ok(self.buffer.clone()) + } + pub fn read_line(&mut self, buf: &mut Vec) -> io::Result { - self.inner.read_until(b'\n', buf).map(|size| size > 0) + if self.buffer.is_empty() { + self.inner.read_until(b'\n', buf).map(|size| size > 0) + } else { + buf.append(&mut self.buffer); + return Ok(true); + } } } @@ -48,22 +62,26 @@ impl<'a> InputFile<'a> { #[test] fn basic() { - let content = b"hello\nworld"; + let content = b"#!/bin/bash\necho hello"; let mut reader = InputFileReader::new(&content[..]); + let first_line = reader.get_first_line(); + assert!(first_line.is_ok()); + assert_eq!(b"#!/bin/bash\n", &first_line.unwrap()[..]); + let mut buffer = vec![]; let res = reader.read_line(&mut buffer); assert!(res.is_ok()); assert_eq!(true, res.unwrap()); - assert_eq!(b"hello\n", &buffer[..]); + assert_eq!(b"#!/bin/bash\n", &buffer[..]); buffer.clear(); let res = reader.read_line(&mut buffer); assert!(res.is_ok()); assert_eq!(true, res.unwrap()); - assert_eq!(b"world", &buffer[..]); + assert_eq!(b"echo hello", &buffer[..]); buffer.clear();