parse-net 0.9.0

Grammar for Internet message fields: RFC 9110 field syntax, media types, RFC 9651 Structured Fields, HTTP and RFC 5322 dates, negotiation, entity tags, ranges, Content-Disposition, Cache-Control, Forwarded, auth challenges, and the email lexical layer. no_std, no allocation, sans-IO, zero dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! RFC 2047 encoded words in unstructured header text.

use crate::{
    class,
    error::{ErrorKind, ParseError, Result, WriteError, err},
    limits::Limits,
    utf8::Utf8,
    write::{CountSink, Sink, reserve},
};

/// The longest encoded word (RFC 2047 section 2).
const WORD_LIMIT: usize = 75;
/// `=?UTF-8?Q?` and `?=`.
const OVERHEAD: usize = 12;

/// Whether `b` is written as itself inside a Q-encoded word in a header
/// (RFC 2047 section 5, rule 3).
const fn q_plain(b: u8) -> bool {
    b.is_ascii_alphanumeric() || matches!(b, b'!' | b'*' | b'+' | b'-' | b'/')
}

/// The Q-encoded length of every byte: 1 for a byte written as itself or
/// as `_` (a space), 3 for `=XX`. One lookup instead of the class tests.
// Built at compile time; `b` runs over 0..256, the array's own bounds.
#[allow(clippy::indexing_slicing)]
const Q_LEN: [u8; 256] = {
    let mut t = [3u8; 256];
    let mut b = 0usize;
    while b < 256 {
        if q_plain(b as u8) || b == b' ' as usize {
            t[b] = 1;
        }
        b += 1;
    }
    t
};

/// The Q-encoded length of one byte.
#[inline]
fn q_byte_len(b: u8) -> usize {
    usize::from(Q_LEN.get(usize::from(b)).copied().unwrap_or(3))
}

/// The length in bytes of the UTF-8 character that starts with `b`.
const fn utf8_width(b: u8) -> usize {
    match b {
        0x00..=0x7f => 1,
        0xc0..=0xdf => 2,
        0xe0..=0xef => 3,
        _ => 4,
    }
}

/// The payload of one encoded word, built on the stack: at most 75 bytes
/// less the 12 of `=?UTF-8?Q?` and `?=`.
struct Payload {
    buf: [u8; WORD_LIMIT - OVERHEAD],
    len: usize,
}

impl Payload {
    /// Appends the Q encoding of `ch` (one UTF-8 character); the caller has
    /// checked that it fits.
    fn push(&mut self, ch: &[u8]) {
        const HEX: &[u8; 16] = b"0123456789ABCDEF";
        for &b in ch {
            let len = self.len;
            if q_byte_len(b) == 1 {
                if let Some(d) = self.buf.get_mut(len) {
                    *d = if b == b' ' { b'_' } else { b };
                }
                self.len = len + 1;
            } else {
                let hi = HEX.get(usize::from(b >> 4)).copied().unwrap_or(b'0');
                let lo = HEX.get(usize::from(b & 0xf)).copied().unwrap_or(b'0');
                if let Some([x, y, z]) = self.buf.get_mut(len..len + 3) {
                    (*x, *y, *z) = (b'=', hi, lo);
                }
                self.len = len + 3;
            }
        }
    }

    fn as_bytes(&self) -> &[u8] {
        self.buf.get(..self.len).unwrap_or(&[])
    }
}

