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

duesee / imap-codec / 18434670509

11 Oct 2025 09:00PM UTC coverage: 91.801% (+0.03%) from 91.768%
18434670509

Pull #675

github

web-flow
Merge 0edbab740 into 450fdf51c
Pull Request #675: feat: Implement `UTF8={ACCEPT,ONLY}`

35 of 56 new or added lines in 10 files covered. (62.5%)

2 existing lines in 1 file now uncovered.

10312 of 11233 relevant lines covered (91.8%)

941.31 hits per line

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

83.05
/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
//!     CommandCodec,
11
//!     encode::{Encoder, Fragment},
12
//!     imap_types::{
13
//!         command::{Command, CommandBody},
14
//!         core::LiteralMode,
15
//!     },
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, engine::general_purpose::STANDARD as base64};
53
use chrono::{DateTime as ChronoDateTime, FixedOffset};
54
#[cfg(feature = "ext_condstore_qresync")]
55
use imap_types::command::{FetchModifier, SelectParameter, StoreModifier};
56
use imap_types::{
57
    auth::{AuthMechanism, AuthenticateData},
58
    body::{
59
        BasicFields, Body, BodyExtension, BodyStructure, Disposition, Language, Location,
60
        MultiPartExtensionData, SinglePartExtensionData, SpecificFields,
61
    },
62
    command::{Command, CommandBody},
63
    core::{
64
        AString, Atom, AtomExt, Charset, IString, Literal, LiteralMode, NString, NString8, Quoted,
65
        QuotedChar, Tag, Text,
66
    },
67
    datetime::{DateTime, NaiveDate},
68
    envelope::{Address, Envelope},
69
    extensions::idle::IdleDone,
70
    fetch::{
71
        Macro, MacroOrMessageDataItemNames, MessageDataItem, MessageDataItemName, Part, Section,
72
    },
73
    flag::{Flag, FlagFetch, FlagNameAttribute, FlagPerm, StoreResponse, StoreType},
74
    mailbox::{ListCharString, ListMailbox, Mailbox, MailboxOther},
75
    response::{
76
        Bye, Capability, Code, CodeOther, CommandContinuationRequest, Data, Greeting, GreetingKind,
77
        Response, Status, StatusBody, StatusKind, Tagged,
78
    },
79
    search::SearchKey,
80
    sequence::{SeqOrUid, Sequence, SequenceSet},
81
    status::{StatusDataItem, StatusDataItemName},
82
    utils::escape_quoted,
83
};
84
use utils::{List1AttributeValueOrNil, List1OrNil, join_serializable};
85

86
use crate::{AuthenticateDataCodec, CommandCodec, GreetingCodec, IdleDoneCodec, ResponseCodec};
87

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

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

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

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

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

142
        out
2,028✔
143
    }
2,028✔
144
}
145

146
impl Iterator for Encoded {
147
    type Item = Fragment;
148

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

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

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

164
//--------------------------------------------------------------------------------------------------
165

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

172
impl EncodeContext {
173
    pub fn new() -> Self {
2,496✔
174
        Self::default()
2,496✔
175
    }
2,496✔
176

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

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

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

196
        if !accumulator.is_empty() {
2,496✔
197
            items.push_back(Fragment::Line { data: accumulator });
2,496✔
198
        }
2,496✔
199

200
        items
2,496✔
201
    }
2,496✔
202

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

207
        for item in self.into_items() {
506✔
208
            match item {
506✔
209
                Fragment::Line { data } | Fragment::Literal { data, .. } => {
478✔
210
                    out.extend_from_slice(&data)
506✔
211
                }
212
            }
213
        }
214

215
        out
450✔
216
    }
450✔
217
}
218

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

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

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

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

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

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

253
// -------------------------------------------------------------------------------------------------
254

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

259
// ----- Primitive ---------------------------------------------------------------------------------
260

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

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

273
// ----- Command -----------------------------------------------------------------------------------
274

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

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

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

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

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

319
                Ok(())
10✔
320
            }
321
            CommandBody::Login { username, password } => {
56✔
322
                ctx.write_all(b"LOGIN")?;
56✔
323
                ctx.write_all(b" ")?;
56✔
324
                username.encode_ctx(ctx)?;
56✔
325
                ctx.write_all(b" ")?;
56✔
326
                password.declassify().encode_ctx(ctx)
56✔
327
            }
328
            CommandBody::Select {
329
                mailbox,
20✔
330
                #[cfg(feature = "ext_condstore_qresync")]
331
                parameters,
20✔
332
            } => {
333
                ctx.write_all(b"SELECT")?;
20✔
334
                ctx.write_all(b" ")?;
20✔
335
                mailbox.encode_ctx(ctx)?;
20✔
336

337
                #[cfg(feature = "ext_condstore_qresync")]
338
                if !parameters.is_empty() {
20✔
339
                    ctx.write_all(b" (")?;
×
340
                    join_serializable(parameters, b" ", ctx)?;
×
341
                    ctx.write_all(b")")?;
×
342
                }
20✔
343

344
                Ok(())
20✔
345
            }
346
            CommandBody::Unselect => ctx.write_all(b"UNSELECT"),
2✔
347
            CommandBody::Examine {
348
                mailbox,
8✔
349
                #[cfg(feature = "ext_condstore_qresync")]
350
                parameters,
8✔
351
            } => {
352
                ctx.write_all(b"EXAMINE")?;
8✔
353
                ctx.write_all(b" ")?;
8✔
354
                mailbox.encode_ctx(ctx)?;
8✔
355

356
                #[cfg(feature = "ext_condstore_qresync")]
357
                if !parameters.is_empty() {
8✔
358
                    ctx.write_all(b" (")?;
×
359
                    join_serializable(parameters, b" ", ctx)?;
×
360
                    ctx.write_all(b")")?;
×
361
                }
8✔
362

363
                Ok(())
8✔
364
            }
365
            CommandBody::Create { mailbox } => {
16✔
366
                ctx.write_all(b"CREATE")?;
16✔
367
                ctx.write_all(b" ")?;
16✔
368
                mailbox.encode_ctx(ctx)
16✔
369
            }
370
            CommandBody::Delete { mailbox } => {
48✔
371
                ctx.write_all(b"DELETE")?;
48✔
372
                ctx.write_all(b" ")?;
48✔
373
                mailbox.encode_ctx(ctx)
48✔
374
            }
375
            CommandBody::Rename {
376
                from: mailbox,
24✔
377
                to: new_mailbox,
24✔
378
            } => {
379
                ctx.write_all(b"RENAME")?;
24✔
380
                ctx.write_all(b" ")?;
24✔
381
                mailbox.encode_ctx(ctx)?;
24✔
382
                ctx.write_all(b" ")?;
24✔
383
                new_mailbox.encode_ctx(ctx)
24✔
384
            }
385
            CommandBody::Subscribe { mailbox } => {
8✔
386
                ctx.write_all(b"SUBSCRIBE")?;
8✔
387
                ctx.write_all(b" ")?;
8✔
388
                mailbox.encode_ctx(ctx)
8✔
389
            }
390
            CommandBody::Unsubscribe { mailbox } => {
8✔
391
                ctx.write_all(b"UNSUBSCRIBE")?;
8✔
392
                ctx.write_all(b" ")?;
8✔
393
                mailbox.encode_ctx(ctx)
8✔
394
            }
395
            CommandBody::List {
396
                reference,
104✔
397
                mailbox_wildcard,
104✔
398
            } => {
399
                ctx.write_all(b"LIST")?;
104✔
400
                ctx.write_all(b" ")?;
104✔
401
                reference.encode_ctx(ctx)?;
104✔
402
                ctx.write_all(b" ")?;
104✔
403
                mailbox_wildcard.encode_ctx(ctx)
104✔
404
            }
405
            CommandBody::Lsub {
406
                reference,
16✔
407
                mailbox_wildcard,
16✔
408
            } => {
409
                ctx.write_all(b"LSUB")?;
16✔
410
                ctx.write_all(b" ")?;
16✔
411
                reference.encode_ctx(ctx)?;
16✔
412
                ctx.write_all(b" ")?;
16✔
413
                mailbox_wildcard.encode_ctx(ctx)
16✔
414
            }
415
            CommandBody::Status {
416
                mailbox,
10✔
417
                item_names,
10✔
418
            } => {
419
                ctx.write_all(b"STATUS")?;
10✔
420
                ctx.write_all(b" ")?;
10✔
421
                mailbox.encode_ctx(ctx)?;
10✔
422
                ctx.write_all(b" ")?;
10✔
423
                ctx.write_all(b"(")?;
10✔
424
                join_serializable(item_names, b" ", ctx)?;
10✔
425
                ctx.write_all(b")")
10✔
426
            }
427
            CommandBody::Append {
428
                mailbox,
×
429
                flags,
×
430
                date,
×
431
                message,
×
432
            } => {
433
                ctx.write_all(b"APPEND")?;
×
434
                ctx.write_all(b" ")?;
×
435
                mailbox.encode_ctx(ctx)?;
×
436

437
                if !flags.is_empty() {
×
438
                    ctx.write_all(b" ")?;
×
439
                    ctx.write_all(b"(")?;
×
440
                    join_serializable(flags, b" ", ctx)?;
×
441
                    ctx.write_all(b")")?;
×
442
                }
×
443

444
                if let Some(date) = date {
×
445
                    ctx.write_all(b" ")?;
×
446
                    date.encode_ctx(ctx)?;
×
447
                }
×
448

449
                ctx.write_all(b" ")?;
×
450
                message.encode_ctx(ctx)
×
451
            }
452
            CommandBody::Check => ctx.write_all(b"CHECK"),
8✔
453
            CommandBody::Close => ctx.write_all(b"CLOSE"),
8✔
454
            CommandBody::Expunge => ctx.write_all(b"EXPUNGE"),
16✔
455
            CommandBody::ExpungeUid { sequence_set } => {
6✔
456
                ctx.write_all(b"UID EXPUNGE ")?;
6✔
457
                sequence_set.encode_ctx(ctx)
6✔
458
            }
459
            CommandBody::Search {
460
                charset,
16✔
461
                criteria,
16✔
462
                uid,
16✔
463
            } => {
464
                if *uid {
16✔
465
                    ctx.write_all(b"UID SEARCH")?;
×
466
                } else {
467
                    ctx.write_all(b"SEARCH")?;
16✔
468
                }
469
                if let Some(charset) = charset {
16✔
470
                    ctx.write_all(b" CHARSET ")?;
×
471
                    charset.encode_ctx(ctx)?;
×
472
                }
16✔
473
                ctx.write_all(b" ")?;
16✔
474
                join_serializable(criteria.as_ref(), b" ", ctx)
16✔
475
            }
476
            CommandBody::Sort {
477
                sort_criteria,
24✔
478
                charset,
24✔
479
                search_criteria,
24✔
480
                uid,
24✔
481
            } => {
482
                if *uid {
24✔
483
                    ctx.write_all(b"UID SORT (")?;
×
484
                } else {
485
                    ctx.write_all(b"SORT (")?;
24✔
486
                }
487
                join_serializable(sort_criteria.as_ref(), b" ", ctx)?;
24✔
488
                ctx.write_all(b") ")?;
24✔
489
                charset.encode_ctx(ctx)?;
24✔
490
                ctx.write_all(b" ")?;
24✔
491
                join_serializable(search_criteria.as_ref(), b" ", ctx)
24✔
492
            }
