make import::open_blk_dir prettier

This commit is contained in:
debris 2016-10-31 15:28:28 +01:00
parent 4f9d68cd99
commit f604574713
1 changed files with 11 additions and 28 deletions

View File

@ -1,7 +1,7 @@
use std::{io, fs, path};
use ser::{ReadIterator, deserialize_iterator, Error as ReaderError};
use block::Block;
use fs::{read_blk_dir, ReadBlkDir};
use fs::read_blk_dir;
pub fn open_blk_file<P>(path: P) -> Result<BlkFile, io::Error> where P: AsRef<path::Path> {
let file = try!(fs::File::open(path));
@ -24,45 +24,28 @@ impl Iterator for BlkFile {
}
pub fn open_blk_dir<P>(path: P) -> Result<BlkDir, io::Error> where P: AsRef<path::Path> {
let dir_iter = try!(read_blk_dir(path));
let iter = try!(read_blk_dir(path))
// flatten results...
.flat_map(|entry| entry.and_then(|file| open_blk_file(file.path)))
// flat iterators over each block in each file
.flat_map(|file| file);
let blk_dir = BlkDir {
dir_iter: dir_iter,
current_file: None,
iter: Box::new(iter),
};
Ok(blk_dir)
}
pub struct BlkDir {
dir_iter: ReadBlkDir,
current_file: Option<BlkFile>,
iter: Box<Iterator<Item = Result<Block, ReaderError>>>,
}
impl Iterator for BlkDir {
type Item = Result<Block, ReaderError>;
fn next(&mut self) -> Option<Self::Item> {
// TODO: use chained iterators instead
let next_file = match self.current_file {
Some(ref mut file) => match file.next() {
Some(block) => return Some(block),
None => self.dir_iter.next(),
},
None => self.dir_iter.next(),
};
match next_file {
Some(Ok(next_file)) => {
self.current_file = match open_blk_file(next_file.path) {
Err(_) => return Some(Err(ReaderError::MalformedData)),
Ok(file) => Some(file),
};
self.next()
},
Some(Err(_)) => {
Some(Err(ReaderError::MalformedData))
},
None => None,
}
self.iter.next()
}
}