daaki-imap 0.1.0

An IMAP4rev1/IMAP4rev2 async 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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
//! FETCH response and request types, APPEND helpers, and BINARY extension types.
//!
//! FETCH responses are defined in RFC 3501 Section 7.4.2 / RFC 9051 Section 7.5.2.
//! FETCH command attributes are defined in RFC 3501 Section 6.4.5 / RFC 9051 Section 6.4.5.
//! MULTIAPPEND is defined in RFC 3502.
//! BINARY extension is defined in RFC 3516.

use super::{BodyStructure, Envelope, Flag};

/// A parsed FETCH response for a single message
/// (RFC 3501 Section 7.4.2 / RFC 9051 Section 7.5.2).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct FetchResponse {
    /// Message sequence number (RFC 3501 Section 7.4.2 / RFC 9051 Section 7.5.2).
    pub seq: u32,
    /// `UID` value (RFC 3501 Section 2.3.1.1).
    pub uid: Option<u32>,
    /// `FLAGS` value (RFC 3501 Section 2.3.2).
    pub flags: Option<Vec<Flag>>,
    /// Parsed `ENVELOPE` (RFC 3501 Section 7.4.2).
    pub envelope: Option<Envelope>,
    /// Parsed `BODYSTRUCTURE` (RFC 3501 Section 7.4.2).
    pub body_structure: Option<BodyStructure>,
    /// `RFC822.SIZE` in bytes (RFC 3501 Section 7.4.2 / RFC 9051 Section 7.5.2).
    ///
    /// RFC 9051 widens this from `number` to `number64` to support messages > 4 GiB.
    pub rfc822_size: Option<u64>,
    /// `INTERNALDATE` timestamp string (RFC 3501 Section 7.4.2).
    ///
    /// The date-time string in IMAP format, e.g. `"17-Jul-1996 02:44:25 -0700"`.
    pub internal_date: Option<String>,
    /// Fetched body sections per `BODY[section]<partial>` (RFC 3501 Section 6.4.5).
    pub body_sections: Vec<BodySection>,
    /// `MODSEQ` value (RFC 7162 CONDSTORE Section 3.1.3).
    pub mod_seq: Option<u64>,
    /// `SAVEDATE` timestamp string (RFC 8514 Section 3).
    ///
    /// The date-time when the message was saved to the mailbox, or `None` if
    /// the server returned NIL (message predates SAVEDATE tracking).
    pub save_date: Option<String>,
    /// `BINARY[section]` data items (RFC 3516 Section 4.2).
    pub binary_sections: Vec<BinarySection>,
    /// `BINARY.SIZE[section]` values (RFC 3516 Section 4.3 / RFC 9051 Section 7.5.2).
    ///
    /// Each entry is `(section_parts, size_in_bytes)`.
    /// RFC 9051 Section 9 defines the size as `number` (u32), but stored as
    /// `u64` for Postel's-law leniency with servers that send larger values.
    pub binary_sizes: Vec<(Vec<u32>, u64)>,
    /// `PREVIEW` text (RFC 8970 Section 3).
    ///
    /// A short plaintext snippet of the message, or `None` if the server
    /// returned NIL (e.g., for LAZY requests where the preview is not yet computed).
    pub preview: Option<String>,
    /// `EMAILID` value (RFC 8474 Section 4).
    ///
    /// A server-assigned unique identifier for this particular instance of a message.
    /// The value is an `objectid` string (1-255 alphanumeric/dash/underscore characters).
    pub email_id: Option<String>,
    /// `THREADID` value (RFC 8474 Section 4).
    ///
    /// A server-assigned identifier grouping related messages into threads,
    /// or `None` if the server returned NIL (no thread association).
    pub thread_id: Option<String>,
}

/// A single fetched BINARY section (RFC 3516 Section 4.2).
///
/// Returned as `BINARY[section]<origin>` in FETCH responses.
/// The content has been decoded from its Content-Transfer-Encoding
/// (RFC 3516 Section 4.2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BinarySection {
    /// The numeric section path (e.g. `[1, 2, 3]` for `BINARY[1.2.3]`).
    pub section: Vec<u32>,
    /// Byte offset if this was a partial fetch (`<origin>` per RFC 3516 Section 4.2).
    ///
    /// RFC 9051 Section 7.5.2 widens this from `number` (u32) to `number64` (u64)
    /// to support messages > 4 GiB.
    pub origin: Option<u64>,
    /// The decoded binary data, or `None` if the server returned NIL.
    pub data: Option<Vec<u8>>,
}