fn put_words(
    text: &str,
    room_first_line: usize,
    out: &mut impl Sink,
) -> core::result::Result<(), WriteError> {
    let bytes = text.as_bytes();
    // Plain text goes out as it is while its line stays legal; past that it
    // is encoded, which breaks it into words.
    let used = super::SOFT_LIMIT.saturating_sub(room_first_line);
    if bytes.iter().all(|b| (0x20..=0x7e).contains(b))
        && !text.contains("=?")
        && used + bytes.len() <= super::HARD_LIMIT
    {
        out.put(bytes)?;
        return Ok(());
    }
    let mut limit = room_first_line.min(WORD_LIMIT);
    let mut word = Payload {
        buf: [0; WORD_LIMIT - OVERHEAD],
        len: 0,
    };
    let mut open = false;
    let mut i = 0usize;
    while let Some(&lead) = bytes.get(i) {
        let ch = bytes.get(i..i + utf8_width(lead)).unwrap_or(&[]);
        i += ch.len().max(1);
        let mut n = 0usize;
        for &b in ch {
            n += q_byte_len(b);
        }
        if open && OVERHEAD + word.len + n > limit {
            out.put(word.as_bytes())?;
            out.put(b"?=\r\n ")?;
            open = false;
            limit = WORD_LIMIT;
        }
        if !open {
            if OVERHEAD + n > limit {
                // Not even one character fits in the room left on the first
                // line: start on a new one.
                out.put(b"\r\n ")?;
                limit = WORD_LIMIT;
            }
            out.put(b"=?UTF-8?Q?")?;
            open = true;
            word.len = 0;
        }
        word.push(ch);
    }
    if open {
        out.put(word.as_bytes())?;
        out.put(b"?=")?;
    }
    Ok(())
}

/// Writes `text` for an unstructured header field: as it is when it is
/// printable ASCII without `=?` that fits in a 998-byte line, otherwise as
/// RFC 2047 `=?UTF-8?Q?...?=`
/// words of at most 75 bytes, split only between characters, separated by
/// CRLF SP. The first word fits in `room_first_line` (the columns left after
/// `Name: `); when not even one character fits there, the words start on a
/// new line.
///
/// # Errors
///
/// [`WriteError::Forbidden`] for a control character (C0, DEL, or C1);
/// [`WriteError::Full`] (nothing written when the sink reports its room).
///
/// # Examples
///
/// ```
/// use parse_net::{mail, SliceSink};
///
/// let mut buf = [0u8; 256];
/// let mut out = SliceSink::new(&mut buf);
/// mail::encode_words("Caf\u{e9} au lait", 64, &mut out).expect("room");
/// assert_eq!(out.written(), b"=?UTF-8?Q?Caf=C3=A9_au_lait?=");
/// ```
pub fn encode_words(
    text: &str,
    room_first_line: usize,
    out: &mut impl Sink,
) -> core::result::Result<(), WriteError> {
    if let Some((at, _)) = text.char_indices().find(|&(_, c)| c.is_control()) {
        return Err(WriteError::forbidden(at));
    }
    let mut count = CountSink::new();
    put_words(text, room_first_line, &mut count)?;
    reserve(out, count.count())?;
    put_words(text, room_first_line, out)
}

/// The charsets decoded.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Charset {
    Utf8,
    Ascii,
    Latin1,
}

/// The parts of an encoded word.
struct Encoded<'a> {
    charset: Charset,
    /// The `B` encoding.
    base64: bool,
    text: &'a [u8],
    /// The index after the closing `?=`.
    end: usize,
}

/// An encoded word at `v[i..]`: `=?charset?enc?text?=`, standing alone.
/// `Ok(None)` when the bytes do not have that shape, or do not stand between
/// whitespace: they are then ordinary text, whatever charset they name. Each
/// scan stops at the first byte that cannot continue, so failed candidates
/// never add up to a second pass over the value.
fn shape(v: &[u8], i: usize) -> Result<Option<Encoded<'_>>> {
    let rest = v.get(i + 2..).unwrap_or(&[]);
    let q1 = rest
        .iter()
        .position(|&b| !class::is_mime_token_char(b))
        .unwrap_or(rest.len());
    if q1 == 0 || rest.get(q1) != Some(&b'?') {
        return Ok(None);
    }
    let charset = rest.get(..q1).unwrap_or(&[]);
    let after = rest.get(q1 + 1..).unwrap_or(&[]);
    let (Some(&enc), Some(b'?')) = (after.first(), after.get(1)) else {
        return Ok(None);
    };
    let text_start = i + 2 + q1 + 3;
    let text_rest = v.get(text_start..).unwrap_or(&[]);
    let Some(end) = text_rest
        .iter()
        .position(|&b| matches!(b, b'?' | b' ' | b'\t'))
    else {
        return Ok(None);
    };
    if text_rest.get(end..end + 2) != Some(b"?=") {
        return Ok(None);
    }
    let text = text_rest.get(..end).unwrap_or(&[]);
    let after_word = text_start + end + 2;
    if after_word != v.len() && ws_len(v, after_word) == 0 {
        return Ok(None);
    }
    // RFC 2231 section 5: `charset*language`.
    let name = charset.split(|&b| b == b'*').next().unwrap_or(&[]);
    let cs = if name.eq_ignore_ascii_case(b"utf-8") {
        Charset::Utf8
    } else if name.eq_ignore_ascii_case(b"us-ascii") {
        Charset::Ascii
    } else if name.eq_ignore_ascii_case(b"iso-8859-1") {
        Charset::Latin1
    } else {
        return err(ErrorKind::UnsupportedCharset, i + 2);
    };
    let b = match enc {
        b'Q' | b'q' => false,
        b'B' | b'b' => true,
        _ => return err(ErrorKind::InvalidEncodedWord, i + 2 + q1 + 1),
    };
    Ok(Some(Encoded {
        charset: cs,
        base64: b,
        text,
        end: after_word,
    }))
}

