#![deny(warnings, missing_docs)]
use std::io::{self, Read, BufRead};
use std::fs::File;
use std::path::{Path, PathBuf};
pub fn read_all_to_string<P: AsRef<Path>>(filename: P) -> io::Result<String> {
let mut out = String::new();
let mut file = File::open(filename)?;
file.read_to_string(&mut out)?;
Ok(out)
}
pub fn read_all_bytes<P: AsRef<Path>>(filename: P) -> io::Result<Vec<u8>> {
let mut out = Vec::new();
let mut file = File::open(filename)?;
file.read_to_end(&mut out)?;
Ok(out)
}
pub fn iterate_all_lines<P: AsRef<Path>>(filename: P) -> Lines {
Lines {
filename: filename.as_ref().to_path_buf(),
iter: None,
}
}
pub fn read_all_lines<P: AsRef<Path>>(filename: P) -> io::Result<Vec<String>> {
iterate_all_lines(filename).collect()
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Lines {
filename: PathBuf,
iter: Option<io::Lines<io::BufReader<File>>>,
}
impl Iterator for Lines {
type Item = io::Result<String>;
fn next(&mut self) -> Option<Self::Item> {
if self.iter.is_none() {
match File::open(&self.filename) {
Ok(f) => self.iter = Some(io::BufReader::new(f).lines()),
Err(e) => return Some(Err(e)),
}
}
self.iter.as_mut().and_then(|i| i.next())
}
}