493
            CommandBody::Thread {
494
                algorithm,
24✔
495
                charset,
24✔
496
                search_criteria,
24✔
497
                uid,
24✔
498
            } => {
499
                if *uid {
24✔
500
                    ctx.write_all(b"UID THREAD ")?;
×
501
                } else {
502
                    ctx.write_all(b"THREAD ")?;
24✔
503
                }
504
                algorithm.encode_ctx(ctx)?;
24✔
505
                ctx.write_all(b" ")?;
24✔
506
                charset.encode_ctx(ctx)?;
24✔
507
                ctx.write_all(b" ")?;
24✔
508
                join_serializable(search_criteria.as_ref(), b" ", ctx)
24✔
509
            }
510
            CommandBody::Fetch {
511
                sequence_set,
32✔
512
                macro_or_item_names,
32✔
513
                uid,
32✔
514
                #[cfg(feature = "ext_condstore_qresync")]
515
                modifiers,
32✔
516
            } => {
517
                if *uid {
32✔
518
                    ctx.write_all(b"UID FETCH ")?;
8✔
519
                } else {
520
                    ctx.write_all(b"FETCH ")?;
24✔
521
                }
522

523
                sequence_set.encode_ctx(ctx)?;
32✔
524
                ctx.write_all(b" ")?;
32✔
525
                macro_or_item_names.encode_ctx(ctx)?;
32✔
526

527
                #[cfg(feature = "ext_condstore_qresync")]
528
                if !modifiers.is_empty() {
32✔
529
                    ctx.write_all(b" (")?;
×
530
                    join_serializable(modifiers, b" ", ctx)?;
×
531
                    ctx.write_all(b")")?;
×
532
                }
32✔
533

534
                Ok(())
32✔
535
            }
536
            CommandBody::Store {
537
                sequence_set,
16✔
538
                kind,
16✔
539
                response,
16✔
540
                flags,
16✔
541
                uid,
16✔
542
                #[cfg(feature = "ext_condstore_qresync")]
543
                modifiers,
16✔
544
            } => {
545
                if *uid {
16✔
546
                    ctx.write_all(b"UID STORE ")?;
×
547
                } else {
548
                    ctx.write_all(b"STORE ")?;
16✔
549
                }
550

551
                sequence_set.encode_ctx(ctx)?;
16✔
552
                ctx.write_all(b" ")?;
16✔
553

554
                #[cfg(feature = "ext_condstore_qresync")]
555
                if !modifiers.is_empty() {
16✔
556
                    ctx.write_all(b"(")?;
×
557
                    join_serializable(modifiers, b" ", ctx)?;
×
558
                    ctx.write_all(b") ")?;
×
559
                }
16✔
560

561
                match kind {
16✔
562
                    StoreType::Add => ctx.write_all(b"+")?,
16✔
563
                    StoreType::Remove => ctx.write_all(b"-")?,
×
564
                    StoreType::Replace => {}
×
565
                }
566

567
                ctx.write_all(b"FLAGS")?;
16✔
568

569
                match response {
16✔
570
                    StoreResponse::Answer => {}
16✔
571
                    StoreResponse::Silent => ctx.write_all(b".SILENT")?,
×
572
                }
573

574
                ctx.write_all(b" (")?;
16✔
575
                join_serializable(flags, b" ", ctx)?;
16✔
576
                ctx.write_all(b")")
16✔
577
            }
578
            CommandBody::Copy {
579
                sequence_set,
24✔
580
                mailbox,
24✔
581
                uid,
24✔
582
            } => {
583
                if *uid {
24✔
584
                    ctx.write_all(b"UID COPY ")?;
×
585
                } else {
586
                    ctx.write_all(b"COPY ")?;
24✔
587
                }
588
                sequence_set.encode_ctx(ctx)?;
24✔
589
                ctx.write_all(b" ")?;
24✔
590
                mailbox.encode_ctx(ctx)
24✔
591
            }
592
            CommandBody::Idle => ctx.write_all(b"IDLE"),
4✔
593
            CommandBody::Enable { capabilities } => {
22✔
594
                ctx.write_all(b"ENABLE ")?;
22✔
595
                join_serializable(capabilities.as_ref(), b" ", ctx)
22✔
596
            }
597
            CommandBody::Compress { algorithm } => {
4✔
598
                ctx.write_all(b"COMPRESS ")?;
4✔
599
                algorithm.encode_ctx(ctx)
4✔
600
            }
601
            CommandBody::GetQuota { root } => {
10✔
602
                ctx.write_all(b"GETQUOTA ")?;
10✔
603
                root.encode_ctx(ctx)
10✔
604
            }
605
            CommandBody::GetQuotaRoot { mailbox } => {
6✔
606
                ctx.write_all(b"GETQUOTAROOT ")?;
6✔
607
                mailbox.encode_ctx(ctx)
6✔
608
            }
609
            CommandBody::SetQuota { root, quotas } => {
12✔
610
                ctx.write_all(b"SETQUOTA ")?;
12✔
611
                root.encode_ctx(ctx)?;
12✔
612
                ctx.write_all(b" (")?;
12✔
613
                join_serializable(quotas.as_ref(), b" ", ctx)?;
12✔
614
                ctx.write_all(b")")
12✔
615
            }
616
            CommandBody::Move {
617
                sequence_set,
6✔
618
                mailbox,
6✔
619
                uid,
6✔
620
            } => {
621
                if *uid {
6✔
622
                    ctx.write_all(b"UID MOVE ")?;
2✔
623
                } else {
624
                    ctx.write_all(b"MOVE ")?;
4✔
625
                }
626
                sequence_set.encode_ctx(ctx)?;
6✔
627
                ctx.write_all(b" ")?;
6✔
628
                mailbox.encode_ctx(ctx)
6✔
629
            }
630
            #[cfg(feature = "ext_id")]
631
            CommandBody::Id { parameters } => {
8✔
632
                ctx.write_all(b"ID ")?;
8✔
633

634
                match parameters {
8✔
635
                    Some(parameters) => {
4✔
636
                        if let Some((first, tail)) = parameters.split_first() {
4✔
637
                            ctx.write_all(b"(")?;
4✔
638

639
                            first.0.encode_ctx(ctx)?;
4✔
640
                            ctx.write_all(b" ")?;
4✔
641
                            first.1.encode_ctx(ctx)?;
4✔
642

643
                            for parameter in tail {
4✔
644
                                ctx.write_all(b" ")?;
×
645
                                parameter.0.encode_ctx(ctx)?;
×
646
                                ctx.write_all(b" ")?;
×
647
                                parameter.1.encode_ctx(ctx)?;
×
648
                            }
649

650
                            ctx.write_all(b")")
4✔
651
                        } else {
652
                            #[cfg(not(feature = "quirk_id_empty_to_nil"))]
653
                            {
654
                                ctx.write_all(b"()")
655
                            }
656
                            #[cfg(feature = "quirk_id_empty_to_nil")]
657
                            {
658
                                ctx.write_all(b"NIL")
×
659
                            }
660
                        }
661
                    }
662
                    None => ctx.write_all(b"NIL"),
4✔
663
                }
664
            }
665
            #[cfg(feature = "ext_metadata")]
666
            CommandBody::SetMetadata {
667
                mailbox,
6✔
668
                entry_values,
6✔
669
            } => {
670
                ctx.write_all(b"SETMETADATA ")?;
6✔
671
                mailbox.encode_ctx(ctx)?;
6✔
672
                ctx.write_all(b" (")?;
6✔
673
                join_serializable(entry_values.as_ref(), b" ", ctx)?;
6✔
674
                ctx.write_all(b")")
6✔
675
            }
676
            #[cfg(feature = "ext_metadata")]
677
            CommandBody::GetMetadata {
678
                options,
14✔
679
                mailbox,
14✔
680
                entries,
14✔
681
            } => {
682
                ctx.write_all(b"GETMETADATA")?;
14✔
683

684
                if !options.is_empty() {
14✔
685
                    ctx.write_all(b" (")?;
10✔
686
                    join_serializable(options, b" ", ctx)?;
10✔
687
                    ctx.write_all(b")")?;
10✔
688
                }
4✔
689

690
                ctx.write_all(b" ")?;
14✔
691
                mailbox.encode_ctx(ctx)?;
14✔
692

693
                ctx.write_all(b" ")?;
14✔
694

695
                if entries.as_ref().len() == 1 {
14✔
696
                    entries.as_ref()[0].encode_ctx(ctx)
14✔
697
                } else {
698
                    ctx.write_all(b"(")?;
×
699
                    join_serializable(entries.as_ref(), b" ", ctx)?;
×
700
                    ctx.write_all(b")")
×
701
                }
702
            }
703
        }
704
    }
698✔
705
}
706

707
#[cfg(feature = "ext_condstore_qresync")]
708
impl EncodeIntoContext for FetchModifier {
709
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
710
        match self {
×
711
            FetchModifier::ChangedSince(since) => write!(ctx, "CHANGEDSINCE {since}"),
×
712
            FetchModifier::Vanished => write!(ctx, "VANISHED"),
×
713
        }
714
    }
×
715
}
716

717
#[cfg(feature = "ext_condstore_qresync")]
718
impl EncodeIntoContext for StoreModifier {
719
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
720
        match self {
×
721
            StoreModifier::UnchangedSince(since) => write!(ctx, "UNCHANGEDSINCE {since}"),
×
722
        }
723
    }
×
724
}
725

726
#[cfg(feature = "ext_condstore_qresync")]
727
impl EncodeIntoContext for SelectParameter {
728
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
729
        match self {
×
730
            SelectParameter::CondStore => write!(ctx, "CONDSTORE"),
×
731
            SelectParameter::QResync {
732
                uid_validity,
×
733
                mod_sequence_value,
×
734
                known_uids,
×
735
                seq_match_data,
×
736
            } => {
737
                write!(ctx, "QRESYNC (")?;
×
738
                uid_validity.encode_ctx(ctx)?;
×
739
                write!(ctx, " ")?;
×
740
                mod_sequence_value.encode_ctx(ctx)?;
×
741

742
                if let Some(known_uids) = known_uids {
×
743
                    write!(ctx, " ")?;
×
744
                    known_uids.encode_ctx(ctx)?;
×
745
                }
×
746

747
                if let Some((known_sequence_set, known_uid_set)) = seq_match_data {
×
748
                    write!(ctx, " (")?;
×
749
                    known_sequence_set.encode_ctx(ctx)?;
×
750
                    write!(ctx, " ")?;
×
751
                    known_uid_set.encode_ctx(ctx)?;
×
752
                    write!(ctx, ")")?;
×
753
                }
×
754

755
                write!(ctx, ")")
×
756
            }
757
        }
758
    }
×
759
}
760

761
impl EncodeIntoContext for AuthMechanism<'_> {
762
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
22✔
763
        write!(ctx, "{self}")
22✔
764
    }
22✔
765
}
766

767
impl EncodeIntoContext for AuthenticateData<'_> {
768
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
769
        match self {
8✔
770
            Self::Continue(data) => {
6✔
771
                let encoded = base64.encode(data.declassify());
6✔
772
                ctx.write_all(encoded.as_bytes())?;
6✔
773
                ctx.write_all(b"\r\n")
6✔
774
            }
775
            Self::Cancel => ctx.write_all(b"*\r\n"),
2✔
776
        }
