melib 0.5.0

backend mail client library
Documentation
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
/*
 * meli - notmuch backend
 *
 * Copyright 2019 - 2020 Manos Pitsidianakis
 *
 * This file is part of meli.
 *
 * meli is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * meli is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with meli. If not, see <http://www.gnu.org/licenses/>.
 */

use crate::async_workers::{Async, AsyncBuilder, AsyncStatus, WorkContext};
use crate::backends::FolderHash;
use crate::backends::{
    BackendFolder, BackendOp, Folder, FolderPermissions, MailBackend, RefreshEventConsumer,
    SpecialUsageMailbox,
};
use crate::conf::AccountSettings;
use crate::email::{Envelope, EnvelopeHash, Flag};
use crate::error::{MeliError, Result};
use crate::shellexpand::ShellExpandTrait;
use fnv::FnvHashMap;
use smallvec::SmallVec;
use std::collections::hash_map::DefaultHasher;
use std::collections::BTreeMap;
use std::ffi::{CStr, CString};
use std::hash::{Hash, Hasher};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock};

pub mod bindings;
use bindings::*;

#[derive(Debug, Clone)]
struct DbWrapper {
    inner: Arc<RwLock<*mut notmuch_database_t>>,
    database_ph: std::marker::PhantomData<&'static mut notmuch_database_t>,
}

unsafe impl Send for DbWrapper {}
unsafe impl Sync for DbWrapper {}

#[derive(Debug)]
pub struct NotmuchDb {
    database: DbWrapper,
    folders: Arc<RwLock<FnvHashMap<FolderHash, NotmuchFolder>>>,
    index: Arc<RwLock<FnvHashMap<EnvelopeHash, &'static CStr>>>,
    tag_index: Arc<RwLock<BTreeMap<u64, String>>>,
    path: PathBuf,
    save_messages_to: Option<PathBuf>,
}

unsafe impl Send for NotmuchDb {}
unsafe impl Sync for NotmuchDb {}

impl Drop for NotmuchDb {
    fn drop(&mut self) {
        for f in self.folders.write().unwrap().values_mut() {
            if let Some(query) = f.query.take() {
                unsafe {
                    notmuch_query_destroy(query);
                }
            }
        }
        let inner = self.database.inner.write().unwrap();
        unsafe {
            notmuch_database_close(*inner);
            notmuch_database_destroy(*inner);
        }
    }
}

#[derive(Debug, Clone, Default)]
struct NotmuchFolder {
    hash: FolderHash,
    children: Vec<FolderHash>,
    parent: Option<FolderHash>,
    name: String,
    path: String,
    query_str: String,
    query: Option<*mut notmuch_query_t>,
    phantom: std::marker::PhantomData<&'static mut notmuch_query_t>,
    usage: Arc<RwLock<SpecialUsageMailbox>>,

    total: Arc<Mutex<usize>>,
    unseen: Arc<Mutex<usize>>,
}

impl BackendFolder for NotmuchFolder {
    fn hash(&self) -> FolderHash {
        self.hash
    }

    fn name(&self) -> &str {
        self.name.as_str()
    }

    fn path(&self) -> &str {
        self.path.as_str()
    }

    fn change_name(&mut self, _s: &str) {}

    fn clone(&self) -> Folder {
        Box::new(std::clone::Clone::clone(self))
    }

    fn children(&self) -> &[FolderHash] {
        &self.children
    }

    fn parent(&self) -> Option<FolderHash> {
        self.parent
    }

    fn special_usage(&self) -> SpecialUsageMailbox {
        *self.usage.read().unwrap()
    }

    fn permissions(&self) -> FolderPermissions {
        FolderPermissions::default()
    }

    fn is_subscribed(&self) -> bool {
        true
    }

    fn set_is_subscribed(&mut self, _new_val: bool) -> Result<()> {
        Ok(())
    }

    fn set_special_usage(&mut self, new_val: SpecialUsageMailbox) -> Result<()> {
        *self.usage.write()? = new_val;
        Ok(())
    }

    fn count(&self) -> Result<(usize, usize)> {
        Ok((*self.unseen.lock()?, *self.total.lock()?))
    }
}

unsafe impl Send for NotmuchFolder {}
unsafe impl Sync for NotmuchFolder {}

