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

duesee / imap-codec / 12774391941

14 Jan 2025 06:49PM UTC coverage: 92.35% (-0.5%) from 92.896%
12774391941

Pull #631

github

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

143 of 225 new or added lines in 8 files covered. (63.56%)

2 existing lines in 2 files now uncovered.

11457 of 12406 relevant lines covered (92.35%)

894.45 hits per line

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

84.29
/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::SelectParameter;
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
                changed_since,
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 let Some(changed_since) = changed_since {
32✔
529
                    ctx.write_all(b" (CHANGEDSINCE ")?;
×
530
                    changed_since.encode_ctx(ctx)?;
×
531
                    ctx.write_all(b" ")?;
×
532
                }
32✔
533

534
                Ok(())
32✔
535
            }
536
            CommandBody::Store {
537
                sequence_set,
16✔
538
                kind,
16✔
539
                response,
16✔
540
                flags,
16✔
541
                uid,
16✔
542
                #[cfg(feature = "ext_condstore_qresync")]
16✔
543
                unchanged_since,
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 let Some(unchanged_since) = unchanged_since {
16✔
556
                    ctx.write_all(b"(UNCHANGEDSINCE ")?;
×
557
                    unchanged_since.encode_ctx(ctx)?;
×
558
                    ctx.write_all(b") ")?;
×
559
                }
16✔
560

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

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

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

574
                ctx.write_all(b" (")?;
16✔
575
                join_serializable(flags, b" ", ctx)?;
16✔
576
                ctx.write_all(b")")
16✔
577
            }
578
            CommandBody::Copy {
579
                sequence_set,
24✔
580
                mailbox,
24✔
581
                uid,
24✔
582
            } => {
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 SelectParameter {
NEW
709
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
NEW
710
        match self {
×
NEW
711
            SelectParameter::CondStore => write!(ctx, "CONDSTORE"),
×
712
            SelectParameter::QResync {
NEW
713
                uid_validity,
×
NEW
714
                mod_sequence_value,
×
NEW
715
                known_uids,
×
NEW
716
                seq_match_data,
×
NEW
717
            } => {
×
NEW
718
                write!(ctx, "QRESYNC (")?;
×
NEW
719
                uid_validity.encode_ctx(ctx)?;
×
NEW
720
                write!(ctx, " ")?;
×
NEW
721
                mod_sequence_value.encode_ctx(ctx)?;
×
722

NEW
723
                if let Some(known_uids) = known_uids {
×
NEW
724
                    write!(ctx, " ")?;
×
NEW
725
                    known_uids.encode_ctx(ctx)?;
×
NEW
726
                }
×
727

NEW
728
                if let Some((known_sequence_set, known_uid_set)) = seq_match_data {
×
NEW
729
                    write!(ctx, " (")?;
×
NEW
730
                    known_sequence_set.encode_ctx(ctx)?;
×
NEW
731
                    write!(ctx, " ")?;
×
NEW
732
                    known_uid_set.encode_ctx(ctx)?;
×
NEW
733
                    write!(ctx, ")")?;
×
NEW
734
                }
×
735

NEW
736
                write!(ctx, ")")
×
737
            }
738
        }
NEW
739
    }
×
740
}
741

742
impl EncodeIntoContext for AuthMechanism<'_> {
743
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
22✔
744
        write!(ctx, "{}", self)
22✔
745
    }
22✔
746
}
747

748
impl EncodeIntoContext for AuthenticateData<'_> {
749
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
750
        match self {
8✔
751
            Self::Continue(data) => {
6✔
752
                let encoded = base64.encode(data.declassify());
6✔
753
                ctx.write_all(encoded.as_bytes())?;
6✔
754
                ctx.write_all(b"\r\n")
6✔
755
            }
756
            Self::Cancel => ctx.write_all(b"*\r\n"),
2✔
757
        }
758
    }
8✔
759
}
760

761
impl EncodeIntoContext for AString<'_> {
762
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
792✔
763
        match self {
792✔
764
            AString::Atom(atom) => atom.encode_ctx(ctx),
580✔
765
            AString::String(imap_str) => imap_str.encode_ctx(ctx),
212✔
766
        }
767
    }
792✔
768
}
769

770
impl EncodeIntoContext for Atom<'_> {
771
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
54✔
772
        ctx.write_all(self.inner().as_bytes())
54✔
773
    }
54✔
774
}
775

776
impl EncodeIntoContext for AtomExt<'_> {
777
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
580✔
778
        ctx.write_all(self.inner().as_bytes())
580✔
779
    }
580✔
780
}
781

782
impl EncodeIntoContext for IString<'_> {
783
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
516✔
784
        match self {
516✔
785
            Self::Literal(val) => val.encode_ctx(ctx),
44✔
786
            Self::Quoted(val) => val.encode_ctx(ctx),
472✔
787
        }
788
    }
516✔
789
}
790

791
impl EncodeIntoContext for Literal<'_> {
792
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
44✔
793
        match self.mode() {
44✔
794
            LiteralMode::Sync => write!(ctx, "{{{}}}\r\n", self.as_ref().len())?,
30✔
795
            LiteralMode::NonSync => write!(ctx, "{{{}+}}\r\n", self.as_ref().len())?,
14✔
796
        }
797

798
        ctx.push_line();
44✔
799
        ctx.write_all(self.as_ref())?;
44✔
800
        ctx.push_literal(self.mode());
44✔
801

44✔
802
        Ok(())
44✔
803
    }
44✔
804
}
805

806
impl EncodeIntoContext for Quoted<'_> {
807
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
480✔
808
        write!(ctx, "\"{}\"", escape_quoted(self.inner()))
480✔
809
    }
480✔
810
}
811

812
impl EncodeIntoContext for Mailbox<'_> {
813
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
616✔
814
        match self {
616✔
815
            Mailbox::Inbox => ctx.write_all(b"INBOX"),
80✔
816
            Mailbox::Other(other) => other.encode_ctx(ctx),
536✔
817
        }
818
    }
616✔
819
}
820

821
impl EncodeIntoContext for MailboxOther<'_> {
822
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
536✔
823
        self.inner().encode_ctx(ctx)
536✔
824
    }
536✔
825
}
826

827
impl EncodeIntoContext for ListMailbox<'_> {
828
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
120✔
829
        match self {
120✔
830
            ListMailbox::Token(lcs) => lcs.encode_ctx(ctx),
80✔
831
            ListMailbox::String(istr) => istr.encode_ctx(ctx),
40✔
832
        }
833
    }
120✔
834
}
835

836
impl EncodeIntoContext for ListCharString<'_> {
837
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
80✔
838
        ctx.write_all(self.as_ref())
80✔
839
    }
80✔
840
}
841