777
    }
8✔
778
}
779

780
impl EncodeIntoContext for AString<'_> {
781
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
794✔
782
        match self {
794✔
783
            AString::Atom(atom) => atom.encode_ctx(ctx),
580✔
784
            AString::String(imap_str) => imap_str.encode_ctx(ctx),
214✔
785
        }
786
    }
794✔
787
}
788

789
impl EncodeIntoContext for Atom<'_> {
790
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
54✔
791
        ctx.write_all(self.inner().as_bytes())
54✔
792
    }
54✔
793
}
794

795
impl EncodeIntoContext for AtomExt<'_> {
796
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
580✔
797
        ctx.write_all(self.inner().as_bytes())
580✔
798
    }
580✔
799
}
800

801
impl EncodeIntoContext for IString<'_> {
802
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
518✔
803
        match self {
518✔
804
            Self::Literal(val) => val.encode_ctx(ctx),
44✔
805
            Self::Quoted(val) => val.encode_ctx(ctx),
474✔
806
            #[cfg(feature = "ext_utf8")]
NEW
807
            Self::QuotedUtf8(val) => val.encode_ctx(ctx),
×
808
        }
809
    }
518✔
810
}
811

812
impl EncodeIntoContext for Literal<'_> {
813
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
44✔
814
        match self.mode() {
44✔
815
            LiteralMode::Sync => write!(ctx, "{{{}}}\r\n", self.as_ref().len())?,
30✔
816
            LiteralMode::NonSync => write!(ctx, "{{{}+}}\r\n", self.as_ref().len())?,
14✔
817
        }
818

819
        ctx.push_line();
44✔
820
        ctx.write_all(self.as_ref())?;
44✔
821
        ctx.push_literal(self.mode());
44✔
822

823
        Ok(())
44✔
824
    }
44✔
825
}
826

827
impl EncodeIntoContext for Quoted<'_> {
828
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
482✔
829
        write!(ctx, "\"{}\"", escape_quoted(self.inner()))
482✔
830
    }
482✔
831
}
832

833
impl EncodeIntoContext for Mailbox<'_> {
834
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
616✔
835
        match self {
616✔
836
            Mailbox::Inbox => ctx.write_all(b"INBOX"),
80✔
837
            Mailbox::Other(other) => other.encode_ctx(ctx),
536✔
838
        }
839
    }
616✔
840
}
841

842
impl EncodeIntoContext for MailboxOther<'_> {
843
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
536✔
844
        self.inner().encode_ctx(ctx)
536✔
845
    }
536✔
846
}
847

848
impl EncodeIntoContext for ListMailbox<'_> {
849
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
120✔
850
        match self {
120✔
851
            ListMailbox::Token(lcs) => lcs.encode_ctx(ctx),
80✔
852
            ListMailbox::String(istr) => istr.encode_ctx(ctx),
40✔
853
        }
854
    }
120✔
855
}
856

857
impl EncodeIntoContext for ListCharString<'_> {
858
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
80✔
859
        ctx.write_all(self.as_ref())
80✔
860
    }
80✔
861
}
862

863
impl EncodeIntoContext for StatusDataItemName {
864
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
36✔
865
        match self {
36✔
866
            Self::Messages => ctx.write_all(b"MESSAGES"),
12✔
867
            Self::Recent => ctx.write_all(b"RECENT"),
2✔
868
            Self::UidNext => ctx.write_all(b"UIDNEXT"),
10✔
869
            Self::UidValidity => ctx.write_all(b"UIDVALIDITY"),
2✔
870
            Self::Unseen => ctx.write_all(b"UNSEEN"),
2✔
871
            Self::Deleted => ctx.write_all(b"DELETED"),
4✔
872
            Self::DeletedStorage => ctx.write_all(b"DELETED-STORAGE"),
4✔
873
            #[cfg(feature = "ext_condstore_qresync")]
874
            Self::HighestModSeq => ctx.write_all(b"HIGHESTMODSEQ"),
×
875
        }
876
    }
36✔
877
}
878

879
impl EncodeIntoContext for Flag<'_> {
880
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
312✔
881
        write!(ctx, "{self}")
312✔
882
    }
312✔
883
}
884

885
impl EncodeIntoContext for FlagFetch<'_> {
886
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
120✔
887
        match self {
120✔
888
            Self::Flag(flag) => flag.encode_ctx(ctx),
120✔
889
            Self::Recent => ctx.write_all(b"\\Recent"),
×
890
        }
891
    }
120✔
892
}
893

894
impl EncodeIntoContext for FlagPerm<'_> {
895
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
24✔
896
        match self {
24✔
897
            Self::Flag(flag) => flag.encode_ctx(ctx),
16✔
898
            Self::Asterisk => ctx.write_all(b"\\*"),
8✔
899
        }
900
    }
24✔
901
}
902

903
impl EncodeIntoContext for DateTime {
904
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
14✔
905
        self.as_ref().encode_ctx(ctx)
14✔
906
    }
14✔
907
}
908

909
impl EncodeIntoContext for Charset<'_> {
910
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
58✔
911
        match self {
58✔
912
            Charset::Atom(atom) => atom.encode_ctx(ctx),
50✔
913
            Charset::Quoted(quoted) => quoted.encode_ctx(ctx),
8✔
914
        }
915
    }
58✔
916
}
917

918
impl EncodeIntoContext for SearchKey<'_> {
919
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
176✔
920
        match self {
176✔
921
            SearchKey::All => ctx.write_all(b"ALL"),
10✔
922
            SearchKey::Answered => ctx.write_all(b"ANSWERED"),
6✔
923
            SearchKey::Bcc(astring) => {
2✔
924
                ctx.write_all(b"BCC ")?;
2✔
925
                astring.encode_ctx(ctx)
2✔
926
            }
927
            SearchKey::Before(date) => {
2✔
928
                ctx.write_all(b"BEFORE ")?;
2✔
929
                date.encode_ctx(ctx)
2✔
930
            }
931
            SearchKey::Body(astring) => {
2✔
932
                ctx.write_all(b"BODY ")?;
2✔
933
                astring.encode_ctx(ctx)
2✔
934
            }
935
            SearchKey::Cc(astring) => {
2✔
936
                ctx.write_all(b"CC ")?;
2✔
937
                astring.encode_ctx(ctx)
2✔
938
            }
939
            SearchKey::Deleted => ctx.write_all(b"DELETED"),
2✔
940
            SearchKey::Flagged => ctx.write_all(b"FLAGGED"),
10✔
941
            SearchKey::From(astring) => {
10✔
942
                ctx.write_all(b"FROM ")?;
10✔
943
                astring.encode_ctx(ctx)
10✔
944
            }
945
            SearchKey::Keyword(flag_keyword) => {
2✔
946
                ctx.write_all(b"KEYWORD ")?;
2✔
947
                flag_keyword.encode_ctx(ctx)
2✔
948
            }
949
            SearchKey::New => ctx.write_all(b"NEW"),
6✔
950
            SearchKey::Old => ctx.write_all(b"OLD"),
2✔
951
            SearchKey::On(date) => {
2✔
952
                ctx.write_all(b"ON ")?;
2✔
953
                date.encode_ctx(ctx)
2✔
954
            }
955
            SearchKey::Recent => ctx.write_all(b"RECENT"),
4✔
956
            SearchKey::Seen => ctx.write_all(b"SEEN"),
4✔
957
            SearchKey::Since(date) => {
34✔
958
                ctx.write_all(b"SINCE ")?;
34✔
959
                date.encode_ctx(ctx)
34✔
960
            }
961
            SearchKey::Subject(astring) => {
2✔
962
                ctx.write_all(b"SUBJECT ")?;
2✔
963
                astring.encode_ctx(ctx)
2✔
964
            }
965
            SearchKey::Text(astring) => {
26✔
966
                ctx.write_all(b"TEXT ")?;
26✔
967
                astring.encode_ctx(ctx)
26✔
968
            }
969
            SearchKey::To(astring) => {
2✔
970
                ctx.write_all(b"TO ")?;
2✔
971
                astring.encode_ctx(ctx)
2✔
972
            }
973
            SearchKey::Unanswered => ctx.write_all(b"UNANSWERED"),
2✔
974
            SearchKey::Undeleted => ctx.write_all(b"UNDELETED"),
2✔
975
            SearchKey::Unflagged => ctx.write_all(b"UNFLAGGED"),
2✔
976
            SearchKey::Unkeyword(flag_keyword) => {
2✔
977
                ctx.write_all(b"UNKEYWORD ")?;
2✔
978
                flag_keyword.encode_ctx(ctx)
2✔
979
            }
980
            SearchKey::Unseen => ctx.write_all(b"UNSEEN"),
2✔
981
            SearchKey::Draft => ctx.write_all(b"DRAFT"),
2✔
982
            SearchKey::Header(header_fld_name, astring) => {
2✔
983
                ctx.write_all(b"HEADER ")?;
2✔
984
                header_fld_name.encode_ctx(ctx)?;
2✔
985
                ctx.write_all(b" ")?;
2✔
986
                astring.encode_ctx(ctx)
2✔
987
            }
988
            SearchKey::Larger(number) => write!(ctx, "LARGER {number}"),
2✔
989
            SearchKey::Not(search_key) => {
10✔
990
                ctx.write_all(b"NOT ")?;
10✔
991
                search_key.encode_ctx(ctx)
10✔
992
            }
993
            SearchKey::Or(search_key_a, search_key_b) => {
2✔
994
                ctx.write_all(b"OR ")?;
2✔
995
                search_key_a.encode_ctx(ctx)?;
2✔
996
                ctx.write_all(b" ")?;
2✔
997
                search_key_b.encode_ctx(ctx)
2✔
998
            }
999
            SearchKey::SentBefore(date) => {
2✔
1000
                ctx.write_all(b"SENTBEFORE ")?;
2✔
1001
                date.encode_ctx(ctx)
2✔
1002
            }
1003
            SearchKey::SentOn(date) => {
2✔
1004
                ctx.write_all(b"SENTON ")?;
2✔
1005
                date.encode_ctx(ctx)
2✔
1006
            }
1007
            SearchKey::SentSince(date) => {
2✔
1008
                ctx.write_all(b"SENTSINCE ")?;
2✔
1009
                date.encode_ctx(ctx)
2✔
1010
            }
1011
            SearchKey::Smaller(number) => write!(ctx, "SMALLER {number}"),
2✔
1012
            SearchKey::Uid(sequence_set) => {
2✔
1013
                ctx.write_all(b"UID ")?;
2✔
1014
                sequence_set.encode_ctx(ctx)
2✔
1015
            }
1016
            SearchKey::Undraft => ctx.write_all(b"UNDRAFT"),
2✔
1017
            #[cfg(feature = "ext_condstore_qresync")]
1018
            SearchKey::ModSequence { entry, modseq } => {
×
1019
                ctx.write_all(b"MODSEQ")?;
×
1020
                if let Some((attribute_flag, entry_type_req)) = entry {
×
1021
                    write!(ctx, " \"/flags/{attribute_flag}\"")?;
×
1022
                    write!(ctx, " {entry_type_req}")?;
×
1023
                }
×
1024
                ctx.write_all(b" ")?;
×
1025
                modseq.encode_ctx(ctx)
×
1026
            }
1027
            SearchKey::SequenceSet(sequence_set) => sequence_set.encode_ctx(ctx),
2✔
1028
            SearchKey::And(search_keys) => {
4✔
1029
                ctx.write_all(b"(")?;
4✔
1030
                join_serializable(search_keys.as_ref(), b" ", ctx)?;
4✔
1031
                ctx.write_all(b")")
4✔
1032
            }
1033
        }
