2
0
mirror of https://github.com/sharkdp/bat synced 2024-11-08 19:10:41 +00:00
bat/src/inputfile.rs

48 lines
1.3 KiB
Rust
Raw Normal View History

2018-10-07 09:54:01 +00:00
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use errors::*;
const THEME_PREVIEW_FILE: &[u8] = include_bytes!("../assets/theme_preview.rs");
pub struct InputFileReader<'a> {
inner: Box<dyn BufRead + 'a>,
}
impl<'a> InputFileReader<'a> {
fn new<R: BufRead + 'a>(reader: R) -> InputFileReader<'a> {
InputFileReader {
inner: Box::new(reader),
}
}
pub fn read_line(&mut self, buf: &mut Vec<u8>) -> io::Result<bool> {
self.inner.read_until(b'\n', buf).map(|size| size > 0)
}
}
2018-10-07 09:21:41 +00:00
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum InputFile<'a> {
StdIn,
Ordinary(&'a str),
ThemePreviewFile,
}
2018-10-07 09:54:01 +00:00
impl<'a> InputFile<'a> {
pub fn get_reader(&self, stdin: &'a io::Stdin) -> Result<InputFileReader> {
2018-10-07 09:54:01 +00:00
match self {
InputFile::StdIn => Ok(InputFileReader::new(stdin.lock())),
2018-10-07 09:54:01 +00:00
InputFile::Ordinary(filename) => {
let file = File::open(filename)?;
if file.metadata()?.is_dir() {
return Err(format!("'{}' is a directory.", filename).into());
}
Ok(InputFileReader::new(BufReader::new(file)))
2018-10-07 09:54:01 +00:00
}
InputFile::ThemePreviewFile => Ok(InputFileReader::new(THEME_PREVIEW_FILE)),
2018-10-07 09:54:01 +00:00
}
}
}