• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

duesee / imap-codec / 12734576929

12 Jan 2025 02:57PM UTC coverage: 93.011% (-0.02%) from 93.034%
12734576929

Pull #628

github

web-flow
Merge 1110c40fb into a29d5a3ef
Pull Request #628: feat: Implement Condstore Status Codes

24 of 34 new or added lines in 4 files covered. (70.59%)

1 existing line in 1 file now uncovered.

11286 of 12134 relevant lines covered (93.01%)

909.3 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

87.61
/imap-codec/src/codec/encode.rs
1
//! # Encoding of messages.
2
//!
3
//! To facilitates handling of literals, [Encoder::encode] returns an instance of [`Encoded`].
4
//! The idea is that the encoder not only "dumps" the final serialization of a message but can be iterated over.
5
//!
6
//! # Example
7
//!
8
//! ```rust
9
//! use imap_codec::{
10
//!     encode::{Encoder, Fragment},
11
//!     imap_types::{
12
//!         command::{Command, CommandBody},
13
//!         core::LiteralMode,
14
//!     },
15
//!     CommandCodec,
16
//! };
17
//!
18
//! let command = Command::new("A1", CommandBody::login("Alice", "Pa²²W0rD").unwrap()).unwrap();
19
//!
20
//! for fragment in CommandCodec::default().encode(&command) {
21
//!     match fragment {
22
//!         Fragment::Line { data } => {
23
//!             // A line that is ready to be send.
24
//!             println!("C: {}", String::from_utf8(data).unwrap());
25
//!         }
26
//!         Fragment::Literal { data, mode } => match mode {
27
//!             LiteralMode::Sync => {
28
//!                 // Wait for a continuation request.
29
//!                 println!("S: + ...")
30
//!             }
31
//!             LiteralMode::NonSync => {
32
//!                 // We don't need to wait for a continuation request
33
//!                 // as the server will also not send it.
34
//!             }
35
//!         },
36
//!     }
37
//! }
38
//! ```
39
//!
40
//! Output of example:
41
//!
42
//! ```imap
43
//! C: A1 LOGIN alice {10}
44
//! S: + ...
45
//! C: Pa²²W0rD
46
//! ```
47

48
#[cfg(feature = "ext_condstore_qresync")]
49
use std::num::NonZeroU64;
50
use std::{borrow::Borrow, collections::VecDeque, io::Write, num::NonZeroU32};
51

52
use base64::{engine::general_purpose::STANDARD as base64, Engine};
53
use chrono::{DateTime as ChronoDateTime, FixedOffset};
54
use imap_types::{
55
    auth::{AuthMechanism, AuthenticateData},
56
    body::{
57
        BasicFields, Body, BodyExtension, BodyStructure, Disposition, Language, Location,
58
        MultiPartExtensionData, SinglePartExtensionData, SpecificFields,
59
    },
60
    command::{Command, CommandBody},
61
    core::{
62
        AString, Atom, AtomExt, Charset, IString, Literal, LiteralMode, NString, NString8, Quoted,
63
        QuotedChar, Tag, Text,
64
    },
65
    datetime::{DateTime, NaiveDate},
66
    envelope::{Address, Envelope},
67
    extensions::idle::IdleDone,
68
    fetch::{
69
        Macro, MacroOrMessageDataItemNames, MessageDataItem, MessageDataItemName, Part, Section,
70
    },
71
    flag::{Flag, FlagFetch, FlagNameAttribute, FlagPerm, StoreResponse, StoreType},
72
    mailbox::{ListCharString, ListMailbox, Mailbox, MailboxOther},
73
    response::{
74
        Bye, Capability, Code, CodeOther, CommandContinuationRequest, Data, Greeting, GreetingKind,
75
        Response, Status, StatusBody, StatusKind, Tagged,
76
    },
77
    search::SearchKey,
78
    sequence::{SeqOrUid, Sequence, SequenceSet},
79
    status::{StatusDataItem, StatusDataItemName},
80
    utils::escape_quoted,
81
};
82
use utils::{join_serializable, List1AttributeValueOrNil, List1OrNil};
83

84
use crate::{AuthenticateDataCodec, CommandCodec, GreetingCodec, IdleDoneCodec, ResponseCodec};
85

86
/// Encoder.
87
///
88
/// Implemented for types that know how to encode a specific IMAP message. See [implementors](trait.Encoder.html#implementors).
89
pub trait Encoder {
90
    type Message<'a>;
91

92
    /// Encode this message.
93
    ///
94
    /// This will return an [`Encoded`] message.
95
    fn encode(&self, message: &Self::Message<'_>) -> Encoded;
96
}
97

98
/// An encoded message.
99
///
100
/// This struct facilitates the implementation of IMAP client- and server implementations by
101
/// yielding the encoding of a message through [`Fragment`]s. This is required, because the usage of
102
/// literals (and some other types) may change the IMAP message flow. Thus, in many cases, it is an
103
/// error to just "dump" a message and send it over the network.
104
///
105
/// # Example
106
///
107
/// ```rust
108
/// use imap_codec::{
109
///     encode::{Encoder, Fragment},
110
///     imap_types::command::{Command, CommandBody},
111
///     CommandCodec,
112
/// };
113
///
114
/// let cmd = Command::new("A", CommandBody::login("alice", "pass").unwrap()).unwrap();
115
///
116
/// for fragment in CommandCodec::default().encode(&cmd) {
117
///     match fragment {
118
///         Fragment::Line { data } => {}
119
///         Fragment::Literal { data, mode } => {}
120
///     }
121
/// }
122
/// ```
123
#[derive(Clone, Debug)]
124
pub struct Encoded {
125
    items: VecDeque<Fragment>,
126
}
127

128
impl Encoded {
129
    /// Dump the (remaining) encoded data without being guided by [`Fragment`]s.
130
    pub fn dump(self) -> Vec<u8> {
2,028✔
131
        let mut out = Vec::new();
2,028✔
132

133
        for fragment in self.items {
4,076✔
134
            match fragment {
2,048✔
135
                Fragment::Line { mut data } => out.append(&mut data),
2,038✔
136
                Fragment::Literal { mut data, .. } => out.append(&mut data),
10✔
137
            }
138
        }
139

140
        out
2,028✔
141
    }
2,028✔
142
}
143

144
impl Iterator for Encoded {
145
    type Item = Fragment;
146

147
    fn next(&mut self) -> Option<Self::Item> {
52✔
148
        self.items.pop_front()
52✔
149
    }
52✔
150
}
151

152
/// The intended action of a client or server.
153
#[derive(Clone, Debug, Eq, PartialEq)]
154
pub enum Fragment {
155
    /// A line that is ready to be send.
156
    Line { data: Vec<u8> },
157

158
    /// A literal that may require an action before it should be send.
159
    Literal { data: Vec<u8>, mode: LiteralMode },
160
}
161

162
//--------------------------------------------------------------------------------------------------
163

164
#[derive(Clone, Debug, Default, Eq, PartialEq)]
165
pub(crate) struct EncodeContext {
166
    accumulator: Vec<u8>,
167
    items: VecDeque<Fragment>,
168
}
169

170
impl EncodeContext {
171
    pub fn new() -> Self {
2,494✔
172
        Self::default()
2,494✔
173
    }
2,494✔
174

175
    pub fn push_line(&mut self) {
46✔
176
        self.items.push_back(Fragment::Line {
46✔
177
            data: std::mem::take(&mut self.accumulator),
46✔
178
        })
46✔
179
    }
46✔
180

181
    pub fn push_literal(&mut self, mode: LiteralMode) {
46✔
182
        self.items.push_back(Fragment::Literal {
46✔
183
            data: std::mem::take(&mut self.accumulator),
46✔
184
            mode,
46✔
185
        })
46✔
186
    }
46✔
187

188
    pub fn into_items(self) -> VecDeque<Fragment> {
2,494✔
189
        let Self {
2,494✔
190
            accumulator,
2,494✔
191
            mut items,
2,494✔
192
        } = self;
2,494✔
193

2,494✔
194
        if !accumulator.is_empty() {
2,494✔
195
            items.push_back(Fragment::Line { data: accumulator });
2,494✔
196
        }
2,494✔
197

198
        items
2,494✔
199
    }
2,494✔
200

201
    #[cfg(test)]
202
    pub(crate) fn dump(self) -> Vec<u8> {
448✔
203
        let mut out = Vec::new();
448✔
204

205
        for item in self.into_items() {
504✔
206
            match item {
504✔
207
                Fragment::Line { data } | Fragment::Literal { data, .. } => {
476✔
208
                    out.extend_from_slice(&data)
504✔
209
                }
210
            }
211
        }
212

213
        out
448✔
214
    }
448✔
215
}
216

217
impl Write for EncodeContext {
218
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
19,248✔
219
        self.accumulator.extend_from_slice(buf);
19,248✔
220
        Ok(buf.len())
19,248✔
221
    }
19,248✔
222

223
    fn flush(&mut self) -> std::io::Result<()> {
×
224
        Ok(())
×
225
    }
×
226
}
227

228
macro_rules! impl_encoder_for_codec {
229
    ($codec:ty, $message:ty) => {
230
        impl Encoder for $codec {
231
            type Message<'a> = $message;
232

233
            fn encode(&self, message: &Self::Message<'_>) -> Encoded {
1,540✔
234
                let mut encode_context = EncodeContext::new();
1,540✔
235
                EncodeIntoContext::encode_ctx(message.borrow(), &mut encode_context).unwrap();
1,540✔
236

1,540✔
237
                Encoded {
1,540✔
238
                    items: encode_context.into_items(),
1,540✔
239
                }
1,540✔
240
            }
1,540✔
241
        }
242
    };
243
}
244

245
impl_encoder_for_codec!(GreetingCodec, Greeting<'a>);
246
impl_encoder_for_codec!(CommandCodec, Command<'a>);
247
impl_encoder_for_codec!(AuthenticateDataCodec, AuthenticateData<'a>);
248
impl_encoder_for_codec!(ResponseCodec, Response<'a>);
249
impl_encoder_for_codec!(IdleDoneCodec, IdleDone);
250

251
// -------------------------------------------------------------------------------------------------
252

253
pub(crate) trait EncodeIntoContext {
254
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()>;
255
}
256

257
// ----- Primitive ---------------------------------------------------------------------------------
258

259
impl EncodeIntoContext for u32 {
260
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
44✔
261
        ctx.write_all(self.to_string().as_bytes())
44✔
262
    }
44✔
263
}
264

265
impl EncodeIntoContext for u64 {
266
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
4✔
267
        ctx.write_all(self.to_string().as_bytes())
4✔
268
    }
4✔
269
}
270

271
// ----- Command -----------------------------------------------------------------------------------
272

273
impl EncodeIntoContext for Command<'_> {
274
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
698✔
275
        self.tag.encode_ctx(ctx)?;
698✔
276
        ctx.write_all(b" ")?;
698✔
277
        self.body.encode_ctx(ctx)?;
698✔
278
        ctx.write_all(b"\r\n")
698✔
279
    }
698✔
280
}
281

282
impl EncodeIntoContext for Tag<'_> {
283
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
1,304✔
284
        ctx.write_all(self.inner().as_bytes())
1,304✔
285
    }
1,304✔
286
}
287

