add IndexFile trait

We want to be able to iterate through digests of index
files, but without always having to distinguish between
dynamic and fixed types, so add a trait we can use as a
trait object.

Unfortunately the iterator needs to yield copies as
iterators cannot yield values with life times when
represented as trait objects (Box<dyn Iterator<Item = ?>>)

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
This commit is contained in:
Wolfgang Bumiller
2019-02-27 14:32:34 +01:00
parent 5be4065baf
commit 7bc1d72778
4 changed files with 81 additions and 2 deletions

44
src/backup/index.rs Normal file
View File

@ -0,0 +1,44 @@
pub trait IndexFile {
fn index_count(&self) -> usize;
fn index_digest(&self, pos: usize) -> Option<&[u8; 32]>;
}
pub struct IndexIterator {
pos: usize,
count: usize,
reader: Box<dyn IndexFile + Send>,
}
impl Iterator for IndexIterator {
type Item = [u8; 32];
fn next(&mut self) -> Option<Self::Item> {
if self.pos == self.count {
return None;
}
let digest = self.reader.index_digest(self.pos).unwrap();
self.pos += 1;
Some(*digest)
}
}
impl From<Box<dyn IndexFile + Send>> for IndexIterator {
fn from(file: Box<dyn IndexFile + Send>) -> Self {
Self {
pos: 0,
count: file.index_count(),
reader: file,
}
}
}
impl<T: IndexFile + Send + 'static> From<Box<T>> for IndexIterator {
fn from(file: Box<T>) -> Self {
Self {
pos: 0,
count: file.index_count(),
reader: file,
}
}
}