impl NotmuchDb {
    pub fn new(
        s: &AccountSettings,
        _is_subscribed: Box<dyn Fn(&str) -> bool>,
    ) -> Result<Box<dyn MailBackend>> {
        let mut database: *mut notmuch_database_t = std::ptr::null_mut();
        let path = Path::new(s.root_folder.as_str()).expand().to_path_buf();
        if !path.exists() {
            return Err(MeliError::new(format!(
                "\"root_folder\" {} for account {} is not a valid path.",
                s.root_folder.as_str(),
                s.name()
            )));
        }

        let path_c = std::ffi::CString::new(path.to_str().unwrap()).unwrap();
        let path_ptr = path_c.as_ptr();
        let status = unsafe {
            bindings::notmuch_database_open(
                path_ptr,
                notmuch_database_mode_t_NOTMUCH_DATABASE_MODE_READ_WRITE,
                &mut database as *mut _,
            )
        };
        if status != 0 {
            return Err(MeliError::new(format!(
                "Could not open notmuch database at path {}. notmuch_database_open returned {}.",
                s.root_folder.as_str(),
                status
            )));
        }
        assert!(!database.is_null());
        let mut folders = FnvHashMap::default();
        for (k, f) in s.folders.iter() {
            if let Some(query_str) = f.extra.get("query") {
                let hash = {
                    let mut h = DefaultHasher::new();
                    k.hash(&mut h);
                    h.finish()
                };
                folders.insert(
                    hash,
                    NotmuchFolder {
                        hash,
                        name: k.to_string(),
                        path: k.to_string(),
                        children: vec![],
                        parent: None,
                        query: None,
                        query_str: query_str.to_string(),
                        usage: Arc::new(RwLock::new(SpecialUsageMailbox::Normal)),
                        phantom: std::marker::PhantomData,
                        total: Arc::new(Mutex::new(0)),
                        unseen: Arc::new(Mutex::new(0)),
                    },
                );
            } else {
                return Err(MeliError::new(format!(
                    "notmuch folder configuration entry \"{}\" should have a \"query\" value set.",
                    k
                )));
            }
        }
        Ok(Box::new(NotmuchDb {
            database: DbWrapper {
                inner: Arc::new(RwLock::new(database)),
                database_ph: std::marker::PhantomData,
            },
            path,
            index: Arc::new(RwLock::new(Default::default())),
            tag_index: Arc::new(RwLock::new(Default::default())),

            folders: Arc::new(RwLock::new(folders)),
            save_messages_to: None,
        }))
    }

    pub fn validate_config(s: &AccountSettings) -> Result<()> {
        let path = Path::new(s.root_folder.as_str()).expand().to_path_buf();
        if !path.exists() {
            return Err(MeliError::new(format!(
                "\"root_folder\" {} for account {} is not a valid path.",
                s.root_folder.as_str(),
                s.name()
            )));
        }
        for (k, f) in s.folders.iter() {
            if f.extra.get("query").is_none() {
                return Err(MeliError::new(format!(
                    "notmuch folder configuration entry \"{}\" should have a \"query\" value set.",
                    k
                )));
            }
        }
        Ok(())
    }

    pub fn search(&self, query_s: &str) -> Result<SmallVec<[EnvelopeHash; 512]>> {
        let database_lck = self.database.inner.read().unwrap();
        let query_str = std::ffi::CString::new(query_s).unwrap();
        let query: *mut notmuch_query_t =
            unsafe { notmuch_query_create(*database_lck, query_str.as_ptr()) };
        if query.is_null() {
            return Err(MeliError::new("Could not create query. Out of memory?"));
        }
        let mut messages: *mut notmuch_messages_t = std::ptr::null_mut();
        let status = unsafe { notmuch_query_search_messages(query, &mut messages as *mut _) };
        if status != 0 {
            return Err(MeliError::new(format!(
                "Search for {} returned {}",
                query_s, status,
            )));
        }
        assert!(!messages.is_null());
        let iter = MessageIterator { messages };
        let mut ret = SmallVec::new();
        for message in iter {
            let fs_path = unsafe { notmuch_message_get_filename(message) };
            let c_str = unsafe { CStr::from_ptr(fs_path) };
            let env_hash = {
                let mut hasher = DefaultHasher::default();
                c_str.hash(&mut hasher);
                hasher.finish()
            };
            ret.push(env_hash);
        }

        Ok(ret)
    }
}

