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

duesee / imap-codec / 12776576452

14 Jan 2025 09:19PM UTC coverage: 92.13% (-0.8%) from 92.896%
12776576452

Pull #631

github

web-flow
Merge cebba81e3 into a4498b1ec
Pull Request #631: feat: Implement CONDSTORE/QRESYNC (3/N)

166 of 281 new or added lines in 8 files covered. (59.07%)

4 existing lines in 3 files now uncovered.

11449 of 12427 relevant lines covered (92.13%)

892.51 hits per line

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

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

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

52
use base64::{engine::general_purpose::STANDARD as base64, Engine};
53
use chrono::{DateTime as ChronoDateTime, FixedOffset};
54
#[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::{join_serializable, List1AttributeValueOrNil, List1OrNil};
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
///     encode::{Encoder, Fragment},
112
///     imap_types::command::{Command, CommandBody},
113
///     CommandCodec,
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,494✔
174
        Self::default()
2,494✔
175
    }
2,494✔
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,494✔
191
        let Self {
2,494✔
192
            accumulator,
2,494✔
193
            mut items,
2,494✔
194
        } = self;
2,494✔
195

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

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

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

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

215
        out
448✔
216
    }
448✔
217
}
218

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

1,540✔
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
            } => {
10✔
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")]
20✔
331
                parameters,
20✔
332
            } => {
20✔
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✔
NEW
339
                    ctx.write_all(b" (")?;
×
NEW
340
                    join_serializable(parameters, b" ", ctx)?;
×
NEW
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")]
8✔
350
                parameters,
8✔
351
            } => {
8✔
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✔
NEW
358
                    ctx.write_all(b" (")?;
×
NEW
359
                    join_serializable(parameters, b" ", ctx)?;
×
NEW
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
            } => {
24✔
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
            } => {
104✔
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
            } => {
16✔
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
            } => {
10✔
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
            } => {
16✔
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
            } => {
24✔
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
            } => {
24✔
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")]
32✔
515
                modifiers,
32✔
516
            } => {
32✔
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✔
NEW
529
                    ctx.write_all(b" (")?;
×
NEW
530
                    join_serializable(modifiers, b" ", ctx)?;
×
UNCOV
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")]
16✔
543
                modifiers,
16✔
544
            } => {
16✔
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✔
NEW
556
                    ctx.write_all(b"(")?;
×
NEW
557
                    join_serializable(modifiers, b" ", ctx)?;
×
UNCOV
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
            } => {
24✔
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
            } => {
6✔
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
            } => {
6✔
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
            } => {
14✔
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 {
NEW
709
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
NEW
710
        match self {
×
NEW
711
            FetchModifier::ChangedSince(since) => write!(ctx, "CHANGEDSINCE {since}"),
×
NEW
712
            FetchModifier::Vanished => write!(ctx, "VANISHED"),
×
713
        }
NEW
714
    }
×
715
}
716

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

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

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

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

NEW
755
                write!(ctx, ")")
×
756
            }
757
        }
NEW
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<()> {
792✔
782
        match self {
792✔
783
            AString::Atom(atom) => atom.encode_ctx(ctx),
580✔
784
            AString::String(imap_str) => imap_str.encode_ctx(ctx),
212✔
785
        }
786
    }
792✔
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<()> {
516✔
803
        match self {
516✔
804
            Self::Literal(val) => val.encode_ctx(ctx),
44✔
805
            Self::Quoted(val) => val.encode_ctx(ctx),
472✔
806
        }
807
    }
516✔
808
}
809

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

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

44✔
821
        Ok(())
44✔
822
    }
44✔
823
}
824

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

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

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

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

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

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

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

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

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

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

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

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

1025
impl EncodeIntoContext for SequenceSet {
1026
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
88✔
1027
        join_serializable(self.0.as_ref(), b",", ctx)
88✔
1028
    }
88✔
1029
}
1030

1031
impl EncodeIntoContext for Sequence {
1032
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
94✔
1033
        match self {
94✔
1034
            Sequence::Single(seq_no) => seq_no.encode_ctx(ctx),
38✔
1035
            Sequence::Range(from, to) => {
56✔
1036
                from.encode_ctx(ctx)?;
56✔
1037
                ctx.write_all(b":")?;
56✔
1038
                to.encode_ctx(ctx)
56✔
1039
            }
1040
        }
1041
    }
94✔
1042
}
1043

1044
impl EncodeIntoContext for SeqOrUid {
1045
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
150✔
1046
        match self {
150✔
1047
            SeqOrUid::Value(number) => write!(ctx, "{number}"),
140✔
1048
            SeqOrUid::Asterisk => ctx.write_all(b"*"),
10✔
1049
        }
1050
    }
150✔
1051
}
1052

1053
impl EncodeIntoContext for NaiveDate {
1054
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
44✔
1055
        write!(ctx, "\"{}\"", self.as_ref().format("%d-%b-%Y"))
44✔
1056
    }
44✔
1057
}
1058

1059
impl EncodeIntoContext for MacroOrMessageDataItemNames<'_> {
1060
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
32✔
1061
        match self {
32✔
1062
            Self::Macro(m) => m.encode_ctx(ctx),
8✔
1063
            Self::MessageDataItemNames(item_names) => {
24✔
1064
                if item_names.len() == 1 {
24✔
1065
                    item_names[0].encode_ctx(ctx)
16✔
1066
                } else {
1067
                    ctx.write_all(b"(")?;
8✔
1068
                    join_serializable(item_names.as_slice(), b" ", ctx)?;
8✔
1069
                    ctx.write_all(b")")
8✔
1070
                }
1071
            }
1072
        }
1073
    }
32✔
1074
}
1075