842
impl EncodeIntoContext for StatusDataItemName {
843
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
36✔
844
        match self {
36✔
845
            Self::Messages => ctx.write_all(b"MESSAGES"),
12✔
846
            Self::Recent => ctx.write_all(b"RECENT"),
2✔
847
            Self::UidNext => ctx.write_all(b"UIDNEXT"),
10✔
848
            Self::UidValidity => ctx.write_all(b"UIDVALIDITY"),
2✔
849
            Self::Unseen => ctx.write_all(b"UNSEEN"),
2✔
850
            Self::Deleted => ctx.write_all(b"DELETED"),
4✔
851
            Self::DeletedStorage => ctx.write_all(b"DELETED-STORAGE"),
4✔
852
            #[cfg(feature = "ext_condstore_qresync")]
853
            Self::HighestModSeq => ctx.write_all(b"HIGHESTMODSEQ"),
×
854
        }
855
    }
36✔
856
}
857

858
impl EncodeIntoContext for Flag<'_> {
859
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
312✔
860
        write!(ctx, "{}", self)
312✔
861
    }
312✔
862
}
863

864
impl EncodeIntoContext for FlagFetch<'_> {
865
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
120✔
866
        match self {
120✔
867
            Self::Flag(flag) => flag.encode_ctx(ctx),
120✔
868
            Self::Recent => ctx.write_all(b"\\Recent"),
×
869
        }
870
    }
120✔
871
}
872

873
impl EncodeIntoContext for FlagPerm<'_> {
874
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
24✔
875
        match self {
24✔
876
            Self::Flag(flag) => flag.encode_ctx(ctx),
16✔
877
            Self::Asterisk => ctx.write_all(b"\\*"),
8✔
878
        }
879
    }
24✔
880
}
881

882
impl EncodeIntoContext for DateTime {
883
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
14✔
884
        self.as_ref().encode_ctx(ctx)
14✔
885
    }
14✔
886
}
887

888
impl EncodeIntoContext for Charset<'_> {
889
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
58✔
890
        match self {
58✔
891
            Charset::Atom(atom) => atom.encode_ctx(ctx),
50✔
892
            Charset::Quoted(quoted) => quoted.encode_ctx(ctx),
8✔
893
        }
894
    }
58✔
895
}
896

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

1006
impl EncodeIntoContext for SequenceSet {
1007
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
88✔
1008
        join_serializable(self.0.as_ref(), b",", ctx)
88✔
1009
    }
88✔
1010
}
1011

1012
impl EncodeIntoContext for Sequence {
1013
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
94✔
1014
        match self {
94✔
1015
            Sequence::Single(seq_no) => seq_no.encode_ctx(ctx),
38✔
1016
            Sequence::Range(from, to) => {
56✔
1017
                from.encode_ctx(ctx)?;
56✔
1018
                ctx.write_all(b":")?;
56✔
1019
                to.encode_ctx(ctx)
56✔
1020
            }
1021
        }
1022
    }
94✔
1023
}
1024

1025
impl EncodeIntoContext for SeqOrUid {
1026
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
150✔
1027
        match self {
150✔
1028
            SeqOrUid::Value(number) => write!(ctx, "{number}"),
140✔
1029
            SeqOrUid::Asterisk => ctx.write_all(b"*"),
10✔
1030
        }
1031
    }
150✔
1032
}
1033

1034
impl EncodeIntoContext for NaiveDate {
1035
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
44✔
1036
        write!(ctx, "\"{}\"", self.as_ref().format("%d-%b-%Y"))
44✔
1037
    }
44✔
1038
}
1039

1040
impl EncodeIntoContext for MacroOrMessageDataItemNames<'_> {
1041
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
32✔
1042
        match self {
32✔
1043
            Self::Macro(m) => m.encode_ctx(ctx),
8✔
1044
            Self::MessageDataItemNames(item_names) => {
24✔
1045
                if item_names.len() == 1 {
24✔
1046
                    item_names[0].encode_ctx(ctx)
16✔
1047
                } else {
1048
                    ctx.write_all(b"(")?;
8✔
1049
                    join_serializable(item_names.as_slice(), b" ", ctx)?;
8✔
1050
                    ctx.write_all(b")")
8✔
1051
                }
1052
            }
1053
        }
1054
    }
32✔
1055
}
1056

1057
impl EncodeIntoContext for Macro {
1058
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
1059
        write!(ctx, "{}", self)
8✔
1060
    }
8✔
1061
}
1062

1063
impl EncodeIntoContext for MessageDataItemName<'_> {
1064
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
54✔
1065
        match self {
54✔
1066
            Self::Body => ctx.write_all(b"BODY"),
2✔
1067
            Self::BodyExt {
18✔
1068
                section,
18✔
1069
                partial,
18✔
1070
                peek,
18✔
1071
            } => {
18✔
1072
                if *peek {
18✔
1073
                    ctx.write_all(b"BODY.PEEK[")?;
×
1074
                } else {
1075
                    ctx.write_all(b"BODY[")?;
18✔
1076
                }
1077
                if let Some(section) = section {
18✔
1078
                    section.encode_ctx(ctx)?;
16✔
1079
                }
2✔
1080
                ctx.write_all(b"]")?;
18✔
1081
                if let Some((a, b)) = partial {
18✔
1082
                    write!(ctx, "<{a}.{b}>")?;
×
1083
                }
18✔
1084

1085
                Ok(())
18✔
1086
            }
1087
            Self::BodyStructure => ctx.write_all(b"BODYSTRUCTURE"),
2✔
1088
            Self::Envelope => ctx.write_all(b"ENVELOPE"),
2✔
1089
            Self::Flags => ctx.write_all(b"FLAGS"),
18✔
1090
            Self::InternalDate => ctx.write_all(b"INTERNALDATE"),
2✔
1091
            Self::Rfc822 => ctx.write_all(b"RFC822"),
2✔
1092
            Self::Rfc822Header => ctx.write_all(b"RFC822.HEADER"),
2✔
1093
            Self::Rfc822Size => ctx.write_all(b"RFC822.SIZE"),
2✔
1094
            Self::Rfc822Text => ctx.write_all(b"RFC822.TEXT"),
2✔
1095
            Self::Uid => ctx.write_all(b"UID"),
2✔
1096
            MessageDataItemName::Binary {
1097
                section,
×
1098
                partial,
×
1099
                peek,
×
1100
            } => {
×
1101
                ctx.write_all(b"BINARY")?;
×
1102
                if *peek {
×
1103
                    ctx.write_all(b".PEEK")?;
×
1104
                }
×
1105

1106
                ctx.write_all(b"[")?;
×
1107
                join_serializable(section, b".", ctx)?;
×
1108
                ctx.write_all(b"]")?;
×
1109

1110
                if let Some((a, b)) = partial {
×
1111
                    ctx.write_all(b"<")?;
×
1112
                    a.encode_ctx(ctx)?;
×
1113
                    ctx.write_all(b".")?;
×
1114
                    b.encode_ctx(ctx)?;
×
1115
                    ctx.write_all(b">")?;
×
1116
                }
×
1117

1118
                Ok(())
×
1119
            }
1120
            MessageDataItemName::BinarySize { section } => {
×
1121
                ctx.write_all(b"BINARY.SIZE")?;
×
1122

1123
                ctx.write_all(b"[")?;
×
1124
                join_serializable(section, b".", ctx)?;
×
1125
                ctx.write_all(b"]")
×
1126
            }
1127
            #[cfg(feature = "ext_condstore_qresync")]
1128
            MessageDataItemName::ModSeq => ctx.write_all(b"MODSEQ"),
×
1129
        }
