summaryrefslogtreecommitdiffstats
path: root/lib/domain/libimagmail/src/iter.rs
blob: f1bb11a0433eae2b812cfda1eed7281375738641 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use anyhow::Result;
use anyhow::Context;
use anyhow::Error;


use libimagstore::iter::get::StoreGetIterator;
use libimagstore::store::FileLockEntry;

use crate::mail::Mail;

pub struct MailIterator<'a> {
    inner: StoreGetIterator<'a>,
    ignore_ungetable: bool,
}

impl<'a> MailIterator<'a> {
    pub fn new(sgi: StoreGetIterator<'a>) -> Self {
        MailIterator { inner: sgi, ignore_ungetable: true }
    }

    pub fn ignore_ungetable(mut self, b: bool) -> Self {
        self.ignore_ungetable = b;
        self
    }
}

pub trait IntoMailIterator<'a> {
    fn into_mail_iterator(self) -> MailIterator<'a>;
}

impl<'a> IntoMailIterator<'a> for StoreGetIterator<'a> {
    fn into_mail_iterator(self) -> MailIterator<'a> {
        MailIterator::new(self)
    }
}

impl<'a> Iterator for MailIterator<'a> {
    type Item = Result<FileLockEntry<'a>>;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(n) = self.inner.next() {
            match n {
                Ok(Some(fle)) => {
                    match fle.is_mail().context("Checking whether entry is a Mail").map_err(Error::from) {
                        Err(e)    => return Some(Err(e)),
                        Ok(true)  => return Some(Ok(fle)),
                        Ok(false) => continue,
                    }
                },

                Ok(None) => if self.ignore_ungetable {
                    continue
                } else {
                    return Some(Err(anyhow!("Failed to get one entry")))
                },

                Err(e) => return Some(Err(e)),
            }
        }

        None
    }
}