1076
impl EncodeIntoContext for Macro {
1077
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
1078
        write!(ctx, "{}", self)
8✔
1079
    }
8✔
1080
}
1081

1082
impl EncodeIntoContext for MessageDataItemName<'_> {
1083
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
54✔
1084
        match self {
54✔
1085
            Self::Body => ctx.write_all(b"BODY"),
2✔
1086
            Self::BodyExt {
18✔
1087
                section,
18✔
1088
                partial,
18✔
1089
                peek,
18✔
1090
            } => {
18✔
1091
                if *peek {
18✔
1092
                    ctx.write_all(b"BODY.PEEK[")?;
×
1093
                } else {
1094
                    ctx.write_all(b"BODY[")?;
18✔
1095
                }
1096
                if let Some(section) = section {
18✔
1097
                    section.encode_ctx(ctx)?;
16✔
1098
                }
2✔
1099
                ctx.write_all(b"]")?;
18✔
1100
                if let Some((a, b)) = partial {
18✔
1101
                    write!(ctx, "<{a}.{b}>")?;
×
1102
                }
18✔
1103

1104
                Ok(())
18✔
1105
            }
1106
            Self::BodyStructure => ctx.write_all(b"BODYSTRUCTURE"),
2✔
1107
            Self::Envelope => ctx.write_all(b"ENVELOPE"),
2✔
1108
            Self::Flags => ctx.write_all(b"FLAGS"),
18✔
1109
            Self::InternalDate => ctx.write_all(b"INTERNALDATE"),
2✔
1110
            Self::Rfc822 => ctx.write_all(b"RFC822"),
2✔
1111
            Self::Rfc822Header => ctx.write_all(b"RFC822.HEADER"),
2✔
1112
            Self::Rfc822Size => ctx.write_all(b"RFC822.SIZE"),
2✔
1113
            Self::Rfc822Text => ctx.write_all(b"RFC822.TEXT"),
2✔
1114
            Self::Uid => ctx.write_all(b"UID"),
2✔
1115
            MessageDataItemName::Binary {
1116
                section,
×
1117
                partial,
×
1118
                peek,
×
1119
            } => {
×
1120
                ctx.write_all(b"BINARY")?;
×
1121
                if *peek {
×
1122
                    ctx.write_all(b".PEEK")?;
×
1123
                }
×
1124

1125
                ctx.write_all(b"[")?;
×
1126
                join_serializable(section, b".", ctx)?;
×
1127
                ctx.write_all(b"]")?;
×
1128

1129
                if let Some((a, b)) = partial {
×
1130
                    ctx.write_all(b"<")?;
×
1131
                    a.encode_ctx(ctx)?;
×
1132
                    ctx.write_all(b".")?;
×
1133
                    b.encode_ctx(ctx)?;
×
1134
                    ctx.write_all(b">")?;
×
1135
                }
×
1136

1137
                Ok(())
×
1138
            }
1139
            MessageDataItemName::BinarySize { section } => {
×
1140
                ctx.write_all(b"BINARY.SIZE")?;
×
1141

1142
                ctx.write_all(b"[")?;
×
1143
                join_serializable(section, b".", ctx)?;
×
1144
                ctx.write_all(b"]")
×
1145
            }
1146
            #[cfg(feature = "ext_condstore_qresync")]
1147
            MessageDataItemName::ModSeq => ctx.write_all(b"MODSEQ"),
×
1148
        }
1149
    }
54✔
1150
}
1151

1152
impl EncodeIntoContext for Section<'_> {
1153
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
44✔
1154
        match self {
44✔
1155
            Section::Part(part) => part.encode_ctx(ctx),
2✔
1156
            Section::Header(maybe_part) => match maybe_part {
20✔
1157
                Some(part) => {
2✔
1158
                    part.encode_ctx(ctx)?;
2✔
1159
                    ctx.write_all(b".HEADER")
2✔
1160
                }
1161
                None => ctx.write_all(b"HEADER"),
18✔
1162
            },
1163
            Section::HeaderFields(maybe_part, header_list) => {
12✔
1164
                match maybe_part {
12✔
1165
                    Some(part) => {
2✔
1166
                        part.encode_ctx(ctx)?;
2✔
1167
                        ctx.write_all(b".HEADER.FIELDS (")?;
2✔
1168
                    }
1169
                    None => ctx.write_all(b"HEADER.FIELDS (")?,
10✔
1170
                };
1171
                join_serializable(header_list.as_ref(), b" ", ctx)?;
12✔
1172
                ctx.write_all(b")")
12✔
1173
            }
1174
            Section::HeaderFieldsNot(maybe_part, header_list) => {
4✔
1175
                match maybe_part {
4✔
1176
                    Some(part) => {
2✔
1177
                        part.encode_ctx(ctx)?;
2✔
1178
                        ctx.write_all(b".HEADER.FIELDS.NOT (")?;
2✔
1179
                    }
1180
                    None => ctx.write_all(b"HEADER.FIELDS.NOT (")?,
2✔
1181
                };
1182
                join_serializable(header_list.as_ref(), b" ", ctx)?;
4✔
1183
                ctx.write_all(b")")
4✔
1184
            }
1185
            Section::Text(maybe_part) => match maybe_part {
4✔
1186
                Some(part) => {
2✔
1187
                    part.encode_ctx(ctx)?;
2✔
1188
                    ctx.write_all(b".TEXT")
2✔
1189
                }
1190
                None => ctx.write_all(b"TEXT"),
2✔
1191
            },
1192
            Section::Mime(part) => {
2✔
1193
                part.encode_ctx(ctx)?;
2✔
1194
                ctx.write_all(b".MIME")
2✔
1195
            }
1196
        }
1197
    }
44✔
1198
}
1199

