aboutsummaryrefslogtreecommitdiffstats
path: root/src/threads.rs
blob: f99ffb1a34718849f379f9620f05eb286a9fe52a (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
use std::ops::Drop;

use supercow::{Phantomcow, Supercow};
use utils::{StreamingIterator, StreamingIteratorExt};

use ffi;
use thread::ThreadOwner;
use Thread;

pub trait ThreadsOwner {}

#[derive(Debug)]
pub(crate) struct ThreadsPtr {
    pub ptr: *mut ffi::notmuch_threads_t,
}

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

#[derive(Debug)]
pub struct Threads<'o, O>
where
    O: ThreadsOwner + 'o,
{
    handle: ThreadsPtr,
    marker: Phantomcow<'o, O>,
}

impl<'o, O> ThreadOwner for Threads<'o, O> where O: ThreadsOwner + 'o {}

impl<'o, O> Threads<'o, O>
where
    O: ThreadsOwner + 'o,
{
    pub fn from_ptr<P>(ptr: *mut ffi::notmuch_threads_t, owner: P) -> Threads<'o, O>
    where
        P: Into<Phantomcow<'o, O>>,
    {
        Threads {
            handle: ThreadsPtr { ptr },
            marker: owner.into(),
        }
    }
}

impl<'s, 'o: 's, O> StreamingIterator<'s, Thread<'s, Self>> for Threads<'o, O>
where
    O: ThreadsOwner + 'o,
{
    fn next(&'s mut self) -> Option<Thread<'s, Self>> {
        <Self as StreamingIteratorExt<'s, Thread<'s, Self>>>::next(Supercow::borrowed(self))
    }
}

pub trait ThreadsExt<'o, O>
where
    O: ThreadsOwner + 'o,
{
}

impl<'o, O> ThreadsExt<'o, O> for Threads<'o, O> where O: ThreadsOwner + 'o {}

impl<'s, 'o: 's, O> StreamingIteratorExt<'s, Thread<'s, Self>> for Threads<'o, O>
where
    O: ThreadsOwner + 'o,
{
    fn next<S>(threads: S) -> Option<Thread<'s, Self>>
    where
        S: Into<Supercow<'s, Threads<'o, O>>>,
    {
        let threadsref = threads.into();
        let valid = unsafe { ffi::notmuch_threads_valid(threadsref.handle.ptr) };

        if valid == 0 {
            return None;
        }

        let cmsg = unsafe {
            let msg = ffi::notmuch_threads_get(threadsref.handle.ptr);
            ffi::notmuch_threads_move_to_next(threadsref.handle.ptr);
            msg
        };

        Some(Thread::from_ptr(cmsg, Supercow::phantom(threadsref)))
    }
}

unsafe impl<'o, O> Send for Threads<'o, O> where O: ThreadsOwner + 'o {}
unsafe impl<'o, O> Sync for Threads<'o, O> where O: ThreadsOwner + 'o {}