1034
    }
176✔
1035
}
1036

1037
impl EncodeIntoContext for SequenceSet {
1038
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
88✔
1039
        join_serializable(self.0.as_ref(), b",", ctx)
88✔
1040
    }
88✔
1041
}
1042

1043
impl EncodeIntoContext for Sequence {
1044
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
94✔
1045
        match self {
94✔
1046
            Sequence::Single(seq_no) => seq_no.encode_ctx(ctx),
38✔
1047
            Sequence::Range(from, to) => {
56✔
1048
                from.encode_ctx(ctx)?;
56✔
1049
                ctx.write_all(b":")?;
56✔
1050
                to.encode_ctx(ctx)
56✔
1051
            }
1052
        }
1053
    }
94✔
1054
}
1055

1056
impl EncodeIntoContext for SeqOrUid {
1057
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
150✔
1058
        match self {
150✔
1059
            SeqOrUid::Value(number) => write!(ctx, "{number}"),
140✔
1060
            SeqOrUid::Asterisk => ctx.write_all(b"*"),
10✔
1061
        }
1062
    }
150✔
1063
}
1064

1065
impl EncodeIntoContext for NaiveDate {
1066
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
44✔
1067
        write!(ctx, "\"{}\"", self.as_ref().format("%d-%b-%Y"))
44✔
1068
    }
44✔
1069
}
1070

1071
impl EncodeIntoContext for MacroOrMessageDataItemNames<'_> {
1072
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
32✔
1073
        match self {
32✔
1074
            Self::Macro(m) => m.encode_ctx(ctx),
8✔
1075
            Self::MessageDataItemNames(item_names) => {
24✔
1076
                if item_names.len() == 1 {
24✔
1077
                    item_names[0].encode_ctx(ctx)
16✔
1078
                } else {
1079
                    ctx.write_all(b"(")?;
8✔
1080
                    join_serializable(item_names.as_slice(), b" ", ctx)?;
8✔
1081
                    ctx.write_all(b")")
8✔
1082
                }
1083
            }
1084
        }
1085
    }
32✔
1086
}
1087

1088
impl EncodeIntoContext for Macro {
1089
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
1090
        write!(ctx, "{self}")
8✔
1091
    }
8✔
1092
}
1093

1094
impl EncodeIntoContext for MessageDataItemName<'_> {
1095
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
54✔
1096
        match self {
54✔
1097
            Self::Body => ctx.write_all(b"BODY"),
2✔
1098
            Self::BodyExt {
18✔
1099
                section,
18✔
1100
                partial,
18✔
1101
                peek,
18✔
1102
            } => {
18✔
1103
                if *peek {
18✔
1104
                    ctx.write_all(b"BODY.PEEK[")?;
×
1105
                } else {
1106
                    ctx.write_all(b"BODY[")?;
18✔
1107
                }
1108
                if let Some(section) = section {
18✔
1109
                    section.encode_ctx(ctx)?;
16✔
1110
                }
2✔
1111
                ctx.write_all(b"]")?;
18✔
1112
                if let Some((a, b)) = partial {
18✔
1113
                    write!(ctx, "<{a}.{b}>")?;
×
1114
                }
18✔
1115

1116
                Ok(())
18✔
1117
            }
1118
            Self::BodyStructure => ctx.write_all(b"BODYSTRUCTURE"),
2✔
1119
            Self::Envelope => ctx.write_all(b"ENVELOPE"),
2✔
1120
            Self::Flags => ctx.write_all(b"FLAGS"),
18✔
1121
            Self::InternalDate => ctx.write_all(b"INTERNALDATE"),
2✔
1122
            Self::Rfc822 => ctx.write_all(b"RFC822"),
2✔
1123
            Self::Rfc822Header => ctx.write_all(b"RFC822.HEADER"),
2✔
1124
            Self::Rfc822Size => ctx.write_all(b"RFC822.SIZE"),
2✔
1125
            Self::Rfc822Text => ctx.write_all(b"RFC822.TEXT"),
2✔
1126
            Self::Uid => ctx.write_all(b"UID"),
2✔
1127
            MessageDataItemName::Binary {
1128
                section,
×
1129
                partial,
×
1130
                peek,
×
1131
            } => {
1132
                ctx.write_all(b"BINARY")?;
×
1133
                if *peek {
×
1134
                    ctx.write_all(b".PEEK")?;
×
1135
                }
×
1136

1137
                ctx.write_all(b"[")?;
×
1138
                join_serializable(section, b".", ctx)?;
×
1139
                ctx.write_all(b"]")?;
×
1140

1141
                if let Some((a, b)) = partial {
×
1142
                    ctx.write_all(b"<")?;
×
1143
                    a.encode_ctx(ctx)?;
×
1144
                    ctx.write_all(b".")?;
×
1145
                    b.encode_ctx(ctx)?;
×
1146
                    ctx.write_all(b">")?;
×
1147
                }
×
1148

1149
                Ok(())
×
1150
            }
1151
            MessageDataItemName::BinarySize { section } => {
×
1152
                ctx.write_all(b"BINARY.SIZE")?;
×
1153

1154
                ctx.write_all(b"[")?;
×
1155
                join_serializable(section, b".", ctx)?;
×
1156
                ctx.write_all(b"]")
×
1157
            }
1158
            #[cfg(feature = "ext_condstore_qresync")]
1159
            MessageDataItemName::ModSeq => ctx.write_all(b"MODSEQ"),
×
1160
        }
1161
    }
54✔
1162
}
1163

1164
impl EncodeIntoContext for Section<'_> {
1165
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
44✔
1166
        match self {
44✔
1167
            Section::Part(part) => part.encode_ctx(ctx),
2✔
1168
            Section::Header(maybe_part) => match maybe_part {
20✔
1169
                Some(part) => {
2✔
1170
                    part.encode_ctx(ctx)?;
2✔
1171
                    ctx.write_all(b".HEADER")
2✔
1172
                }
1173
                None => ctx.write_all(b"HEADER"),
18✔
1174
            },
1175
            Section::HeaderFields(maybe_part, header_list) => {
12✔
1176
                match maybe_part {
12✔
1177
                    Some(part) => {
2✔
1178
                        part.encode_ctx(ctx)?;
2✔
1179
                        ctx.write_all(b".HEADER.FIELDS (")?;
2✔
1180
                    }
1181
                    None => ctx.write_all(b"HEADER.FIELDS (")?,
10✔
1182
                };
1183
                join_serializable(header_list.as_ref(), b" ", ctx)?;
12✔
1184
                ctx.write_all(b")")
12✔
1185
            }
1186
            Section::HeaderFieldsNot(maybe_part, header_list) => {
4✔
1187
                match maybe_part {
4✔
1188
                    Some(part) => {
2✔
1189
                        part.encode_ctx(ctx)?;
2✔
1190
                        ctx.write_all(b".HEADER.FIELDS.NOT (")?;
2✔
1191
                    }
1192
                    None => ctx.write_all(b"HEADER.FIELDS.NOT (")?,
2✔
1193
                };
1194
                join_serializable(header_list.as_ref(), b" ", ctx)?;
4✔
1195
                ctx.write_all(b")")
4✔
1196
            }
1197
            Section::Text(maybe_part) => match maybe_part {
4✔
1198
                Some(part) => {
2✔
1199
                    part.encode_ctx(ctx)?;
2✔
1200
                    ctx.write_all(b".TEXT")
2✔
1201
                }
1202
                None => ctx.write_all(b"TEXT"),
2✔
1203
            },
1204
            Section::Mime(part) => {
2✔
1205
                part.encode_ctx(ctx)?;
2✔
1206
                ctx.write_all(b".MIME")
2✔
1207
            }
1208
        }
1209
    }
44✔
1210
}
1211

1212
impl EncodeIntoContext for Part {
1213
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
12✔
1214
        join_serializable(self.0.as_ref(), b".", ctx)
12✔
1215
    }
12✔
1216
}
1217

1218
impl EncodeIntoContext for NonZeroU32 {
1219
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
246✔
1220
        write!(ctx, "{self}")
246✔
1221
    }
246✔
1222
}
1223

1224
#[cfg(feature = "ext_condstore_qresync")]
1225
impl EncodeIntoContext for NonZeroU64 {
1226
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
1227
        write!(ctx, "{self}")
×
1228
    }
×
1229
}
1230

1231
impl EncodeIntoContext for Capability<'_> {
1232
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
232✔
1233
        write!(ctx, "{self}")
232✔
1234
    }
232✔
1235
}
1236

1237
// ----- Responses ---------------------------------------------------------------------------------
1238

1239
impl EncodeIntoContext for Response<'_> {
1240
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
1,550✔
1241
        match self {
1,550✔
1242
            Response::Status(status) => status.encode_ctx(ctx),
824✔
1243
            Response::Data(data) => data.encode_ctx(ctx),
718✔
1244
            Response::CommandContinuationRequest(continue_request) => {
8✔
1245
                continue_request.encode_ctx(ctx)
8✔
1246
            }
1247
        }
1248
    }
1,550✔
1249
}
1250

1251
impl EncodeIntoContext for Greeting<'_> {
1252
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
26✔
1253
        ctx.write_all(b"* ")?;
26✔
1254
        self.kind.encode_ctx(ctx)?;
26✔
1255
        ctx.write_all(b" ")?;
26✔
1256

1257
        if let Some(ref code) = self.code {
26✔
1258
            ctx.write_all(b"[")?;
12✔
1259
            code.encode_ctx(ctx)?;
12✔
1260
            ctx.write_all(b"] ")?;
12✔
1261
        }
14✔
1262

1263
        self.text.encode_ctx(ctx)?;
26✔
1264
        ctx.write_all(b"\r\n")
26✔
1265
    }
26✔
1266
}
1267

1268
impl EncodeIntoContext for GreetingKind {
1269
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
26✔
1270
        match self {
26✔
1271
            GreetingKind::Ok => ctx.write_all(b"OK"),
12✔
1272
            GreetingKind::PreAuth => ctx.write_all(b"PREAUTH"),
12✔
1273
            GreetingKind::Bye => ctx.write_all(b"BYE"),
2✔
1274
        }
1275
    }
26✔
1276
}
1277

1278
impl EncodeIntoContext for Status<'_> {
1279
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
824✔
1280
        fn format_status(
824✔
1281
            tag: Option<&Tag>,
824✔
1282
            status: &str,
824✔
1283
            code: &Option<Code>,
824✔
1284
            comment: &Text,
824✔
1285
            ctx: &mut EncodeContext,
824✔
1286
        ) -> std::io::Result<()> {
824✔
1287
            match tag {
824✔
1288
                Some(tag) => tag.encode_ctx(ctx)?,
606✔
1289
                None => ctx.write_all(b"*")?,
218✔
1290
            }
1291
            ctx.write_all(b" ")?;
824✔
1292
            ctx.write_all(status.as_bytes())?;
824✔
1293
            ctx.write_all(b" ")?;
824✔
1294
            if let Some(code) = code {
824✔
1295
                ctx.write_all(b"[")?;
148✔
1296
                code.encode_ctx(ctx)?;
148✔
1297
                ctx.write_all(b"] ")?;
148✔
1298
            }
676✔
1299
            comment.encode_ctx(ctx)?;
824✔
1300
            ctx.write_all(b"\r\n")
824✔
1301
        }
