aboutsummaryrefslogtreecommitdiffstats
path: root/src/messages.rs
blob: 2401293798d4516a2249678bbf70a640f8a7057f (plain) (blame)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use std::ops::Drop;

use ffi;
use utils::ScopedPhantomcow;
use MessageOwner;
use Message;
use Tags;
use TagsOwner;
use Query;

#[derive(Debug)]
pub struct MessagesPtr {
    pub ptr: *mut ffi::notmuch_messages_t,
}

impl Drop for MessagesPtr {
    fn drop(self: &mut Self) {
        unsafe { ffi::notmuch_messages_destroy(self.ptr) };
    }
}

#[derive(Debug)]
pub struct Messages<'d, 'q>
where
    'd: 'q,
{
    pub(crate) handle: MessagesPtr,
    marker: ScopedPhantomcow<'q, Query<'d>>,
}

impl<'d, 'q> Messages<'d, 'q>
where
    'd: 'q,
{
    pub(crate) fn from_ptr<P>(ptr: *mut ffi::notmuch_messages_t, owner: P) -> Messages<'d, 'q>
    where
        P: Into<ScopedPhantomcow<'q, Query<'d>>>,
    {
        Messages {
            handle: MessagesPtr { ptr },
            marker: owner.into(),
        }
    }
}

impl<'d, 'q> MessageOwner for Messages<'d, 'q> where 'd: 'q {}
impl<'d, 'q> TagsOwner for Messages<'d, 'q> where 'd: 'q {}

impl<'d, 'q> Messages<'d, 'q>
where
    'd: 'q,
{
    /**
     * Return a list of tags from all messages.
     *
     * The resulting list is guaranteed not to contain duplicated tags.
     *
     * WARNING: You can no longer iterate over messages after calling this
     * function, because the iterator will point at the end of the list.
     * We do not have a function to reset the iterator yet and the only
     * way how you can iterate over the list again is to recreate the
     * message list.
     *
     * The function returns NULL on error.
     */
    pub fn collect_tags<'m>(self: &'m Self) -> Tags<'m, Self> {
        Tags::from_ptr(
            unsafe { ffi::notmuch_messages_collect_tags(self.handle.ptr) },
            self,
        )
    }
}

impl<'d, 'q> Iterator for Messages<'d, 'q>
where
    'd: 'q,
{
    type Item = Message<'d, 'q>;

    fn next(&mut self) -> Option<Self::Item> {
        let valid = unsafe { ffi::notmuch_messages_valid(self.handle.ptr) };

        if valid == 0 {
            return None;
        }

        let cthrd = unsafe {
            let thrd = ffi::notmuch_messages_get(self.handle.ptr);
            ffi::notmuch_messages_move_to_next(self.handle.ptr);
            thrd
        };

        Some(Message::from_ptr(cthrd, ScopedPhantomcow::<'q, Query<'d>>::share(&mut self.marker)))
    }
}



pub trait MessagesExt<'d, 'q>
where
    'd: 'q,
{
}

impl<'d, 'q> MessagesExt<'q, 'q> for Messages<'d, 'q> where 'd: 'q {}


unsafe impl<'d, 'q> Send for Messages<'d, 'q> where 'd: 'q {}
unsafe impl<'d, 'q> Sync for Messages<'d, 'q> where 'd: 'q {}