1200
impl EncodeIntoContext for Part {
1201
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
12✔
1202
        join_serializable(self.0.as_ref(), b".", ctx)
12✔
1203
    }
12✔
1204
}
1205

1206
impl EncodeIntoContext for NonZeroU32 {
1207
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
246✔
1208
        write!(ctx, "{self}")
246✔
1209
    }
246✔
1210
}
1211

1212
#[cfg(feature = "ext_condstore_qresync")]
1213
impl EncodeIntoContext for NonZeroU64 {
1214
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
1215
        write!(ctx, "{self}")
×
1216
    }
×
1217
}
1218

1219
impl EncodeIntoContext for Capability<'_> {
1220
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
232✔
1221
        write!(ctx, "{}", self)
232✔
1222
    }
232✔
1223
}
1224

1225
// ----- Responses ---------------------------------------------------------------------------------
1226

1227
impl EncodeIntoContext for Response<'_> {
1228
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
1,548✔
1229
        match self {
1,548✔
1230
            Response::Status(status) => status.encode_ctx(ctx),
824✔
1231
            Response::Data(data) => data.encode_ctx(ctx),
716✔
1232
            Response::CommandContinuationRequest(continue_request) => {
8✔
1233
                continue_request.encode_ctx(ctx)
8✔
1234
            }
1235
        }
1236
    }
1,548✔
1237
}
1238

1239
impl EncodeIntoContext for Greeting<'_> {
1240
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
26✔
1241
        ctx.write_all(b"* ")?;
26✔
1242
        self.kind.encode_ctx(ctx)?;
26✔
1243
        ctx.write_all(b" ")?;
26✔
1244

1245
        if let Some(ref code) = self.code {
26✔
1246
            ctx.write_all(b"[")?;
12✔
1247
            code.encode_ctx(ctx)?;
12✔
1248
            ctx.write_all(b"] ")?;
12✔
1249
        }
14✔
1250

1251
        self.text.encode_ctx(ctx)?;
26✔
1252
        ctx.write_all(b"\r\n")
26✔
1253
    }
26✔
1254
}
1255

1256
impl EncodeIntoContext for GreetingKind {
1257
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
26✔
1258
        match self {
26✔
1259
            GreetingKind::Ok => ctx.write_all(b"OK"),
12✔
1260
            GreetingKind::PreAuth => ctx.write_all(b"PREAUTH"),
12✔
1261
            GreetingKind::Bye => ctx.write_all(b"BYE"),
2✔
1262
        }
1263
    }
26✔
1264
}
1265

1266
impl EncodeIntoContext for Status<'_> {
1267
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
824✔
1268
        fn format_status(
824✔
1269
            tag: Option<&Tag>,
824✔
1270
            status: &str,
824✔
1271
            code: &Option<Code>,
824✔
1272
            comment: &Text,
824✔
1273
            ctx: &mut EncodeContext,
824✔
1274
        ) -> std::io::Result<()> {
824✔
1275
            match tag {
824✔
1276
                Some(tag) => tag.encode_ctx(ctx)?,
606✔
1277
                None => ctx.write_all(b"*")?,
218✔
1278
            }
1279
            ctx.write_all(b" ")?;
824✔
1280
            ctx.write_all(status.as_bytes())?;
824✔
1281
            ctx.write_all(b" ")?;
824✔
1282
            if let Some(code) = code {
824✔
1283
                ctx.write_all(b"[")?;
148✔
1284
                code.encode_ctx(ctx)?;
148✔
1285
                ctx.write_all(b"] ")?;
148✔
1286
            }
676✔
1287
            comment.encode_ctx(ctx)?;
824✔
1288
            ctx.write_all(b"\r\n")
824✔
1289
        }
824✔
1290

1291
        match self {
824✔
1292
            Self::Untagged(StatusBody { kind, code, text }) => match kind {
192✔
1293
                StatusKind::Ok => format_status(None, "OK", code, text, ctx),
134✔
1294
                StatusKind::No => format_status(None, "NO", code, text, ctx),
30✔
1295
                StatusKind::Bad => format_status(None, "BAD", code, text, ctx),
28✔
1296
            },
1297
            Self::Tagged(Tagged {
606✔
1298
                tag,
606✔
1299
                body: StatusBody { kind, code, text },
606✔
1300
            }) => match kind {
606✔
1301
                StatusKind::Ok => format_status(Some(tag), "OK", code, text, ctx),
572✔
1302
                StatusKind::No => format_status(Some(tag), "NO", code, text, ctx),
22✔
1303
                StatusKind::Bad => format_status(Some(tag), "BAD", code, text, ctx),
12✔
1304
            },
1305
            Self::Bye(Bye { code, text }) => format_status(None, "BYE", code, text, ctx),
26✔
1306
        }
1307
    }
824✔
1308
}
1309

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

1402
impl EncodeIntoContext for CodeOther<'_> {
1403
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
1404
        ctx.write_all(self.inner())
×
1405
    }
×
1406
}
1407

1408
impl EncodeIntoContext for Text<'_> {
1409
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
858✔
1410
        ctx.write_all(self.inner().as_bytes())
858✔
1411
    }
858✔
1412
}
1413