/// The length of the whitespace unit at `v[i]`: SP, HTAB, or a `CRLF WSP`
/// fold; 0 for anything else.
fn ws_len(v: &[u8], i: usize) -> usize {
    match (v.get(i), v.get(i + 1), v.get(i + 2)) {
        (Some(b' ' | b'\t'), _, _) => 1,
        (Some(b'\r'), Some(b'\n'), Some(b' ' | b'\t')) => 3,
        _ => 0,
    }
}

/// The text outside encoded words, checked as it is copied: UTF-8 (raw bytes
/// above 0x7F are RFC 6532 text), with no control character but HTAB.
struct Text {
    utf8: Utf8,
    prev: u8,
}

impl Text {
    fn check(&mut self, b: u8, at: usize) -> Result<()> {
        if b != b'\t' && crate::scan::is_control(b) {
            return err(crate::scan::control_kind(b), at);
        }
        if self.prev == 0xc2 && (0x80..=0x9f).contains(&b) {
            return err(ErrorKind::Control, at);
        }
        if !self.utf8.push(b) {
            return err(ErrorKind::InvalidUtf8, at);
        }
        self.prev = b;
        Ok(())
    }

    /// Copies a whitespace run, leaving out the CRLF of its folds.
    fn run(&mut self, v: &[u8], s: usize, e: usize, emit: &mut impl FnMut(&[u8])) -> Result<()> {
        let mut i = s;
        while i < e {
            let n = ws_len(v, i);
            let at = i + n - 1;
            let wsp = v.get(at).copied().unwrap_or(b' ');
            self.check(wsp, at)?;
            emit(&[wsp]);
            i += n;
        }
        Ok(())
    }
}

/// The index of the `"` closing a quoted string whose body starts at `from`.
fn closing_quote(v: &[u8], from: usize) -> Option<usize> {
    let mut i = from;
    loop {
        match v.get(i)? {
            b'\\' => i += 2,
            b'"' => return Some(i),
            _ => i += 1,
        }
    }
}

