mirror of
https://github.com/sharkdp/bat.git
synced 2024-11-23 00:03:27 +01:00
Add possibility to get first line
This commit is contained in:
parent
078228deac
commit
869cf6368c
@ -7,17 +7,31 @@ const THEME_PREVIEW_FILE: &[u8] = include_bytes!("../assets/theme_preview.rs");
|
|||||||
|
|
||||||
pub struct InputFileReader<'a> {
|
pub struct InputFileReader<'a> {
|
||||||
inner: Box<dyn BufRead + 'a>,
|
inner: Box<dyn BufRead + 'a>,
|
||||||
|
buffer: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> InputFileReader<'a> {
|
impl<'a> InputFileReader<'a> {
|
||||||
fn new<R: BufRead + 'a>(reader: R) -> InputFileReader<'a> {
|
fn new<R: BufRead + 'a>(reader: R) -> InputFileReader<'a> {
|
||||||
InputFileReader {
|
InputFileReader {
|
||||||
inner: Box::new(reader),
|
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> {
|
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]
|
#[test]
|
||||||
fn basic() {
|
fn basic() {
|
||||||
let content = b"hello\nworld";
|
let content = b"#!/bin/bash\necho hello";
|
||||||
let mut reader = InputFileReader::new(&content[..]);
|
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 mut buffer = vec![];
|
||||||
|
|
||||||
let res = reader.read_line(&mut buffer);
|
let res = reader.read_line(&mut buffer);
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
assert_eq!(true, res.unwrap());
|
assert_eq!(true, res.unwrap());
|
||||||
assert_eq!(b"hello\n", &buffer[..]);
|
assert_eq!(b"#!/bin/bash\n", &buffer[..]);
|
||||||
|
|
||||||
buffer.clear();
|
buffer.clear();
|
||||||
|
|
||||||
let res = reader.read_line(&mut buffer);
|
let res = reader.read_line(&mut buffer);
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
assert_eq!(true, res.unwrap());
|
assert_eq!(true, res.unwrap());
|
||||||
assert_eq!(b"world", &buffer[..]);
|
assert_eq!(b"echo hello", &buffer[..]);
|
||||||
|
|
||||||
buffer.clear();
|
buffer.clear();
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user