1414
impl EncodeIntoContext for Data<'_> {
1415
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
716✔
1416
        match self {
716✔
1417
            Data::Capability(caps) => {
64✔
1418
                ctx.write_all(b"* CAPABILITY ")?;
64✔
1419
                join_serializable(caps.as_ref(), b" ", ctx)?;
64✔
1420
            }
1421
            Data::List {
1422
                items,
210✔
1423
                delimiter,
210✔
1424
                mailbox,
210✔
1425
            } => {
210✔
1426
                ctx.write_all(b"* LIST (")?;
210✔
1427
                join_serializable(items, b" ", ctx)?;
210✔
1428
                ctx.write_all(b") ")?;
210✔
1429

1430
                if let Some(delimiter) = delimiter {
210✔
1431
                    ctx.write_all(b"\"")?;
210✔
1432
                    delimiter.encode_ctx(ctx)?;
210✔
1433
                    ctx.write_all(b"\"")?;
210✔
1434
                } else {
1435
                    ctx.write_all(b"NIL")?;
×
1436
                }
1437
                ctx.write_all(b" ")?;
210✔
1438
                mailbox.encode_ctx(ctx)?;
210✔
1439
            }
1440
            Data::Lsub {
1441
                items,
32✔
1442
                delimiter,
32✔
1443
                mailbox,
32✔
1444
            } => {
32✔
1445
                ctx.write_all(b"* LSUB (")?;
32✔
1446
                join_serializable(items, b" ", ctx)?;
32✔
1447
                ctx.write_all(b") ")?;
32✔
1448

1449
                if let Some(delimiter) = delimiter {
32✔
1450
                    ctx.write_all(b"\"")?;
32✔
1451
                    delimiter.encode_ctx(ctx)?;
32✔
1452
                    ctx.write_all(b"\"")?;
32✔
1453
                } else {
1454
                    ctx.write_all(b"NIL")?;
×
1455
                }
1456
                ctx.write_all(b" ")?;
32✔
1457
                mailbox.encode_ctx(ctx)?;
32✔
1458
            }
1459
            Data::Status { mailbox, items } => {
18✔
1460
                ctx.write_all(b"* STATUS ")?;
18✔
1461
                mailbox.encode_ctx(ctx)?;
18✔
1462
                ctx.write_all(b" (")?;
18✔
1463
                join_serializable(items, b" ", ctx)?;
18✔
1464
                ctx.write_all(b")")?;
18✔
1465
            }
1466
            // TODO: Exclude pattern via cfg?
1467
            #[cfg(not(feature = "ext_condstore_qresync"))]
1468
            Data::Search(seqs) => {
1469
                if seqs.is_empty() {
1470
                    ctx.write_all(b"* SEARCH")?;
1471
                } else {
1472
                    ctx.write_all(b"* SEARCH ")?;
1473
                    join_serializable(seqs, b" ", ctx)?;
1474
                }
1475
            }
1476
            // TODO: Exclude pattern via cfg?
1477
            #[cfg(feature = "ext_condstore_qresync")]
1478
            Data::Search(seqs, modseq) => {
38✔
1479
                if seqs.is_empty() {
38✔
1480
                    ctx.write_all(b"* SEARCH")?;
8✔
1481
                } else {
1482
                    ctx.write_all(b"* SEARCH ")?;
30✔
1483
                    join_serializable(seqs, b" ", ctx)?;
30✔
1484
                }
1485

1486
                if let Some(modseq) = modseq {
38✔
NEW
1487
                    ctx.write_all(b" (MODSEQ ")?;
×
NEW
1488
                    modseq.encode_ctx(ctx)?;
×
NEW
1489
                    ctx.write_all(b")")?;
×
1490
                }
38✔
1491
            }
1492
            // TODO: Exclude pattern via cfg?
1493
            #[cfg(not(feature = "ext_condstore_qresync"))]
1494
            Data::Sort(seqs) => {
1495
                if seqs.is_empty() {
1496
                    ctx.write_all(b"* SORT")?;
1497
                } else {
1498
                    ctx.write_all(b"* SORT ")?;
1499
                    join_serializable(seqs, b" ", ctx)?;
1500
                }
1501
            }
1502
            // TODO: Exclude pattern via cfg?
1503
            #[cfg(feature = "ext_condstore_qresync")]
1504
            Data::Sort(seqs, modseq) => {
24✔
1505
                if seqs.is_empty() {
24✔
1506
                    ctx.write_all(b"* SORT")?;
8✔
1507
                } else {
1508
                    ctx.write_all(b"* SORT ")?;
16✔
1509
                    join_serializable(seqs, b" ", ctx)?;
16✔
1510
                }
1511

1512
                if let Some(modseq) = modseq {
24✔
NEW
1513
                    ctx.write_all(b" (MODSEQ ")?;
×
NEW
1514
                    modseq.encode_ctx(ctx)?;
×
NEW
1515
                    ctx.write_all(b")")?;
×
1516
                }
24✔
1517
            }
1518
            Data::Thread(threads) => {
24✔
1519
                if threads.is_empty() {
24✔
1520
                    ctx.write_all(b"* THREAD")?;
8✔
1521
                } else {
1522
                    ctx.write_all(b"* THREAD ")?;
16✔
1523
                    for thread in threads {
400✔
1524
                        thread.encode_ctx(ctx)?;
384✔
1525
                    }
1526
                }
1527
            }
1528
            Data::Flags(flags) => {
32✔
1529
                ctx.write_all(b"* FLAGS (")?;
32✔
1530
                join_serializable(flags, b" ", ctx)?;
32✔
1531
                ctx.write_all(b")")?;
32✔
1532
            }
1533
            Data::Exists(count) => write!(ctx, "* {count} EXISTS")?,
42✔
1534
            Data::Recent(count) => write!(ctx, "* {count} RECENT")?,
42✔
1535
            Data::Expunge(msg) => write!(ctx, "* {msg} EXPUNGE")?,
50✔
1536
            Data::Fetch { seq, items } => {
96✔
1537
                write!(ctx, "* {seq} FETCH (")?;
96✔
1538
                join_serializable(items.as_ref(), b" ", ctx)?;
96✔
1539
                ctx.write_all(b")")?;
96✔
1540
            }
1541
            Data::Enabled { capabilities } => {
16✔
1542
                write!(ctx, "* ENABLED")?;
16✔
1543

1544
                for cap in capabilities {
32✔
1545
                    ctx.write_all(b" ")?;
16✔
1546
                    cap.encode_ctx(ctx)?;
16✔
1547
                }
1548
            }
1549
            Data::Quota { root, quotas } => {
12✔
1550
                ctx.write_all(b"* QUOTA ")?;
12✔
1551
                root.encode_ctx(ctx)?;
12✔
1552
                ctx.write_all(b" (")?;
12✔
1553
                join_serializable(quotas.as_ref(), b" ", ctx)?;
12✔
1554
                ctx.write_all(b")")?;
12✔
1555
            }
1556
            Data::QuotaRoot { mailbox, roots } => {
10✔
1557
                ctx.write_all(b"* QUOTAROOT ")?;
10✔
1558
                mailbox.encode_ctx(ctx)?;
10✔
1559
                for root in roots {
20✔
1560
                    ctx.write_all(b" ")?;
10✔
1561
                    root.encode_ctx(ctx)?;
10✔
1562
                }
1563
            }
1564
            #[cfg(feature = "ext_id")]
1565
            Data::Id { parameters } => {
2✔
1566
                ctx.write_all(b"* ID ")?;
2✔
1567

1568
                match parameters {
2✔
1569
                    Some(parameters) => {
×
1570
                        if let Some((first, tail)) = parameters.split_first() {
×
1571
                            ctx.write_all(b"(")?;
×
1572

1573
                            first.0.encode_ctx(ctx)?;
×
1574
                            ctx.write_all(b" ")?;
×
1575
                            first.1.encode_ctx(ctx)?;
×
1576

1577
                            for parameter in tail {
×
1578
                                ctx.write_all(b" ")?;
×
1579
                                parameter.0.encode_ctx(ctx)?;
×
1580
                                ctx.write_all(b" ")?;
×
1581
                                parameter.1.encode_ctx(ctx)?;
×
1582
                            }
1583

1584
                            ctx.write_all(b")")?;
×
1585
                        } else {
1586
                            #[cfg(not(feature = "quirk_id_empty_to_nil"))]
1587
                            {
1588
                                ctx.write_all(b"()")?;
1589
                            }
1590
                            #[cfg(feature = "quirk_id_empty_to_nil")]
1591
                            {
1592
                                ctx.write_all(b"NIL")?;
×
1593
                            }
1594
                        }
1595
                    }
1596
                    None => {
1597
                        ctx.write_all(b"NIL")?;
2✔
1598
                    }
1599
                }
1600
            }
1601
            #[cfg(feature = "ext_metadata")]
1602
            Data::Metadata { mailbox, items } => {
4✔
1603
                ctx.write_all(b"* METADATA ")?;
4✔
1604
                mailbox.encode_ctx(ctx)?;
4✔
1605
                ctx.write_all(b" ")?;
4✔
1606
                items.encode_ctx(ctx)?;
4✔
1607
            }
1608
            #[cfg(feature = "ext_condstore_qresync")]
1609
            Data::Vanished {
NEW
1610
                earlier,
×
NEW
1611
                sequence_set,
×
NEW
1612
            } => {
×
NEW
1613
                ctx.write_all(b"* VANISHED")?;
×
NEW
1614
                if *earlier {
×
NEW
1615
                    ctx.write_all(b" (EARLIER)")?;
×
NEW
1616
                }
×
NEW
1617
                ctx.write_all(b" ")?;
×
NEW
1618
                sequence_set.encode_ctx(ctx)?;
×
1619
            }
1620
        }