824✔
1302

1303
        match self {
824✔
1304
            Self::Untagged(StatusBody { kind, code, text }) => match kind {
192✔
1305
                StatusKind::Ok => format_status(None, "OK", code, text, ctx),
134✔
1306
                StatusKind::No => format_status(None, "NO", code, text, ctx),
30✔
1307
                StatusKind::Bad => format_status(None, "BAD", code, text, ctx),
28✔
1308
            },
1309
            Self::Tagged(Tagged {
606✔
1310
                tag,
606✔
1311
                body: StatusBody { kind, code, text },
606✔
1312
            }) => match kind {
606✔
1313
                StatusKind::Ok => format_status(Some(tag), "OK", code, text, ctx),
572✔
1314
                StatusKind::No => format_status(Some(tag), "NO", code, text, ctx),
22✔
1315
                StatusKind::Bad => format_status(Some(tag), "BAD", code, text, ctx),
12✔
1316
            },
1317
            Self::Bye(Bye { code, text }) => format_status(None, "BYE", code, text, ctx),
26✔
1318
        }
1319
    }
824✔
1320
}
1321

1322
impl EncodeIntoContext for Code<'_> {
1323
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
160✔
1324
        match self {
160✔
1325
            Code::Alert => ctx.write_all(b"ALERT"),
24✔
1326
            Code::BadCharset { allowed } => {
2✔
1327
                if allowed.is_empty() {
2✔
1328
                    ctx.write_all(b"BADCHARSET")
2✔
1329
                } else {
1330
                    ctx.write_all(b"BADCHARSET (")?;
×
1331
                    join_serializable(allowed, b" ", ctx)?;
×
1332
                    ctx.write_all(b")")
×
1333
                }
1334
            }
1335
            Code::Capability(caps) => {
4✔
1336
                ctx.write_all(b"CAPABILITY ")?;
4✔
1337
                join_serializable(caps.as_ref(), b" ", ctx)
4✔
1338
            }
1339
            Code::Parse => ctx.write_all(b"PARSE"),
×
1340
            Code::PermanentFlags(flags) => {
16✔
1341
                ctx.write_all(b"PERMANENTFLAGS (")?;
16✔
1342
                join_serializable(flags, b" ", ctx)?;
16✔
1343
                ctx.write_all(b")")
16✔
1344
            }
1345
            Code::ReadOnly => ctx.write_all(b"READ-ONLY"),
8✔
1346
            Code::ReadWrite => ctx.write_all(b"READ-WRITE"),
16✔
1347
            Code::TryCreate => ctx.write_all(b"TRYCREATE"),
×
1348
            Code::UidNext(next) => {
16✔
1349
                ctx.write_all(b"UIDNEXT ")?;
16✔
1350
                next.encode_ctx(ctx)
16✔
1351
            }
1352
            Code::UidValidity(validity) => {
24✔
1353
                ctx.write_all(b"UIDVALIDITY ")?;
24✔
1354
                validity.encode_ctx(ctx)
24✔
1355
            }
1356
            Code::Unseen(seq) => {
28✔
1357
                ctx.write_all(b"UNSEEN ")?;
28✔
1358
                seq.encode_ctx(ctx)
28✔
1359
            }
1360
            // RFC 2221
1361
            #[cfg(any(feature = "ext_login_referrals", feature = "ext_mailbox_referrals"))]
1362
            Code::Referral(url) => {
×
1363
                ctx.write_all(b"REFERRAL ")?;
×
1364
                ctx.write_all(url.as_bytes())
×
1365
            }
1366
            // RFC 4551
1367
            #[cfg(feature = "ext_condstore_qresync")]
1368
            Code::HighestModSeq(modseq) => {
×
1369
                ctx.write_all(b"HIGHESTMODSEQ ")?;
×
1370
                modseq.encode_ctx(ctx)
×
1371
            }
1372
            #[cfg(feature = "ext_condstore_qresync")]
1373
            Code::NoModSeq => ctx.write_all(b"NOMODSEQ"),
×
1374
            #[cfg(feature = "ext_condstore_qresync")]
1375
            Code::Modified(sequence_set) => {
×
1376
                ctx.write_all(b"MODIFIED ")?;
×
1377
                sequence_set.encode_ctx(ctx)
×
1378
            }
1379
            #[cfg(feature = "ext_condstore_qresync")]
1380
            Code::Closed => ctx.write_all(b"CLOSED"),
×
1381
            Code::CompressionActive => ctx.write_all(b"COMPRESSIONACTIVE"),
×
1382
            Code::OverQuota => ctx.write_all(b"OVERQUOTA"),
4✔
1383
            Code::TooBig => ctx.write_all(b"TOOBIG"),
×
1384
            #[cfg(feature = "ext_metadata")]
1385
            Code::Metadata(code) => {
12✔
1386
                ctx.write_all(b"METADATA ")?;
12✔
1387
                code.encode_ctx(ctx)
12✔
1388
            }
1389
            Code::UnknownCte => ctx.write_all(b"UNKNOWN-CTE"),
×
1390
            Code::AppendUid { uid_validity, uid } => {
2✔
1391
                ctx.write_all(b"APPENDUID ")?;
2✔
1392
                uid_validity.encode_ctx(ctx)?;
2✔
1393
                ctx.write_all(b" ")?;
2✔
1394
                uid.encode_ctx(ctx)
2✔
1395
            }
1396
            Code::CopyUid {
1397
                uid_validity,
2✔
1398
                source,
2✔
1399
                destination,
2✔
1400
            } => {
1401
                ctx.write_all(b"COPYUID ")?;
2✔
1402
                uid_validity.encode_ctx(ctx)?;
2✔
1403
                ctx.write_all(b" ")?;
2✔
1404
                source.encode_ctx(ctx)?;
2✔
1405
                ctx.write_all(b" ")?;
2✔
1406
                destination.encode_ctx(ctx)
2✔
1407
            }
1408
            Code::UidNotSticky => ctx.write_all(b"UIDNOTSTICKY"),
2✔
1409
            Code::Other(unknown) => unknown.encode_ctx(ctx),
×
1410
        }
1411
    }
160✔
1412
}
1413

1414
impl EncodeIntoContext for CodeOther<'_> {
1415
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
1416
        ctx.write_all(self.inner())
×
1417
    }
×
1418
}
1419

1420
impl EncodeIntoContext for Text<'_> {
1421
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
858✔
1422
        ctx.write_all(self.inner().as_bytes())
858✔
1423
    }
858✔
1424
}
1425