288
impl EncodeIntoContext for CommandBody<'_> {
289
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
698✔
290
        match self {
698✔
291
            CommandBody::Capability => ctx.write_all(b"CAPABILITY"),
48✔
292
            CommandBody::Noop => ctx.write_all(b"NOOP"),
22✔
293
            CommandBody::Logout => ctx.write_all(b"LOGOUT"),
16✔
294
            #[cfg(feature = "starttls")]
295
            CommandBody::StartTLS => ctx.write_all(b"STARTTLS"),
16✔
296
            CommandBody::Authenticate {
297
                mechanism,
10✔
298
                initial_response,
10✔
299
            } => {
10✔
300
                ctx.write_all(b"AUTHENTICATE")?;
10✔
301
                ctx.write_all(b" ")?;
10✔
302
                mechanism.encode_ctx(ctx)?;
10✔
303

304
                if let Some(ir) = initial_response {
10✔
305
                    ctx.write_all(b" ")?;
6✔
306

307
                    // RFC 4959 (https://datatracker.ietf.org/doc/html/rfc4959#section-3)
308
                    // "To send a zero-length initial response, the client MUST send a single pad character ("=").
309
                    // This indicates that the response is present, but is a zero-length string."
310
                    if ir.declassify().is_empty() {
6✔
311
                        ctx.write_all(b"=")?;
2✔
312
                    } else {
313
                        ctx.write_all(base64.encode(ir.declassify()).as_bytes())?;
4✔
314
                    };
315
                };
4✔
316

317
                Ok(())
10✔
318
            }
319
            CommandBody::Login { username, password } => {
56✔
320
                ctx.write_all(b"LOGIN")?;
56✔
321
                ctx.write_all(b" ")?;
56✔
322
                username.encode_ctx(ctx)?;
56✔
323
                ctx.write_all(b" ")?;
56✔
324
                password.declassify().encode_ctx(ctx)
56✔
325
            }
326
            CommandBody::Select { mailbox } => {
20✔
327
                ctx.write_all(b"SELECT")?;
20✔
328
                ctx.write_all(b" ")?;
20✔
329
                mailbox.encode_ctx(ctx)
20✔
330
            }
331
            CommandBody::Unselect => ctx.write_all(b"UNSELECT"),
2✔
332
            CommandBody::Examine { mailbox } => {
8✔
333
                ctx.write_all(b"EXAMINE")?;
8✔
334
                ctx.write_all(b" ")?;
8✔
335
                mailbox.encode_ctx(ctx)
8✔
336
            }
337
            CommandBody::Create { mailbox } => {
16✔
338
                ctx.write_all(b"CREATE")?;
16✔
339
                ctx.write_all(b" ")?;
16✔
340
                mailbox.encode_ctx(ctx)
16✔
341
            }
342
            CommandBody::Delete { mailbox } => {
48✔
343
                ctx.write_all(b"DELETE")?;
48✔
344
                ctx.write_all(b" ")?;
48✔
345
                mailbox.encode_ctx(ctx)
48✔
346
            }
347
            CommandBody::Rename {
348
                from: mailbox,
24✔
349
                to: new_mailbox,
24✔
350
            } => {
24✔
351
                ctx.write_all(b"RENAME")?;
24✔
352
                ctx.write_all(b" ")?;
24✔
353
                mailbox.encode_ctx(ctx)?;
24✔
354
                ctx.write_all(b" ")?;
24✔
355
                new_mailbox.encode_ctx(ctx)
24✔
356
            }
357
            CommandBody::Subscribe { mailbox } => {
8✔
358
                ctx.write_all(b"SUBSCRIBE")?;
8✔
359
                ctx.write_all(b" ")?;
8✔
360
                mailbox.encode_ctx(ctx)
8✔
361
            }
362
            CommandBody::Unsubscribe { mailbox } => {
8✔
363
                ctx.write_all(b"UNSUBSCRIBE")?;
8✔
364
                ctx.write_all(b" ")?;
8✔
365
                mailbox.encode_ctx(ctx)
8✔
366
            }
367
            CommandBody::List {
368
                reference,
104✔
369
                mailbox_wildcard,
104✔
370
            } => {
104✔
371
                ctx.write_all(b"LIST")?;
104✔
372
                ctx.write_all(b" ")?;
104✔
373
                reference.encode_ctx(ctx)?;
104✔
374
                ctx.write_all(b" ")?;
104✔
375
                mailbox_wildcard.encode_ctx(ctx)
104✔
376
            }
377
            CommandBody::Lsub {
378
                reference,
16✔
379
                mailbox_wildcard,
16✔
380
            } => {
16✔
381
                ctx.write_all(b"LSUB")?;
16✔
382
                ctx.write_all(b" ")?;
16✔
383
                reference.encode_ctx(ctx)?;
16✔
384
                ctx.write_all(b" ")?;
16✔
385
                mailbox_wildcard.encode_ctx(ctx)
16✔
386
            }
387
            CommandBody::Status {
388
                mailbox,
10✔
389
                item_names,
10✔
390
            } => {
10✔
391
                ctx.write_all(b"STATUS")?;
10✔
392
                ctx.write_all(b" ")?;
10✔
393
                mailbox.encode_ctx(ctx)?;
10✔
394
                ctx.write_all(b" ")?;
10✔
395
                ctx.write_all(b"(")?;
10✔
396
                join_serializable(item_names, b" ", ctx)?;
10✔
397
                ctx.write_all(b")")
10✔
398
            }
399
            CommandBody::Append {
400
                mailbox,
×
401
                flags,
×
402
                date,
×
403
                message,
×
404
            } => {
×
405
                ctx.write_all(b"APPEND")?;
×
406
                ctx.write_all(b" ")?;
×
407
                mailbox.encode_ctx(ctx)?;
×
408

409
                if !flags.is_empty() {
×
410
                    ctx.write_all(b" ")?;
×
411
                    ctx.write_all(b"(")?;
×
412
                    join_serializable(flags, b" ", ctx)?;
×
413
                    ctx.write_all(b")")?;
×
414
                }
×
415

416
                if let Some(date) = date {
×
417
                    ctx.write_all(b" ")?;
×
418
                    date.encode_ctx(ctx)?;
×
419
                }
×
420

421
                ctx.write_all(b" ")?;
×
422
                message.encode_ctx(ctx)
×
423
            }
424
            CommandBody::Check => ctx.write_all(b"CHECK"),
8✔
425
            CommandBody::Close => ctx.write_all(b"CLOSE"),
8✔
426
            CommandBody::Expunge => ctx.write_all(b"EXPUNGE"),
16✔
427
            CommandBody::ExpungeUid { sequence_set } => {
6✔
428
                ctx.write_all(b"UID EXPUNGE ")?;
6✔
429
                sequence_set.encode_ctx(ctx)
6✔
430
            }
431
            CommandBody::Search {
432
                charset,
16✔
433
                criteria,
16✔
434
                uid,
16✔
435
            } => {
16✔
436
                if *uid {
16✔
437
                    ctx.write_all(b"UID SEARCH")?;
×
438
                } else {
439
                    ctx.write_all(b"SEARCH")?;
16✔
440
                }
441
                if let Some(charset) = charset {
16✔
442
                    ctx.write_all(b" CHARSET ")?;
×
443
                    charset.encode_ctx(ctx)?;
×
444
                }
16✔
445
                ctx.write_all(b" ")?;
16✔
446
                join_serializable(criteria.as_ref(), b" ", ctx)
16✔
447
            }
448
            CommandBody::Sort {
449
                sort_criteria,
24✔
450
                charset,
24✔
451
                search_criteria,
24✔
452
                uid,
24✔
453
            } => {
24✔
454
                if *uid {
24✔
455
                    ctx.write_all(b"UID SORT (")?;
×
456
                } else {
457
                    ctx.write_all(b"SORT (")?;
24✔
458
                }
459
                join_serializable(sort_criteria.as_ref(), b" ", ctx)?;
24✔
460
                ctx.write_all(b") ")?;
24✔
461
                charset.encode_ctx(ctx)?;
24✔
462
                ctx.write_all(b" ")?;
24✔
463
                join_serializable(search_criteria.as_ref(), b" ", ctx)
24✔
464
            }
465
            CommandBody::Thread {
466
                algorithm,
24✔
467
                charset,
24✔
468
                search_criteria,
24✔
469
                uid,
24✔
470
            } => {
24✔
471
                if *uid {
24✔
472
                    ctx.write_all(b"UID THREAD ")?;
×
473
                } else {
474
                    ctx.write_all(b"THREAD ")?;
24✔
475
                }
476
                algorithm.encode_ctx(ctx)?;
24✔
477
                ctx.write_all(b" ")?;
24✔
478
                charset.encode_ctx(ctx)?;
24✔
479
                ctx.write_all(b" ")?;
24✔
480
                join_serializable(search_criteria.as_ref(), b" ", ctx)
24✔
481
            }
482
            CommandBody::Fetch {
483
                sequence_set,
32✔
484
                macro_or_item_names,
32✔
485
                uid,
32✔
486
            } => {
32✔
487
                if *uid {
32✔
488
                    ctx.write_all(b"UID FETCH ")?;
8✔
489
                } else {
490
                    ctx.write_all(b"FETCH ")?;
24✔
491
                }
492

493
                sequence_set.encode_ctx(ctx)?;
32✔
494
                ctx.write_all(b" ")?;
32✔
495
                macro_or_item_names.encode_ctx(ctx)
32✔
496
            }
497
            CommandBody::Store {
498
                sequence_set,
16✔
499
                kind,
16✔
500
                response,
16✔
501
                flags,
16✔
502
                uid,
16✔
503
            } => {
16✔
504
                if *uid {
16✔
505
                    ctx.write_all(b"UID STORE ")?;
×
506
                } else {
507
                    ctx.write_all(b"STORE ")?;
16✔
508
                }
509

510
                sequence_set.encode_ctx(ctx)?;
16✔
511
                ctx.write_all(b" ")?;
16✔
512

513
                match kind {
16✔
514
                    StoreType::Add => ctx.write_all(b"+")?,
16✔
515
                    StoreType::Remove => ctx.write_all(b"-")?,
×
516
                    StoreType::Replace => {}
×
517
                }
518

519
                ctx.write_all(b"FLAGS")?;
16✔
520

521
                match response {
16✔
522
                    StoreResponse::Answer => {}
16✔
523
                    StoreResponse::Silent => ctx.write_all(b".SILENT")?,
×
524
                }
525

526
                ctx.write_all(b" (")?;
16✔
527
                join_serializable(flags, b" ", ctx)?;
16✔
528
                ctx.write_all(b")")
16✔
529
            }
530
            CommandBody::Copy {
531
                sequence_set,
24✔
532
                mailbox,
24✔
533
                uid,
24✔
534
            } => {
24✔
535
                if *uid {
24✔
536
                    ctx.write_all(b"UID COPY ")?;
×
537
                } else {
538
                    ctx.write_all(b"COPY ")?;
24✔
539
                }
540
                sequence_set.encode_ctx(ctx)?;
24✔
541
                ctx.write_all(b" ")?;
24✔
542
                mailbox.encode_ctx(ctx)
24✔
543
            }
544
            CommandBody::Idle => ctx.write_all(b"IDLE"),
4✔
545
            CommandBody::Enable { capabilities } => {
22✔
546
                ctx.write_all(b"ENABLE ")?;
22✔
547
                join_serializable(capabilities.as_ref(), b" ", ctx)
22✔
548
            }
549
            CommandBody::Compress { algorithm } => {
4✔
550
                ctx.write_all(b"COMPRESS ")?;
4✔
551
                algorithm.encode_ctx(ctx)
4✔
552
            }
553
            CommandBody::GetQuota { root } => {
10✔
554
                ctx.write_all(b"GETQUOTA ")?;
10✔
555
                root.encode_ctx(ctx)
10✔
556
            }
557
            CommandBody::GetQuotaRoot { mailbox } => {
6✔
558
                ctx.write_all(b"GETQUOTAROOT ")?;
6✔
559
                mailbox.encode_ctx(ctx)
6✔
560
            }
561
            CommandBody::SetQuota { root, quotas } => {
12✔
562
                ctx.write_all(b"SETQUOTA ")?;
12✔
563
                root.encode_ctx(ctx)?;
12✔
564
                ctx.write_all(b" (")?;
12✔
565
                join_serializable(quotas.as_ref(), b" ", ctx)?;
12✔
566
                ctx.write_all(b")")
12✔
567
            }
568
            CommandBody::Move {
569
                sequence_set,
6✔
570
                mailbox,
6✔
571
                uid,
6✔
572
            } => {
6✔
573
                if *uid {
6✔
574
                    ctx.write_all(b"UID MOVE ")?;
2✔
575
                } else {
576
                    ctx.write_all(b"MOVE ")?;
4✔
577
                }
578
                sequence_set.encode_ctx(ctx)?;
6✔
579
                ctx.write_all(b" ")?;
6✔
580
                mailbox.encode_ctx(ctx)
6✔
581
            }
582
            #[cfg(feature = "ext_id")]
583
            CommandBody::Id { parameters } => {
8✔
584
                ctx.write_all(b"ID ")?;
8✔
585

586
                match parameters {
8✔
587
                    Some(parameters) => {
4✔
588
                        if let Some((first, tail)) = parameters.split_first() {
4✔
589
                            ctx.write_all(b"(")?;
4✔
590

591
                            first.0.encode_ctx(ctx)?;
4✔
592
                            ctx.write_all(b" ")?;
4✔
593
                            first.1.encode_ctx(ctx)?;
4✔
594

595
                            for parameter in tail {
4✔
596
                                ctx.write_all(b" ")?;
×
597
                                parameter.0.encode_ctx(ctx)?;
×
598
                                ctx.write_all(b" ")?;
×
599
                                parameter.1.encode_ctx(ctx)?;
×
600
                            }
601

602
                            ctx.write_all(b")")
4✔
603
                        } else {
604
                            #[cfg(not(feature = "quirk_id_empty_to_nil"))]
605
                            {
606
                                ctx.write_all(b"()")
607
                            }
608
                            #[cfg(feature = "quirk_id_empty_to_nil")]
609
                            {
610
                                ctx.write_all(b"NIL")
×
611
                            }
612
                        }
613
                    }
614
                    None => ctx.write_all(b"NIL"),
4✔
615
                }
616
            }
617
            #[cfg(feature = "ext_metadata")]
618
            CommandBody::SetMetadata {
619
                mailbox,
6✔
620
                entry_values,
6✔
621
            } => {
6✔
622
                ctx.write_all(b"SETMETADATA ")?;
6✔
623
                mailbox.encode_ctx(ctx)?;
6✔
624
                ctx.write_all(b" (")?;
6✔
625
                join_serializable(entry_values.as_ref(), b" ", ctx)?;
6✔
626
                ctx.write_all(b")")
6✔
627
            }
628
            #[cfg(feature = "ext_metadata")]
629
            CommandBody::GetMetadata {
630
                options,
14✔
631
                mailbox,
14✔
632
                entries,
14✔
633
            } => {
14✔
634
                ctx.write_all(b"GETMETADATA")?;
14✔
635

636
                if !options.is_empty() {
14✔
637
                    ctx.write_all(b" (")?;
10✔
638
                    join_serializable(options, b" ", ctx)?;
10✔
639
                    ctx.write_all(b")")?;
10✔
640
                }
4✔
641

642
                ctx.write_all(b" ")?;
14✔
643
                mailbox.encode_ctx(ctx)?;
14✔
644

645
                ctx.write_all(b" ")?;
14✔
646

647
                if entries.as_ref().len() == 1 {
14✔
648
                    entries.as_ref()[0].encode_ctx(ctx)
14✔
649
                } else {
650
                    ctx.write_all(b"(")?;
×
651
                    join_serializable(entries.as_ref(), b" ", ctx)?;
×
652
                    ctx.write_all(b")")
×
653
                }
654
            }
655
        }