1621

1622
        ctx.write_all(b"\r\n")
716✔
1623
    }
716✔
1624
}
1625

1626
impl EncodeIntoContext for FlagNameAttribute<'_> {
1627
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
90✔
1628
        write!(ctx, "{}", self)
90✔
1629
    }
90✔
1630
}
1631

1632
impl EncodeIntoContext for QuotedChar {
1633
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
242✔
1634
        match self.inner() {
242✔
1635
            '\\' => ctx.write_all(b"\\\\"),
×
1636
            '"' => ctx.write_all(b"\\\""),
×
1637
            other => ctx.write_all(&[other as u8]),
242✔
1638
        }
1639
    }
242✔
1640
}
1641

1642
impl EncodeIntoContext for StatusDataItem {
1643
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
52✔
1644
        match self {
52✔
1645
            Self::Messages(count) => {
20✔
1646
                ctx.write_all(b"MESSAGES ")?;
20✔
1647
                count.encode_ctx(ctx)
20✔
1648
            }
1649
            Self::Recent(count) => {
2✔
1650
                ctx.write_all(b"RECENT ")?;
2✔
1651
                count.encode_ctx(ctx)
2✔
1652
            }
1653
            Self::UidNext(next) => {
18✔
1654
                ctx.write_all(b"UIDNEXT ")?;
18✔
1655
                next.encode_ctx(ctx)
18✔
1656
            }
1657
            Self::UidValidity(identifier) => {
2✔
1658
                ctx.write_all(b"UIDVALIDITY ")?;
2✔
1659
                identifier.encode_ctx(ctx)
2✔
1660
            }
1661
            Self::Unseen(count) => {
2✔
1662
                ctx.write_all(b"UNSEEN ")?;
2✔
1663
                count.encode_ctx(ctx)
2✔
1664
            }
1665
            Self::Deleted(count) => {
4✔
1666
                ctx.write_all(b"DELETED ")?;
4✔
1667
                count.encode_ctx(ctx)
4✔
1668
            }
1669
            Self::DeletedStorage(count) => {
4✔
1670
                ctx.write_all(b"DELETED-STORAGE ")?;
4✔
1671
                count.encode_ctx(ctx)
4✔
1672
            }
1673
            #[cfg(feature = "ext_condstore_qresync")]
1674
            Self::HighestModSeq(value) => {
×
1675
                ctx.write_all(b"HIGHESTMODSEQ ")?;
×
1676
                value.encode_ctx(ctx)
×
1677
            }
1678
        }
1679
    }