1426
impl EncodeIntoContext for Data<'_> {
1427
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
718✔
1428
        match self {
718✔
1429
            Data::Capability(caps) => {
64✔
1430
                ctx.write_all(b"* CAPABILITY ")?;
64✔
1431
                join_serializable(caps.as_ref(), b" ", ctx)?;
64✔
1432
            }
1433
            Data::List {
1434
                items,
210✔
1435
                delimiter,
210✔
1436
                mailbox,
210✔
1437
            } => {
1438
                ctx.write_all(b"* LIST (")?;
210✔
1439
                join_serializable(items, b" ", ctx)?;
210✔
1440
                ctx.write_all(b") ")?;
210✔
1441

1442
                if let Some(delimiter) = delimiter {
210✔
1443
                    ctx.write_all(b"\"")?;
210✔
1444
                    delimiter.encode_ctx(ctx)?;
210✔
1445
                    ctx.write_all(b"\"")?;
210✔
1446
                } else {
1447
                    ctx.write_all(b"NIL")?;
×
1448
                }
1449
                ctx.write_all(b" ")?;
210✔
1450
                mailbox.encode_ctx(ctx)?;
210✔
1451
            }
1452
            Data::Lsub {
1453
                items,
32✔
1454
                delimiter,
32✔
1455
                mailbox,
32✔
1456
            } => {
1457
                ctx.write_all(b"* LSUB (")?;
32✔
1458
                join_serializable(items, b" ", ctx)?;
32✔
1459
                ctx.write_all(b") ")?;
32✔
1460

1461
                if let Some(delimiter) = delimiter {
32✔
1462
                    ctx.write_all(b"\"")?;
32✔
1463
                    delimiter.encode_ctx(ctx)?;
32✔
1464
                    ctx.write_all(b"\"")?;
32✔
1465
                } else {
1466
                    ctx.write_all(b"NIL")?;
×
1467
                }
1468
                ctx.write_all(b" ")?;
32✔
1469
                mailbox.encode_ctx(ctx)?;
32✔
1470
            }
1471
            Data::Status { mailbox, items } => {
18✔
1472
                ctx.write_all(b"* STATUS ")?;
18✔
1473
                mailbox.encode_ctx(ctx)?;
18✔
1474
                ctx.write_all(b" (")?;
18✔
1475
                join_serializable(items, b" ", ctx)?;
18✔
1476
                ctx.write_all(b")")?;
18✔
1477
            }
1478
            // TODO: Exclude pattern via cfg?
1479
            #[cfg(not(feature = "ext_condstore_qresync"))]
1480
            Data::Search(seqs) => {
1481
                if seqs.is_empty() {
1482
                    ctx.write_all(b"* SEARCH")?;
1483
                } else {
1484
                    ctx.write_all(b"* SEARCH ")?;
1485
                    join_serializable(seqs, b" ", ctx)?;
1486
                }
1487
            }
1488
            // TODO: Exclude pattern via cfg?
1489
            #[cfg(feature = "ext_condstore_qresync")]
1490
            Data::Search(seqs, modseq) => {
38✔
1491
                if seqs.is_empty() {
38✔
1492
                    ctx.write_all(b"* SEARCH")?;
8✔
1493
                } else {
1494
                    ctx.write_all(b"* SEARCH ")?;
30✔
1495
                    join_serializable(seqs, b" ", ctx)?;
30✔
1496
                }
1497

1498
                if let Some(modseq) = modseq {
38✔
1499
                    ctx.write_all(b" (MODSEQ ")?;
×
1500
                    modseq.encode_ctx(ctx)?;
×
1501
                    ctx.write_all(b")")?;
×
1502
                }
38✔
1503
            }
1504
            // TODO: Exclude pattern via cfg?
1505
            #[cfg(not(feature = "ext_condstore_qresync"))]
1506
            Data::Sort(seqs) => {
1507
                if seqs.is_empty() {
1508
                    ctx.write_all(b"* SORT")?;
1509
                } else {
1510
                    ctx.write_all(b"* SORT ")?;
1511
                    join_serializable(seqs, b" ", ctx)?;
1512
                }
1513
            }
1514
            // TODO: Exclude pattern via cfg?
1515
            #[cfg(feature = "ext_condstore_qresync")]
1516
            Data::Sort(seqs, modseq) => {
24✔
1517
                if seqs.is_empty() {
24✔
1518
                    ctx.write_all(b"* SORT")?;
8✔
1519
                } else {
1520
                    ctx.write_all(b"* SORT ")?;
16✔
1521
                    join_serializable(seqs, b" ", ctx)?;
16✔
1522
                }
1523

1524
                if let Some(modseq) = modseq {
24✔
1525
                    ctx.write_all(b" (MODSEQ ")?;
×
1526
                    modseq.encode_ctx(ctx)?;
×
1527
                    ctx.write_all(b")")?;
×
1528
                }
24✔
1529
            }
1530
            Data::Thread(threads) => {
24✔
1531
                if threads.is_empty() {
24✔
1532
                    ctx.write_all(b"* THREAD")?;
8✔
1533
                } else {
1534
                    ctx.write_all(b"* THREAD ")?;
16✔
1535
                    for thread in threads {
400✔
1536
                        thread.encode_ctx(ctx)?;
384✔
1537
                    }
1538
                }
1539
            }
1540
            Data::Flags(flags) => {
32✔
1541
                ctx.write_all(b"* FLAGS (")?;
32✔
1542
                join_serializable(flags, b" ", ctx)?;
32✔
1543
                ctx.write_all(b")")?;
32✔
1544
            }
1545
            Data::Exists(count) => write!(ctx, "* {count} EXISTS")?,
42✔
1546
            Data::Recent(count) => write!(ctx, "* {count} RECENT")?,
42✔
1547
            Data::Expunge(msg) => write!(ctx, "* {msg} EXPUNGE")?,
50✔
1548
            Data::Fetch { seq, items } => {
96✔
1549
                write!(ctx, "* {seq} FETCH (")?;
96✔
1550
                join_serializable(items.as_ref(), b" ", ctx)?;
96✔
1551
                ctx.write_all(b")")?;
96✔
1552
            }
1553
            Data::Enabled { capabilities } => {
16✔
1554
                write!(ctx, "* ENABLED")?;
16✔
1555

1556
                for cap in capabilities {
32✔
1557
                    ctx.write_all(b" ")?;
16✔
1558
                    cap.encode_ctx(ctx)?;
16✔
1559
                }
1560
            }
1561
            Data::Quota { root, quotas } => {
14✔
1562
                ctx.write_all(b"* QUOTA ")?;
14✔
1563
                root.encode_ctx(ctx)?;
14✔
1564
                ctx.write_all(b" (")?;
14✔
1565
                join_serializable(quotas.as_ref(), b" ", ctx)?;
14✔
1566
                ctx.write_all(b")")?;
14✔
1567
            }
1568
            Data::QuotaRoot { mailbox, roots } => {
10✔
1569
                ctx.write_all(b"* QUOTAROOT ")?;
10✔
1570
                mailbox.encode_ctx(ctx)?;
10✔
1571
                for root in roots {
20✔
1572
                    ctx.write_all(b" ")?;
10✔
1573
                    root.encode_ctx(ctx)?;
10✔
1574
                }
1575
            }
1576
            #[cfg(feature = "ext_id")]
1577
            Data::Id { parameters } => {
2✔
1578
                ctx.write_all(b"* ID ")?;
2✔
1579

1580
                match parameters {
2✔
1581
                    Some(parameters) => {
×
1582
                        if let Some((first, tail)) = parameters.split_first() {
×
1583
                            ctx.write_all(b"(")?;
×
1584

1585
                            first.0.encode_ctx(ctx)?;
×
1586
                            ctx.write_all(b" ")?;
×
1587
                            first.1.encode_ctx(ctx)?;
×
1588

1589
                            for parameter in tail {
×
1590
                                ctx.write_all(b" ")?;
×
1591
                                parameter.0.encode_ctx(ctx)?;
×
1592
                                ctx.write_all(b" ")?;
×
1593
                                parameter.1.encode_ctx(ctx)?;
×
1594
                            }
1595

1596
                            ctx.write_all(b")")?;
×
1597
                        } else {
1598
                            #[cfg(not(feature = "quirk_id_empty_to_nil"))]
1599
                            {
1600
                                ctx.write_all(b"()")?;
1601
                            }
1602
                            #[cfg(feature = "quirk_id_empty_to_nil")]
1603
                            {
1604
                                ctx.write_all(b"NIL")?;
×
1605
                            }
1606
                        }
1607
                    }
1608
                    None => {
1609
                        ctx.write_all(b"NIL")?;
2✔
1610
                    }
1611
                }
1612
            }
1613
            #[cfg(feature = "ext_metadata")]
1614
            Data::Metadata { mailbox, items } => {
4✔
1615
                ctx.write_all(b"* METADATA ")?;
4✔
1616
                mailbox.encode_ctx(ctx)?;
4✔
1617
                ctx.write_all(b" ")?;
4✔
1618
                items.encode_ctx(ctx)?;
4✔
1619
            }
1620
            #[cfg(feature = "ext_condstore_qresync")]
1621
            Data::Vanished {
1622
                earlier,
×
1623
                known_uids,
×
1624
            } => {
1625
                ctx.write_all(b"* VANISHED")?;
×
1626
                if *earlier {
×
1627
                    ctx.write_all(b" (EARLIER)")?;
×
1628
                }
×
1629
                ctx.write_all(b" ")?;
×
1630
                known_uids.encode_ctx(ctx)?;
×
1631
            }
1632
        }
1633

1634
        ctx.write_all(b"\r\n")
718✔
1635
    }
718✔
1636
}
1637

1638
impl EncodeIntoContext for FlagNameAttribute<'_> {
1639
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
90✔
1640
        write!(ctx, "{self}")
90✔
1641
    }
90✔
1642
}
1643

1644
impl EncodeIntoContext for QuotedChar {
1645
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
242✔
1646
        match self.inner() {
242✔
1647
            '\\' => ctx.write_all(b"\\\\"),
×
1648
            '"' => ctx.write_all(b"\\\""),
×
1649
            other => ctx.write_all(&[other as u8]),
242✔
1650
        }
1651
    }
242✔
1652
}
1653

1654
impl EncodeIntoContext for StatusDataItem {
1655
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
52✔
1656
        match self {
52✔
1657
            Self::Messages(count) => {
20✔
1658
                ctx.write_all(b"MESSAGES ")?;
20✔
1659
                count.encode_ctx(ctx)
20✔
1660
            }
1661
            Self::Recent(count) => {
2✔
1662
                ctx.write_all(b"RECENT ")?;
2✔
1663
                count.encode_ctx(ctx)
2✔
1664
            }
1665
            Self::UidNext(next) => {
18✔
1666
                ctx.write_all(b"UIDNEXT ")?;
18✔
1667
                next.encode_ctx(ctx)
18✔
1668
            }
1669
            Self::UidValidity(identifier) => {
2✔
1670
                ctx.write_all(b"UIDVALIDITY ")?;
2✔
1671
                identifier.encode_ctx(ctx)
2✔
1672
            }
1673
            Self::Unseen(count) => {
2✔
1674
                ctx.write_all(b"UNSEEN ")?;
2✔
1675
                count.encode_ctx(ctx)
2✔
1676
            }
1677
            Self::Deleted(count) => {
4✔
1678
                ctx.write_all(b"DELETED ")?;
4✔
1679
                count.encode_ctx(ctx)
4✔
1680
            }
1681
            Self::DeletedStorage(count) => {
4✔
1682
                ctx.write_all(b"DELETED-STORAGE ")?;
4✔
1683
                count.encode_ctx(ctx)
4✔
1684
            }
1685
            #[cfg(feature = "ext_condstore_qresync")]
1686
            Self::HighestModSeq(value) => {
×
1687
                ctx.write_all(b"HIGHESTMODSEQ ")?;
×
1688
                value.encode_ctx(ctx)
×
1689
            }
1690
        }
1691
    }
52✔
1692
}
1693

1694
impl EncodeIntoContext for MessageDataItem<'_> {
1695
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
184✔
1696
        match self {
184✔
1697
            Self::BodyExt {
16✔
1698
                section,
16✔
1699
                origin,
16✔
1700
                data,
16✔
1701
            } => {
16✔
1702
                ctx.write_all(b"BODY[")?;
16✔
1703
                if let Some(section) = section {
16✔
1704
                    section.encode_ctx(ctx)?;
8✔
1705
                }
8✔
1706
                ctx.write_all(b"]")?;
16✔
1707
                if let Some(origin) = origin {
16✔
1708
                    write!(ctx, "<{origin}>")?;
2✔
1709
                }
14✔
1710
                ctx.write_all(b" ")?;
16✔
1711
                data.encode_ctx(ctx)
16✔
1712
            }
1713
            // FIXME: do not return body-ext-1part and body-ext-mpart here
1714
            Self::Body(body) => {
10✔
1715
                ctx.write_all(b"BODY ")?;
10✔
1716
                body.encode_ctx(ctx)
10✔
1717
            }
1718
            Self::BodyStructure(body) => {
4✔
1719
                ctx.write_all(b"BODYSTRUCTURE ")?;
4✔
1720
                body.encode_ctx(ctx)
4✔
1721
            }
1722
            Self::Envelope(envelope) => {
10✔
1723
                ctx.write_all(b"ENVELOPE ")?;
10✔
1724
                envelope.encode_ctx(ctx)
10✔
1725
            }
1726
            Self::Flags(flags) => {
82✔
1727
                ctx.write_all(b"FLAGS (")?;
82✔
1728
                join_serializable(flags, b" ", ctx)?;
82✔
1729
                ctx.write_all(b")")
82✔
1730
            }
1731
            Self::InternalDate(datetime) => {
10✔
1732
                ctx.write_all(b"INTERNALDATE ")?;
10✔
1733
                datetime.encode_ctx(ctx)
10✔
1734
            }
1735
            Self::Rfc822(nstring) => {
4✔
1736
                ctx.write_all(b"RFC822 ")?;
4✔
1737
                nstring.encode_ctx(ctx)
4✔
1738
            }
1739
            Self::Rfc822Header(nstring) => {
2✔
1740
                ctx.write_all(b"RFC822.HEADER ")?;
2✔
1741
                nstring.encode_ctx(ctx)
2✔
1742
            }
1743
            Self::Rfc822Size(size) => write!(ctx, "RFC822.SIZE {size}"),
18✔
1744
            Self::Rfc822Text(nstring) => {
2✔
1745
                ctx.write_all(b"RFC822.TEXT ")?;
2✔
1746
                nstring.encode_ctx(ctx)
2✔
1747
            }
1748
            Self::Uid(uid) => write!(ctx, "UID {uid}"),
26✔
1749
            Self::Binary { section, value } => {
×
1750
                ctx.write_all(b"BINARY[")?;
×
1751
                join_serializable(section, b".", ctx)?;
×
1752
                ctx.write_all(b"] ")?;
×
1753
                value.encode_ctx(ctx)
×
1754
            }
1755
            Self::BinarySize { section, size } => {
×
1756
                ctx.write_all(b"BINARY.SIZE[")?;
×
1757
                join_serializable(section, b".", ctx)?;
×
1758
                ctx.write_all(b"] ")?;
×
1759
                size.encode_ctx(ctx)
×
1760
            }
1761
            #[cfg(feature = "ext_condstore_qresync")]
1762
            Self::ModSeq(value) => write!(ctx, "MODSEQ {value}"),
×
1763
        }
1764
    }
184✔
1765
}
1766