/// Decodes one Q word's text, emitting UTF-8.
fn decode_q(cs: Charset, text: &[u8], at: usize, emit: &mut impl FnMut(&[u8])) -> Result<()> {
    let mut utf8 = Utf8::new();
    let (mut i, mut prev) = (0usize, 0u8);
    while let Some(&b) = text.get(i) {
        let start = at + i;
        let byte = match b {
            b'_' => b' ',
            b'=' => {
                let hi = text.get(i + 1).copied().and_then(class::hex_value);
                let lo = text.get(i + 2).copied().and_then(class::hex_value);
                let (Some(hi), Some(lo)) = (hi, lo) else {
                    return err(ErrorKind::InvalidEncodedWord, start);
                };
                i += 2;
                (hi << 4) | lo
            }
            0x21..=0x7e => b,
            _ => return err(ErrorKind::InvalidEncodedWord, start),
        };
        i += 1;
        // Every control character is refused, as in ext-values: C0 (HTAB
        // included), DEL, and C1 (U+0080 to U+009F: `C2 80` to `C2 9F` in
        // UTF-8, where 0xC2 is always a lead byte; bytes 0x80 to 0x9F in
        // ISO-8859-1).
        let c1 = match cs {
            Charset::Utf8 => prev == 0xc2 && (0x80..=0x9f).contains(&byte),
            Charset::Latin1 => (0x80..=0x9f).contains(&byte),
            Charset::Ascii => false,
        };
        if byte < 0x20 || byte == 0x7f || c1 {
            return err(ErrorKind::ControlInDecoded, start);
        }
        prev = byte;
        match cs {
            Charset::Utf8 => {
                if !utf8.push(byte) {
                    return err(ErrorKind::InvalidUtf8, start);
                }
                emit(&[byte]);
            }
            Charset::Ascii if byte >= 0x80 => {
                return err(ErrorKind::InvalidEncodedWord, start);
            }
            Charset::Ascii => emit(&[byte]),
            Charset::Latin1 if byte >= 0x80 => emit(&[0xc0 | (byte >> 6), 0x80 | (byte & 0x3f)]),
            Charset::Latin1 => emit(&[byte]),
        }
    }
    if !utf8.is_complete() {
        // Each encoded word holds whole characters (RFC 2047 section 5).
        return err(ErrorKind::InvalidUtf8, at + text.len());
    }
    Ok(())
}

/// Walks `v`, emitting the decoded text. Whitespace includes folds, whose
/// CRLF is dropped, so the folded output of [`encode_words`] reads back. A
/// quoted string starts at a word boundary and needs its closing `"`: a lone
/// `"` (`5" disk`) is ordinary text. One pass: every scan ahead either
/// consumes what it read or stops at the first byte that rules it out.
fn walk(v: &[u8], limits: &Limits, emit: &mut impl FnMut(&[u8])) -> Result<()> {
    let mut text = Text {
        utf8: Utf8::new(),
        prev: 0,
    };
    let (mut i, mut words) = (0usize, 0usize);
    let (mut boundary, mut after_word) = (true, false);
    let mut held: Option<(usize, usize)> = None;
    // Inside a quoted string while `i` is below this.
    let mut quoted_until = 0usize;
    // Cleared when no closing quote is left, so that scan is not repeated.
    let mut closes = true;
    while let Some(&b) = v.get(i) {
        if i < quoted_until {
            if ws_len(v, i) == 3 {
                i += 2;
                continue;
            }
            text.check(b, i)?;
            emit(&[b]);
            i += 1;
            continue;
        }
        if ws_len(v, i) > 0 {
            let start = i;
            while ws_len(v, i) > 0 {
                i += ws_len(v, i);
            }
            if after_word {
                held = Some((start, i));
            } else {
                text.run(v, start, i, emit)?;
            }
            boundary = true;
            continue;
        }
        if boundary && v.get(i..i + 2) == Some(b"=?") {
            if let Some(Encoded {
                charset: cs,
                base64: b64,
                text: word,
                end,
            }) = shape(v, i)?
            {
                if !text.utf8.is_complete() {
                    return err(ErrorKind::InvalidUtf8, i);
                }
                words += 1;
                if words > usize::from(limits.encoded_words) {
                    return err(ErrorKind::TooManyMembers, i);
                }
                if b64 {
                    // Base64 decoding comes with encode-lib (D-002).
                    return err(ErrorKind::InvalidEncodedWord, i);
                }
                // Whitespace between two encoded words is dropped
                // (RFC 2047 section 6.2).
                held = None;
                decode_q(cs, word, end - 2 - word.len(), emit)?;
                after_word = true;
                boundary = false;
                i = end;
                continue;
            }
        }
        if let Some((s, e)) = held.take() {
            text.run(v, s, e, emit)?;
        }
        after_word = false;
        if b == b'"' && boundary && closes {
            match closing_quote(v, i + 1) {
                Some(close) => quoted_until = close + 1,
                None => closes = false,
            }
        }
        boundary = false;
        text.check(b, i)?;
        emit(&[b]);
        i += 1;
    }
    if let Some((s, e)) = held {
        text.run(v, s, e, emit)?;
    }
    if !text.utf8.is_complete() {
        return err(ErrorKind::InvalidUtf8, v.len());
    }
    Ok(())
}