656
    }
698✔
657
}
658

659
impl EncodeIntoContext for AuthMechanism<'_> {
660
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
22✔
661
        write!(ctx, "{}", self)
22✔
662
    }
22✔
663
}
664

665
impl EncodeIntoContext for AuthenticateData<'_> {
666
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
667
        match self {
8✔
668
            Self::Continue(data) => {
6✔
669
                let encoded = base64.encode(data.declassify());
6✔
670
                ctx.write_all(encoded.as_bytes())?;
6✔
671
                ctx.write_all(b"\r\n")
6✔
672
            }
673
            Self::Cancel => ctx.write_all(b"*\r\n"),
2✔
674
        }
675
    }
8✔
676
}
677

678
impl EncodeIntoContext for AString<'_> {
679
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
792✔
680
        match self {
792✔
681
            AString::Atom(atom) => atom.encode_ctx(ctx),
580✔
682
            AString::String(imap_str) => imap_str.encode_ctx(ctx),
212✔
683
        }
684
    }
792✔
685
}
686

687
impl EncodeIntoContext for Atom<'_> {
688
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
54✔
689
        ctx.write_all(self.inner().as_bytes())
54✔
690
    }
54✔
691
}
692

693
impl EncodeIntoContext for AtomExt<'_> {
694
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
580✔
695
        ctx.write_all(self.inner().as_bytes())
580✔
696
    }
580✔
697
}
698

699
impl EncodeIntoContext for IString<'_> {
700
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
516✔
701
        match self {
516✔
702
            Self::Literal(val) => val.encode_ctx(ctx),
44✔
703
            Self::Quoted(val) => val.encode_ctx(ctx),
472✔
704
        }
705
    }
516✔
706
}
707

708
impl EncodeIntoContext for Literal<'_> {
709
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
44✔
710
        match self.mode() {
44✔
711
            LiteralMode::Sync => write!(ctx, "{{{}}}\r\n", self.as_ref().len())?,
30✔
712
            LiteralMode::NonSync => write!(ctx, "{{{}+}}\r\n", self.as_ref().len())?,
14✔
713
        }
714

715
        ctx.push_line();
44✔
716
        ctx.write_all(self.as_ref())?;
44✔
717
        ctx.push_literal(self.mode());
44✔
718

44✔
719
        Ok(())
44✔
720
    }
44✔
721
}
722

723
impl EncodeIntoContext for Quoted<'_> {
724
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
480✔
725
        write!(ctx, "\"{}\"", escape_quoted(self.inner()))
480✔
726
    }
480✔
727
}
728

729
impl EncodeIntoContext for Mailbox<'_> {
730
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
616✔
731
        match self {
616✔
732
            Mailbox::Inbox => ctx.write_all(b"INBOX"),
80✔
733
            Mailbox::Other(other) => other.encode_ctx(ctx),
536✔
734
        }
735
    }
616✔
736
}
737

738
impl EncodeIntoContext for MailboxOther<'_> {
739
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
536✔
740
        self.inner().encode_ctx(ctx)
536✔
741
    }
536✔
742
}
743

744
impl EncodeIntoContext for ListMailbox<'_> {
745
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
120✔
746
        match self {
120✔
747
            ListMailbox::Token(lcs) => lcs.encode_ctx(ctx),
80✔
748
            ListMailbox::String(istr) => istr.encode_ctx(ctx),
40✔
749
        }
750
    }
120✔
751
}
752

753
impl EncodeIntoContext for ListCharString<'_> {
754
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
80✔
755
        ctx.write_all(self.as_ref())
80✔
756
    }
80✔
757
}
758

759
impl EncodeIntoContext for StatusDataItemName {
760
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
36✔
761
        match self {
36✔
762
            Self::Messages => ctx.write_all(b"MESSAGES"),
12✔
763
            Self::Recent => ctx.write_all(b"RECENT"),
2✔
764
            Self::UidNext => ctx.write_all(b"UIDNEXT"),
10✔
765
            Self::UidValidity => ctx.write_all(b"UIDVALIDITY"),
2✔
766
            Self::Unseen => ctx.write_all(b"UNSEEN"),
2✔
767
            Self::Deleted => ctx.write_all(b"DELETED"),
4✔
768
            Self::DeletedStorage => ctx.write_all(b"DELETED-STORAGE"),
4✔
769
            #[cfg(feature = "ext_condstore_qresync")]
770
            Self::HighestModSeq => ctx.write_all(b"HIGHESTMODSEQ"),
×
771
        }
772
    }
36✔
773
}
774

775
impl EncodeIntoContext for Flag<'_> {
776
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
312✔
777
        write!(ctx, "{}", self)
312✔
778
    }
312✔
779
}
780

781
impl EncodeIntoContext for FlagFetch<'_> {
782
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
120✔
783
        match self {
120✔
784
            Self::Flag(flag) => flag.encode_ctx(ctx),
120✔
785
            Self::Recent => ctx.write_all(b"\\Recent"),
×
786
        }
787
    }
120✔
788
}
789

790
impl EncodeIntoContext for FlagPerm<'_> {
791
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
24✔
792
        match self {
24✔
793
            Self::Flag(flag) => flag.encode_ctx(ctx),
16✔
794
            Self::Asterisk => ctx.write_all(b"\\*"),
8✔
795
        }
796
    }
24✔
797
}
798

799
impl EncodeIntoContext for DateTime {
800
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
14✔
801
        self.as_ref().encode_ctx(ctx)
14✔
802
    }
14✔
803
}
804

805
impl EncodeIntoContext for Charset<'_> {
806
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
58✔
807
        match self {
58✔
808
            Charset::Atom(atom) => atom.encode_ctx(ctx),
50✔
809
            Charset::Quoted(quoted) => quoted.encode_ctx(ctx),
8✔
810
        }
811
    }
58✔
812
}
813

