| 1 | use std::fs::File; |
| 2 | use std::io::{BufReader, Error as IOError, ErrorKind, Read}; |
| 3 | use std::path::PathBuf; |
| 4 | |
| 5 | pub(crate) trait Source { |
| 6 | type Item; |
| 7 | type Error; |
| 8 | |
| 9 | fn load(&self) -> Result<Self::Item, Self::Error>; |
| 10 | } |
| 11 | |
| 12 | pub(crate) struct FileSource { |
| 13 | path: PathBuf, |
| 14 | } |
| 15 | |
| 16 | impl FileSource { |
| 17 | pub(crate) fn new(path: PathBuf) -> FileSource { |
| 18 | FileSource { path } |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | impl Source for FileSource { |
| 23 | type Item = String; |
| 24 | type Error = IOError; |
| 25 | |
| 26 | fn load(&self) -> Result<Self::Item, Self::Error> { |
| 27 | let mut reader = BufReader::new(File::open(&self.path)?); |
| 28 | |
| 29 | let mut buf = String::new(); |
| 30 | reader.read_to_string(&mut buf)?; |
| 31 | |
| 32 | Ok(buf) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | pub(crate) struct LazySource<F: Fn() -> Option<String>> { |
| 37 | loader: F, |
| 38 | } |
| 39 | |
| 40 | impl<F: Fn() -> Option<String>> LazySource<F> { |
| 41 | pub(crate) fn new(loader: F) -> LazySource<F> { |
| 42 | LazySource { loader } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | impl<F: Fn() -> Option<String>> Source for LazySource<F> { |
| 47 | type Item = String; |
| 48 | type Error = IOError; |
| 49 | |
| 50 | fn load(&self) -> Result<Self::Item, Self::Error> { |
| 51 | (self.loader)().ok_or(IOError::new(ErrorKind::Other, "Source load error")) |
| 52 | } |
| 53 | } |