1767
impl EncodeIntoContext for NString<'_> {
1768
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
318✔
1769
        match &self.0 {
318✔
1770
            Some(imap_str) => imap_str.encode_ctx(ctx),
188✔
1771
            None => ctx.write_all(b"NIL"),
130✔
1772
        }
1773
    }
318✔
1774
}
1775

1776
impl EncodeIntoContext for NString8<'_> {
1777
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
1778
        match self {
8✔
1779
            NString8::NString(nstring) => nstring.encode_ctx(ctx),
6✔
1780
            NString8::Literal8(literal8) => literal8.encode_ctx(ctx),
2✔
1781
        }
1782
    }
8✔
1783
}
1784

1785
impl EncodeIntoContext for BodyStructure<'_> {
1786
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
32✔
1787
        ctx.write_all(b"(")?;
32✔
1788
        match self {
32✔
1789
            BodyStructure::Single {
1790
                body,
20✔
1791
                extension_data: extension,
20✔
1792
            } => {
1793
                body.encode_ctx(ctx)?;
20✔
1794
                if let Some(extension) = extension {
20✔
1795
                    ctx.write_all(b" ")?;
4✔
1796
                    extension.encode_ctx(ctx)?;
4✔
1797
                }
16✔
1798
            }
1799
            BodyStructure::Multi {
1800
                bodies,
12✔
1801
                subtype,
12✔
1802
                extension_data,
12✔
1803
            } => {
1804
                for body in bodies.as_ref() {
12✔
1805
                    body.encode_ctx(ctx)?;
12✔
1806
                }
1807
                ctx.write_all(b" ")?;
12✔
1808
                subtype.encode_ctx(ctx)?;
12✔
1809

1810
                if let Some(extension) = extension_data {
12✔
1811
                    ctx.write_all(b" ")?;
×
1812
                    extension.encode_ctx(ctx)?;
×
1813
                }
12✔
1814
            }
1815
        }
1816
        ctx.write_all(b")")
32✔
1817
    }
32✔
1818
}
1819

1820
impl EncodeIntoContext for Body<'_> {
1821
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
20✔
1822
        match self.specific {
20✔
1823
            SpecificFields::Basic {
1824
                r#type: ref type_,
4✔
1825
                ref subtype,
4✔
1826
            } => {
1827
                type_.encode_ctx(ctx)?;
4✔
1828
                ctx.write_all(b" ")?;
4✔
1829
                subtype.encode_ctx(ctx)?;
4✔
1830
                ctx.write_all(b" ")?;
4✔
1831
                self.basic.encode_ctx(ctx)
4✔
1832
            }
1833
            SpecificFields::Message {
1834
                ref envelope,
×
1835
                ref body_structure,
×
1836
                number_of_lines,
×
1837
            } => {
1838
                ctx.write_all(b"\"MESSAGE\" \"RFC822\" ")?;
×
1839
                self.basic.encode_ctx(ctx)?;
×
1840
                ctx.write_all(b" ")?;
×
1841
                envelope.encode_ctx(ctx)?;
×
1842
                ctx.write_all(b" ")?;
×
1843
                body_structure.encode_ctx(ctx)?;
×
1844
                ctx.write_all(b" ")?;
×
1845
                write!(ctx, "{number_of_lines}")
×
1846
            }
1847
            SpecificFields::Text {
1848
                ref subtype,
16✔
1849
                number_of_lines,
16✔
1850
            } => {
1851
                ctx.write_all(b"\"TEXT\" ")?;
16✔
1852
                subtype.encode_ctx(ctx)?;
16✔
1853
                ctx.write_all(b" ")?;
16✔
1854
                self.basic.encode_ctx(ctx)?;
16✔
1855
                ctx.write_all(b" ")?;
16✔
1856
                write!(ctx, "{number_of_lines}")
16✔
1857
            }
1858
        }
1859
    }
20✔
1860
}
1861

1862
impl EncodeIntoContext for BasicFields<'_> {
1863
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
20✔
1864
        List1AttributeValueOrNil(&self.parameter_list).encode_ctx(ctx)?;
20✔
1865
        ctx.write_all(b" ")?;
20✔
1866
        self.id.encode_ctx(ctx)?;
20✔
1867
        ctx.write_all(b" ")?;
20✔
1868
        self.description.encode_ctx(ctx)?;
20✔
1869
        ctx.write_all(b" ")?;
20✔
1870
        self.content_transfer_encoding.encode_ctx(ctx)?;
20✔
1871
        ctx.write_all(b" ")?;
20✔
1872
        write!(ctx, "{}", self.size)
20✔
1873
    }
20✔
1874
}
1875

1876
impl EncodeIntoContext for Envelope<'_> {
1877
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
10✔
1878
        ctx.write_all(b"(")?;
10✔
1879
        self.date.encode_ctx(ctx)?;
10✔
1880
        ctx.write_all(b" ")?;
10✔
1881
        self.subject.encode_ctx(ctx)?;
10✔
1882
        ctx.write_all(b" ")?;
10✔
1883
        List1OrNil(&self.from, b"").encode_ctx(ctx)?;
10✔
1884
        ctx.write_all(b" ")?;
10✔
1885
        List1OrNil(&self.sender, b"").encode_ctx(ctx)?;
10✔
1886
        ctx.write_all(b" ")?;
10✔
1887
        List1OrNil(&self.reply_to, b"").encode_ctx(ctx)?;
10✔
1888
        ctx.write_all(b" ")?;
10✔
1889
        List1OrNil(&self.to, b"").encode_ctx(ctx)?;
10✔
1890
        ctx.write_all(b" ")?;
10✔
1891
        List1OrNil(&self.cc, b"").encode_ctx(ctx)?;
10✔
1892
        ctx.write_all(b" ")?;
10✔
1893
        List1OrNil(&self.bcc, b"").encode_ctx(ctx)?;
10✔
1894
        ctx.write_all(b" ")?;
10✔
1895
        self.in_reply_to.encode_ctx(ctx)?;
10✔
1896
        ctx.write_all(b" ")?;
10✔
1897
        self.message_id.encode_ctx(ctx)?;
10✔
1898
        ctx.write_all(b")")
10✔
1899
    }
10✔
1900
}
1901

1902
impl EncodeIntoContext for Address<'_> {
1903
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
48✔
1904
        ctx.write_all(b"(")?;
48✔
1905
        self.name.encode_ctx(ctx)?;
48✔
1906
        ctx.write_all(b" ")?;
48✔
1907
        self.adl.encode_ctx(ctx)?;
48✔
1908
        ctx.write_all(b" ")?;
48✔
1909
        self.mailbox.encode_ctx(ctx)?;
48✔
1910
        ctx.write_all(b" ")?;
48✔
1911
        self.host.encode_ctx(ctx)?;
48✔
1912
        ctx.write_all(b")")?;
48✔
1913

1914
        Ok(())
48✔
1915
    }
48✔
1916
}
1917

1918
impl EncodeIntoContext for SinglePartExtensionData<'_> {
1919
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1920
        self.md5.encode_ctx(ctx)?;
6✔
1921

1922
        if let Some(disposition) = &self.tail {
6✔
1923
            ctx.write_all(b" ")?;
6✔
1924
            disposition.encode_ctx(ctx)?;
6✔
1925
        }
×
1926

1927
        Ok(())
6✔
1928
    }
6✔
1929
}
1930

1931
impl EncodeIntoContext for MultiPartExtensionData<'_> {
1932
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
1933
        List1AttributeValueOrNil(&self.parameter_list).encode_ctx(ctx)?;
×
1934

1935
        if let Some(disposition) = &self.tail {
×
1936
            ctx.write_all(b" ")?;
×
1937
            disposition.encode_ctx(ctx)?;
×
1938
        }
×
1939

1940
        Ok(())
×
1941
    }
×
1942
}
1943

1944
impl EncodeIntoContext for Disposition<'_> {
1945
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1946
        match &self.disposition {
6✔
1947
            Some((s, param)) => {
×
1948
                ctx.write_all(b"(")?;
×
1949
                s.encode_ctx(ctx)?;
×
1950
                ctx.write_all(b" ")?;
×
1951
                List1AttributeValueOrNil(param).encode_ctx(ctx)?;
×
1952
                ctx.write_all(b")")?;
×
1953
            }
1954
            None => ctx.write_all(b"NIL")?,
6✔
1955
        }
1956

1957
        if let Some(language) = &self.tail {
6✔
1958
            ctx.write_all(b" ")?;
6✔
1959
            language.encode_ctx(ctx)?;
6✔
1960
        }
×
1961

1962
        Ok(())
6✔
1963
    }
6✔
1964
}
1965

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

1970
        if let Some(location) = &self.tail {
6✔
1971
            ctx.write_all(b" ")?;
6✔
1972
            location.encode_ctx(ctx)?;
6✔
1973
        }
×
1974

1975
        Ok(())
6✔
1976
    }
6✔
1977
}
1978

1979
impl EncodeIntoContext for Location<'_> {
1980
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1981
        self.location.encode_ctx(ctx)?;
6✔
1982

1983
        for body_extension in &self.extensions {
10✔
1984
            ctx.write_all(b" ")?;
4✔
1985
            body_extension.encode_ctx(ctx)?;
4✔
1986
        }
1987

1988
        Ok(())
6✔
1989
    }
6✔
1990
}
1991

1992
impl EncodeIntoContext for BodyExtension<'_> {
1993
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1994
        match self {
6✔
1995
            BodyExtension::NString(nstring) => nstring.encode_ctx(ctx),
×
1996
            BodyExtension::Number(number) => number.encode_ctx(ctx),
4✔
1997
            BodyExtension::List(list) => {
2✔
1998
                ctx.write_all(b"(")?;
2✔
1999
                join_serializable(list.as_ref(), b" ", ctx)?;
2✔
2000
                ctx.write_all(b")")
2✔
2001
            }
2002
        }
2003
    }
6✔
2004
}
2005

2006
impl EncodeIntoContext for ChronoDateTime<FixedOffset> {
2007
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
14✔
2008
        write!(ctx, "\"{}\"", self.format("%d-%b-%Y %H:%M:%S %z"))
14✔
2009
    }
14✔
2010
}
2011

2012
impl EncodeIntoContext for CommandContinuationRequest<'_> {
2013
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
2014
        match self {
8✔
2015
            Self::Basic(continue_basic) => match continue_basic.code() {
8✔
2016
                Some(code) => {
×
2017
                    ctx.write_all(b"+ [")?;
×
2018
                    code.encode_ctx(ctx)?;
×
2019
                    ctx.write_all(b"] ")?;
×
2020
                    continue_basic.text().encode_ctx(ctx)?;
×
2021
                    ctx.write_all(b"\r\n")
×
2022
                }
2023
                None => {
2024
                    ctx.write_all(b"+ ")?;
8✔
2025
                    continue_basic.text().encode_ctx(ctx)?;
8✔
2026
                    ctx.write_all(b"\r\n")
8✔
2027
                }
2028
            },
2029
            Self::Base64(data) => {
×
2030
                ctx.write_all(b"+ ")?;
×
2031
                ctx.write_all(base64.encode(data).as_bytes())?;
×
2032
                ctx.write_all(b"\r\n")
×
2033
            }
2034
        }
2035
    }
8✔
2036
}
2037