814
impl EncodeIntoContext for SearchKey<'_> {
815
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
176✔
816
        match self {
176✔
817
            SearchKey::All => ctx.write_all(b"ALL"),
10✔
818
            SearchKey::Answered => ctx.write_all(b"ANSWERED"),
6✔
819
            SearchKey::Bcc(astring) => {
2✔
820
                ctx.write_all(b"BCC ")?;
2✔
821
                astring.encode_ctx(ctx)
2✔
822
            }
823
            SearchKey::Before(date) => {
2✔
824
                ctx.write_all(b"BEFORE ")?;
2✔
825
                date.encode_ctx(ctx)
2✔
826
            }
827
            SearchKey::Body(astring) => {
2✔
828
                ctx.write_all(b"BODY ")?;
2✔
829
                astring.encode_ctx(ctx)
2✔
830
            }
831
            SearchKey::Cc(astring) => {
2✔
832
                ctx.write_all(b"CC ")?;
2✔
833
                astring.encode_ctx(ctx)
2✔
834
            }
835
            SearchKey::Deleted => ctx.write_all(b"DELETED"),
2✔
836
            SearchKey::Flagged => ctx.write_all(b"FLAGGED"),
10✔
837
            SearchKey::From(astring) => {
10✔
838
                ctx.write_all(b"FROM ")?;
10✔
839
                astring.encode_ctx(ctx)
10✔
840
            }
841
            SearchKey::Keyword(flag_keyword) => {
2✔
842
                ctx.write_all(b"KEYWORD ")?;
2✔
843
                flag_keyword.encode_ctx(ctx)
2✔
844
            }
845
            SearchKey::New => ctx.write_all(b"NEW"),
6✔
846
            SearchKey::Old => ctx.write_all(b"OLD"),
2✔
847
            SearchKey::On(date) => {
2✔
848
                ctx.write_all(b"ON ")?;
2✔
849
                date.encode_ctx(ctx)
2✔
850
            }
851
            SearchKey::Recent => ctx.write_all(b"RECENT"),
4✔
852
            SearchKey::Seen => ctx.write_all(b"SEEN"),
4✔
853
            SearchKey::Since(date) => {
34✔
854
                ctx.write_all(b"SINCE ")?;
34✔
855
                date.encode_ctx(ctx)
34✔
856
            }
857
            SearchKey::Subject(astring) => {
2✔
858
                ctx.write_all(b"SUBJECT ")?;
2✔
859
                astring.encode_ctx(ctx)
2✔
860
            }
861
            SearchKey::Text(astring) => {
26✔
862
                ctx.write_all(b"TEXT ")?;
26✔
863
                astring.encode_ctx(ctx)
26✔
864
            }
865
            SearchKey::To(astring) => {
2✔
866
                ctx.write_all(b"TO ")?;
2✔
867
                astring.encode_ctx(ctx)
2✔
868
            }
869
            SearchKey::Unanswered => ctx.write_all(b"UNANSWERED"),
2✔
870
            SearchKey::Undeleted => ctx.write_all(b"UNDELETED"),
2✔
871
            SearchKey::Unflagged => ctx.write_all(b"UNFLAGGED"),
2✔
872
            SearchKey::Unkeyword(flag_keyword) => {
2✔
873
                ctx.write_all(b"UNKEYWORD ")?;
2✔
874
                flag_keyword.encode_ctx(ctx)
2✔
875
            }
876
            SearchKey::Unseen => ctx.write_all(b"UNSEEN"),
2✔
877
            SearchKey::Draft => ctx.write_all(b"DRAFT"),
2✔
878
            SearchKey::Header(header_fld_name, astring) => {
2✔
879
                ctx.write_all(b"HEADER ")?;
2✔
880
                header_fld_name.encode_ctx(ctx)?;
2✔
881
                ctx.write_all(b" ")?;
2✔
882
                astring.encode_ctx(ctx)
2✔
883
            }
884
            SearchKey::Larger(number) => write!(ctx, "LARGER {number}"),
2✔
885
            SearchKey::Not(search_key) => {
10✔
886
                ctx.write_all(b"NOT ")?;
10✔
887
                search_key.encode_ctx(ctx)
10✔
888
            }
889
            SearchKey::Or(search_key_a, search_key_b) => {
2✔
890
                ctx.write_all(b"OR ")?;
2✔
891
                search_key_a.encode_ctx(ctx)?;
2✔
892
                ctx.write_all(b" ")?;
2✔
893
                search_key_b.encode_ctx(ctx)
2✔
894
            }
895
            SearchKey::SentBefore(date) => {
2✔
896
                ctx.write_all(b"SENTBEFORE ")?;
2✔
897
                date.encode_ctx(ctx)
2✔
898
            }
899
            SearchKey::SentOn(date) => {
2✔
900
                ctx.write_all(b"SENTON ")?;
2✔
901
                date.encode_ctx(ctx)
2✔
902
            }
903
            SearchKey::SentSince(date) => {
2✔
904
                ctx.write_all(b"SENTSINCE ")?;
2✔
905
                date.encode_ctx(ctx)
2✔
906
            }
907
            SearchKey::Smaller(number) => write!(ctx, "SMALLER {number}"),
2✔
908
            SearchKey::Uid(sequence_set) => {
2✔
909
                ctx.write_all(b"UID ")?;
2✔
910
                sequence_set.encode_ctx(ctx)
2✔
911
            }
912
            SearchKey::Undraft => ctx.write_all(b"UNDRAFT"),
2✔
913
            SearchKey::SequenceSet(sequence_set) => sequence_set.encode_ctx(ctx),
2✔
914
            SearchKey::And(search_keys) => {
4✔
915
                ctx.write_all(b"(")?;
4✔
916
                join_serializable(search_keys.as_ref(), b" ", ctx)?;
4✔
917
                ctx.write_all(b")")
4✔
918
            }
919
        }
920
    }
176✔
921
}
922

923
impl EncodeIntoContext for SequenceSet {
924
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
88✔
925
        join_serializable(self.0.as_ref(), b",", ctx)
88✔
926
    }
88✔
927
}
928

929
impl EncodeIntoContext for Sequence {
930
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
94✔
931
        match self {
94✔
932
            Sequence::Single(seq_no) => seq_no.encode_ctx(ctx),
38✔
933
            Sequence::Range(from, to) => {
56✔
934
                from.encode_ctx(ctx)?;
56✔
935
                ctx.write_all(b":")?;
56✔
936
                to.encode_ctx(ctx)
56✔
937
            }
938
        }
939
    }
94✔
940
}
941

942
impl EncodeIntoContext for SeqOrUid {
943
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
150✔
944
        match self {
150✔
945
            SeqOrUid::Value(number) => write!(ctx, "{number}"),
140✔
946
            SeqOrUid::Asterisk => ctx.write_all(b"*"),
10✔
947
        }
948
    }
150✔
949
}
950

951
impl EncodeIntoContext for NaiveDate {
952
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
44✔
953
        write!(ctx, "\"{}\"", self.as_ref().format("%d-%b-%Y"))
44✔
954
    }
44✔
955
}
956

957
impl EncodeIntoContext for MacroOrMessageDataItemNames<'_> {
958
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
32✔
959
        match self {
32✔
960
            Self::Macro(m) => m.encode_ctx(ctx),
8✔
961
            Self::MessageDataItemNames(item_names) => {
24✔
962
                if item_names.len() == 1 {
24✔
963
                    item_names[0].encode_ctx(ctx)
16✔
964
                } else {
965
                    ctx.write_all(b"(")?;
8✔
966
                    join_serializable(item_names.as_slice(), b" ", ctx)?;
8✔
967
                    ctx.write_all(b")")
8✔
968
                }
969
            }
970
        }
971
    }
32✔
972
}
973

974
impl EncodeIntoContext for Macro {
975
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
976
        write!(ctx, "{}", self)
8✔
977
    }
8✔
978
}
979

980
impl EncodeIntoContext for MessageDataItemName<'_> {
981
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
54✔
982
        match self {
54✔
983
            Self::Body => ctx.write_all(b"BODY"),
2✔
984
            Self::BodyExt {
18✔
985
                section,
18✔
986
                partial,
18✔
987
                peek,
18✔
988
            } => {
18✔
989
                if *peek {
18✔
990
                    ctx.write_all(b"BODY.PEEK[")?;
×
991
                } else {
992
                    ctx.write_all(b"BODY[")?;
18✔
993
                }
994
                if let Some(section) = section {
18✔
995
                    section.encode_ctx(ctx)?;
16✔
996
                }
2✔
997
                ctx.write_all(b"]")?;
18✔
998
                if let Some((a, b)) = partial {
18✔
999
                    write!(ctx, "<{a}.{b}>")?;
×
1000
                }
18✔
1001

1002
                Ok(())
18✔
1003
            }
1004
            Self::BodyStructure => ctx.write_all(b"BODYSTRUCTURE"),
2✔
1005
            Self::Envelope => ctx.write_all(b"ENVELOPE"),
2✔
1006
            Self::Flags => ctx.write_all(b"FLAGS"),
18✔
1007
            Self::InternalDate => ctx.write_all(b"INTERNALDATE"),
2✔
1008
            Self::Rfc822 => ctx.write_all(b"RFC822"),
2✔
1009
            Self::Rfc822Header => ctx.write_all(b"RFC822.HEADER"),
2✔
1010
            Self::Rfc822Size => ctx.write_all(b"RFC822.SIZE"),
2✔
1011
            Self::Rfc822Text => ctx.write_all(b"RFC822.TEXT"),
2✔
1012
            Self::Uid => ctx.write_all(b"UID"),
2✔
1013
            MessageDataItemName::Binary {
1014
                section,
×
1015
                partial,
×
1016
                peek,
×
1017
            } => {
×
1018
                ctx.write_all(b"BINARY")?;
×
1019
                if *peek {
×
1020
                    ctx.write_all(b".PEEK")?;
×
1021
                }
×
1022

1023
                ctx.write_all(b"[")?;
×
1024
                join_serializable(section, b".", ctx)?;
×
1025
                ctx.write_all(b"]")?;
×
1026

1027
                if let Some((a, b)) = partial {
×
1028
                    ctx.write_all(b"<")?;
×
1029
                    a.encode_ctx(ctx)?;
×
1030
                    ctx.write_all(b".")?;
×
1031
                    b.encode_ctx(ctx)?;
×
1032
                    ctx.write_all(b">")?;
×
1033
                }
×
1034

1035
                Ok(())
×
1036
            }
1037
            MessageDataItemName::BinarySize { section } => {
×
1038
                ctx.write_all(b"BINARY.SIZE")?;
×
1039

1040
                ctx.write_all(b"[")?;
×
1041
                join_serializable(section, b".", ctx)?;
×
1042
                ctx.write_all(b"]")
×
1043
            }
1044
        }
1045
    }
54✔
1046
}
1047

1048
impl EncodeIntoContext for Section<'_> {
1049
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
44✔
1050
        match self {
44✔
1051
            Section::Part(part) => part.encode_ctx(ctx),
2✔
1052
            Section::Header(maybe_part) => match maybe_part {
20✔
1053
                Some(part) => {
2✔
1054
                    part.encode_ctx(ctx)?;
2✔
1055
                    ctx.write_all(b".HEADER")
2✔
1056
                }
1057
                None => ctx.write_all(b"HEADER"),
18✔
1058
            },
1059
            Section::HeaderFields(maybe_part, header_list) => {
12✔
1060
                match maybe_part {
12✔
1061
                    Some(part) => {
2✔
1062
                        part.encode_ctx(ctx)?;
2✔
1063
                        ctx.write_all(b".HEADER.FIELDS (")?;
2✔
1064
                    }
1065
                    None => ctx.write_all(b"HEADER.FIELDS (")?,
10✔
1066
                };
1067
                join_serializable(header_list.as_ref(), b" ", ctx)?;
12✔
1068
                ctx.write_all(b")")
12✔
1069
            }
1070
            Section::HeaderFieldsNot(maybe_part, header_list) => {
4✔
1071
                match maybe_part {
4✔
1072
                    Some(part) => {
2✔
1073
                        part.encode_ctx(ctx)?;
2✔
1074
                        ctx.write_all(b".HEADER.FIELDS.NOT (")?;
2✔
1075
                    }
1076
                    None => ctx.write_all(b"HEADER.FIELDS.NOT (")?,
2✔
1077
                };
1078
                join_serializable(header_list.as_ref(), b" ", ctx)?;
4✔
1079
                ctx.write_all(b")")
4✔
1080
            }
1081
            Section::Text(maybe_part) => match maybe_part {
4✔
1082
                Some(part) => {
2✔
1083
                    part.encode_ctx(ctx)?;
2✔
1084
                    ctx.write_all(b".TEXT")
2✔
1085
                }
1086
                None => ctx.write_all(b"TEXT"),
2✔
1087
            },
1088
            Section::Mime(part) => {
2✔
1089
                part.encode_ctx(ctx)?;
2✔
1090
                ctx.write_all(b".MIME")
2✔
1091
            }
1092
        }
1093
    }