52✔
1680
}
1681

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

1755
impl EncodeIntoContext for NString<'_> {
1756
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
318✔
1757
        match &self.0 {
318✔
1758
            Some(imap_str) => imap_str.encode_ctx(ctx),
188✔
1759
            None => ctx.write_all(b"NIL"),
130✔
1760
        }
1761
    }
318✔
1762
}
1763

1764
impl EncodeIntoContext for NString8<'_> {
1765
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
1766
        match self {
8✔
1767
            NString8::NString(nstring) => nstring.encode_ctx(ctx),
6✔
1768
            NString8::Literal8(literal8) => literal8.encode_ctx(ctx),
2✔
1769
        }
1770
    }
8✔
1771
}
1772

1773
impl EncodeIntoContext for BodyStructure<'_> {
1774
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
32✔
1775
        ctx.write_all(b"(")?;
32✔
1776
        match self {
32✔
1777
            BodyStructure::Single {
1778
                body,
20✔
1779
                extension_data: extension,
20✔
1780
            } => {
20✔
1781
                body.encode_ctx(ctx)?;
20✔
1782
                if let Some(extension) = extension {
20✔
1783
                    ctx.write_all(b" ")?;
4✔
1784
                    extension.encode_ctx(ctx)?;
4✔
1785
                }
16✔
1786
            }
1787
            BodyStructure::Multi {
1788
                bodies,
12✔
1789
                subtype,
12✔
1790
                extension_data,
12✔
1791
            } => {
1792
                for body in bodies.as_ref() {
12✔
1793
                    body.encode_ctx(ctx)?;
12✔
1794
                }
1795
                ctx.write_all(b" ")?;
12✔
1796
                subtype.encode_ctx(ctx)?;
12✔
1797

1798
                if let Some(extension) = extension_data {
12✔
1799
                    ctx.write_all(b" ")?;
×
1800
                    extension.encode_ctx(ctx)?;
×
1801
                }
12✔
1802
            }
1803
        }
1804
        ctx.write_all(b")")
32✔
1805
    }
32✔
1806
}
1807

1808
impl EncodeIntoContext for Body<'_> {
1809
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
20✔
1810
        match self.specific {
20✔
1811
            SpecificFields::Basic {
1812
                r#type: ref type_,
4✔
1813
                ref subtype,
4✔
1814
            } => {
4✔
1815
                type_.encode_ctx(ctx)?;
4✔
1816
                ctx.write_all(b" ")?;
4✔
1817
                subtype.encode_ctx(ctx)?;
4✔
1818
                ctx.write_all(b" ")?;
4✔
1819
                self.basic.encode_ctx(ctx)
4✔
1820
            }
1821
            SpecificFields::Message {
1822
                ref envelope,
×
1823
                ref body_structure,
×
1824
                number_of_lines,
×
1825
            } => {
×
1826
                ctx.write_all(b"\"MESSAGE\" \"RFC822\" ")?;
×
1827
                self.basic.encode_ctx(ctx)?;
×
1828
                ctx.write_all(b" ")?;
×
1829
                envelope.encode_ctx(ctx)?;
×
1830
                ctx.write_all(b" ")?;
×
1831
                body_structure.encode_ctx(ctx)?;
×
1832
                ctx.write_all(b" ")?;
×
1833
                write!(ctx, "{number_of_lines}")
×
1834
            }
1835
            SpecificFields::Text {
1836
                ref subtype,
16✔
1837
                number_of_lines,
16✔
1838
            } => {
16✔
1839
                ctx.write_all(b"\"TEXT\" ")?;
16✔
1840
                subtype.encode_ctx(ctx)?;
16✔
1841
                ctx.write_all(b" ")?;
16✔
1842
                self.basic.encode_ctx(ctx)?;
16✔
1843
                ctx.write_all(b" ")?;
16✔
1844
                write!(ctx, "{number_of_lines}")
16✔
1845
            }
1846
        }
1847
    }
20✔
1848
}
1849

1850
impl EncodeIntoContext for BasicFields<'_> {
1851
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
20✔
1852
        List1AttributeValueOrNil(&self.parameter_list).encode_ctx(ctx)?;
20✔
1853
        ctx.write_all(b" ")?;
20✔
1854
        self.id.encode_ctx(ctx)?;
20✔
1855
        ctx.write_all(b" ")?;
20✔
1856
        self.description.encode_ctx(ctx)?;
20✔
1857
        ctx.write_all(b" ")?;
20✔
1858
        self.content_transfer_encoding.encode_ctx(ctx)?;
20✔
1859
        ctx.write_all(b" ")?;
20✔
1860
        write!(ctx, "{}", self.size)
20✔
1861
    }
20✔
1862
}
1863

1864
impl EncodeIntoContext for Envelope<'_> {
1865
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
10✔
1866
        ctx.write_all(b"(")?;
10✔
1867
        self.date.encode_ctx(ctx)?;
10✔
1868
        ctx.write_all(b" ")?;
10✔
1869
        self.subject.encode_ctx(ctx)?;
10✔
1870
        ctx.write_all(b" ")?;
10✔
1871
        List1OrNil(&self.from, b"").encode_ctx(ctx)?;
10✔
1872
        ctx.write_all(b" ")?;
