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
use std::ops::Drop;

use ffi;
use Thread;
use Query;
use utils::ScopedPhantomcow;


#[derive(Debug)]
pub struct Threads<'d, 'q>
where
    'd: 'q
{
    ptr: *mut ffi::notmuch_threads_t,
    marker: ScopedPhantomcow<'q, Query<'d>>,
}

impl<'d, 'q> Drop for Threads<'d, 'q>
where
    'd: 'q,
{
    fn drop(&mut self) {
        unsafe { ffi::notmuch_threads_destroy(self.ptr) };
    }
}

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

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

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

        if valid == 0 {
            return None;
        }

        let cthrd = unsafe {
            let thrd = ffi::notmuch_threads_get(self.ptr);
            ffi::notmuch_threads_move_to_next(self.ptr);
            thrd
        };

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


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

impl<'d, 'q> ThreadsExt<'d, 'q> for Threads<'d, 'q> where 'd: 'q {}


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