/// Decodes the RFC 2047 encoded words in unstructured header text into
/// `out` and returns the text. Text outside encoded words is copied;
/// whitespace between two adjacent encoded words is dropped (section 6.2);
/// `_` is a space in Q; an encoded word must stand alone between whitespace,
/// and words inside a quoted string are not decoded (section 5). Charsets:
/// UTF-8, US-ASCII, ISO-8859-1 (transcoded), with an optional RFC 2231
/// `*language`. `B` words need the `encode-lib` feature, which is not yet
/// available (D-002). `CRLF WSP` folds count as whitespace, so the output of
/// [`encode_words`] reads back as written.
///
/// # Errors
///
/// [`ErrorKind::UnsupportedCharset`]; [`ErrorKind::InvalidEncodedWord`] (a
/// bad encoding letter, a broken `=XX`, a byte not allowed in a Q word, a
/// `B` word); [`ErrorKind::ControlInDecoded`] for a decoded control
/// character (C0 including CR, LF, NUL, and HTAB; DEL; C1), as in ext-values;
/// a control kind for a control byte outside the words, other than HTAB and
/// the CRLF of a fold; [`ErrorKind::InvalidUtf8`] (a UTF-8 word that is not
/// whole characters, or text outside the words that is not UTF-8);
/// [`ErrorKind::TooManyMembers`]
/// beyond `max_encoded_words`; [`ErrorKind::BufferTooSmall`]. Nothing is
/// written on error.
///
/// # Examples
///
/// ```
/// use parse_net::{mail, Limits};
///
/// let mut buf = [0u8; 64];
/// let s = mail::decode_words(b"=?utf-8?q?Caf=C3=A9?= =?ISO-8859-1?Q?_cr=E8me?= now", &Limits::DEFAULT, &mut buf)?;
/// assert_eq!(s, "Caf\u{e9} cr\u{e8}me now");
/// # Ok::<(), parse_net::ParseError>(())
/// ```
pub fn decode_words<'b>(value: &[u8], limits: &Limits, out: &'b mut [u8]) -> Result<&'b str> {
    let mut len = 0usize;
    walk(value, limits, &mut |b: &[u8]| len += b.len())?;
    let Some(dst) = out.get_mut(..len) else {
        return err(ErrorKind::BufferTooSmall, 0);
    };
    let mut n = 0usize;
    walk(value, limits, &mut |b: &[u8]| {
        if let Some(d) = dst.get_mut(n..n + b.len()) {
            d.copy_from_slice(b);
        }
        n += b.len();
    })?;
    // The first walk checked the text; this is the safe conversion.
    core::str::from_utf8(dst).map_err(|e| ParseError::new(ErrorKind::InvalidUtf8, e.valid_up_to()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{string::String, vec};

    fn enc(text: &str, room: usize) -> String {
        let mut buf = vec![0u8; 2048];
        let mut out = crate::SliceSink::new(&mut buf);
        encode_words(text, room, &mut out).unwrap();
        String::from_utf8(out.written().to_vec()).unwrap()
    }

    fn dec(v: &[u8]) -> Result<String> {
        let mut buf = vec![0u8; 2048];
        decode_words(v, &Limits::DEFAULT, &mut buf).map(String::from)
    }

    #[test]
    fn test_encode_words_edge_cases() {
        assert_eq!(enc("plain ascii", 10), "plain ascii");
        assert_eq!(enc("a =?b", 70), "=?UTF-8?Q?a_=3D=3Fb?=");
        let long = "\u{e9}".repeat(40);
        let e = enc(&long, 75);
        for word in e.split("\r\n ") {
            assert!(word.len() <= 75 && word.starts_with("=?UTF-8?Q?") && word.ends_with("?="));
            // Each word holds whole characters, so it decodes on its own.
            assert!(dec(word.as_bytes()).is_ok());
        }
        assert_eq!(dec(e.replace("\r\n", "").as_bytes()).unwrap(), long);
        // An encoded word of exactly 75 bytes: 63 bytes of payload.
        let e = enc(&"\u{20ac}".repeat(7), 75);
        assert_eq!(e.len(), 12 + 63);
        assert!(!e.starts_with("\r\n "));
        assert!(enc("\u{e9}", 5).starts_with("\r\n =?UTF-8?Q?"));
        let mut buf = [0u8; 8];
        let mut out = crate::SliceSink::new(&mut buf);
        assert_eq!(
            encode_words("a\nb", 70, &mut out),
            Err(WriteError::Forbidden { at: 1 })
        );
        assert_eq!(
            encode_words("a\u{85}", 70, &mut out),
            Err(WriteError::Forbidden { at: 1 })
        );
        assert_eq!(
            encode_words("\u{e9}\u{e9}", 70, &mut out),
            Err(WriteError::Full)
        );
        assert!(out.is_empty());
    }

    #[test]
    fn test_decode_words_edge_cases() {
        assert_eq!(dec(b"=?utf-8?q?a_b?=").unwrap(), "a b");
        assert_eq!(dec(b"=?UTF-8?Q?a?=  \t =?UTF-8?Q?b?=").unwrap(), "ab");
        assert_eq!(dec(b"=?UTF-8?Q?a?= x =?UTF-8?Q?b?= ").unwrap(), "a x b ");
        assert_eq!(dec(b"\"=?UTF-8?Q?a?=\"").unwrap(), "\"=?UTF-8?Q?a?=\"");
        assert_eq!(dec(b"x=?UTF-8?Q?a?=").unwrap(), "x=?UTF-8?Q?a?=");
        assert_eq!(dec(b"=?UTF-8?Q?a?=x").unwrap(), "=?UTF-8?Q?a?=x");
        assert_eq!(dec(b"=?UTF-8*en?Q?a?=").unwrap(), "a");
        assert_eq!(dec(b"=? not a word").unwrap(), "=? not a word");
        assert_eq!(dec(b"=?US-ASCII?Q?ok?=").unwrap(), "ok");
        assert_eq!(
            dec(b"=?KOI8-R?Q?a?=").unwrap_err().kind(),
            ErrorKind::UnsupportedCharset
        );
        assert_eq!(
            dec(b"=?UTF-8?X?a?=").unwrap_err().kind(),
            ErrorKind::InvalidEncodedWord
        );
        assert_eq!(
            dec(b"=?UTF-8?Q?=4?=").unwrap_err().kind(),
            ErrorKind::InvalidEncodedWord
        );
        assert_eq!(
            dec(b"=?UTF-8?B?YQ==?=").unwrap_err().kind(),
            ErrorKind::InvalidEncodedWord
        );
        assert_eq!(
            dec(b"=?UTF-8?Q?=0D=0A?=").unwrap_err().kind(),
            ErrorKind::ControlInDecoded
        );
        assert_eq!(
            dec(b"=?UTF-8?Q?=C3?=").unwrap_err().kind(),
            ErrorKind::InvalidUtf8
        );
        assert_eq!(
            dec(b"=?US-ASCII?Q?=E9?=").unwrap_err().kind(),
            ErrorKind::InvalidEncodedWord
        );
        assert_eq!(dec(b"raw \xe9").unwrap_err().kind(), ErrorKind::InvalidUtf8);
        let l = Limits::DEFAULT.max_encoded_words(2);
        let mut buf = [0u8; 64];
        assert!(decode_words(b"=?UTF-8?Q?a?= =?UTF-8?Q?b?=", &l, &mut buf).is_ok());
        assert_eq!(
            decode_words(b"=?UTF-8?Q?a?= =?UTF-8?Q?b?= =?UTF-8?Q?c?=", &l, &mut buf)
                .unwrap_err()
                .kind(),
            ErrorKind::TooManyMembers
        );
        let mut small = [0u8; 2];
        assert_eq!(
            decode_words(b"abc", &Limits::DEFAULT, &mut small)
                .unwrap_err()
                .kind(),
            ErrorKind::BufferTooSmall
        );
        assert_eq!(small, [0, 0]);
    }
}