10✔
1873
        List1OrNil(&self.sender, b"").encode_ctx(ctx)?;
10✔
1874
        ctx.write_all(b" ")?;
10✔
1875
        List1OrNil(&self.reply_to, b"").encode_ctx(ctx)?;
10✔
1876
        ctx.write_all(b" ")?;
10✔
1877
        List1OrNil(&self.to, b"").encode_ctx(ctx)?;
10✔
1878
        ctx.write_all(b" ")?;
10✔
1879
        List1OrNil(&self.cc, b"").encode_ctx(ctx)?;
10✔
1880
        ctx.write_all(b" ")?;
10✔
1881
        List1OrNil(&self.bcc, b"").encode_ctx(ctx)?;
10✔
1882
        ctx.write_all(b" ")?;
10✔
1883
        self.in_reply_to.encode_ctx(ctx)?;
10✔
1884
        ctx.write_all(b" ")?;
10✔
1885
        self.message_id.encode_ctx(ctx)?;
10✔
1886
        ctx.write_all(b")")
10✔
1887
    }
10✔
1888
}
1889

1890
impl EncodeIntoContext for Address<'_> {
1891
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
48✔
1892
        ctx.write_all(b"(")?;
48✔
1893
        self.name.encode_ctx(ctx)?;
48✔
1894
        ctx.write_all(b" ")?;
48✔
1895
        self.adl.encode_ctx(ctx)?;
48✔
1896
        ctx.write_all(b" ")?;
48✔
1897
        self.mailbox.encode_ctx(ctx)?;
48✔
1898
        ctx.write_all(b" ")?;
48✔
1899
        self.host.encode_ctx(ctx)?;
48✔
1900
        ctx.write_all(b")")?;
48✔
1901

1902
        Ok(())
48✔
1903
    }
48✔
1904
}
1905

1906
impl EncodeIntoContext for SinglePartExtensionData<'_> {
1907
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1908
        self.md5.encode_ctx(ctx)?;
6✔
1909

1910
        if let Some(disposition) = &self.tail {
6✔
1911
            ctx.write_all(b" ")?;
6✔
1912
            disposition.encode_ctx(ctx)?;
6✔
1913
        }
×
1914

1915
        Ok(())
6✔
1916
    }
6✔
1917
}
1918

1919
impl EncodeIntoContext for MultiPartExtensionData<'_> {
1920
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
1921
        List1AttributeValueOrNil(&self.parameter_list).encode_ctx(ctx)?;
×
1922

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

1928
        Ok(())
×
1929
    }
×
1930
}
1931

1932
impl EncodeIntoContext for Disposition<'_> {
1933
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1934
        match &self.disposition {
6✔
1935
            Some((s, param)) => {
×
1936
                ctx.write_all(b"(")?;
×
1937
                s.encode_ctx(ctx)?;
×
1938
                ctx.write_all(b" ")?;
×
1939
                List1AttributeValueOrNil(param).encode_ctx(ctx)?;
×
1940
                ctx.write_all(b")")?;
×
1941
            }
1942
            None => ctx.write_all(b"NIL")?,
6✔
1943
        }
1944

1945
        if let Some(language) = &self.tail {
6✔
1946
            ctx.write_all(b" ")?;
6✔
1947
            language.encode_ctx(ctx)?;
6✔
1948
        }
×
1949

1950
        Ok(())
6✔
1951
    }
6✔
1952
}
1953

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

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

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

1967
impl EncodeIntoContext for Location<'_> {
1968
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1969
        self.location.encode_ctx(ctx)?;
6✔
1970

1971
        for body_extension in &self.extensions {
10✔
1972
            ctx.write_all(b" ")?;
4✔
1973
            body_extension.encode_ctx(ctx)?;
4✔
1974
        }
1975

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

1980
impl EncodeIntoContext for BodyExtension<'_> {
1981
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1982
        match self {
6✔
1983
            BodyExtension::NString(nstring) => nstring.encode_ctx(ctx),
×
1984
            BodyExtension::Number(number) => number.encode_ctx(ctx),
4✔
1985
            BodyExtension::List(list) => {
2✔
1986
                ctx.write_all(b"(")?;
2✔
1987
                join_serializable(list.as_ref(), b" ", ctx)?;
2✔
1988
                ctx.write_all(b")")
2✔
1989
            }
1990
        }
1991
    }
6✔
1992
}
1993

1994
impl EncodeIntoContext for ChronoDateTime<FixedOffset> {
1995
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
14✔
1996
        write!(ctx, "\"{}\"", self.format("%d-%b-%Y %H:%M:%S %z"))
14✔
1997
    }
14✔
1998
}
1999

2000
impl EncodeIntoContext for CommandContinuationRequest<'_> {
2001
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
2002
        match self {
8✔
2003
            Self::Basic(continue_basic) => match continue_basic.code() {
8✔
2004
                Some(code) => {
×
2005
                    ctx.write_all(b"+ [")?;
×
2006
                    code.encode_ctx(ctx)?;
×
2007
                    ctx.write_all(b"] ")?;
×
2008
                    continue_basic.text().encode_ctx(ctx)?;
×
2009
                    ctx.write_all(b"\r\n")
×
2010
                }
2011
                None => {
2012
                    ctx.write_all(b"+ ")?;
8✔
2013
                    continue_basic.text().encode_ctx(ctx)?;
8✔
2014
                    ctx.write_all(b"\r\n")
8✔
2015
                }
2016
            },
2017
            Self::Base64(data) => {
×
2018
                ctx.write_all(b"+ ")?;
×
2019
                ctx.write_all(base64.encode(data).as_bytes())?;
×
2020
                ctx.write_all(b"\r\n")
×
2021
            }
2022
        }
