Add possibility to get first line

This commit is contained in:
sharkdp 2018-10-07 13:25:49 +02:00 committed by David Peter
parent 078228deac
commit 869cf6368c

View File

@ -7,17 +7,31 @@ const THEME_PREVIEW_FILE: &[u8] = include_bytes!("../assets/theme_preview.rs");
pub struct InputFileReader<'a> {
inner: Box<dyn BufRead + 'a>,
buffer: Vec<u8>,
}
impl<'a> InputFileReader<'a> {
fn new<R: BufRead + 'a>(reader: R) -> InputFileReader<'a> {
InputFileReader {
inner: Box::new(reader),
buffer: vec![],
}
}
pub fn get_first_line(&mut self) -> io::Result<Vec<u8>> {
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<u8>) -> io::Result<bool> {
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();