aboutsummaryrefslogtreecommitdiffstats
path: root/src/query.rs
blob: a90a0fe68751cd86d80a31dea1ce938dde179e69 (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
use std::ops::Drop;
use std::ptr;
use supercow::Phantomcow;

use error::Result;
use ffi;
use ffi::Sort;
use Database;
use Messages;
use MessagesOwner;
use Threads;
use ThreadsOwner;

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

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

#[derive(Debug)]
pub struct Query<'d> {
    pub(crate) handle: QueryPtr,
    marker: Phantomcow<'d, Database>,
}

impl<'d> ThreadsOwner for Query<'d> {}
impl<'d> MessagesOwner for Query<'d> {}

impl<'d> Query<'d> {
    pub fn from_ptr<O: Into<Phantomcow<'d, Database>>>(
        ptr: *mut ffi::notmuch_query_t,
        owner: O,
    ) -> Query<'d> {
        Query {
            handle: QueryPtr { ptr },
            marker: owner.into(),
        }
    }

    pub fn create(db: &'d Database, query_string: &str) -> Result<Self> {
        db.create_query(query_string)
    }

    /// Specify the sorting desired for this query.
    pub fn set_sort(self: &Self, sort: Sort) {
        unsafe { ffi::notmuch_query_set_sort(self.handle.ptr, sort.into()) }
    }

    /// Return the sort specified for this query. See
    /// `set_sort`.
    pub fn sort(self: &Self) -> Sort {
        unsafe { ffi::notmuch_query_get_sort(self.handle.ptr) }.into()
    }

    /// Filter messages according to the query and return
    pub fn search_messages<'q>(self: &'d Self) -> Result<Messages<'q, Self>> {
        let mut msgs = ptr::null_mut();
        try!(
            unsafe { ffi::notmuch_query_search_messages(self.handle.ptr, &mut msgs,) }.as_result()
        );

        Ok(Messages::from_ptr(msgs, self))
    }

    pub fn count_messages(self: &Self) -> Result<u32> {
        let mut cnt = 0;
        try!(unsafe { ffi::notmuch_query_count_messages(self.handle.ptr, &mut cnt,) }.as_result());

        Ok(cnt)
    }

    pub fn search_threads<'q>(self: &'d Self) -> Result<Threads<'q, Self>> {
        let mut thrds = ptr::null_mut();
        try!(
            unsafe { ffi::notmuch_query_search_threads(self.handle.ptr, &mut thrds,) }.as_result()
        );

        Ok(Threads::from_ptr(thrds, self))
    }

    pub fn count_threads(self: &Self) -> Result<u32> {
        let mut cnt = 0;
        try!(unsafe { ffi::notmuch_query_count_threads(self.handle.ptr, &mut cnt,) }.as_result());

        Ok(cnt)
    }
}

unsafe impl<'d> Send for Query<'d> {}
unsafe impl<'d> Sync for Query<'d> {}