44✔
1094
}
1095

1096
impl EncodeIntoContext for Part {
1097
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
12✔
1098
        join_serializable(self.0.as_ref(), b".", ctx)
12✔
1099
    }
12✔
1100
}
1101

1102
impl EncodeIntoContext for NonZeroU32 {
1103
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
246✔
1104
        write!(ctx, "{self}")
246✔
1105
    }
246✔
1106
}
1107

1108
#[cfg(feature = "ext_condstore_qresync")]
1109
impl EncodeIntoContext for NonZeroU64 {
NEW
1110
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
NEW
1111
        write!(ctx, "{self}")
×
NEW
1112
    }
×
1113
}
1114

1115
impl EncodeIntoContext for Capability<'_> {
1116
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
232✔
1117
        write!(ctx, "{}", self)
232✔
1118
    }
232✔
1119
}
1120

1121
// ----- Responses ---------------------------------------------------------------------------------
1122

1123
impl EncodeIntoContext for Response<'_> {
1124
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
1,548✔
1125
        match self {
1,548✔
1126
            Response::Status(status) => status.encode_ctx(ctx),
824✔
1127
            Response::Data(data) => data.encode_ctx(ctx),
716✔
1128
            Response::CommandContinuationRequest(continue_request) => {
8✔
1129
                continue_request.encode_ctx(ctx)
8✔
1130
            }
1131
        }
1132
    }
1,548✔
1133
}
1134

1135
impl EncodeIntoContext for Greeting<'_> {
1136
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
26✔
1137
        ctx.write_all(b"* ")?;
26✔
1138
        self.kind.encode_ctx(ctx)?;
26✔
1139
        ctx.write_all(b" ")?;
26✔
1140

1141
        if let Some(ref code) = self.code {
26✔
1142
            ctx.write_all(b"[")?;
12✔
1143
            code.encode_ctx(ctx)?;
12✔
1144
            ctx.write_all(b"] ")?;
12✔
1145
        }
14✔
1146

1147
        self.text.encode_ctx(ctx)?;
26✔
1148
        ctx.write_all(b"\r\n")
26✔
1149
    }
26✔
1150
}
1151

1152
impl EncodeIntoContext for GreetingKind {
1153
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
26✔
1154
        match self {
26✔
1155
            GreetingKind::Ok => ctx.write_all(b"OK"),
12✔
1156
            GreetingKind::PreAuth => ctx.write_all(b"PREAUTH"),
12✔
1157
            GreetingKind::Bye => ctx.write_all(b"BYE"),
2✔
1158
        }
1159
    }
26✔
1160
}
1161

1162
impl EncodeIntoContext for Status<'_> {
1163
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
824✔
1164
        fn format_status(
824✔
1165
            tag: Option<&Tag>,
824✔
1166
            status: &str,
824✔
1167
            code: &Option<Code>,
824✔
1168
            comment: &Text,
824✔
1169
            ctx: &mut EncodeContext,
824✔
1170
        ) -> std::io::Result<()> {
824✔
1171
            match tag {
824✔
1172
                Some(tag) => tag.encode_ctx(ctx)?,
606✔
1173
                None => ctx.write_all(b"*")?,
218✔
1174
            }
1175
            ctx.write_all(b" ")?;
824✔
1176
            ctx.write_all(status.as_bytes())?;
824✔
1177
            ctx.write_all(b" ")?;
824✔
1178
            if let Some(code) = code {
824✔
1179
                ctx.write_all(b"[")?;
148✔
1180
                code.encode_ctx(ctx)?;
148✔
1181
                ctx.write_all(b"] ")?;
148✔
1182
            }
676✔
1183
            comment.encode_ctx(ctx)?;
824✔
1184
            ctx.write_all(b"\r\n")
824✔
1185
        }
824✔
1186

1187
        match self {
824✔
1188
            Self::Untagged(StatusBody { kind, code, text }) => match kind {
192✔
1189
                StatusKind::Ok => format_status(None, "OK", code, text, ctx),
134✔
1190
                StatusKind::No => format_status(None, "NO", code, text, ctx),
30✔
1191
                StatusKind::Bad => format_status(None, "BAD", code, text, ctx),
28✔
1192
            },
1193
            Self::Tagged(Tagged {
606✔
1194
                tag,
606✔
1195
                body: StatusBody { kind, code, text },
606✔
1196
            }) => match kind {
606✔
1197
                StatusKind::Ok => format_status(Some(tag), "OK", code, text, ctx),
572✔
1198
                StatusKind::No => format_status(Some(tag), "NO", code, text, ctx),
22✔
1199
                StatusKind::Bad => format_status(Some(tag), "BAD", code, text, ctx),
12✔
1200
            },
1201
            Self::Bye(Bye { code, text }) => format_status(None, "BYE", code, text, ctx),
26✔
1202
        }
1203
    }
824✔
1204
}
1205

1206
impl EncodeIntoContext for Code<'_> {
1207
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
160✔
1208
        match self {
160✔
1209
            Code::Alert => ctx.write_all(b"ALERT"),
24✔
1210
            Code::BadCharset { allowed } => {
2✔
1211
                if allowed.is_empty() {
2✔
1212
                    ctx.write_all(b"BADCHARSET")
2✔
1213
                } else {
1214
                    ctx.write_all(b"BADCHARSET (")?;
×
1215
                    join_serializable(allowed, b" ", ctx)?;
×
1216
                    ctx.write_all(b")")
×
1217
                }
1218
            }
1219
            Code::Capability(caps) => {
4✔
1220
                ctx.write_all(b"CAPABILITY ")?;
4✔
1221
                join_serializable(caps.as_ref(), b" ", ctx)
4✔
1222
            }
1223
            Code::Parse => ctx.write_all(b"PARSE"),
×
1224
            Code::PermanentFlags(flags) => {
16✔
1225
                ctx.write_all(b"PERMANENTFLAGS (")?;
16✔
1226
                join_serializable(flags, b" ", ctx)?;
16✔
1227
                ctx.write_all(b")")
16✔
1228
            }
1229
            Code::ReadOnly => ctx.write_all(b"READ-ONLY"),
8✔
1230
            Code::ReadWrite => ctx.write_all(b"READ-WRITE"),
16✔
1231
            Code::TryCreate => ctx.write_all(b"TRYCREATE"),
×
1232
            Code::UidNext(next) => {
16✔
1233
                ctx.write_all(b"UIDNEXT ")?;
16✔
1234
                next.encode_ctx(ctx)
16✔
1235
            }
1236
            Code::UidValidity(validity) => {
24✔
1237
                ctx.write_all(b"UIDVALIDITY ")?;
24✔
1238
                validity.encode_ctx(ctx)
24✔
1239
            }
1240
            Code::Unseen(seq) => {
28✔
1241
                ctx.write_all(b"UNSEEN ")?;
28✔
1242
                seq.encode_ctx(ctx)
28✔
1243
            }
1244
            // RFC 2221
1245
            #[cfg(any(feature = "ext_login_referrals", feature = "ext_mailbox_referrals"))]
1246
            Code::Referral(url) => {
×
1247
                ctx.write_all(b"REFERRAL ")?;
×
1248
                ctx.write_all(url.as_bytes())
×
1249
            }
1250
            // RFC 4551
1251
            #[cfg(feature = "ext_condstore_qresync")]
NEW
1252
            Code::HighestModSeq(modseq) => {
×
NEW
1253
                ctx.write_all(b"HIGHESTMODSEQ ")?;
×
NEW
1254
                modseq.encode_ctx(ctx)
×
1255
            }
1256
            #[cfg(feature = "ext_condstore_qresync")]
NEW
1257
            Code::NoModSeq => ctx.write_all(b"NOMODSEQ"),
×
1258
            #[cfg(feature = "ext_condstore_qresync")]
NEW
1259
            Code::Modified(sequence_set) => {
×
NEW
1260
                ctx.write_all(b"MODIFIED ")?;
×
NEW
1261
                sequence_set.encode_ctx(ctx)
×
1262
            }
UNCOV
1263
            Code::CompressionActive => ctx.write_all(b"COMPRESSIONACTIVE"),
×
1264
            Code::OverQuota => ctx.write_all(b"OVERQUOTA"),
4✔
1265
            Code::TooBig => ctx.write_all(b"TOOBIG"),
×
1266
            #[cfg(feature = "ext_metadata")]
1267
            Code::Metadata(code) => {
12✔
1268
                ctx.write_all(b"METADATA ")?;
12✔
1269
                code.encode_ctx(ctx)
12✔
1270
            }
1271
            Code::UnknownCte => ctx.write_all(b"UNKNOWN-CTE"),
×
1272
            Code::AppendUid { uid_validity, uid } => {
2✔
1273
                ctx.write_all(b"APPENDUID ")?;
2✔
1274
                uid_validity.encode_ctx(ctx)?;
2✔
1275
                ctx.write_all(b" ")?;
2✔
1276
                uid.encode_ctx(ctx)
2✔
1277
            }
1278
            Code::CopyUid {
1279
                uid_validity,
2✔
1280
                source,
2✔
1281
                destination,
2✔
1282
            } => {
2✔
1283
                ctx.write_all(b"COPYUID ")?;
2✔
1284
                uid_validity.encode_ctx(ctx)?;
2✔
1285
                ctx.write_all(b" ")?;
2✔
1286
                source.encode_ctx(ctx)?;
2✔
1287
                ctx.write_all(b" ")?;
2✔
1288
                destination.encode_ctx(ctx)
2✔
1289
            }
1290
            Code::UidNotSticky => ctx.write_all(b"UIDNOTSTICKY"),
2✔
1291
            Code::Other(unknown) => unknown.encode_ctx(ctx),
×
1292
        }
1293
    }
160✔
1294
}
1295

1296
impl EncodeIntoContext for CodeOther<'_> {
1297
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
1298
        ctx.write_all(self.inner())
×
1299
    }
×
1300
}
1301

1302
impl EncodeIntoContext for Text<'_> {
1303
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
858✔
1304
        ctx.write_all(self.inner().as_bytes())
858✔
1305
    }
858✔
1306
}
1307