1130
    }
54✔
1131
}
1132

1133
impl EncodeIntoContext for Section<'_> {
1134
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
44✔
1135
        match self {
44✔
1136
            Section::Part(part) => part.encode_ctx(ctx),
2✔
1137
            Section::Header(maybe_part) => match maybe_part {
20✔
1138
                Some(part) => {
2✔
1139
                    part.encode_ctx(ctx)?;
2✔
1140
                    ctx.write_all(b".HEADER")
2✔
1141
                }
1142
                None => ctx.write_all(b"HEADER"),
18✔
1143
            },
1144
            Section::HeaderFields(maybe_part, header_list) => {
12✔
1145
                match maybe_part {
12✔
1146
                    Some(part) => {
2✔
1147
                        part.encode_ctx(ctx)?;
2✔
1148
                        ctx.write_all(b".HEADER.FIELDS (")?;
2✔
1149
                    }
1150
                    None => ctx.write_all(b"HEADER.FIELDS (")?,
10✔
1151
                };
1152
                join_serializable(header_list.as_ref(), b" ", ctx)?;
12✔
1153
                ctx.write_all(b")")
12✔
1154
            }
1155
            Section::HeaderFieldsNot(maybe_part, header_list) => {
4✔
1156
                match maybe_part {
4✔
1157
                    Some(part) => {
2✔
1158
                        part.encode_ctx(ctx)?;
2✔
1159
                        ctx.write_all(b".HEADER.FIELDS.NOT (")?;
2✔
1160
                    }
1161
                    None => ctx.write_all(b"HEADER.FIELDS.NOT (")?,
2✔
1162
                };
1163
                join_serializable(header_list.as_ref(), b" ", ctx)?;
4✔
1164
                ctx.write_all(b")")
4✔
1165
            }
1166
            Section::Text(maybe_part) => match maybe_part {
4✔
1167
                Some(part) => {
2✔
1168
                    part.encode_ctx(ctx)?;
2✔
1169
                    ctx.write_all(b".TEXT")
2✔
1170
                }
1171
                None => ctx.write_all(b"TEXT"),
2✔
1172
            },
1173
            Section::Mime(part) => {
2✔
1174
                part.encode_ctx(ctx)?;
2✔
1175
                ctx.write_all(b".MIME")
2✔
1176
            }
1177
        }
1178
    }
44✔
1179
}
1180

1181
impl EncodeIntoContext for Part {
1182
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
12✔
1183
        join_serializable(self.0.as_ref(), b".", ctx)
12✔
1184
    }
12✔
1185
}
1186

1187
impl EncodeIntoContext for NonZeroU32 {
1188
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
246✔
1189
        write!(ctx, "{self}")
246✔
1190
    }
246✔
1191
}
1192

1193
#[cfg(feature = "ext_condstore_qresync")]
1194
impl EncodeIntoContext for NonZeroU64 {
1195
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
1196
        write!(ctx, "{self}")
×
1197
    }
×
1198
}
1199

1200
impl EncodeIntoContext for Capability<'_> {
1201
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
232✔
1202
        write!(ctx, "{}", self)
232✔
1203
    }
232✔
1204
}
1205

1206
// ----- Responses ---------------------------------------------------------------------------------
1207

1208
impl EncodeIntoContext for Response<'_> {
1209
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
1,548✔
1210
        match self {
1,548✔
1211
            Response::Status(status) => status.encode_ctx(ctx),
824✔
1212
            Response::Data(data) => data.encode_ctx(ctx),
716✔
1213
            Response::CommandContinuationRequest(continue_request) => {
8✔
1214
                continue_request.encode_ctx(ctx)
8✔
1215
            }
1216
        }
1217
    }
1,548✔
1218
}
1219

1220
impl EncodeIntoContext for Greeting<'_> {
1221
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
26✔
1222
        ctx.write_all(b"* ")?;
26✔
1223
        self.kind.encode_ctx(ctx)?;
26✔
1224
        ctx.write_all(b" ")?;
26✔
1225

1226
        if let Some(ref code) = self.code {
26✔
1227
            ctx.write_all(b"[")?;
12✔
1228
            code.encode_ctx(ctx)?;
12✔
1229
            ctx.write_all(b"] ")?;
12✔
1230
        }
14✔
1231

1232
        self.text.encode_ctx(ctx)?;
26✔
1233
        ctx.write_all(b"\r\n")
26✔
1234
    }
26✔
1235
}
1236

1237
impl EncodeIntoContext for GreetingKind {
1238
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
26✔
1239
        match self {
26✔
1240
            GreetingKind::Ok => ctx.write_all(b"OK"),
12✔
1241
            GreetingKind::PreAuth => ctx.write_all(b"PREAUTH"),
12✔
1242
            GreetingKind::Bye => ctx.write_all(b"BYE"),
2✔
1243
        }
1244
    }
26✔
1245
}
1246

1247
impl EncodeIntoContext for Status<'_> {
1248
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
824✔
1249
        fn format_status(
824✔
1250
            tag: Option<&Tag>,
824✔
1251
            status: &str,
824✔
1252
            code: &Option<Code>,
824✔
1253
            comment: &Text,
824✔
1254
            ctx: &mut EncodeContext,
824✔
1255
        ) -> std::io::Result<()> {
824✔
1256
            match tag {
824✔
1257
                Some(tag) => tag.encode_ctx(ctx)?,
606✔
1258
                None => ctx.write_all(b"*")?,
218✔
1259
            }
1260
            ctx.write_all(b" ")?;
824✔
1261
            ctx.write_all(status.as_bytes())?;
824✔
1262
            ctx.write_all(b" ")?;
824✔
1263
            if let Some(code) = code {
824✔
1264
                ctx.write_all(b"[")?;
148✔
1265
                code.encode_ctx(ctx)?;
148✔
1266
                ctx.write_all(b"] ")?;
148✔
1267
            }
676✔
1268
            comment.encode_ctx(ctx)?;
824✔
1269
            ctx.write_all(b"\r\n")
824✔
1270
        }
824✔
1271

1272
        match self {
824✔
1273
            Self::Untagged(StatusBody { kind, code, text }) => match kind {
192✔
1274
                StatusKind::Ok => format_status(None, "OK", code, text, ctx),
134✔
1275
                StatusKind::No => format_status(None, "NO", code, text, ctx),
30✔
1276
                StatusKind::Bad => format_status(None, "BAD", code, text, ctx),
28✔
1277
            },
1278
            Self::Tagged(Tagged {
606✔
1279
                tag,
606✔
1280
                body: StatusBody { kind, code, text },
606✔
1281
            }) => match kind {
606✔
1282
                StatusKind::Ok => format_status(Some(tag), "OK", code, text, ctx),
572✔
1283
                StatusKind::No => format_status(Some(tag), "NO", code, text, ctx),
22✔
1284
                StatusKind::Bad => format_status(Some(tag), "BAD", code, text, ctx),
12✔
1285
            },
1286
            Self::Bye(Bye { code, text }) => format_status(None, "BYE", code, text, ctx),
26✔
1287
        }
1288
    }
824✔
1289
}
1290

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

