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
use std::rc::Rc;
use std::ops::Drop;
use std::fmt::Debug;

use from_variants::FromVariants;

use ffi;
use Query;
use Thread;

#[derive(Clone, Debug, FromVariants)]
pub(crate) enum ThreadsOwner {
    Query(Query),
}

#[derive(Debug)]
pub struct ThreadsPtr(*mut ffi::notmuch_threads_t);

impl Drop for ThreadsPtr
{
    fn drop(&mut self) {
        unsafe { ffi::notmuch_threads_destroy(self.0) };
    }
}

#[derive(Clone, Debug)]
pub struct Threads
{
    ptr: Rc<ThreadsPtr>,
    owner: Box<ThreadsOwner>,
}

impl Threads
{
    pub(crate) fn from_ptr<O>(ptr: *mut ffi::notmuch_threads_t, owner: O) -> Threads
    where
        O: Into<ThreadsOwner>,
    {
        Threads {
            ptr: Rc::new(ThreadsPtr(ptr)),
            owner: Box::new(owner.into()),
        }
    }
}

impl Iterator for Threads
{
    type Item = Thread;

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

        if valid == 0 {
            return None;
        }

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

        Some(Thread::from_ptr(cthrd, self.clone()))
    }
}