1308
impl EncodeIntoContext for Data<'_> {
1309
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
716✔
1310
        match self {
716✔
1311
            Data::Capability(caps) => {
64✔
1312
                ctx.write_all(b"* CAPABILITY ")?;
64✔
1313
                join_serializable(caps.as_ref(), b" ", ctx)?;
64✔
1314
            }
1315
            Data::List {
1316
                items,
210✔
1317
                delimiter,
210✔
1318
                mailbox,
210✔
1319
            } => {
210✔
1320
                ctx.write_all(b"* LIST (")?;
210✔
1321
                join_serializable(items, b" ", ctx)?;
210✔
1322
                ctx.write_all(b") ")?;
210✔
1323

1324
                if let Some(delimiter) = delimiter {
210✔
1325
                    ctx.write_all(b"\"")?;
210✔
1326
                    delimiter.encode_ctx(ctx)?;
210✔
1327
                    ctx.write_all(b"\"")?;
210✔
1328
                } else {
1329
                    ctx.write_all(b"NIL")?;
×
1330
                }
1331
                ctx.write_all(b" ")?;
210✔
1332
                mailbox.encode_ctx(ctx)?;
210✔
1333
            }
1334
            Data::Lsub {
1335
                items,
32✔
1336
                delimiter,
32✔
1337
                mailbox,
32✔
1338
            } => {
32✔
1339
                ctx.write_all(b"* LSUB (")?;
32✔
1340
                join_serializable(items, b" ", ctx)?;
32✔
1341
                ctx.write_all(b") ")?;
32✔
1342

1343
                if let Some(delimiter) = delimiter {
32✔
1344
                    ctx.write_all(b"\"")?;
32✔
1345
                    delimiter.encode_ctx(ctx)?;
32✔
1346
                    ctx.write_all(b"\"")?;
32✔
1347
                } else {
1348
                    ctx.write_all(b"NIL")?;
×
1349
                }
1350
                ctx.write_all(b" ")?;
32✔
1351
                mailbox.encode_ctx(ctx)?;
32✔
1352
            }
1353
            Data::Status { mailbox, items } => {
18✔
1354
                ctx.write_all(b"* STATUS ")?;
18✔
1355
                mailbox.encode_ctx(ctx)?;
18✔
1356
                ctx.write_all(b" (")?;
18✔
1357
                join_serializable(items, b" ", ctx)?;
18✔
1358
                ctx.write_all(b")")?;
18✔
1359
            }
1360
            Data::Search(seqs) => {
38✔
1361
                if seqs.is_empty() {
38✔
1362
                    ctx.write_all(b"* SEARCH")?;
8✔
1363
                } else {
1364
                    ctx.write_all(b"* SEARCH ")?;
30✔
1365
                    join_serializable(seqs, b" ", ctx)?;
30✔
1366
                }
1367
            }
1368
            Data::Sort(seqs) => {
24✔
1369
                if seqs.is_empty() {
24✔
1370
                    ctx.write_all(b"* SORT")?;
8✔
1371
                } else {
1372
                    ctx.write_all(b"* SORT ")?;
16✔
1373
                    join_serializable(seqs, b" ", ctx)?;
16✔
1374
                }
1375
            }
1376
            Data::Thread(threads) => {
24✔
1377
                if threads.is_empty() {
24✔
1378
                    ctx.write_all(b"* THREAD")?;
8✔
1379
                } else {
1380
                    ctx.write_all(b"* THREAD ")?;
16✔
1381
                    for thread in threads {
400✔
1382
                        thread.encode_ctx(ctx)?;
384✔
1383
                    }
1384
                }
1385
            }
1386
            Data::Flags(flags) => {
32✔
1387
                ctx.write_all(b"* FLAGS (")?;
32✔
1388
                join_serializable(flags, b" ", ctx)?;
32✔
1389
                ctx.write_all(b")")?;
32✔
1390
            }
1391
            Data::Exists(count) => write!(ctx, "* {count} EXISTS")?,
42✔
1392
            Data::Recent(count) => write!(ctx, "* {count} RECENT")?,
42✔
1393
            Data::Expunge(msg) => write!(ctx, "* {msg} EXPUNGE")?,
50✔
1394
            Data::Fetch { seq, items } => {
96✔
1395
                write!(ctx, "* {seq} FETCH (")?;
96✔
1396
                join_serializable(items.as_ref(), b" ", ctx)?;
96✔
1397
                ctx.write_all(b")")?;
96✔
1398
            }
1399
            Data::Enabled { capabilities } => {
16✔
1400
                write!(ctx, "* ENABLED")?;
16✔
1401

1402
                for cap in capabilities {
32✔
1403
                    ctx.write_all(b" ")?;
16✔
1404
                    cap.encode_ctx(ctx)?;
16✔
1405
                }
1406
            }
1407
            Data::Quota { root, quotas } => {
12✔
1408
                ctx.write_all(b"* QUOTA ")?;
12✔
1409
                root.encode_ctx(ctx)?;
12✔
1410
                ctx.write_all(b" (")?;
12✔
1411
                join_serializable(quotas.as_ref(), b" ", ctx)?;
12✔
1412
                ctx.write_all(b")")?;
12✔
1413
            }
1414
            Data::QuotaRoot { mailbox, roots } => {
10✔
1415
                ctx.write_all(b"* QUOTAROOT ")?;
10✔
1416
                mailbox.encode_ctx(ctx)?;
10✔
1417
                for root in roots {
20✔
1418
                    ctx.write_all(b" ")?;
10✔
1419
                    root.encode_ctx(ctx)?;
10✔
1420
                }
1421
            }
1422
            #[cfg(feature = "ext_id")]
1423
            Data::Id { parameters } => {
2✔
1424
                ctx.write_all(b"* ID ")?;
2✔
1425

1426
                match parameters {
2✔
1427
                    Some(parameters) => {
×
1428
                        if let Some((first, tail)) = parameters.split_first() {
×
1429
                            ctx.write_all(b"(")?;
×
1430

1431
                            first.0.encode_ctx(ctx)?;
×
1432
                            ctx.write_all(b" ")?;
×
1433
                            first.1.encode_ctx(ctx)?;
×
1434

1435
                            for parameter in tail {
×
1436
                                ctx.write_all(b" ")?;
×
1437
                                parameter.0.encode_ctx(ctx)?;
×
1438
                                ctx.write_all(b" ")?;
×
1439
                                parameter.1.encode_ctx(ctx)?;
×
1440
                            }
1441

1442
                            ctx.write_all(b")")?;
×
1443
                        } else {
1444
                            #[cfg(not(feature = "quirk_id_empty_to_nil"))]
1445
                            {
1446
                                ctx.write_all(b"()")?;
1447
                            }
1448
                            #[cfg(feature = "quirk_id_empty_to_nil")]
1449
                            {
1450
                                ctx.write_all(b"NIL")?;
×
1451
                            }
1452
                        }
1453
                    }
1454
                    None => {
1455
                        ctx.write_all(b"NIL")?;
2✔
1456
                    }
1457
                }
1458
            }
1459
            #[cfg(feature = "ext_metadata")]
1460
            Data::Metadata { mailbox, items } => {
4✔
1461
                ctx.write_all(b"* METADATA ")?;
4✔
1462
                mailbox.encode_ctx(ctx)?;
4✔
1463
                ctx.write_all(b" ")?;
4✔
1464
                items.encode_ctx(ctx)?;
4✔
1465
            }
1466
        }
1467

1468
        ctx.write_all(b"\r\n")
716✔
1469
    }
716✔
1470
}
1471

1472
impl EncodeIntoContext for FlagNameAttribute<'_> {
1473
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
90✔
1474
        write!(ctx, "{}", self)
90✔
1475
    }
90✔
1476
}
1477

1478
impl EncodeIntoContext for QuotedChar {
1479
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
242✔
1480
        match self.inner() {
242✔
1481
            '\\' => ctx.write_all(b"\\\\"),
×
1482
            '"' => ctx.write_all(b"\\\""),
×
1483
            other => ctx.write_all(&[other as u8]),
242✔
1484
        }
1485
    }
242✔
1486
}
1487

1488
impl EncodeIntoContext for StatusDataItem {
1489
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
52✔
1490
        match self {
52✔
1491
            Self::Messages(count) => {
20✔
1492
                ctx.write_all(b"MESSAGES ")?;
20✔
1493
                count.encode_ctx(ctx)
20✔
1494
            }
1495
            Self::Recent(count) => {
2✔
1496
                ctx.write_all(b"RECENT ")?;
2✔
1497
                count.encode_ctx(ctx)
2✔
1498
            }
1499
            Self::UidNext(next) => {
18✔
1500
                ctx.write_all(b"UIDNEXT ")?;
18✔
1501
                next.encode_ctx(ctx)
18✔
1502
            }
1503
            Self::UidValidity(identifier) => {
2✔
1504
                ctx.write_all(b"UIDVALIDITY ")?;
2✔
1505
                identifier.encode_ctx(ctx)
2✔
1506
            }
1507
            Self::Unseen(count) => {
2✔
1508
                ctx.write_all(b"UNSEEN ")?;
2✔
1509
                count.encode_ctx(ctx)
2✔
1510
            }
1511
            Self::Deleted(count) => {
4✔
1512
                ctx.write_all(b"DELETED ")?;
4✔
1513
                count.encode_ctx(ctx)
4✔
1514
            }
1515
            Self::DeletedStorage(count) => {
4✔
1516
                ctx.write_all(b"DELETED-STORAGE ")?;
4✔
1517
                count.encode_ctx(ctx)
4✔
1518
            }
1519
        }
1520
    }
52✔
1521
}
1522

1523
impl EncodeIntoContext for MessageDataItem<'_> {
1524
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
184✔
1525
        match self {
184✔
1526
            Self::BodyExt {
16✔
1527
                section,
16✔
1528
                origin,
16✔
1529
                data,
16✔
1530
            } => {
16✔
1531
                ctx.write_all(b"BODY[")?;
16✔
1532
                if let Some(section) = section {
16✔
1533
                    section.encode_ctx(ctx)?;
8✔
1534
                }
8✔
1535
                ctx.write_all(b"]")?;
16✔
1536
                if let Some(origin) = origin {
16✔
1537
                    write!(ctx, "<{origin}>")?;
2✔
1538
                }
14✔
1539
                ctx.write_all(b" ")?;
16✔
1540
                data.encode_ctx(ctx)
16✔
1541
            }
1542
            // FIXME: do not return body-ext-1part and body-ext-mpart here
1543
            Self::Body(body) => {
10✔
1544
                ctx.write_all(b"BODY ")?;
10✔
1545
                body.encode_ctx(ctx)
10✔
1546
            }
1547
            Self::BodyStructure(body) => {
4✔
1548
                ctx.write_all(b"BODYSTRUCTURE ")?;
4✔
1549
                body.encode_ctx(ctx)
4✔
1550
            }
1551
            Self::Envelope(envelope) => {
10✔
1552
                ctx.write_all(b"ENVELOPE ")?;
10✔
1553
                envelope.encode_ctx(ctx)
10✔
1554
            }
1555
            Self::Flags(flags) => {
82✔
1556
                ctx.write_all(b"FLAGS (")?;
82✔
1557
                join_serializable(flags, b" ", ctx)?;
82✔
1558
                ctx.write_all(b")")
82✔
1559
            }
1560
            Self::InternalDate(datetime) => {
10✔
1561
                ctx.write_all(b"INTERNALDATE ")?;
10✔
1562
                datetime.encode_ctx(ctx)
10✔
1563
            }
1564
            Self::Rfc822(nstring) => {
4✔
1565
                ctx.write_all(b"RFC822 ")?;
4✔
1566
                nstring.encode_ctx(ctx)
4✔
1567
            }
1568
            Self::Rfc822Header(nstring) => {
2✔
1569
                ctx.write_all(b"RFC822.HEADER ")?;
2✔
1570
                nstring.encode_ctx(ctx)
2✔
1571
            }
1572
            Self::Rfc822Size(size) => write!(ctx, "RFC822.SIZE {size}"),
18✔
1573
            Self::Rfc822Text(nstring) => {
2✔
1574
                ctx.write_all(b"RFC822.TEXT ")?;
2✔
1575
                nstring.encode_ctx(ctx)
2✔
1576
            }
1577
            Self::Uid(uid) => write!(ctx, "UID {uid}"),
26✔
1578
            Self::Binary { section, value } => {
×
1579
                ctx.write_all(b"BINARY[")?;
×
1580
                join_serializable(section, b".", ctx)?;
×
1581
                ctx.write_all(b"] ")?;
×
1582
                value.encode_ctx(ctx)
×
1583
            }
1584
            Self::BinarySize { section, size } => {
×
1585
                ctx.write_all(b"BINARY.SIZE[")?;
×
1586
                join_serializable(section, b".", ctx)?;
×
1587
                ctx.write_all(b"] ")?;
×
1588
                size.encode_ctx(ctx)
×
1589
            }
1590
        }