impl MailBackend for NotmuchDb {
    fn is_online(&self) -> Result<()> {
        Ok(())
    }
    fn get(&mut self, folder: &Folder) -> Async<Result<Vec<Envelope>>> {
        let mut w = AsyncBuilder::new();
        let folder_hash = folder.hash();
        let database = self.database.clone();
        let index = self.index.clone();
        let tag_index = self.tag_index.clone();
        let folders = self.folders.clone();
        let handle = {
            let tx = w.tx();
            let closure = move |_work_context| {
                let mut ret: Vec<Envelope> = Vec::new();
                let database_lck = database.inner.read().unwrap();
                let mut folders_lck = folders.write().unwrap();
                let folder = folders_lck.get_mut(&folder_hash).unwrap();
                let query_str = std::ffi::CString::new(folder.query_str.as_str()).unwrap();
                let query: *mut notmuch_query_t =
                    unsafe { notmuch_query_create(*database_lck, query_str.as_ptr()) };
                if query.is_null() {
                    tx.send(AsyncStatus::Payload(Err(MeliError::new(
                        "Could not create query. Out of memory?",
                    ))))
                    .unwrap();
                    tx.send(AsyncStatus::Finished).unwrap();
                    return;
                }
                let mut messages: *mut notmuch_messages_t = std::ptr::null_mut();
                let status =
                    unsafe { notmuch_query_search_messages(query, &mut messages as *mut _) };
                if status != 0 {
                    tx.send(AsyncStatus::Payload(Err(MeliError::new(format!(
                        "Search for {} returned {}",
                        folder.query_str.as_str(),
                        status,
                    )))))
                    .unwrap();
                    tx.send(AsyncStatus::Finished).unwrap();
                    return;
                }
                assert!(!messages.is_null());
                let iter = MessageIterator { messages };
                for message in iter {
                    let mut response = String::new();
                    let fs_path = unsafe { notmuch_message_get_filename(message) };
                    let mut f = match std::fs::File::open(unsafe {
                        CStr::from_ptr(fs_path)
                            .to_string_lossy()
                            .into_owned()
                            .as_str()
                    }) {
                        Ok(f) => f,
                        Err(e) => {
                            debug!("could not open fs_path {:?} {}", fs_path, e);
                            continue;
                        }
                    };
                    response.clear();
                    if let Err(e) = f.read_to_string(&mut response) {
                        debug!("could not read fs_path {:?} {}", fs_path, e);
                        continue;
                    }
                    let c_str = unsafe { CStr::from_ptr(fs_path) };
                    let env_hash = {
                        let mut hasher = DefaultHasher::default();
                        c_str.hash(&mut hasher);
                        hasher.finish()
                    };
                    index.write().unwrap().insert(env_hash, c_str);
                    let op = Box::new(NotmuchOp {
                        database: database.clone(),
                        hash: env_hash,
                        index: index.clone(),
                        bytes: Some(response),
                        tag_index: tag_index.clone(),
                    });
                    if let Some(mut env) = Envelope::from_token(op, env_hash) {
                        let mut tag_lock = tag_index.write().unwrap();
                        for tag in (TagIterator {
                            tags: unsafe { notmuch_message_get_tags(message) },
                        }) {
                            let tag = tag.to_string_lossy().into_owned();

                            let mut hasher = DefaultHasher::new();
                            hasher.write(tag.as_bytes());
                            let num = hasher.finish();
                            if !tag_lock.contains_key(&num) {
                                tag_lock.insert(num, tag);
                            }
                            env.labels_mut().push(num);
                        }
                        ret.push(env);
                    } else {
                        debug!("could not parse path {:?}", c_str);
                        index.write().unwrap().remove(&env_hash);
                    }
                }
                folder.query = Some(query);
                tx.send(AsyncStatus::Payload(Ok(ret))).unwrap();
                tx.send(AsyncStatus::Finished).unwrap();
            };
            Box::new(closure)
        };
        w.build(handle)
    }

    fn watch(
        &self,
        _sender: RefreshEventConsumer,
        _work_context: WorkContext,
    ) -> Result<std::thread::ThreadId> {
        let handle = std::thread::Builder::new()
            .name(format!(
                "watching {}",
                self.path.file_name().unwrap().to_str().unwrap()
            ))
            .spawn(move || {})?;
        Ok(handle.thread().id())
    }
    fn folders(&self) -> Result<FnvHashMap<FolderHash, Folder>> {
        Ok(self
            .folders
            .read()
            .unwrap()
            .iter()
            .map(|(k, f)| (*k, BackendFolder::clone(f)))
            .collect())
    }
    fn operation(&self, hash: EnvelopeHash) -> Box<dyn BackendOp> {
        Box::new(NotmuchOp {
            database: self.database.clone(),
            hash,
            index: self.index.clone(),
            bytes: None,
            tag_index: self.tag_index.clone(),
        })
    }