/// A single fetched body section (RFC 3501 Section 6.4.5).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BodySection {
    /// The section specification (e.g. `"HEADER"`, `"1.2"`, `"TEXT"`).
    pub section: String,
    /// Byte offset if this was a partial fetch (`<origin.count>`).
    ///
    /// RFC 9051 Section 7.5.2 widens this from `number` (u32) to `number64` (u64)
    /// to support messages > 4 GiB.
    pub origin: Option<u64>,
    /// The raw body data, or `None` if the server returned NIL.
    pub data: Option<Vec<u8>>,
}

/// FETCH item attributes the client can request
/// (RFC 3501 Section 6.4.5 / RFC 9051 Section 6.4.5).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FetchAttr {
    /// UID (RFC 3501 Section 2.3.1.1).
    Uid,
    /// FLAGS (RFC 3501 Section 2.3.2).
    Flags,
    /// ENVELOPE (RFC 3501 Section 7.4.2).
    Envelope,
    /// BODYSTRUCTURE (RFC 3501 Section 7.4.2).
    BodyStructure,
    /// RFC822.SIZE (RFC 3501 Section 7.4.2).
    Rfc822Size,
    /// INTERNALDATE (RFC 3501 Section 6.4.5 / RFC 9051 Section 6.4.5).
    InternalDate,
    /// RFC822 — functionally equivalent to `BODY[]` (RFC 3501 Section 6.4.5).
    Rfc822,
    /// RFC822.HEADER — functionally equivalent to `BODY.PEEK[HEADER]` (RFC 3501 Section 6.4.5).
    Rfc822Header,
    /// RFC822.TEXT — functionally equivalent to `BODY[TEXT]` (RFC 3501 Section 6.4.5).
    Rfc822Text,
    /// `BODY.PEEK[section]<partial>` or `BODY[section]<partial>`
    /// (RFC 3501 Section 6.4.5 / RFC 9051 Section 6.4.5).
    ///
    /// RFC 9051 widens partial ranges from `number` to `number64` / `nz-number64`.
    BodySection {
        peek: bool,
        section: Option<String>,
        partial: Option<(u64, u64)>,
    },
    /// MODSEQ (RFC 7162 CONDSTORE Section 3.1.3).
    ModSeq,
    /// SAVEDATE (RFC 8514 Section 3).
    ///
    /// Returns the date-time the message was saved to the mailbox.
    /// Value is a quoted date-time string (same format as INTERNALDATE) or NIL.
    SaveDate,
    /// `BINARY[section]<partial>` or `BINARY.PEEK[section]<partial>`
    /// (RFC 3516 Section 4.5.1).
    ///
    /// Fetches the content of a MIME part, decoded from its
    /// Content-Transfer-Encoding. The section is a dot-separated list of
    /// part numbers (e.g. `[1, 2]` for section `1.2`).
    Binary {
        /// Whether to use `BINARY.PEEK` (no `\Seen` flag set) or `BINARY`.
        peek: bool,
        /// Numeric section path (e.g. `[1, 2, 3]`).
        section: Vec<u32>,
        /// Optional partial range `(offset, count)`.
        ///
        /// RFC 9051 widens partial ranges from `number` to `number64` / `nz-number64`.
        partial: Option<(u64, u64)>,
    },
    /// `BINARY.SIZE[section]` (RFC 3516 Section 4.5.2).
    ///
    /// Returns the decoded size in bytes of a MIME part.
    BinarySize {
        /// Numeric section path (e.g. `[1, 2, 3]`).
        section: Vec<u32>,
    },
    /// `PREVIEW` (RFC 8970 Section 3).
    ///
    /// Returns a short plaintext snippet of the message. The server generates
    /// the preview text from the message body.
    Preview,
    /// `PREVIEW (LAZY)` (RFC 8970 Section 3).
    ///
    /// Like `Preview`, but allows the server to return NIL if the preview
    /// is not yet computed, avoiding delays.
    PreviewLazy,
    /// `EMAILID` (RFC 8474 Section 4).
    ///
    /// Returns the server-assigned unique identifier for this message instance.
    EmailId,
    /// `THREADID` (RFC 8474 Section 4).
    ///
    /// Returns the server-assigned thread identifier, or NIL if no thread association.
    ThreadId,
}

