use read;
use std::fs::File;
use std::io::{self, BufReader, Stdin};
use std::path::Path;
#[derive(Default)]
pub struct FromFile {
file: Option<BufReader<File>>,
}
impl FromFile {
pub fn new() -> FromFile {
FromFile { file: None }
}
pub fn from_path<T: AsRef<Path>>(path: T) -> FromFile {
FromFile { file: File::open(path).ok().map(BufReader::new) }
}
pub fn with_fallback(self) -> WithFallback {
WithFallback {
file: self.file,
stdin: None,
}
}
pub fn all(&mut self) -> String {
match self.file {
None => String::new(),
Some(ref mut read) => read::whole_stream(read),
}
}
}
pub struct WithFallback {
file: Option<BufReader<File>>,
stdin: Option<BufReader<Stdin>>,
}
impl WithFallback {
pub fn all(&mut self) -> String {
if let Some(ref mut file) = self.file {
return read::whole_stream(file);
}
if let Some(ref mut stdin) = self.stdin {
return read::whole_stream(stdin);
}
let mut stdin = BufReader::new(io::stdin());
let ret = read::whole_stream(&mut stdin);
self.stdin = Some(stdin);
ret
}
}
impl Iterator for FromFile {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
match self.file {
None => None,
Some(ref mut file) => read::next_line(file),
}
}
}
impl Iterator for WithFallback {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
if let Some(ref mut file) = self.file {
return read::next_line(file);
}
if let Some(ref mut stdin) = self.stdin {
return read::next_line(stdin);
}
let mut stdin = BufReader::new(io::stdin());
let ret = read::next_line(&mut stdin);
self.stdin = Some(stdin);
ret
}
}