1383
impl EncodeIntoContext for CodeOther<'_> {
1384
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
1385
        ctx.write_all(self.inner())
×
1386
    }
×
1387
}
1388

1389
impl EncodeIntoContext for Text<'_> {
1390
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
858✔
1391
        ctx.write_all(self.inner().as_bytes())
858✔
1392
    }
858✔
1393
}
1394

1395
impl EncodeIntoContext for Data<'_> {
1396
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
716✔
1397
        match self {
716✔
1398
            Data::Capability(caps) => {
64✔
1399
                ctx.write_all(b"* CAPABILITY ")?;
64✔
1400
                join_serializable(caps.as_ref(), b" ", ctx)?;
64✔
1401
            }
1402
            Data::List {
1403
                items,
210✔
1404
                delimiter,
210✔
1405
                mailbox,
210✔
1406
            } => {
210✔
1407
                ctx.write_all(b"* LIST (")?;
210✔
1408
                join_serializable(items, b" ", ctx)?;
210✔
1409
                ctx.write_all(b") ")?;
210✔
1410

1411
                if let Some(delimiter) = delimiter {
210✔
1412
                    ctx.write_all(b"\"")?;
210✔
1413
                    delimiter.encode_ctx(ctx)?;
210✔
1414
                    ctx.write_all(b"\"")?;
210✔
1415
                } else {
1416
                    ctx.write_all(b"NIL")?;
×
1417
                }
1418
                ctx.write_all(b" ")?;
210✔
1419
                mailbox.encode_ctx(ctx)?;
210✔
1420
            }
1421
            Data::Lsub {
1422
                items,
32✔
1423
                delimiter,
32✔
1424
                mailbox,
32✔
1425
            } => {
32✔
1426
                ctx.write_all(b"* LSUB (")?;
32✔
1427
                join_serializable(items, b" ", ctx)?;
32✔
1428
                ctx.write_all(b") ")?;
32✔
1429

1430
                if let Some(delimiter) = delimiter {
32✔
1431
                    ctx.write_all(b"\"")?;
32✔
1432
                    delimiter.encode_ctx(ctx)?;
32✔
1433
                    ctx.write_all(b"\"")?;
32✔
1434
                } else {
1435
                    ctx.write_all(b"NIL")?;
×
1436
                }
1437
                ctx.write_all(b" ")?;
32✔
1438
                mailbox.encode_ctx(ctx)?;
32✔
1439
            }
1440
            Data::Status { mailbox, items } => {
18✔
1441
                ctx.write_all(b"* STATUS ")?;
18✔
1442
                mailbox.encode_ctx(ctx)?;
18✔
1443
                ctx.write_all(b" (")?;
18✔
1444
                join_serializable(items, b" ", ctx)?;
18✔
1445
                ctx.write_all(b")")?;
18✔
1446
            }
1447
            // TODO: Exclude pattern via cfg?
1448
            #[cfg(not(feature = "ext_condstore_qresync"))]
1449
            Data::Search(seqs) => {
1450
                if seqs.is_empty() {
1451
                    ctx.write_all(b"* SEARCH")?;
1452
                } else {
1453
                    ctx.write_all(b"* SEARCH ")?;
1454
                    join_serializable(seqs, b" ", ctx)?;
1455
                }
1456
            }
1457
            // TODO: Exclude pattern via cfg?
1458
            #[cfg(feature = "ext_condstore_qresync")]
1459
            Data::Search(seqs, modseq) => {
38✔
1460
                if seqs.is_empty() {
38✔
1461
                    ctx.write_all(b"* SEARCH")?;
8✔
1462
                } else {
1463
                    ctx.write_all(b"* SEARCH ")?;
30✔
1464
                    join_serializable(seqs, b" ", ctx)?;
30✔
1465
                }
1466

1467
                if let Some(modseq) = modseq {
38✔
NEW
1468
                    ctx.write_all(b" (MODSEQ ")?;
×
NEW
1469
                    modseq.encode_ctx(ctx)?;
×
NEW
1470
                    ctx.write_all(b")")?;
×
1471
                }
38✔
1472
            }
1473
            // TODO: Exclude pattern via cfg?
1474
            #[cfg(not(feature = "ext_condstore_qresync"))]
1475
            Data::Sort(seqs) => {
1476
                if seqs.is_empty() {
1477
                    ctx.write_all(b"* SORT")?;
1478
                } else {
1479
                    ctx.write_all(b"* SORT ")?;
1480
                    join_serializable(seqs, b" ", ctx)?;
1481
                }
1482
            }
1483
            // TODO: Exclude pattern via cfg?
1484
            #[cfg(feature = "ext_condstore_qresync")]
1485
            Data::Sort(seqs, modseq) => {
24✔
1486
                if seqs.is_empty() {
24✔
1487
                    ctx.write_all(b"* SORT")?;
8✔
1488
                } else {
1489
                    ctx.write_all(b"* SORT ")?;
16✔
1490
                    join_serializable(seqs, b" ", ctx)?;
16✔
1491
                }
1492

1493
                if let Some(modseq) = modseq {
24✔
NEW
1494
                    ctx.write_all(b" (MODSEQ ")?;
×
NEW
1495
                    modseq.encode_ctx(ctx)?;
×
NEW
1496
                    ctx.write_all(b")")?;
×
1497
                }
24✔
1498
            }
1499
            Data::Thread(threads) => {
24✔
1500
                if threads.is_empty() {
24✔
1501
                    ctx.write_all(b"* THREAD")?;
8✔
1502
                } else {
1503
                    ctx.write_all(b"* THREAD ")?;
16✔
1504
                    for thread in threads {
400✔
1505
                        thread.encode_ctx(ctx)?;
384✔
1506
                    }
1507
                }
1508
            }
1509
            Data::Flags(flags) => {
32✔
1510
                ctx.write_all(b"* FLAGS (")?;
32✔
1511
                join_serializable(flags, b" ", ctx)?;
32✔
1512
                ctx.write_all(b")")?;
32✔
1513
            }
1514
            Data::Exists(count) => write!(ctx, "* {count} EXISTS")?,
42✔
1515
            Data::Recent(count) => write!(ctx, "* {count} RECENT")?,
42✔
1516
            Data::Expunge(msg) => write!(ctx, "* {msg} EXPUNGE")?,
50✔
1517
            Data::Fetch { seq, items } => {
96✔
1518
                write!(ctx, "* {seq} FETCH (")?;
96✔
1519
                join_serializable(items.as_ref(), b" ", ctx)?;
96✔
1520
                ctx.write_all(b")")?;
96✔
1521
            }
1522
            Data::Enabled { capabilities } => {
16✔
1523
                write!(ctx, "* ENABLED")?;
16✔
1524

1525
                for cap in capabilities {
32✔
1526
                    ctx.write_all(b" ")?;
16✔
1527
                    cap.encode_ctx(ctx)?;
16✔
1528
                }
1529
            }
1530
            Data::Quota { root, quotas } => {
12✔
1531
                ctx.write_all(b"* QUOTA ")?;
12✔
1532
                root.encode_ctx(ctx)?;
12✔
1533
                ctx.write_all(b" (")?;
12✔
1534
                join_serializable(quotas.as_ref(), b" ", ctx)?;
12✔
1535
                ctx.write_all(b")")?;
12✔
1536
            }
1537
            Data::QuotaRoot { mailbox, roots } => {
10✔
1538
                ctx.write_all(b"* QUOTAROOT ")?;
10✔
1539
                mailbox.encode_ctx(ctx)?;
10✔
1540
                for root in roots {
20✔
1541
                    ctx.write_all(b" ")?;
10✔
1542
                    root.encode_ctx(ctx)?;
10✔
1543
                }
1544
            }
1545
            #[cfg(feature = "ext_id")]
1546
            Data::Id { parameters } => {
2✔
1547
                ctx.write_all(b"* ID ")?;
2✔
1548

1549
                match parameters {
2✔
1550
                    Some(parameters) => {
×
1551
                        if let Some((first, tail)) = parameters.split_first() {
×
1552
                            ctx.write_all(b"(")?;
×
1553

1554
                            first.0.encode_ctx(ctx)?;
×
1555
                            ctx.write_all(b" ")?;
×
1556
                            first.1.encode_ctx(ctx)?;
×
1557

1558
                            for parameter in tail {
×
1559
                                ctx.write_all(b" ")?;
×
1560
                                parameter.0.encode_ctx(ctx)?;
×
1561
                                ctx.write_all(b" ")?;
×
1562
                                parameter.1.encode_ctx(ctx)?;
×
1563
                            }
1564

1565
                            ctx.write_all(b")")?;
×
1566
                        } else {
1567
                            #[cfg(not(feature = "quirk_id_empty_to_nil"))]
1568
                            {
1569
                                ctx.write_all(b"()")?;
1570
                            }
1571
                            #[cfg(feature = "quirk_id_empty_to_nil")]
1572
                            {
1573
                                ctx.write_all(b"NIL")?;
×
1574
                            }
1575
                        }
1576
                    }
1577
                    None => {
1578
                        ctx.write_all(b"NIL")?;
2✔
1579
                    }
1580
                }
1581
            }
1582
            #[cfg(feature = "ext_metadata")]
1583
            Data::Metadata { mailbox, items } => {
4✔
1584
                ctx.write_all(b"* METADATA ")?;
4✔
1585
                mailbox.encode_ctx(ctx)?;
4✔
1586
                ctx.write_all(b" ")?;
4✔
1587
                items.encode_ctx(ctx)?;
4✔
1588
            }
1589
            #[cfg(feature = "ext_condstore_qresync")]
1590
            Data::Vanished {
NEW
1591
                earlier,
×
NEW
1592
                sequence_set,
×
NEW
1593
            } => {
×
NEW
1594
                ctx.write_all(b"* VANISHED")?;
×
NEW
1595
                if *earlier {
×
NEW
1596
                    ctx.write_all(b" (EARLIER)")?;
×
NEW
1597
                }
×
NEW
1598
                ctx.write_all(b" ")?;
×
NEW
1599
                sequence_set.encode_ctx(ctx)?;
×
1600
            }
1601
        }
1602

1603
        ctx.write_all(b"\r\n")
716✔
1604
    }
716✔
1605
}
1606

1607
impl EncodeIntoContext for FlagNameAttribute<'_> {
1608
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
90✔
1609
        write!(ctx, "{}", self)
90✔
1610
    }
90✔
1611
}
1612

1613
impl EncodeIntoContext for QuotedChar {
1614
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
242✔
1615
        match self.inner() {
242✔
1616
            '\\' => ctx.write_all(b"\\\\"),
×
1617
            '"' => ctx.write_all(b"\\\""),
×
1618
            other => ctx.write_all(&[other as u8]),
242✔
1619
        }
1620
    }
242✔
1621
}
1622

1623
impl EncodeIntoContext for StatusDataItem {
1624
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
52✔
1625
        match self {
52✔
1626
            Self::Messages(count) => {
20✔
1627
                ctx.write_all(b"MESSAGES ")?;
20✔
1628
                count.encode_ctx(ctx)
20✔
1629
            }
1630
            Self::Recent(count) => {
2✔
1631
                ctx.write_all(b"RECENT ")?;
2✔
1632
                count.encode_ctx(ctx)
2✔
1633
            }
1634
            Self::UidNext(next) => {
18✔
1635
                ctx.write_all(b"UIDNEXT ")?;
18✔
1636
                next.encode_ctx(ctx)
18✔
1637
            }
1638
            Self::UidValidity(identifier) => {
2✔
1639
                ctx.write_all(b"UIDVALIDITY ")?;
2✔
1640
                identifier.encode_ctx(ctx)
2✔
1641
            }
1642
            Self::Unseen(count) => {
2✔
1643
                ctx.write_all(b"UNSEEN ")?;
2✔
1644
                count.encode_ctx(ctx)
2✔
1645
            }
1646
            Self::Deleted(count) => {
4✔
1647
                ctx.write_all(b"DELETED ")?;
4✔
1648
                count.encode_ctx(ctx)
4✔
1649
            }
1650
            Self::DeletedStorage(count) => {
4✔
1651
                ctx.write_all(b"DELETED-STORAGE ")?;
4✔
1652
                count.encode_ctx(ctx)
4✔
1653
            }
1654
            #[cfg(feature = "ext_condstore_qresync")]
1655
            Self::HighestModSeq(value) => {
×
1656
                ctx.write_all(b"HIGHESTMODSEQ ")?;
×
1657
                value.encode_ctx(ctx)
×
1658
            }
1659
        }
1660
    }
52✔
1661
}
1662

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

1736
impl EncodeIntoContext for NString<'_> {
1737
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
318✔
1738
        match &self.0 {
318✔
1739
            Some(imap_str) => imap_str.encode_ctx(ctx),
188✔
1740
            None => ctx.write_all(b"NIL"),
130✔
1741
        }
1742
    }
318✔
1743
}
1744

1745
impl EncodeIntoContext for NString8<'_> {
1746
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
1747
        match self {
8✔
1748
            NString8::NString(nstring) => nstring.encode_ctx(ctx),
6✔
1749
            NString8::Literal8(literal8) => literal8.encode_ctx(ctx),
2✔
1750
        }
1751
    }
8✔
1752
}
1753

1754
impl EncodeIntoContext for BodyStructure<'_> {
1755
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
32✔
1756
        ctx.write_all(b"(")?;
32✔
1757
        match self {
32✔
1758
            BodyStructure::Single {
1759
                body,
20✔
1760
                extension_data: extension,
20✔
1761
            } => {
20✔
1762
                body.encode_ctx(ctx)?;
20✔
1763
                if let Some(extension) = extension {
20✔
1764
                    ctx.write_all(b" ")?;
4✔
1765
                    extension.encode_ctx(ctx)?;
4✔
1766
                }
16✔
1767
            }
1768
            BodyStructure::Multi {
1769
                bodies,
12✔
1770
                subtype,
12✔
1771
                extension_data,
12✔
1772
            } => {
1773
                for body in bodies.as_ref() {
12✔
1774
                    body.encode_ctx(ctx)?;
12✔
1775
                }
1776
                ctx.write_all(b" ")?;
12✔
1777
                subtype.encode_ctx(ctx)?;
12✔
1778

1779
                if let Some(extension) = extension_data {
12✔
1780
                    ctx.write_all(b" ")?;
×
1781
                    extension.encode_ctx(ctx)?;
×
1782
                }
12✔
1783
            }
1784
        }
1785
        ctx.write_all(b")")
32✔
1786
    }
32✔
1787
}
1788

1789
impl EncodeIntoContext for Body<'_> {
1790
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
20✔
1791
        match self.specific {
20✔
1792
            SpecificFields::Basic {
1793
                r#type: ref type_,
4✔
1794
                ref subtype,
4✔
1795
            } => {
4✔
1796
                type_.encode_ctx(ctx)?;
4✔
1797
                ctx.write_all(b" ")?;
4✔
1798
                subtype.encode_ctx(ctx)?;
4✔
1799
                ctx.write_all(b" ")?;
4✔
1800
                self.basic.encode_ctx(ctx)
4✔
1801
            }
1802
            SpecificFields::Message {
1803
                ref envelope,
×
1804
                ref body_structure,
×
1805
                number_of_lines,
×
1806
            } => {
×
1807
                ctx.write_all(b"\"MESSAGE\" \"RFC822\" ")?;
×
1808
                self.basic.encode_ctx(ctx)?;
×
1809
                ctx.write_all(b" ")?;
×
1810
                envelope.encode_ctx(ctx)?;
×
1811
                ctx.write_all(b" ")?;
×
1812
                body_structure.encode_ctx(ctx)?;
×
1813
                ctx.write_all(b" ")?;
×
1814
                write!(ctx, "{number_of_lines}")
×
1815
            }
1816
            SpecificFields::Text {
1817
                ref subtype,
16✔
1818
                number_of_lines,
16✔
1819
            } => {
16✔
1820
                ctx.write_all(b"\"TEXT\" ")?;
16✔
1821
                subtype.encode_ctx(ctx)?;
16✔
1822
                ctx.write_all(b" ")?;
16✔
1823
                self.basic.encode_ctx(ctx)?;
16✔
1824
                ctx.write_all(b" ")?;
16✔
1825
                write!(ctx, "{number_of_lines}")
16✔
1826
            }
1827
        }
1828
    }
20✔
1829
}
1830

1831
impl EncodeIntoContext for BasicFields<'_> {
1832
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
20✔
1833
        List1AttributeValueOrNil(&self.parameter_list).encode_ctx(ctx)?;
20✔
1834
        ctx.write_all(b" ")?;
20✔
1835
        self.id.encode_ctx(ctx)?;
20✔
1836
        ctx.write_all(b" ")?;
20✔
1837
        self.description.encode_ctx(ctx)?;
20✔
1838
        ctx.write_all(b" ")?;
20✔
1839
        self.content_transfer_encoding.encode_ctx(ctx)?;
20✔
1840
        ctx.write_all(b" ")?;
20✔
1841
        write!(ctx, "{}", self.size)
20✔
1842
    }
20✔
1843
}
1844

1845
impl EncodeIntoContext for Envelope<'_> {
1846
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
10✔
1847
        ctx.write_all(b"(")?;
10✔
1848
        self.date.encode_ctx(ctx)?;
10✔
1849
        ctx.write_all(b" ")?;
10✔
1850
        self.subject.encode_ctx(ctx)?;
10✔
1851
        ctx.write_all(b" ")?;
10✔
1852
        List1OrNil(&self.from, b"").encode_ctx(ctx)?;
10✔
1853
        ctx.write_all(b" ")?;
10✔
1854
        List1OrNil(&self.sender, b"").encode_ctx(ctx)?;
10✔
1855
        ctx.write_all(b" ")?;
10✔
1856
        List1OrNil(&self.reply_to, b"").encode_ctx(ctx)?;
10✔
1857
        ctx.write_all(b" ")?;
10✔
1858
        List1OrNil(&self.to, b"").encode_ctx(ctx)?;
10✔
1859
        ctx.write_all(b" ")?;
10✔
1860
        List1OrNil(&self.cc, b"").encode_ctx(ctx)?;
10✔
1861
        ctx.write_all(b" ")?;
10✔
1862
        List1OrNil(&self.bcc, b"").encode_ctx(ctx)?;
10✔
1863
        ctx.write_all(b" ")?;
10✔
1864
        self.in_reply_to.encode_ctx(ctx)?;
10✔
1865
        ctx.write_all(b" ")?;
10✔
1866
        self.message_id.encode_ctx(ctx)?;
10✔
1867
        ctx.write_all(b")")
10✔
1868
    }
10✔
1869
}
1870

1871
impl EncodeIntoContext for Address<'_> {
1872
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
48✔
1873
        ctx.write_all(b"(")?;
48✔
1874
        self.name.encode_ctx(ctx)?;
48✔
1875
        ctx.write_all(b" ")?;
48✔
1876
        self.adl.encode_ctx(ctx)?;
48✔
1877
        ctx.write_all(b" ")?;
48✔
1878
        self.mailbox.encode_ctx(ctx)?;
48✔
1879
        ctx.write_all(b" ")?;
48✔
1880
        self.host.encode_ctx(ctx)?;
48✔
1881
        ctx.write_all(b")")?;
48✔
1882

1883
        Ok(())
48✔
1884
    }
48✔
1885
}
1886

1887
impl EncodeIntoContext for SinglePartExtensionData<'_> {
1888
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1889
        self.md5.encode_ctx(ctx)?;
6✔
1890

1891
        if let Some(disposition) = &self.tail {
6✔
1892
            ctx.write_all(b" ")?;
6✔
1893
            disposition.encode_ctx(ctx)?;
6✔
1894
        }
×
1895

1896
        Ok(())
6✔
1897
    }
6✔
1898
}
1899

1900
impl EncodeIntoContext for MultiPartExtensionData<'_> {
1901
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
×
1902
        List1AttributeValueOrNil(&self.parameter_list).encode_ctx(ctx)?;
×
1903

1904
        if let Some(disposition) = &self.tail {
×
1905
            ctx.write_all(b" ")?;
×
1906
            disposition.encode_ctx(ctx)?;
×
1907
        }
×
1908

1909
        Ok(())
×
1910
    }
×
1911
}
1912

1913
impl EncodeIntoContext for Disposition<'_> {
1914
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1915
        match &self.disposition {
6✔
1916
            Some((s, param)) => {
×
1917
                ctx.write_all(b"(")?;
×
1918
                s.encode_ctx(ctx)?;
×
1919
                ctx.write_all(b" ")?;
×
1920
                List1AttributeValueOrNil(param).encode_ctx(ctx)?;
×
1921
                ctx.write_all(b")")?;
×
1922
            }
1923
            None => ctx.write_all(b"NIL")?,
6✔
1924
        }
1925

1926
        if let Some(language) = &self.tail {
6✔
1927
            ctx.write_all(b" ")?;
6✔
1928
            language.encode_ctx(ctx)?;
6✔
1929
        }
×
1930

1931
        Ok(())
6✔
1932
    }
6✔
1933
}
1934

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

1939
        if let Some(location) = &self.tail {
6✔
1940
            ctx.write_all(b" ")?;
6✔
1941
            location.encode_ctx(ctx)?;
6✔
1942
        }
×
1943

1944
        Ok(())
6✔
1945
    }
6✔
1946
}
1947

1948
impl EncodeIntoContext for Location<'_> {
1949
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1950
        self.location.encode_ctx(ctx)?;
6✔
1951

1952
        for body_extension in &self.extensions {
10✔
1953
            ctx.write_all(b" ")?;
4✔
1954
            body_extension.encode_ctx(ctx)?;
4✔
1955
        }
1956

1957
        Ok(())
6✔
1958
    }
6✔
1959
}
1960

1961
impl EncodeIntoContext for BodyExtension<'_> {
1962
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
6✔
1963
        match self {
6✔
1964
            BodyExtension::NString(nstring) => nstring.encode_ctx(ctx),
×
1965
            BodyExtension::Number(number) => number.encode_ctx(ctx),
4✔
1966
            BodyExtension::List(list) => {
2✔
1967
                ctx.write_all(b"(")?;
2✔
1968
                join_serializable(list.as_ref(), b" ", ctx)?;
2✔
1969
                ctx.write_all(b")")
2✔
1970
            }
1971
        }
1972
    }
6✔
1973
}
1974

1975
impl EncodeIntoContext for ChronoDateTime<FixedOffset> {
1976
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
14✔
1977
        write!(ctx, "\"{}\"", self.format("%d-%b-%Y %H:%M:%S %z"))
14✔
1978
    }
14✔
1979
}
1980

1981
impl EncodeIntoContext for CommandContinuationRequest<'_> {
1982
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
8✔
1983
        match self {
8✔
1984
            Self::Basic(continue_basic) => match continue_basic.code() {
8✔
1985
                Some(code) => {
×
1986
                    ctx.write_all(b"+ [")?;
×
1987
                    code.encode_ctx(ctx)?;
×
1988
                    ctx.write_all(b"] ")?;
×
1989
                    continue_basic.text().encode_ctx(ctx)?;
×
1990
                    ctx.write_all(b"\r\n")
×
1991
                }
1992
                None => {
1993
                    ctx.write_all(b"+ ")?;
8✔
1994
                    continue_basic.text().encode_ctx(ctx)?;
8✔
1995
                    ctx.write_all(b"\r\n")
8✔
1996
                }
1997
            },
1998
            Self::Base64(data) => {
×
1999
                ctx.write_all(b"+ ")?;
×
2000
                ctx.write_all(base64.encode(data).as_bytes())?;
×
2001
                ctx.write_all(b"\r\n")
×
2002
            }
2003
        }
2004
    }
8✔
2005
}
2006

2007
pub(crate) mod utils {
2008
    use std::io::Write;
2009

2010
    use super::{EncodeContext, EncodeIntoContext};
2011

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

2014
    pub struct List1AttributeValueOrNil<'a, T>(pub &'a Vec<(T, T)>);
2015

2016
    pub(crate) fn join_serializable<I: EncodeIntoContext>(
914✔
2017
        elements: &[I],
914✔
2018
        sep: &[u8],
914✔
2019
        ctx: &mut EncodeContext,
914✔
2020
    ) -> std::io::Result<()> {
914✔
2021
        if let Some((last, head)) = elements.split_last() {
914✔
2022
            for item in head {
1,342✔
2023
                item.encode_ctx(ctx)?;
592✔
2024
                ctx.write_all(sep)?;
592✔
2025
            }
2026

2027
            last.encode_ctx(ctx)
750✔
2028
        } else {
2029
            Ok(())
164✔
2030
        }
2031
    }
914✔
2032

2033
    impl<T> EncodeIntoContext for List1OrNil<'_, T>
2034
    where
2035
        T: EncodeIntoContext,
2036
    {
2037
        fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
66✔
2038
            if let Some((last, head)) = self.0.split_last() {
66✔
2039
                ctx.write_all(b"(")?;
40✔
2040

2041
                for item in head {
48✔
2042
                    item.encode_ctx(ctx)?;
8✔
2043
                    ctx.write_all(self.1)?;
8✔
2044
                }
2045

2046
                last.encode_ctx(ctx)?;
40✔
2047

2048
                ctx.write_all(b")")
40✔
2049
            } else {
2050
                ctx.write_all(b"NIL")
26✔
2051
            }
2052
        }
66✔
2053
    }
2054

2055
    impl<T> EncodeIntoContext for List1AttributeValueOrNil<'_, T>
2056
    where
2057
        T: EncodeIntoContext,
2058
    {
2059
        fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
20✔
2060
            if let Some((last, head)) = self.0.split_last() {
20✔
2061
                ctx.write_all(b"(")?;
8✔
2062

2063
                for (attribute, value) in head {
8✔
2064
                    attribute.encode_ctx(ctx)?;
×
2065
                    ctx.write_all(b" ")?;
×
2066
                    value.encode_ctx(ctx)?;
×
2067
                    ctx.write_all(b" ")?;
×
2068
                }
2069

2070
                let (attribute, value) = last;
8✔
2071
                attribute.encode_ctx(ctx)?;
8✔
2072
                ctx.write_all(b" ")?;
8✔
2073
                value.encode_ctx(ctx)?;
8✔
2074

2075
                ctx.write_all(b")")
8✔
2076
            } else {
2077
                ctx.write_all(b"NIL")
12✔
2078
            }
2079
        }
20✔
2080
    }
2081
}
2082

