~matthiasbeyer/imag

91901fac9659694d6074ef3a3e2613d60c27088d — Matthias Beyer 1 year, 1 month ago b23b816
Add viewer for viewing all entries from an iterator

Signed-off-by: Matthias Beyer <mail@beyermatthias.de>
1 files changed, 66 insertions(+), 0 deletions(-)

M lib/entry/libimagentryview/src/viewer.rs
M lib/entry/libimagentryview/src/viewer.rs => lib/entry/libimagentryview/src/viewer.rs +66 -0
@@ 21,6 21,7 @@ use std::io::Write;
use std::ops::Deref;

use libimagstore::store::Entry;
use libimagstore::store::FileLockEntry;

use crate::error::Result;



@@ 76,3 77,68 @@ impl<I, E> ViewFromIter for I
    }
}

pub trait IntoViewIter<V, W, F, T>
    where Self: Iterator<Item = T> + Sized,
          V: Viewer,
          W: Write,
          F: Fn(&T) -> Option<&FileLockEntry>,
          T: Sized,
{
    fn view_all_if(self, v: V, sink: &mut W, func: F) -> ViewIter<Self, V, W, F, T> {
        ViewIter {
            inner: self,
            viewer: v,
            func,
            sink,
        }
    }
}

impl<I, V, W, F, T> IntoViewIter<V, W, F, T> for I
    where I: Iterator<Item = T>,
          V: Viewer,
          W: Write,
          F: Fn(&T) -> Option<&FileLockEntry>,
          T: Sized,
{
    // default impl
}


pub struct ViewIter<'a, I, V, W, F, T>
    where I: Iterator<Item = T>,
          V: Viewer,
          W: Write,
          F: Fn(&T) -> Option<&FileLockEntry>,
          T: Sized,
{
    inner: I,
    viewer: V,
    func: F,
    sink: &'a mut W
}

impl<'a, I, V, W, F, T> Iterator for ViewIter<'a, I, V, W, F, T>
    where I: Iterator<Item = T>,
          V: Viewer,
          W: Write,
          F: Fn(&T) -> Option<&FileLockEntry>,
          T: Sized,
{
    type Item = failure::Fallible<T>;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(next) = self.inner.next() {
            if let Some(entry) = (self.func)(&next) {
                if let Err(e) = self.viewer.view_entry(&entry, self.sink) {
                    return Some(Err(e).map_err(failure::Error::from))
                }
            }

            return Some(Ok(next))
        }

        None
    }
}