2038
pub(crate) mod utils {
2039
    use std::io::Write;
2040

2041
    use super::{EncodeContext, EncodeIntoContext};
2042

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

2045
    pub struct List1AttributeValueOrNil<'a, T>(pub &'a Vec<(T, T)>);
2046

2047
    pub(crate) fn join_serializable<I: EncodeIntoContext>(
916✔
2048
        elements: &[I],
916✔
2049
        sep: &[u8],
916✔
2050
        ctx: &mut EncodeContext,
916✔
2051
    ) -> std::io::Result<()> {
916✔
2052
        if let Some((last, head)) = elements.split_last() {
916✔
2053
            for item in head {
1,346✔
2054
                item.encode_ctx(ctx)?;
594✔
2055
                ctx.write_all(sep)?;
594✔
2056
            }
2057

2058
            last.encode_ctx(ctx)
752✔
2059
        } else {
2060
            Ok(())
164✔
2061
        }
2062
    }
916✔
2063

2064
    impl<T> EncodeIntoContext for List1OrNil<'_, T>
2065
    where
2066
        T: EncodeIntoContext,
2067
    {
2068
        fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
66✔
2069
            if let Some((last, head)) = self.0.split_last() {
66✔
2070
                ctx.write_all(b"(")?;
40✔
2071

2072
                for item in head {
48✔
2073
                    item.encode_ctx(ctx)?;
8✔
2074
                    ctx.write_all(self.1)?;
8✔
2075
                }
2076

2077
                last.encode_ctx(ctx)?;
40✔
2078

2079
                ctx.write_all(b")")
40✔
2080
            } else {
2081
                ctx.write_all(b"NIL")
26✔
2082
            }
2083
        }
66✔
2084
    }
2085

2086
    impl<T> EncodeIntoContext for List1AttributeValueOrNil<'_, T>
2087
    where
2088
        T: EncodeIntoContext,
2089
    {
2090
        fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
20✔
2091
            if let Some((last, head)) = self.0.split_last() {
20✔
2092
                ctx.write_all(b"(")?;
8✔
2093

2094
                for (attribute, value) in head {
8✔
2095
                    attribute.encode_ctx(ctx)?;
×
2096
                    ctx.write_all(b" ")?;
×
2097
                    value.encode_ctx(ctx)?;
×
2098
                    ctx.write_all(b" ")?;
×
2099
                }
2100

2101
                let (attribute, value) = last;
8✔
2102
                attribute.encode_ctx(ctx)?;
8✔
2103
                ctx.write_all(b" ")?;
8✔
2104
                value.encode_ctx(ctx)?;
8✔
2105

2106
                ctx.write_all(b")")
8✔
2107
            } else {
2108
                ctx.write_all(b"NIL")
12✔
2109
            }
2110
        }
20✔
2111
    }
2112
}
2113

2114
#[cfg(test)]
2115
mod tests {
2116
    use std::num::NonZeroU32;
2117

2118
    use imap_types::{
2119
        auth::AuthMechanism,
2120
        command::{Command, CommandBody},
2121
        core::{AString, Literal, NString, Vec1},
2122
        fetch::MessageDataItem,
2123
        response::{Data, Response},
2124
        utils::escape_byte_string,
2125
    };
2126

2127
    use super::*;
2128

2129
    #[test]
2130
    fn test_api_encoder_usage() {
2✔
2131
        let cmd = Command::new(
2✔
2132
            "A",
2133
            CommandBody::login(
2✔
2134
                AString::from(Literal::unvalidated_non_sync(b"alice".as_ref())),
2✔
2135
                "password",
2136
            )
2137
            .unwrap(),
2✔
2138
        )
2139
        .unwrap();
2✔
2140

2141
        // Dump.
2142
        let got_encoded = CommandCodec::default().encode(&cmd).dump();
2✔
2143

2144
        // Encoded.
2145
        let encoded = CommandCodec::default().encode(&cmd);
2✔
2146

2147
        let mut out = Vec::new();
2✔
2148

2149
        for x in encoded {
8✔
2150
            match x {
6✔
2151
                Fragment::Line { data } => {
4✔
2152
                    println!("C: {}", escape_byte_string(&data));
4✔
2153
                    out.extend_from_slice(&data);
4✔
2154
                }
4✔
2155
                Fragment::Literal { data, mode } => {
2✔
2156
                    match mode {
2✔
2157
                        LiteralMode::Sync => println!("C: <Waiting for continuation request>"),
×
2158
                        LiteralMode::NonSync => println!("C: <Skipped continuation request>"),
2✔
2159
                    }
2160

2161
                    println!("C: {}", escape_byte_string(&data));
2✔
2162
                    out.extend_from_slice(&data);
2✔
2163
                }
2164
            }
2165
        }
2166

2167
        assert_eq!(got_encoded, out);
2✔
2168
    }
2✔
2169

2170
    #[test]
2171
    fn test_encode_command() {
2✔
2172
        kat_encoder::<CommandCodec, Command<'_>, &[Fragment]>(&[
2✔
2173
            (
2✔
2174
                Command::new("A", CommandBody::login("alice", "pass").unwrap()).unwrap(),
2✔
2175
                [Fragment::Line {
2✔
2176
                    data: b"A LOGIN alice pass\r\n".to_vec(),
2✔
2177
                }]
2✔
2178
                .as_ref(),
2✔
2179
            ),
2✔
2180
            (
2✔
2181
                Command::new(
2✔
2182
                    "A",
2✔
2183
                    CommandBody::login("alice", b"\xCA\xFE".as_ref()).unwrap(),
2✔
2184
                )
2✔
2185
                .unwrap(),
2✔
2186
                [
2✔
2187
                    Fragment::Line {
2✔
2188
                        data: b"A LOGIN alice {2}\r\n".to_vec(),
2✔
2189
                    },
2✔
2190
                    Fragment::Literal {
2✔
2191
                        data: b"\xCA\xFE".to_vec(),
2✔
2192
                        mode: LiteralMode::Sync,
2✔
2193
                    },
2✔
2194
                    Fragment::Line {
2✔
2195
                        data: b"\r\n".to_vec(),
2✔
2196
                    },
2✔
2197
                ]
2✔
2198
                .as_ref(),
2✔
2199
            ),
2✔
2200
            (
2✔
2201
                Command::new("A", CommandBody::authenticate(AuthMechanism::Login)).unwrap(),
2✔
2202
                [Fragment::Line {
2✔
2203
                    data: b"A AUTHENTICATE LOGIN\r\n".to_vec(),
2✔
2204
                }]
2✔
2205
                .as_ref(),
2✔
2206
            ),
2✔
2207
            (
2✔
2208
                Command::new(
2✔
2209
                    "A",
2✔
2210
                    CommandBody::authenticate_with_ir(AuthMechanism::Login, b"alice".as_ref()),
2✔
2211
                )
2✔
2212
                .unwrap(),
2✔
2213
                [Fragment::Line {
2✔
2214
                    data: b"A AUTHENTICATE LOGIN YWxpY2U=\r\n".to_vec(),
2✔
2215
                }]
2✔
2216
                .as_ref(),
2✔
2217
            ),
2✔
2218
            (
2✔
2219
                Command::new("A", CommandBody::authenticate(AuthMechanism::Plain)).unwrap(),
2✔
2220
                [Fragment::Line {
2✔
2221
                    data: b"A AUTHENTICATE PLAIN\r\n".to_vec(),
2✔
2222
                }]
2✔
2223
                .as_ref(),
2✔
2224
            ),
2✔
2225
            (
2✔
2226
                Command::new(
2✔
2227
                    "A",
2✔
2228
                    CommandBody::authenticate_with_ir(
2✔
2229
                        AuthMechanism::Plain,
2✔
2230
                        b"\x00alice\x00pass".as_ref(),
2✔
2231
                    ),
2✔
2232
                )
2✔
2233
                .unwrap(),
2✔
2234
                [Fragment::Line {
2✔
2235
                    data: b"A AUTHENTICATE PLAIN AGFsaWNlAHBhc3M=\r\n".to_vec(),
2✔
2236
                }]
2✔
2237
                .as_ref(),
2✔
2238
            ),
2✔
2239
        ]);
2✔
2240
    }
2✔
2241

2242
    #[test]
2243
    fn test_encode_response() {
2✔
2244
        kat_encoder::<ResponseCodec, Response<'_>, &[Fragment]>(&[
2✔
2245
            (
2✔
2246
                Response::Data(Data::Fetch {
2✔
2247
                    seq: NonZeroU32::new(12345).unwrap(),
2✔
2248
                    items: Vec1::from(MessageDataItem::BodyExt {
2✔
2249
                        section: None,
2✔
2250
                        origin: None,
2✔
2251
                        data: NString::from(Literal::unvalidated(b"ABCDE".as_ref())),
2✔
2252
                    }),
2✔
2253
                }),
2✔
2254
                [
2✔
2255
                    Fragment::Line {
2✔
2256
                        data: b"* 12345 FETCH (BODY[] {5}\r\n".to_vec(),
2✔
2257
                    },
2✔
2258
                    Fragment::Literal {
2✔
2259
                        data: b"ABCDE".to_vec(),
2✔
2260
                        mode: LiteralMode::Sync,
2✔
2261
                    },
2✔
2262
                    Fragment::Line {
2✔
2263
                        data: b")\r\n".to_vec(),
2✔
2264
                    },
2✔
2265
                ]
2✔
2266
                .as_ref(),
2✔
2267
            ),
2✔
2268
            (
2✔
2269
                Response::Data(Data::Fetch {
2✔
2270
                    seq: NonZeroU32::new(12345).unwrap(),
2✔
2271
                    items: Vec1::from(MessageDataItem::BodyExt {
2✔
2272
                        section: None,
2✔
2273
                        origin: None,
2✔
2274
                        data: NString::from(Literal::unvalidated_non_sync(b"ABCDE".as_ref())),
2✔
2275
                    }),
2✔
2276
                }),
2✔
2277
                [
2✔
2278
                    Fragment::Line {
2✔
2279
                        data: b"* 12345 FETCH (BODY[] {5+}\r\n".to_vec(),
2✔
2280
                    },
2✔
2281
                    Fragment::Literal {
2✔
2282
                        data: b"ABCDE".to_vec(),
2✔
2283
                        mode: LiteralMode::NonSync,
2✔
2284
                    },
2✔
2285
                    Fragment::Line {
2✔
2286
                        data: b")\r\n".to_vec(),
2✔
2287
                    },
2✔
2288
                ]
2✔
2289
                .as_ref(),
2✔
2290
            ),
2✔
2291
        ])
2✔
2292
    }
2✔
2293

2294
    fn kat_encoder<'a, E, M, F>(tests: &'a [(M, F)])
4✔
2295
    where
4✔
2296
        E: Encoder<Message<'a> = M> + Default,
4✔
2297
        F: AsRef<[Fragment]>,
4✔
2298
    {
2299
        for (i, (obj, actions)) in tests.iter().enumerate() {
16✔
2300
            println!("# Testing {i}");
16✔
2301

2302
            let encoder = E::default().encode(obj);
16✔
2303
            let actions = actions.as_ref();
16✔
2304

2305
            assert_eq!(encoder.collect::<Vec<_>>(), actions);
16✔
2306
        }
2307
    }
4✔
2308
}
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

© 2026 Coveralls, Inc