1591
    }
184✔
1592
}
1593

1594
impl EncodeIntoContext for NString<'_> {
1595
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
318✔
1596
        match &self.0 {
318✔
1597
            Some(imap_str) => imap_str.encode_ctx(ctx),
188✔
1598
            None => ctx.write_all(b"NIL"),
130✔
1599
        }
1600
    }
318✔
1601
}
1602

1603
impl EncodeIntoContext for NString8<'_> {
1604
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
1605
        match self {
8✔
1606
            NString8::NString(nstring) => nstring.encode_ctx(ctx),
6✔
1607
            NString8::Literal8(literal8) => literal8.encode_ctx(ctx),
2✔
1608
        }
1609
    }
8✔
1610
}
1611

1612
impl EncodeIntoContext for BodyStructure<'_> {
1613
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
32✔
1614
        ctx.write_all(b"(")?;
32✔
1615
        match self {
32✔
1616
            BodyStructure::Single {
1617
                body,
20✔
1618
                extension_data: extension,
20✔
1619
            } => {
20✔
1620
                body.encode_ctx(ctx)?;
20✔
1621
                if let Some(extension) = extension {
20✔
1622
                    ctx.write_all(b" ")?;
4✔
1623
                    extension.encode_ctx(ctx)?;
4✔
1624
                }
16✔
1625
            }
1626
            BodyStructure::Multi {
1627
                bodies,
12✔
1628
                subtype,
12✔
1629
                extension_data,
12✔
1630
            } => {
1631
                for body in bodies.as_ref() {
12✔
1632
                    body.encode_ctx(ctx)?;
12✔
1633
                }
1634
                ctx.write_all(b" ")?;
12✔
1635
                subtype.encode_ctx(ctx)?;
12✔
1636

1637
                if let Some(extension) = extension_data {
12✔
1638
                    ctx.write_all(b" ")?;
×
1639
                    extension.encode_ctx(ctx)?;
×
1640
                }
12✔
1641
            }
1642
        }
1643
        ctx.write_all(b")")
32✔
1644
    }
32✔
1645
}
1646

1647
impl EncodeIntoContext for Body<'_> {
1648
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
20✔
1649
        match self.specific {
20✔
1650
            SpecificFields::Basic {
1651
                r#type: ref type_,
4✔
1652
                ref subtype,
4✔
1653
            } => {
4✔
1654
                type_.encode_ctx(ctx)?;
4✔
1655
                ctx.write_all(b" ")?;
4✔
1656
                subtype.encode_ctx(ctx)?;
4✔
1657
                ctx.write_all(b" ")?;
4✔
1658
                self.basic.encode_ctx(ctx)
4✔
1659
            }
1660
            SpecificFields::Message {
1661
                ref envelope,
×
1662
                ref body_structure,
×
1663
                number_of_lines,
×
1664
            } => {
×
1665
                ctx.write_all(b"\"MESSAGE\" \"RFC822\" ")?;
×
1666
                self.basic.encode_ctx(ctx)?;
×
1667
                ctx.write_all(b" ")?;
×
1668
                envelope.encode_ctx(ctx)?;
×
1669
                ctx.write_all(b" ")?;
×
1670
                body_structure.encode_ctx(ctx)?;
×
1671
                ctx.write_all(b" ")?;
×
1672
                write!(ctx, "{number_of_lines}")
×
1673
            }
1674
            SpecificFields::Text {
1675
                ref subtype,
16✔
1676
                number_of_lines,
16✔
1677
            } => {
16✔
1678
                ctx.write_all(b"\"TEXT\" ")?;
16✔
1679
                subtype.encode_ctx(ctx)?;
16✔
1680
                ctx.write_all(b" ")?;
16✔
1681
                self.basic.encode_ctx(ctx)?;
16✔
1682
                ctx.write_all(b" ")?;
16✔
1683
                write!(ctx, "{number_of_lines}")
16✔
1684
            }
1685
        }
1686
    }
20✔
1687
}
1688

1689
impl EncodeIntoContext for BasicFields<'_> {
1690
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
20✔
1691
        List1AttributeValueOrNil(&self.parameter_list).encode_ctx(ctx)?;
20✔
1692
        ctx.write_all(b" ")?;
20✔
1693
        self.id.encode_ctx(ctx)?;
20✔
1694
        ctx.write_all(b" ")?;
20✔
1695
        self.description.encode_ctx(ctx)?;
20✔
1696
        ctx.write_all(b" ")?;
20✔
1697
        self.content_transfer_encoding.encode_ctx(ctx)?;
20✔
1698
        ctx.write_all(b" ")?;
20✔
1699
        write!(ctx, "{}", self.size)
20✔
1700
    }
20✔
1701
}
1702

1703
impl EncodeIntoContext for Envelope<'_> {
1704
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
10✔
1705
        ctx.write_all(b"(")?;
10✔
1706
        self.date.encode_ctx(ctx)?;
10✔
1707
        ctx.write_all(b" ")?;
10✔
1708
        self.subject.encode_ctx(ctx)?;
10✔
1709
        ctx.write_all(b" ")?;
10✔
1710
        List1OrNil(&self.from, b"").encode_ctx(ctx)?;
10✔
1711
        ctx.write_all(b" ")?;
10✔
1712
        List1OrNil(&self.sender, b"").encode_ctx(ctx)?;
10✔
1713
        ctx.write_all(b" ")?;
10✔
1714
        List1OrNil(&self.reply_to, b"").encode_ctx(ctx)?;
10✔
1715
        ctx.write_all(b" ")?;
10✔
1716
        List1OrNil(&self.to, b"").encode_ctx(ctx)?;
10✔
1717
        ctx.write_all(b" ")?;
10✔
1718
        List1OrNil(&self.cc, b"").encode_ctx(ctx)?;
10✔
1719
        ctx.write_all(b" ")?;
10✔
1720
        List1OrNil(&self.bcc, b"").encode_ctx(ctx)?;
10✔
1721
        ctx.write_all(b" ")?;
10✔
1722
        self.in_reply_to.encode_ctx(ctx)?;
10✔
1723
        ctx.write_all(b" ")?;
10✔
1724
        self.message_id.encode_ctx(ctx)?;
10✔
1725
        ctx.write_all(b")")
10✔
1726
    }
10✔
1727
}
1728

1729
impl EncodeIntoContext for Address<'_> {
1730
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
48✔
1731
        ctx.write_all(b"(")?;
48✔
1732
        self.name.encode_ctx(ctx)?;
48✔
1733
        ctx.write_all(b" ")?;
48✔
1734
        self.adl.encode_ctx(ctx)?;
48✔
1735
        ctx.write_all(b" ")?;
48✔
1736
        self.mailbox.encode_ctx(ctx)?;
48✔
1737
        ctx.write_all(b" ")?;
48✔
1738
        self.host.encode_ctx(ctx)?;
48✔
1739
        ctx.write_all(b")")?;
48✔
1740

1741
        Ok(())
48✔
1742
    }
48✔
1743
}
1744

1745
impl EncodeIntoContext for SinglePartExtensionData<'_> {
1746
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1747
        self.md5.encode_ctx(ctx)?;
6✔
1748

1749
        if let Some(disposition) = &self.tail {
6✔
1750
            ctx.write_all(b" ")?;
6✔
1751
            disposition.encode_ctx(ctx)?;
6✔
1752
        }
×
1753

1754
        Ok(())
6✔
1755
    }
6✔
1756
}
1757

1758
impl EncodeIntoContext for MultiPartExtensionData<'_> {
1759
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
1760
        List1AttributeValueOrNil(&self.parameter_list).encode_ctx(ctx)?;
×
1761

1762
        if let Some(disposition) = &self.tail {
×
1763
            ctx.write_all(b" ")?;
×
1764
            disposition.encode_ctx(ctx)?;
×
1765
        }
×
1766

1767
        Ok(())
×
1768
    }
×
1769
}
1770

1771
impl EncodeIntoContext for Disposition<'_> {
1772
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1773
        match &self.disposition {
6✔
1774
            Some((s, param)) => {
×
1775
                ctx.write_all(b"(")?;
×
1776
                s.encode_ctx(ctx)?;
×
1777
                ctx.write_all(b" ")?;
×
1778
                List1AttributeValueOrNil(param).encode_ctx(ctx)?;
×
1779
                ctx.write_all(b")")?;
×
1780
            }
1781
            None => ctx.write_all(b"NIL")?,
6✔
1782
        }
1783

1784
        if let Some(language) = &self.tail {
6✔
1785
            ctx.write_all(b" ")?;
6✔
1786
            language.encode_ctx(ctx)?;
6✔
1787
        }
×
1788

1789
        Ok(())
6✔
1790
    }
6✔
1791
}
1792

1793
impl EncodeIntoContext for Language<'_> {
1794
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1795
        List1OrNil(&self.language, b" ").encode_ctx(ctx)?;
6✔
1796

1797
        if let Some(location) = &self.tail {
6✔
1798
            ctx.write_all(b" ")?;
6✔
1799
            location.encode_ctx(ctx)?;
6✔
1800
        }
×
1801

1802
        Ok(())
6✔
1803
    }
6✔
1804
}
1805

1806
impl EncodeIntoContext for Location<'_> {
1807
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1808
        self.location.encode_ctx(ctx)?;
6✔
1809

1810
        for body_extension in &self.extensions {
10✔
1811
            ctx.write_all(b" ")?;
4✔
1812
            body_extension.encode_ctx(ctx)?;
4✔
1813
        }
1814

1815
        Ok(())
6✔
1816
    }
6✔
1817
}
1818

1819
impl EncodeIntoContext for BodyExtension<'_> {
1820
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1821
        match self {
6✔
1822
            BodyExtension::NString(nstring) => nstring.encode_ctx(ctx),
×
1823
            BodyExtension::Number(number) => number.encode_ctx(ctx),
4✔
1824
            BodyExtension::List(list) => {
2✔
1825
                ctx.write_all(b"(")?;
2✔
1826
                join_serializable(list.as_ref(), b" ", ctx)?;
2✔
1827
                ctx.write_all(b")")
2✔
1828
            }
1829
        }
1830
    }
6✔
1831
}
1832

1833
impl EncodeIntoContext for ChronoDateTime<FixedOffset> {
1834
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
14✔
1835
        write!(ctx, "\"{}\"", self.format("%d-%b-%Y %H:%M:%S %z"))
14✔
1836
    }
14✔
1837
}
1838

1839
impl EncodeIntoContext for CommandContinuationRequest<'_> {
1840
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
1841
        match self {
8✔
1842
            Self::Basic(continue_basic) => match continue_basic.code() {
8✔
1843
                Some(code) => {
×
1844
                    ctx.write_all(b"+ [")?;
×
1845
                    code.encode_ctx(ctx)?;
×
1846
                    ctx.write_all(b"] ")?;
×
1847
                    continue_basic.text().encode_ctx(ctx)?;
×
1848
                    ctx.write_all(b"\r\n")
×
1849
                }
1850
                None => {
1851
                    ctx.write_all(b"+ ")?;
8✔
1852
                    continue_basic.text().encode_ctx(ctx)?;
8✔
1853
                    ctx.write_all(b"\r\n")
8✔
1854
                }
1855
            },
1856
            Self::Base64(data) => {
×
1857
                ctx.write_all(b"+ ")?;
×
1858
                ctx.write_all(base64.encode(data).as_bytes())?;
×
1859
                ctx.write_all(b"\r\n")
×
1860
            }
1861
        }
1862
    }
8✔
1863
}
1864

