aboutsummaryrefslogtreecommitdiffstats
path: root/src/filenames.rs
blob: ad4c3e92ffa11740e4f80b698c9aac411cb7769d (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
use std::ffi::CStr;
use std::iter::Iterator;
use std::ops::Drop;
use std::path::PathBuf;

use supercow::Phantomcow;

use crate::ffi;

pub trait FilenamesOwner {}

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

impl Drop for FilenamesPtr {
    fn drop(self: &mut Self) {
        let valid = unsafe { ffi::notmuch_filenames_valid(self.ptr) };

        if valid != 0 {
            unsafe { ffi::notmuch_filenames_destroy(self.ptr) };
        }
    }
}

#[derive(Debug)]
pub struct Filenames<'o, O>
where
    O: FilenamesOwner,
{
    pub(crate) handle: FilenamesPtr,
    pub(crate) marker: Phantomcow<'o, O>,
}

impl<'o, O> Filenames<'o, O>
where
    O: FilenamesOwner + 'o,
{
    pub fn from_ptr<P>(ptr: *mut ffi::notmuch_filenames_t, owner: P) -> Filenames<'o, O>
    where
        P: Into<Phantomcow<'o, O>>,
    {
        Filenames {
            handle: FilenamesPtr { ptr },
            marker: owner.into(),
        }
    }
}

impl<'o, O> Iterator for Filenames<'o, O>
where
    O: FilenamesOwner + 'o,
{
    type Item = PathBuf;

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

        if valid == 0 {
            return None;
        }

        let ctag = unsafe {
            let t = ffi::notmuch_filenames_get(self.handle.ptr);
            ffi::notmuch_filenames_move_to_next(self.handle.ptr);
            CStr::from_ptr(t)
        };

        Some(PathBuf::from(ctag.to_str().unwrap()))
    }
}

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