2023
    }
8✔
2024
}
2025

2026
pub(crate) mod utils {
2027
    use std::io::Write;
2028

2029
    use super::{EncodeContext, EncodeIntoContext};
2030

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

2033
    pub struct List1AttributeValueOrNil<'a, T>(pub &'a Vec<(T, T)>);
2034

2035
    pub(crate) fn join_serializable<I: EncodeIntoContext>(
914✔
2036
        elements: &[I],
914✔
2037
        sep: &[u8],
914✔
2038
        ctx: &mut EncodeContext,
914✔
2039
    ) -> std::io::Result<()> {
914✔
2040
        if let Some((last, head)) = elements.split_last() {
914✔
2041
            for item in head {
1,342✔
2042
                item.encode_ctx(ctx)?;
592✔
2043
                ctx.write_all(sep)?;
592✔
2044
            }
2045

2046
            last.encode_ctx(ctx)
750✔
2047
        } else {
2048
            Ok(())
164✔
2049
        }
2050
    }
914✔
2051

2052
    impl<T> EncodeIntoContext for List1OrNil<'_, T>
2053
    where
2054
        T: EncodeIntoContext,
2055
    {
2056
        fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
66✔
2057
            if let Some((last, head)) = self.0.split_last() {
66✔
2058
                ctx.write_all(b"(")?;
40✔
2059

2060
                for item in head {
48✔
2061
                    item.encode_ctx(ctx)?;
8✔
2062
                    ctx.write_all(self.1)?;
8✔
2063
                }
2064

2065
                last.encode_ctx(ctx)?;
40✔
2066

2067
                ctx.write_all(b")")
40✔
2068
            } else {
2069
                ctx.write_all(b"NIL")
26✔
2070
            }
2071
        }
66✔
2072
    }
2073

2074
    impl<T> EncodeIntoContext for List1AttributeValueOrNil<'_, T>
2075
    where
2076
        T: EncodeIntoContext,
2077
    {
2078
        fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
20✔
2079
            if let Some((last, head)) = self.0.split_last() {
20✔
2080
                ctx.write_all(b"(")?;
8✔
2081

2082
                for (attribute, value) in head {
8✔
2083
                    attribute.encode_ctx(ctx)?;
×
2084
                    ctx.write_all(b" ")?;
×
2085
                    value.encode_ctx(ctx)?;
×
2086
                    ctx.write_all(b" ")?;
×
2087
                }
2088

2089
                let (attribute, value) = last;
8✔
2090
                attribute.encode_ctx(ctx)?;
8✔
2091
                ctx.write_all(b" ")?;
8✔
2092
                value.encode_ctx(ctx)?;
8✔
2093

2094
                ctx.write_all(b")")
8✔
2095
            } else {
2096
                ctx.write_all(b"NIL")
12✔
2097
            }
2098
        }
20✔
2099
    }
2100
}
2101

2102
#[cfg(test)]
2103
mod tests {
2104
    use std::num::NonZeroU32;
2105

2106
    use imap_types::{
2107
        auth::AuthMechanism,
2108
        command::{Command, CommandBody},
2109
        core::{AString, Literal, NString, Vec1},
2110
        fetch::MessageDataItem,
2111
        response::{Data, Response},
2112
        utils::escape_byte_string,
2113
    };
2114

2115
    use super::*;
2116

2117
    #[test]
2118
    fn test_api_encoder_usage() {
2✔
2119
        let cmd = Command::new(
2✔
2120
            "A",
2✔
2121
            CommandBody::login(
2✔
2122
                AString::from(Literal::unvalidated_non_sync(b"alice".as_ref())),
2✔
2123
                "password",
2✔
2124
            )
2✔
2125
            .unwrap(),
2✔
2126
        )
2✔
2127
        .unwrap();
2✔
2128

2✔
2129
        // Dump.
2✔
2130
        let got_encoded = CommandCodec::default().encode(&cmd).dump();
2✔
2131

2✔
2132
        // Encoded.
2✔
2133
        let encoded = CommandCodec::default().encode(&cmd);
2✔
2134

2✔
2135
        let mut out = Vec::new();
2✔
2136

2137
        for x in encoded {
8✔
2138
            match x {
6✔
2139
                Fragment::Line { data } => {
4✔
2140
                    println!("C: {}", escape_byte_string(&data));
4✔
2141
                    out.extend_from_slice(&data);
4✔
2142
                }
4✔
2143
                Fragment::Literal { data, mode } => {
2✔
2144
                    match mode {
2✔
2145
                        LiteralMode::Sync => println!("C: <Waiting for continuation request>"),
×
2146
                        LiteralMode::NonSync => println!("C: <Skipped continuation request>"),
2✔
2147
                    }
2148

2149
                    println!("C: {}", escape_byte_string(&data));
2✔
2150
                    out.extend_from_slice(&data);
2✔
2151
                }
2152
            }
2153
        }
2154

2155
        assert_eq!(got_encoded, out);
2✔
2156
    }
2✔
2157

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

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

2282
    fn kat_encoder<'a, E, M, F>(tests: &'a [(M, F)])
4✔
2283
    where
4✔
2284
        E: Encoder<Message<'a> = M> + Default,
4✔
2285
        F: AsRef<[Fragment]>,
4✔
2286
    {
4✔
2287
        for (i, (obj, actions)) in tests.iter().enumerate() {
16✔
2288
            println!("# Testing {i}");
16✔
2289

16✔
2290
            let encoder = E::default().encode(obj);
16✔
2291
            let actions = actions.as_ref();
16✔
2292

16✔
2293
            assert_eq!(encoder.collect::<Vec<_>>(), actions);
16✔
2294
        }
2295
    }
4✔
2296
}
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