1865
pub(crate) mod utils {
1866
    use std::io::Write;
1867

1868
    use super::{EncodeContext, EncodeIntoContext};
1869

1870
    pub struct List1OrNil<'a, T>(pub &'a Vec<T>, pub &'a [u8]);
1871

1872
    pub struct List1AttributeValueOrNil<'a, T>(pub &'a Vec<(T, T)>);
1873

1874
    pub(crate) fn join_serializable<I: EncodeIntoContext>(
914✔
1875
        elements: &[I],
914✔
1876
        sep: &[u8],
914✔
1877
        ctx: &mut EncodeContext,
914✔
1878
    ) -> std::io::Result<()> {
914✔
1879
        if let Some((last, head)) = elements.split_last() {
914✔
1880
            for item in head {
1,342✔
1881
                item.encode_ctx(ctx)?;
592✔
1882
                ctx.write_all(sep)?;
592✔
1883
            }
1884

1885
            last.encode_ctx(ctx)
750✔
1886
        } else {
1887
            Ok(())
164✔
1888
        }
1889
    }
914✔
1890

1891
    impl<T> EncodeIntoContext for List1OrNil<'_, T>
1892
    where
1893
        T: EncodeIntoContext,
1894
    {
1895
        fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
66✔
1896
            if let Some((last, head)) = self.0.split_last() {
66✔
1897
                ctx.write_all(b"(")?;
40✔
1898

1899
                for item in head {
48✔
1900
                    item.encode_ctx(ctx)?;
8✔
1901
                    ctx.write_all(self.1)?;
8✔
1902
                }
1903

1904
                last.encode_ctx(ctx)?;
40✔
1905

1906
                ctx.write_all(b")")
40✔
1907
            } else {
1908
                ctx.write_all(b"NIL")
26✔
1909
            }
1910
        }
66✔
1911
    }
1912

1913
    impl<T> EncodeIntoContext for List1AttributeValueOrNil<'_, T>
1914
    where
1915
        T: EncodeIntoContext,
1916
    {
1917
        fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
20✔
1918
            if let Some((last, head)) = self.0.split_last() {
20✔
1919
                ctx.write_all(b"(")?;
8✔
1920

1921
                for (attribute, value) in head {
8✔
1922
                    attribute.encode_ctx(ctx)?;
×
1923
                    ctx.write_all(b" ")?;
×
1924
                    value.encode_ctx(ctx)?;
×
1925
                    ctx.write_all(b" ")?;
×
1926
                }
1927

1928
                let (attribute, value) = last;
8✔
1929
                attribute.encode_ctx(ctx)?;
8✔
1930
                ctx.write_all(b" ")?;
8✔
1931
                value.encode_ctx(ctx)?;
8✔
1932

1933
                ctx.write_all(b")")
8✔
1934
            } else {
1935
                ctx.write_all(b"NIL")
12✔
1936
            }
1937
        }
20✔
1938
    }
1939
}
1940

1941
#[cfg(test)]
1942
mod tests {
1943
    use std::num::NonZeroU32;
1944

1945
    use imap_types::{
1946
        auth::AuthMechanism,
1947
        command::{Command, CommandBody},
1948
        core::{AString, Literal, NString, Vec1},
1949
        fetch::MessageDataItem,
1950
        response::{Data, Response},
1951
        utils::escape_byte_string,
1952
    };
1953

1954
    use super::*;
1955

1956
    #[test]
1957
    fn test_api_encoder_usage() {
2✔
1958
        let cmd = Command::new(
2✔
1959
            "A",
2✔
1960
            CommandBody::login(
2✔
1961
                AString::from(Literal::unvalidated_non_sync(b"alice".as_ref())),
2✔
1962
                "password",
2✔
1963
            )
2✔
1964
            .unwrap(),
2✔
1965
        )
2✔
1966
        .unwrap();
2✔
1967

2✔
1968
        // Dump.
2✔
1969
        let got_encoded = CommandCodec::default().encode(&cmd).dump();
2✔
1970

2✔
1971
        // Encoded.
2✔
1972
        let encoded = CommandCodec::default().encode(&cmd);
2✔
1973

2✔
1974
        let mut out = Vec::new();
2✔
1975

1976
        for x in encoded {
8✔
1977
            match x {
6✔
1978
                Fragment::Line { data } => {
4✔
1979
                    println!("C: {}", escape_byte_string(&data));
4✔
1980
                    out.extend_from_slice(&data);
4✔
1981
                }
4✔
1982
                Fragment::Literal { data, mode } => {
2✔
1983
                    match mode {
2✔
1984
                        LiteralMode::Sync => println!("C: <Waiting for continuation request>"),
×
1985
                        LiteralMode::NonSync => println!("C: <Skipped continuation request>"),
2✔
1986
                    }
1987

1988
                    println!("C: {}", escape_byte_string(&data));
2✔
1989
                    out.extend_from_slice(&data);
2✔
1990
                }
1991
            }
1992
        }
1993

1994
        assert_eq!(got_encoded, out);
2✔
1995
    }
2✔
1996

1997
    #[test]
1998
    fn test_encode_command() {
2✔
1999
        kat_encoder::<CommandCodec, Command<'_>, &[Fragment]>(&[
2✔
2000
            (
2✔
2001
                Command::new("A", CommandBody::login("alice", "pass").unwrap()).unwrap(),
2✔
2002
                [Fragment::Line {
2✔
2003
                    data: b"A LOGIN alice pass\r\n".to_vec(),
2✔
2004
                }]
2✔
2005
                .as_ref(),
2✔
2006
            ),
2✔
2007
            (
2✔
2008
                Command::new(
2✔
2009
                    "A",
2✔
2010
                    CommandBody::login("alice", b"\xCA\xFE".as_ref()).unwrap(),
2✔
2011
                )
2✔
2012
                .unwrap(),
2✔
2013
                [
2✔
2014
                    Fragment::Line {
2✔
2015
                        data: b"A LOGIN alice {2}\r\n".to_vec(),
2✔
2016
                    },
2✔
2017
                    Fragment::Literal {
2✔
2018
                        data: b"\xCA\xFE".to_vec(),
2✔
2019
                        mode: LiteralMode::Sync,
2✔
2020
                    },
2✔
2021
                    Fragment::Line {
2✔
2022
                        data: b"\r\n".to_vec(),
2✔
2023
                    },
2✔
2024
                ]
2✔
2025
                .as_ref(),
2✔
2026
            ),
2✔
2027
            (
2✔
2028
                Command::new("A", CommandBody::authenticate(AuthMechanism::Login)).unwrap(),
2✔
2029
                [Fragment::Line {
2✔
2030
                    data: b"A AUTHENTICATE LOGIN\r\n".to_vec(),
2✔
2031
                }]
2✔
2032
                .as_ref(),
2✔
2033
            ),
2✔
2034
            (
2✔
2035
                Command::new(
2✔
2036
                    "A",
2✔
2037
                    CommandBody::authenticate_with_ir(AuthMechanism::Login, b"alice".as_ref()),
2✔
2038
                )
2✔
2039
                .unwrap(),
2✔
2040
                [Fragment::Line {
2✔
2041
                    data: b"A AUTHENTICATE LOGIN YWxpY2U=\r\n".to_vec(),
2✔
2042
                }]
2✔
2043
                .as_ref(),
2✔
2044
            ),
2✔
2045
            (
2✔
2046
                Command::new("A", CommandBody::authenticate(AuthMechanism::Plain)).unwrap(),
2✔
2047
                [Fragment::Line {
2✔
2048
                    data: b"A AUTHENTICATE PLAIN\r\n".to_vec(),
2✔
2049
                }]
2✔
2050
                .as_ref(),
2✔
2051
            ),
2✔
2052
            (
2✔
2053
                Command::new(
2✔
2054
                    "A",
2✔
2055
                    CommandBody::authenticate_with_ir(
2✔
2056
                        AuthMechanism::Plain,
2✔
2057
                        b"\x00alice\x00pass".as_ref(),
2✔
2058
                    ),
2✔
2059
                )
2✔
2060
                .unwrap(),
2✔
2061
                [Fragment::Line {
2✔
2062
                    data: b"A AUTHENTICATE PLAIN AGFsaWNlAHBhc3M=\r\n".to_vec(),
2✔
2063
                }]
2✔
2064
                .as_ref(),
2✔
2065
            ),
2✔
2066
        ]);
2✔
2067
    }
2✔
2068

2069
    #[test]
2070
    fn test_encode_response() {
2✔
2071
        kat_encoder::<ResponseCodec, Response<'_>, &[Fragment]>(&[
2✔
2072
            (
2✔
2073
                Response::Data(Data::Fetch {
2✔
2074
                    seq: NonZeroU32::new(12345).unwrap(),
2✔
2075
                    items: Vec1::from(MessageDataItem::BodyExt {
2✔
2076
                        section: None,
2✔
2077
                        origin: None,
2✔
2078
                        data: NString::from(Literal::unvalidated(b"ABCDE".as_ref())),
2✔
2079
                    }),
2✔
2080
                }),
2✔
2081
                [
2✔
2082
                    Fragment::Line {
2✔
2083
                        data: b"* 12345 FETCH (BODY[] {5}\r\n".to_vec(),
2✔
2084
                    },
2✔
2085
                    Fragment::Literal {
2✔
2086
                        data: b"ABCDE".to_vec(),
2✔
2087
                        mode: LiteralMode::Sync,
2✔
2088
                    },
2✔
2089
                    Fragment::Line {
2✔
2090
                        data: b")\r\n".to_vec(),
2✔
2091
                    },
2✔
2092
                ]
2✔
2093
                .as_ref(),
2✔
2094
            ),
2✔
2095
            (
2✔
2096
                Response::Data(Data::Fetch {
2✔
2097
                    seq: NonZeroU32::new(12345).unwrap(),
2✔
2098
                    items: Vec1::from(MessageDataItem::BodyExt {
2✔
2099
                        section: None,
2✔
2100
                        origin: None,
2✔
2101
                        data: NString::from(Literal::unvalidated_non_sync(b"ABCDE".as_ref())),
2✔
2102
                    }),
2✔
2103
                }),
2✔
2104
                [
2✔
2105
                    Fragment::Line {
2✔
2106
                        data: b"* 12345 FETCH (BODY[] {5+}\r\n".to_vec(),
2✔
2107
                    },
2✔
2108
                    Fragment::Literal {
2✔
2109
                        data: b"ABCDE".to_vec(),
2✔
2110
                        mode: LiteralMode::NonSync,
2✔
2111
                    },
2✔
2112
                    Fragment::Line {
2✔
2113
                        data: b")\r\n".to_vec(),
2✔
2114
                    },
2✔
2115
                ]
2✔
2116
                .as_ref(),
2✔
2117
            ),
2✔
2118
        ])
2✔
2119
    }
2✔
2120

2121
    fn kat_encoder<'a, E, M, F>(tests: &'a [(M, F)])
4✔
2122
    where
4✔
2123
        E: Encoder<Message<'a> = M> + Default,
4✔
2124
        F: AsRef<[Fragment]>,
4✔
2125
    {
4✔
2126
        for (i, (obj, actions)) in tests.iter().enumerate() {
16✔
2127
            println!("# Testing {i}");
16✔
2128

16✔
2129
            let encoder = E::default().encode(obj);
16✔
2130
            let actions = actions.as_ref();
16✔
2131

16✔
2132
            assert_eq!(encoder.collect::<Vec<_>>(), actions);
16✔
2133
        }
2134
    }
4✔
2135
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc