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

duesee / imap-codec / 12847606339

18 Jan 2025 09:32PM UTC coverage: 91.63% (-1.3%) from 92.896%
12847606339

push

github

duesee
feat: Implement missing CONDSTORE/QRESYNC functionality

179 of 364 new or added lines in 11 files covered. (49.18%)

3 existing lines in 3 files now uncovered.

11462 of 12509 relevant lines covered (91.63%)

886.75 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

215
        out
448✔
216
    }
448✔
217
}
218

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

801
impl EncodeIntoContext for IString<'_> {
802
    fn encode_ctx(&self, ctx: &mut EncodeContext) -> std::io::Result<()> {
516✔
803
        match self {
516✔
804
            Self::Literal(val) => val.encode_ctx(ctx),
44✔
805
            Self::Quoted(val) => val.encode_ctx(ctx),
472✔
806
        }
807
    }
516✔
808
}
809

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1235
// ----- Responses ---------------------------------------------------------------------------------
1236

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1632
        ctx.write_all(b"\r\n")
716✔
1633
    }
716✔
1634
}
1635

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

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

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

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

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

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

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

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

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

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

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

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

1912
        Ok(())
48✔
1913
    }
48✔
1914
}
1915

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

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

1925
        Ok(())
6✔
1926
    }
6✔
1927
}
1928

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

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

1938
        Ok(())
×
1939
    }
×
1940
}
1941

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

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

1960
        Ok(())
6✔
1961
    }
6✔
1962
}
1963

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

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

1973
        Ok(())
6✔
1974
    }
6✔
1975
}
1976

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

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

1986
        Ok(())
6✔
1987
    }
6✔
1988
}
1989

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

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

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

2036
pub(crate) mod utils {
2037
    use std::io::Write;
2038

2039
    use super::{EncodeContext, EncodeIntoContext};
2040

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

2043
    pub struct List1AttributeValueOrNil<'a, T>(pub &'a Vec<(T, T)>);
2044

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

2056
            last.encode_ctx(ctx)
750✔
2057
        } else {
2058
            Ok(())
164✔
2059
        }
2060
    }
914✔
2061

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

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

2075
                last.encode_ctx(ctx)?;
40✔
2076

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

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

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

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

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

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

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

2125
    use super::*;
2126

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

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

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

2✔
2145
        let mut out = Vec::new();
2✔
2146

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

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

2165
        assert_eq!(got_encoded, out);
2✔
2166
    }
2✔
2167

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

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

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

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

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

© 2025 Coveralls, Inc