    fn save(&self, bytes: &[u8], _folder: &str, flags: Option<Flag>) -> Result<()> {
        let mut path = self
            .save_messages_to
            .as_ref()
            .unwrap_or(&self.path)
            .to_path_buf();
        if !(path.ends_with("cur") || path.ends_with("new") || path.ends_with("tmp")) {
            for d in &["cur", "new", "tmp"] {
                path.push(d);
                if !path.is_dir() {
                    return Err(MeliError::new(format!(
                        "{} is not a valid maildir folder",
                        path.display()
                    )));
                }
                path.pop();
            }
            path.push("cur");
        }
        crate::backends::MaildirType::save_to_folder(path, bytes, flags)
    }

    fn as_any(&self) -> &dyn::std::any::Any {
        self
    }

    fn tags(&self) -> Option<Arc<RwLock<BTreeMap<u64, String>>>> {
        Some(self.tag_index.clone())
    }
}

#[derive(Debug)]
struct NotmuchOp {
    hash: EnvelopeHash,
    index: Arc<RwLock<FnvHashMap<EnvelopeHash, &'static CStr>>>,
    tag_index: Arc<RwLock<BTreeMap<u64, String>>>,
    database: DbWrapper,
    bytes: Option<String>,
}

impl BackendOp for NotmuchOp {
    fn description(&self) -> String {
        String::new()
    }

    fn as_bytes(&mut self) -> Result<&[u8]> {
        let path = &self.index.read().unwrap()[&self.hash];
        let mut f = std::fs::File::open(path.to_str().unwrap())?;
        let mut response = String::new();
        f.read_to_string(&mut response)?;
        self.bytes = Some(response);
        Ok(self.bytes.as_ref().unwrap().as_bytes())
    }

    fn fetch_flags(&self) -> Flag {
        let mut flag = Flag::default();
        let path = self.index.read().unwrap()[&self.hash].to_str().unwrap();
        if !path.contains(":2,") {
            return flag;
        }

        for f in path.chars().rev() {
            match f {
                ',' => break,
                'D' => flag |= Flag::DRAFT,
                'F' => flag |= Flag::FLAGGED,
                'P' => flag |= Flag::PASSED,
                'R' => flag |= Flag::REPLIED,
                'S' => flag |= Flag::SEEN,
                'T' => flag |= Flag::TRASHED,
                _ => {
                    debug!("DEBUG: in fetch_flags, path is {}", path);
                }
            }
        }

        flag
    }

    fn set_flag(&mut self, _envelope: &mut Envelope, f: Flag, value: bool) -> Result<()> {
        let mut message: *mut notmuch_message_t = std::ptr::null_mut();
        let mut index_lck = self.index.write().unwrap();
        unsafe {
            notmuch_database_find_message_by_filename(
                *self.database.inner.read().unwrap(),
                index_lck[&self.hash].as_ptr(),
                &mut message as *mut _,
            )
        };
        if message.is_null() {
            return Err(MeliError::new(format!(
                "Error, message with path {:?} not found in notmuch database.",
                index_lck[&self.hash]
            )));
        }

        let tags = (TagIterator {
            tags: unsafe { notmuch_message_get_tags(message) },
        })
        .collect::<Vec<&CStr>>();
        debug!(&tags);

        macro_rules! cstr {
            ($l:literal) => {
                CStr::from_bytes_with_nul_unchecked($l)
            };
        }
        macro_rules! add_tag {
            ($l:literal) => {
                unsafe {
                    if tags.contains(&cstr!($l)) {
                        return Ok(());
                    }
                    if notmuch_message_add_tag(message, cstr!($l).as_ptr())
                        != _notmuch_status_NOTMUCH_STATUS_SUCCESS
                    {
                        return Err(MeliError::new("Could not set tag."));
                    }
                }
            };
        }
        macro_rules! remove_tag {
            ($l:literal) => {
                unsafe {
                    if !tags.contains(&cstr!($l)) {
                        return Ok(());
                    }
                    if notmuch_message_remove_tag(message, cstr!($l).as_ptr())
                        != _notmuch_status_NOTMUCH_STATUS_SUCCESS
                    {
                        return Err(MeliError::new("Could not set tag."));
                    }
                }
            };
        }

        match f {
            Flag::DRAFT if value => add_tag!(b"draft\0"),
            Flag::DRAFT => remove_tag!(b"draft\0"),
            Flag::FLAGGED if value => add_tag!(b"flagged\0"),
            Flag::FLAGGED => remove_tag!(b"flagged\0"),
            Flag::PASSED if value => add_tag!(b"passed\0"),
            Flag::PASSED => remove_tag!(b"passed\0"),
            Flag::REPLIED if value => add_tag!(b"replied\0"),
            Flag::REPLIED => remove_tag!(b"replied\0"),
            Flag::SEEN if value => remove_tag!(b"unread\0"),
            Flag::SEEN => add_tag!(b"unread\0"),
            Flag::TRASHED if value => add_tag!(b"trashed\0"),
            Flag::TRASHED => remove_tag!(b"trashed\0"),
            _ => debug!("flags is {:?} value = {}", f, value),
        }

        /* Update message filesystem path. */
        if unsafe { notmuch_message_tags_to_maildir_flags(message) }
            != _notmuch_status_NOTMUCH_STATUS_SUCCESS
        {
            return Err(MeliError::new("Could not set tag."));
        }

        let fs_path = unsafe { notmuch_message_get_filename(message) };
        let c_str = unsafe { CStr::from_ptr(fs_path) };
        if let Some(p) = index_lck.get_mut(&self.hash) {
            *p = c_str;
        }
        let new_hash = {
            let mut hasher = DefaultHasher::default();
            c_str.hash(&mut hasher);
            hasher.finish()
        };
        index_lck.insert(new_hash, c_str);

        Ok(())
    }