/// How flags should be modified in a STORE command
/// (RFC 3501 Section 6.4.6 / RFC 9051 Section 6.4.6).
///
/// RFC 3501 Section 6.4.6 defines:
/// `store-att-flags = (["+" / "-"] "FLAGS" [".SILENT"]) SP (flag-list / NIL)`
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StoreOperation {
    /// `+FLAGS` — add flags.
    Add,
    /// `-FLAGS` — remove flags.
    Remove,
    /// `FLAGS` — replace all flags.
    Replace,
    /// `+FLAGS.SILENT` — add flags, suppress implicit FETCH response
    /// (RFC 3501 Section 6.4.6).
    AddSilent,
    /// `-FLAGS.SILENT` — remove flags, suppress implicit FETCH response
    /// (RFC 3501 Section 6.4.6).
    RemoveSilent,
    /// `FLAGS.SILENT` — replace all flags, suppress implicit FETCH response
    /// (RFC 3501 Section 6.4.6).
    ReplaceSilent,
}

/// Result of a STORE or UID STORE command (RFC 3501 Section 6.4.6, RFC 7162 Section 3.1.3).
///
/// When UNCHANGEDSINCE is used (CONDSTORE), the server may return a
/// `[MODIFIED uid-set]` response code indicating which messages failed the
/// precondition check (RFC 7162 Section 3.1.3). This struct preserves that
/// information so callers can detect partial failures.
///
/// Implements `Deref<Target = Vec<FetchResponse>>` so callers can use it as a
/// slice of fetch responses for backward compatibility (e.g. `.first()`, `.iter()`).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct StoreResult {
    /// Implicit FETCH responses with updated flags (RFC 3501 Section 6.4.6).
    ///
    /// Empty when `.SILENT` operations are used.
    pub fetches: Vec<FetchResponse>,
    /// Response code from the tagged OK, if any.
    ///
    /// When UNCHANGEDSINCE is used, this will be `Some(ResponseCode::Modified(...))`
    /// for messages that failed the precondition (RFC 7162 Section 3.1.3).
    /// `None` when no response code was returned.
    pub code: Option<super::response::ResponseCode>,
}

impl std::ops::Deref for StoreResult {
    type Target = Vec<FetchResponse>;

    fn deref(&self) -> &Vec<FetchResponse> {
        &self.fetches
    }
}