2083
#[cfg(test)]
2084
mod tests {
2085
    use std::num::NonZeroU32;
2086

2087
    use imap_types::{
2088
        auth::AuthMechanism,
2089
        command::{Command, CommandBody},
2090
        core::{AString, Literal, NString, Vec1},
2091
        fetch::MessageDataItem,
2092
        response::{Data, Response},
2093
        utils::escape_byte_string,
2094
    };
2095

2096
    use super::*;
2097

2098
    #[test]
2099
    fn test_api_encoder_usage() {
2✔
2100
        let cmd = Command::new(
2✔
2101
            "A",
2✔
2102
            CommandBody::login(
2✔
2103
                AString::from(Literal::unvalidated_non_sync(b"alice".as_ref())),
2✔
2104
                "password",
2✔
2105
            )
2✔
2106
            .unwrap(),
2✔
2107
        )
2✔
2108
        .unwrap();
2✔
2109

2✔
2110
        // Dump.
2✔
2111
        let got_encoded = CommandCodec::default().encode(&cmd).dump();
2✔
2112

2✔
2113
        // Encoded.
2✔
2114
        let encoded = CommandCodec::default().encode(&cmd);
2✔
2115

2✔
2116
        let mut out = Vec::new();
2✔
2117

2118
        for x in encoded {
8✔
2119
            match x {
6✔
2120
                Fragment::Line { data } => {
4✔
2121
                    println!("C: {}", escape_byte_string(&data));
4✔
2122
                    out.extend_from_slice(&data);
4✔
2123
                }
4✔
2124
                Fragment::Literal { data, mode } => {
2✔
2125
                    match mode {
2✔
2126
                        LiteralMode::Sync => println!("C: <Waiting for continuation request>"),
×
2127
                        LiteralMode::NonSync => println!("C: <Skipped continuation request>"),
2✔
2128
                    }
2129

2130
                    println!("C: {}", escape_byte_string(&data));
2✔
2131
                    out.extend_from_slice(&data);
2✔
2132
                }
2133
            }
2134
        }
2135

2136
        assert_eq!(got_encoded, out);
2✔
2137
    }
2✔
2138

2139
    #[test]
2140
    fn test_encode_command() {
2✔
2141
        kat_encoder::<CommandCodec, Command<'_>, &[Fragment]>(&[
2✔
2142
            (
2✔
2143
                Command::new("A", CommandBody::login("alice", "pass").unwrap()).unwrap(),
2✔
2144
                [Fragment::Line {
2✔
2145
                    data: b"A LOGIN alice pass\r\n".to_vec(),
2✔
2146
                }]
2✔
2147
                .as_ref(),
2✔
2148
            ),
2✔
2149
            (
2✔
2150
                Command::new(
2✔
2151
                    "A",
2✔
2152
                    CommandBody::login("alice", b"\xCA\xFE".as_ref()).unwrap(),
2✔
2153
                )
2✔
2154
                .unwrap(),
2✔
2155
                [
2✔
2156
                    Fragment::Line {
2✔
2157
                        data: b"A LOGIN alice {2}\r\n".to_vec(),
2✔
2158
                    },
2✔
2159
                    Fragment::Literal {
2✔
2160
                        data: b"\xCA\xFE".to_vec(),
2✔
2161
                        mode: LiteralMode::Sync,
2✔
2162
                    },
2✔
2163
                    Fragment::Line {
2✔
2164
                        data: b"\r\n".to_vec(),
2✔
2165
                    },
2✔
2166
                ]
2✔
2167
                .as_ref(),
2✔
2168
            ),
2✔
2169
            (
2✔
2170
                Command::new("A", CommandBody::authenticate(AuthMechanism::Login)).unwrap(),
2✔
2171
                [Fragment::Line {
2✔
2172
                    data: b"A AUTHENTICATE LOGIN\r\n".to_vec(),
2✔
2173
                }]
2✔
2174
                .as_ref(),
2✔
2175
            ),
2✔
2176
            (
2✔
2177
                Command::new(
2✔
2178
                    "A",
2✔
2179
                    CommandBody::authenticate_with_ir(AuthMechanism::Login, b"alice".as_ref()),
2✔
2180
                )
2✔
2181
                .unwrap(),
2✔
2182
                [Fragment::Line {
2✔
2183
                    data: b"A AUTHENTICATE LOGIN YWxpY2U=\r\n".to_vec(),
2✔
2184
                }]
2✔
2185
                .as_ref(),
2✔
2186
            ),
2✔
2187
            (
2✔
2188
                Command::new("A", CommandBody::authenticate(AuthMechanism::Plain)).unwrap(),
2✔
2189
                [Fragment::Line {
2✔
2190
                    data: b"A AUTHENTICATE PLAIN\r\n".to_vec(),
2✔
2191
                }]
2✔
2192
                .as_ref(),
2✔
2193
            ),
2✔
2194
            (
2✔
2195
                Command::new(
2✔
2196
                    "A",
2✔
2197
                    CommandBody::authenticate_with_ir(
2✔
2198
                        AuthMechanism::Plain,
2✔
2199
                        b"\x00alice\x00pass".as_ref(),
2✔
2200
                    ),
2✔
2201
                )
2✔
2202
                .unwrap(),
2✔
2203
                [Fragment::Line {
2✔
2204
                    data: b"A AUTHENTICATE PLAIN AGFsaWNlAHBhc3M=\r\n".to_vec(),
2✔
2205
                }]
2✔
2206
                .as_ref(),
2✔
2207
            ),
2✔
2208
        ]);
2✔
2209
    }
2✔
2210

2211
    #[test]
2212
    fn test_encode_response() {
2✔
2213
        kat_encoder::<ResponseCodec, Response<'_>, &[Fragment]>(&[
2✔
2214
            (
2✔
2215
                Response::Data(Data::Fetch {
2✔
2216
                    seq: NonZeroU32::new(12345).unwrap(),
2✔
2217
                    items: Vec1::from(MessageDataItem::BodyExt {
2✔
2218
                        section: None,
2✔
2219
                        origin: None,
2✔
2220
                        data: NString::from(Literal::unvalidated(b"ABCDE".as_ref())),
2✔
2221
                    }),
2✔
2222
                }),
2✔
2223
                [
2✔
2224
                    Fragment::Line {
2✔
2225
                        data: b"* 12345 FETCH (BODY[] {5}\r\n".to_vec(),
2✔
2226
                    },
2✔
2227
                    Fragment::Literal {
2✔
2228
                        data: b"ABCDE".to_vec(),
2✔
2229
                        mode: LiteralMode::Sync,
2✔
2230
                    },
2✔
2231
                    Fragment::Line {
2✔
2232
                        data: b")\r\n".to_vec(),
2✔
2233
                    },
2✔
2234
                ]
2✔
2235
                .as_ref(),
2✔
2236
            ),
2✔
2237
            (
2✔
2238
                Response::Data(Data::Fetch {
2✔
2239
                    seq: NonZeroU32::new(12345).unwrap(),
2✔
2240
                    items: Vec1::from(MessageDataItem::BodyExt {
2✔
2241
                        section: None,
2✔
2242
                        origin: None,
2✔
2243
                        data: NString::from(Literal::unvalidated_non_sync(b"ABCDE".as_ref())),
2✔
2244
                    }),
2✔
2245
                }),
2✔
2246
                [
2✔
2247
                    Fragment::Line {
2✔
2248
                        data: b"* 12345 FETCH (BODY[] {5+}\r\n".to_vec(),
2✔
2249
                    },
2✔
2250
                    Fragment::Literal {
2✔
2251
                        data: b"ABCDE".to_vec(),
2✔
2252
                        mode: LiteralMode::NonSync,
2✔
2253
                    },
2✔
2254
                    Fragment::Line {
2✔
2255
                        data: b")\r\n".to_vec(),
2✔
2256
                    },
2✔
2257
                ]
2✔
2258
                .as_ref(),
2✔
2259
            ),
2✔
2260
        ])
2✔
2261
    }
2✔
2262

2263
    fn kat_encoder<'a, E, M, F>(tests: &'a [(M, F)])
4✔
2264
    where
4✔
2265
        E: Encoder<Message<'a> = M> + Default,
4✔
2266
        F: AsRef<[Fragment]>,
4✔
2267
    {
4✔
2268
        for (i, (obj, actions)) in tests.iter().enumerate() {
16✔
2269
            println!("# Testing {i}");
16✔
2270

16✔
2271
            let encoder = E::default().encode(obj);
16✔
2272
            let actions = actions.as_ref();
16✔
2273

16✔
2274
            assert_eq!(encoder.collect::<Vec<_>>(), actions);
16✔
2275
        }
2276
    }
4✔
2277
}
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