    fn set_tag(&mut self, envelope: &mut Envelope, tag: String, value: bool) -> Result<()> {
        let mut message: *mut notmuch_message_t = std::ptr::null_mut();
        let index_lck = self.index.read().unwrap();
        unsafe {
            notmuch_database_find_message_by_filename(
                *self.database.inner.read().unwrap(),
                index_lck[&self.hash].as_ptr(),
                &mut message as *mut _,
            )
        };
        if message.is_null() {
            return Err(MeliError::new(format!(
                "Error, message with path {:?} not found in notmuch database.",
                index_lck[&self.hash]
            )));
        }
        if value {
            if unsafe {
                notmuch_message_add_tag(message, CString::new(tag.as_str()).unwrap().as_ptr())
            } != _notmuch_status_NOTMUCH_STATUS_SUCCESS
            {
                return Err(MeliError::new("Could not set tag."));
            }
            debug!("added tag {}", &tag);
        } else {
            if unsafe {
                notmuch_message_remove_tag(message, CString::new(tag.as_str()).unwrap().as_ptr())
            } != _notmuch_status_NOTMUCH_STATUS_SUCCESS
            {
                return Err(MeliError::new("Could not set tag."));
            }
            debug!("removed tag {}", &tag);
        }
        let hash = tag_hash!(tag);
        if value {
            self.tag_index.write().unwrap().insert(hash, tag);
        } else {
            self.tag_index.write().unwrap().remove(&hash);
        }
        if !envelope.labels().iter().any(|&h_| h_ == hash) {
            if value {
                envelope.labels_mut().push(hash);
            }
        }
        if !value {
            if let Some(pos) = envelope.labels().iter().position(|&h_| h_ == hash) {
                envelope.labels_mut().remove(pos);
            }
        }
        Ok(())
    }
}

pub struct MessageIterator {
    messages: *mut notmuch_messages_t,
}

impl Iterator for MessageIterator {
    type Item = *mut notmuch_message_t;
    fn next(&mut self) -> Option<Self::Item> {
        if self.messages.is_null() {
            None
        } else if unsafe { notmuch_messages_valid(self.messages) } == 1 {
            let ret = Some(unsafe { notmuch_messages_get(self.messages) });
            unsafe {
                notmuch_messages_move_to_next(self.messages);
            }
            ret
        } else {
            self.messages = std::ptr::null_mut();
            None
        }
    }
}

pub struct TagIterator {
    tags: *mut notmuch_tags_t,
}

impl Iterator for TagIterator {
    type Item = &'static CStr;
    fn next(&mut self) -> Option<Self::Item> {
        if self.tags.is_null() {
            None
        } else if unsafe { notmuch_tags_valid(self.tags) } == 1 {
            let ret = Some(unsafe { CStr::from_ptr(notmuch_tags_get(self.tags)) });
            unsafe {
                notmuch_tags_move_to_next(self.tags);
            }
            ret
        } else {
            self.tags = std::ptr::null_mut();
            None
        }
    }
}