/// A message to be appended via MULTIAPPEND (RFC 3502).
///
/// Each message carries its own flags, optional internal date, and raw message data.
/// Multiple `AppendMessage` values are sent in a single APPEND command per
/// RFC 3502 Section 3.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AppendMessage {
    /// Flags to set on the appended message (RFC 3501 Section 6.3.11).
    pub flags: Vec<Flag>,
    /// Optional INTERNALDATE in IMAP date-time format (RFC 3501 Section 6.3.11).
    pub date: Option<String>,
    /// Raw RFC 5322 message data.
    pub data: Vec<u8>,
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    // --- FetchResponse tests ---

    #[test]
    fn fetch_response_default() {
        let resp = FetchResponse::default();
        assert_eq!(resp.seq, 0);
        assert!(resp.uid.is_none());
        assert!(resp.flags.is_none());
        assert!(resp.envelope.is_none());
        assert!(resp.body_structure.is_none());
        assert!(resp.rfc822_size.is_none());
        assert!(resp.internal_date.is_none());
        assert!(resp.body_sections.is_empty());
        assert!(resp.mod_seq.is_none());
        assert!(resp.save_date.is_none());
        assert!(resp.binary_sections.is_empty());
        assert!(resp.binary_sizes.is_empty());
        assert!(resp.preview.is_none());
        assert!(resp.email_id.is_none());
        assert!(resp.thread_id.is_none());
    }

    #[test]
    fn fetch_response_with_seq_and_uid() {
        let resp = FetchResponse {
            seq: 5,
            uid: Some(1234),
            ..Default::default()
        };
        assert_eq!(resp.seq, 5);
        assert_eq!(resp.uid, Some(1234));
    }

    #[test]
    fn fetch_response_with_flags() {
        let resp = FetchResponse {
            seq: 1,
            flags: Some(vec![Flag::Seen, Flag::Flagged]),
            ..Default::default()
        };
        let flags = resp.flags.unwrap();
        assert_eq!(flags.len(), 2);
        assert_eq!(flags[0], Flag::Seen);
        assert_eq!(flags[1], Flag::Flagged);
    }

    #[test]
    fn fetch_response_with_envelope() {
        let env = Envelope {
            subject: Some("Test subject".into()),
            ..Default::default()
        };
        let resp = FetchResponse {
            seq: 1,
            envelope: Some(env),
            ..Default::default()
        };
        assert_eq!(
            resp.envelope.unwrap().subject.as_deref(),
            Some("Test subject")
        );
    }

    #[test]
    fn fetch_response_with_rfc822_size() {
        let resp = FetchResponse {
            seq: 1,
            rfc822_size: Some(4096),
            ..Default::default()
        };
        assert_eq!(resp.rfc822_size, Some(4096));
    }

    #[test]
    fn fetch_response_with_internal_date() {
        let resp = FetchResponse {
            seq: 1,
            internal_date: Some("17-Jul-1996 02:44:25 -0700".into()),
            ..Default::default()
        };
        assert_eq!(
            resp.internal_date.as_deref(),
            Some("17-Jul-1996 02:44:25 -0700")
        );
    }

    #[test]
    fn fetch_response_with_mod_seq() {
        let resp = FetchResponse {
            seq: 1,
            mod_seq: Some(99999),
            ..Default::default()
        };
        assert_eq!(resp.mod_seq, Some(99999));
    }

    #[test]
    fn fetch_response_with_save_date() {
        let resp = FetchResponse {
            seq: 1,
            save_date: Some("01-Jan-2024 00:00:00 +0000".into()),
            ..Default::default()
        };
        assert_eq!(
            resp.save_date.as_deref(),
            Some("01-Jan-2024 00:00:00 +0000")
        );
    }

    // --- BodySection tests ---

    #[test]
    fn body_section_full() {
        let section = BodySection {
            section: "HEADER".into(),
            origin: None,
            data: Some(b"Subject: Hi\r\n".to_vec()),
        };
        assert_eq!(section.section, "HEADER");
        assert!(section.origin.is_none());
        assert_eq!(section.data.as_deref(), Some(b"Subject: Hi\r\n".as_slice()));
    }

    #[test]
    fn body_section_with_origin() {
        let section = BodySection {
            section: "1".into(),
            origin: Some(100),
            data: Some(b"partial data".to_vec()),
        };
        assert_eq!(section.origin, Some(100));
    }

    #[test]
    fn body_section_nil_data() {
        let section = BodySection {
            section: "TEXT".into(),
            origin: None,
            data: None,
        };
        assert!(section.data.is_none());
    }

    #[test]
    fn body_section_empty_section_string() {
        let section = BodySection {
            section: String::new(),
            origin: None,
            data: Some(b"full message".to_vec()),
        };
        assert!(section.section.is_empty());
    }

    // --- BinarySection tests ---

    #[test]
    fn binary_section_basic() {
        let section = BinarySection {
            section: vec![1, 2, 3],
            origin: None,
            data: Some(vec![0xFF, 0xD8, 0xFF]),
        };
        assert_eq!(section.section, [1, 2, 3]);
        assert!(section.origin.is_none());
        assert_eq!(section.data.as_deref(), Some([0xFF, 0xD8, 0xFF].as_slice()));
    }

    #[test]
    fn binary_section_with_origin() {
        let section = BinarySection {
            section: vec![1],
            origin: Some(512),
            data: Some(vec![0x00]),
        };
        assert_eq!(section.origin, Some(512));
    }

    #[test]
    fn binary_section_nil_data() {
        let section = BinarySection {
            section: vec![],
            origin: None,
            data: None,
        };
        assert!(section.data.is_none());
    }

    // --- FetchResponse with body sections ---

    #[test]
    fn fetch_response_multiple_body_sections() {
        let resp = FetchResponse {
            seq: 3,
            body_sections: vec![
                BodySection {
                    section: "HEADER".into(),
                    origin: None,
                    data: Some(b"From: alice@example.com\r\n".to_vec()),
                },
                BodySection {
                    section: "TEXT".into(),
                    origin: None,
                    data: Some(b"Hello world".to_vec()),
                },
            ],
            ..Default::default()
        };
        assert_eq!(resp.body_sections.len(), 2);
        assert_eq!(resp.body_sections[0].section, "HEADER");
        assert_eq!(resp.body_sections[1].section, "TEXT");
    }

    #[test]
    fn fetch_response_binary_sizes() {
        let resp = FetchResponse {
            seq: 1,
            binary_sizes: vec![(vec![1], 1024), (vec![2, 1], 512)],
            ..Default::default()
        };
        assert_eq!(resp.binary_sizes.len(), 2);
        assert_eq!(resp.binary_sizes[0], (vec![1], 1024));
        assert_eq!(resp.binary_sizes[1], (vec![2, 1], 512));
    }

    // --- FetchAttr tests ---

    #[test]
    fn fetch_attr_simple_variants() {
        assert_eq!(FetchAttr::Uid, FetchAttr::Uid);
        assert_eq!(FetchAttr::Flags, FetchAttr::Flags);
        assert_eq!(FetchAttr::Envelope, FetchAttr::Envelope);
        assert_eq!(FetchAttr::BodyStructure, FetchAttr::BodyStructure);
        assert_eq!(FetchAttr::Rfc822Size, FetchAttr::Rfc822Size);
        assert_eq!(FetchAttr::InternalDate, FetchAttr::InternalDate);
        assert_eq!(FetchAttr::Rfc822, FetchAttr::Rfc822);
        assert_eq!(FetchAttr::Rfc822Header, FetchAttr::Rfc822Header);
        assert_eq!(FetchAttr::Rfc822Text, FetchAttr::Rfc822Text);
        assert_eq!(FetchAttr::ModSeq, FetchAttr::ModSeq);
        assert_eq!(FetchAttr::SaveDate, FetchAttr::SaveDate);
        assert_eq!(FetchAttr::Preview, FetchAttr::Preview);
        assert_eq!(FetchAttr::PreviewLazy, FetchAttr::PreviewLazy);
        assert_eq!(FetchAttr::EmailId, FetchAttr::EmailId);
        assert_eq!(FetchAttr::ThreadId, FetchAttr::ThreadId);
    }

    #[test]
    fn fetch_response_with_preview() {
        // RFC 8970 Section 3: PREVIEW data item in FETCH response.
        let resp = FetchResponse {
            seq: 1,
            preview: Some("Meeting tomorrow at 3pm to discuss...".into()),
            ..Default::default()
        };
        assert_eq!(
            resp.preview.as_deref(),
            Some("Meeting tomorrow at 3pm to discuss...")
        );
    }

    #[test]
    fn fetch_response_with_preview_nil() {
        // RFC 8970 Section 3: PREVIEW can be NIL (e.g., LAZY mode).
        let resp = FetchResponse {
            seq: 1,
            preview: None,
            ..Default::default()
        };
        assert!(resp.preview.is_none());
    }

    #[test]
    fn fetch_response_with_email_id() {
        let resp = FetchResponse {
            seq: 1,
            email_id: Some("M6d99ac3275826486".into()),
            ..Default::default()
        };
        assert_eq!(resp.email_id.as_deref(), Some("M6d99ac3275826486"));
    }

    #[test]
    fn fetch_response_with_thread_id() {
        let resp = FetchResponse {
            seq: 1,
            thread_id: Some("T64b478a75b7ea9fd".into()),
            ..Default::default()
        };
        assert_eq!(resp.thread_id.as_deref(), Some("T64b478a75b7ea9fd"));
    }

    #[test]
    fn fetch_attr_body_section_peek() {
        let attr = FetchAttr::BodySection {
            peek: true,
            section: Some("HEADER".into()),
            partial: None,
        };
        match &attr {
            FetchAttr::BodySection {
                peek,
                section,
                partial,
            } => {
                assert!(*peek);
                assert_eq!(section.as_deref(), Some("HEADER"));
                assert!(partial.is_none());
            }
            _ => panic!("expected BodySection"),
        }
    }

    #[test]
    fn fetch_attr_body_section_with_partial() {
        let attr = FetchAttr::BodySection {
            peek: false,
            section: Some("1".into()),
            partial: Some((0, 1024)),
        };
        match &attr {
            FetchAttr::BodySection { partial, .. } => {
                assert_eq!(*partial, Some((0, 1024)));
            }
            _ => panic!("expected BodySection"),
        }
    }

    #[test]
    fn fetch_attr_body_section_no_section() {
        let attr = FetchAttr::BodySection {
            peek: false,
            section: None,
            partial: None,
        };
        match &attr {
            FetchAttr::BodySection { section, .. } => {
                assert!(section.is_none());
            }
            _ => panic!("expected BodySection"),
        }
    }

    #[test]
    fn fetch_attr_binary() {
        let attr = FetchAttr::Binary {
            peek: true,
            section: vec![1, 2],
            partial: Some((0, 512)),
        };
        match &attr {
            FetchAttr::Binary {
                peek,
                section,
                partial,
            } => {
                assert!(*peek);
                assert_eq!(section, &[1, 2]);
                assert_eq!(*partial, Some((0, 512)));
            }
            _ => panic!("expected Binary"),
        }
    }

    #[test]
    fn fetch_attr_binary_size() {
        let attr = FetchAttr::BinarySize {
            section: vec![3, 1],
        };
        match &attr {
            FetchAttr::BinarySize { section } => {
                assert_eq!(section, &[3, 1]);
            }
            _ => panic!("expected BinarySize"),
        }
    }

    // --- StoreOperation tests ---

    #[test]
    fn store_operation_variants() {
        assert_eq!(StoreOperation::Add, StoreOperation::Add);
        assert_eq!(StoreOperation::Remove, StoreOperation::Remove);
        assert_eq!(StoreOperation::Replace, StoreOperation::Replace);
        assert_ne!(StoreOperation::Add, StoreOperation::Remove);
        assert_ne!(StoreOperation::Remove, StoreOperation::Replace);
    }

    #[test]
    fn store_operation_copy() {
        let op = StoreOperation::Add;
        let op2 = op; // Copy
        assert_eq!(op, op2);
    }

    // --- AppendMessage tests ---

    #[test]
    fn append_message_basic() {
        let msg = AppendMessage {
            flags: vec![Flag::Seen],
            date: Some("01-Jan-2024 00:00:00 +0000".into()),
            data: b"From: test@example.com\r\nSubject: Hi\r\n\r\nBody".to_vec(),
        };
        assert_eq!(msg.flags.len(), 1);
        assert_eq!(msg.flags[0], Flag::Seen);
        assert!(msg.date.is_some());
        assert!(!msg.data.is_empty());
    }

    #[test]
    fn append_message_no_flags_no_date() {
        let msg = AppendMessage {
            flags: vec![],
            date: None,
            data: b"minimal message".to_vec(),
        };
        assert!(msg.flags.is_empty());
        assert!(msg.date.is_none());
    }

    // --- Clone / Eq ---

    #[test]
    fn fetch_response_clone_eq() {
        let resp = FetchResponse {
            seq: 10,
            uid: Some(500),
            flags: Some(vec![Flag::Draft]),
            ..Default::default()
        };
        let cloned = resp.clone();
        assert_eq!(resp, cloned);
    }

    #[test]
    fn body_section_clone_eq() {
        let section = BodySection {
            section: "1.2".into(),
            origin: Some(0),
            data: Some(b"data".to_vec()),
        };
        let cloned = section.clone();
        assert_eq!(section, cloned);
    }

    // --- StoreResult Deref tests ---

    #[test]
    fn store_result_deref_provides_access_to_fetches() {
        // RFC 3501 Section 6.4.6: STORE returns implicit FETCH responses.
        // The Deref impl lets callers access .fetches transparently.
        let result = StoreResult {
            fetches: vec![
                FetchResponse {
                    seq: 1,
                    uid: Some(100),
                    flags: Some(vec![Flag::Seen]),
                    ..Default::default()
                },
                FetchResponse {
                    seq: 2,
                    uid: Some(101),
                    flags: Some(vec![Flag::Flagged]),
                    ..Default::default()
                },
            ],
            code: None,
        };
        // Access via Deref — len(), indexing, iteration all delegate to Vec<FetchResponse>.
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].seq, 1);
        assert_eq!(result[1].uid, Some(101));
        // Iterate via Deref.
        let seqs: Vec<u32> = result.iter().map(|f| f.seq).collect();
        assert_eq!(seqs, vec![1, 2]);
    }

    #[test]
    fn store_result_deref_empty() {
        // RFC 3501 Section 6.4.6: STORE with .SILENT returns no FETCH responses.
        let result = StoreResult {
            fetches: vec![],
            code: None,
        };
        assert!(result.is_empty());
    }

    #[test]
    fn fetch_response_debug() {
        let resp = FetchResponse {
            seq: 1,
            uid: Some(42),
            ..Default::default()
        };
        let debug = format!("{resp:?}");
        assert!(debug.contains("seq: 1"));
        assert!(debug.contains("uid: Some(42)"));
    }
}