vcard-rs 0.3.1

vCard parser, validator, editor, merger and builder library
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
628
629
630
631
632
633
634
635
636
637
638
639
640
//! # Content line
//!
//! One raw content line of a card: name, parameters, value, line ending.
//!
//! [`VcardLine`] is the syntactic unit a property occupies. It owns the line
//! tokeniser ([`take`](VcardLine::take), which splits one logical line off the
//! remaining input) and the head splitter separating the name from its
//! parameters.
//!
//! It stays generic: what the name means and how the value decodes belong to
//! the lens markers and the [`codec`](crate::tree::codec).
//!
//! Folding, stray blank lines and `QUOTED-PRINTABLE` soft breaks are resolved
//! on parse, so every layer above sees one logical line, and recorded on the
//! line's [`wire`](VcardLine::wire) shape, so serialization puts them back.
//!
//! A card therefore round-trips byte for byte however it was laid out. The
//! final line needs no trailing break.

use core::{fmt, str};

use alloc::{borrow::Cow, string::String, vec, vec::Vec};

use crate::tree::{
    codec::mode::VcardEscaper,
    error::VcardParseError,
    leaf::{VcardLeaf, VcardValueLeaf},
    param::{lens::VcardParamLens, node::VcardParamNode},
    value::node::VcardValueNode,
    wire::VcardWire,
};

/// One raw content line: a name, parameters, a value and the line ending.
///
/// This is a *logical* line: [`take`](Self::take) unfolds RFC 6350 3.2
/// continuations and soft breaks into [`wire`](Self::wire), which puts them
/// back on output. The `BEGIN` / `VERSION` / `END` lines are `VcardLine`s too.
#[derive(Clone, Debug)]
pub struct VcardLine<'a> {
    /// The property name leaf, with any group prefix.
    pub name: VcardLeaf<'a>,
    /// The parameters, in source order.
    pub params: Vec<VcardParamNode<'a>>,
    /// The value.
    pub value: VcardValueNode<'a>,
    /// The line ending (`\r\n` or `\n`).
    pub eol: VcardLeaf<'a>,
    /// How the line was laid out on the wire: its folds, the blank lines before
    /// it, its soft breaks. Empty for a built line, and dropped on output once
    /// an edit changes the line's length (see [`VcardWire`]).
    pub wire: VcardWire<'a>,
}

impl<'a> VcardLine<'a> {
    /// Build a property line with a raw text value and the default `\r\n`
    /// ending. Used to seed BEGIN/VERSION/END and to encode simple values.
    pub fn text(name: impl Into<Cow<'a, str>>, value: impl Into<Cow<'a, str>>) -> Self {
        Self {
            name: VcardLeaf(name.into()),
            params: Vec::new(),
            value: VcardValueNode::from_components(
                vec![vec![VcardValueLeaf::from(value.into())]],
                VcardEscaper::V4_0,
            ),
            eol: VcardLeaf(Cow::Borrowed("\r\n")),
            wire: VcardWire::default(),
        }
    }

    /// Tokenise the logical line at the start of `rest`, unfolding folds.
    ///
    /// RFC 6350 3.2 folds with a CRLF and one leading space or tab; unfolding
    /// drops them into the line's wire shape. A folded line is rebuilt owned,
    /// since its bytes are no longer contiguous; an unfolded one borrows.
    pub fn take(rest: &'a [u8]) -> Result<(Self, &'a [u8]), VcardParseError> {
        // NOTE: Everything this tokeniser resolves is recorded here, so
        // serialization can put it back.
        let mut wire = VcardWire::default();

        // NOTE: skip blank lines: real-world exports sometimes emit them.
        let mut head = rest;

        let (first, eol, mut tail) = loop {
            if head.is_empty() {
                return Err(VcardParseError::MissingCrlf(lossy(rest)));
            }

            let (content, eol, next) = physical_line(head);
            if content.is_empty() {
                head = next;
                continue;
            }

            break (content, eol, next);
        };

        if head.len() < rest.len() {
            wire.skipped(0, ascii(&rest[..rest.len() - head.len()]));
        }

        // NOTE: A dangling continuation (folding whitespace with no line to
        // continue, left by a dropped blank line) would fold into the previous
        // line on reparse; strip the leading whitespace so it stays its own
        // line, and record it so it still round-trips.
        let indented = first;
        let first = strip_leading_wsp(first);

        if first.len() < indented.len() {
            wire.skipped(0, ascii(&indented[..indented.len() - first.len()]));
        }

        // NOTE: QUOTED-PRINTABLE soft line breaks: a line whose head declares
        // ENCODING=QUOTED-PRINTABLE and whose value ends with `=` continues on
        // the next physical line. Param-driven, so it applies to any version's
        // card that uses the encoding, not just 2.1.
        if first.ends_with(b"=") && head_is_quoted_printable(first) {
            let mut logical = Vec::from(&first[..first.len() - 1]);
            wire.soft(logical.len(), is_crlf(eol));

            let mut last_eol;
            loop {
                let (continuation, eol, next) = physical_line(tail);
                last_eol = eol;
                tail = next;

                match continuation.strip_suffix(b"=") {
                    Some(head) => {
                        push_content(&mut logical, &mut wire, head);
                        if tail.is_empty() {
                            // NOTE: The last continuation ends with a
                            // soft-break marker and nothing follows: the `=` is
                            // on the wire, the break after it is the line's own
                            // ending.
                            wire.skipped(logical.len(), "=");
                            break;
                        }
                        wire.soft(logical.len(), is_crlf(eol));
                    }
                    None => {
                        push_content(&mut logical, &mut wire, continuation);
                        break;
                    }
                }
            }

            let mut line = Self::parse(&logical, b"")?.into_static();
            line.eol = eol_leaf(last_eol);
            line.wire.prepend(wire.into_static());

            return Ok((line, tail));
        }

        if !starts_with_wsp(tail) {
            let mut line = Self::parse(first, eol)?;
            line.wire.prepend(wire);

            return Ok((line, tail));
        }

        let mut logical = Vec::from(first);
        let mut last_eol = eol;

        while starts_with_wsp(tail) {
            let (continuation, eol, next) = physical_line(&tail[1..]);
            wire.fold(logical.len(), is_crlf(last_eol), tail[0]);
            push_content(&mut logical, &mut wire, continuation);
            last_eol = eol;
            tail = next;
        }

        let mut line = Self::parse(&logical, b"")?.into_static();
        line.eol = eol_leaf(last_eol);
        line.wire.prepend(wire.into_static());

        Ok((line, tail))
    }

    /// Convert into an owned line whose every leaf is owned (`'static`).
    pub(crate) fn into_static(self) -> VcardLine<'static> {
        VcardLine {
            name: self.name.into_static(),
            params: self
                .params
                .into_iter()
                .map(VcardParamNode::into_static)
                .collect(),
            value: self.value.into_static(),
            eol: self.eol.into_static(),
            wire: self.wire.into_static(),
        }
    }

    /// The raw bytes of the line's first value, for simple single-value lines.
    pub fn raw_value(&self) -> &[u8] {
        self.value.first_value_bytes()
    }

    /// The raw first value as UTF-8 text, lossily; for the ASCII envelope
    /// values (`VERSION`) and diagnostics.
    pub fn raw_value_str(&self) -> Cow<'_, str> {
        String::from_utf8_lossy(self.value.first_value_bytes())
    }

    /// Serialize the whole line to bytes, exactly as parsed: its logical
    /// content, laid back out in the wire shape it arrived in.
    pub(crate) fn write_bytes(&self, out: &mut Vec<u8>) {
        if self.wire.is_empty() {
            self.write_logical(out);
        } else {
            let mut logical = Vec::new();
            self.write_logical(&mut logical);
            self.wire.write_bytes(&logical, out);
        }

        out.extend_from_slice(self.eol.get().as_bytes());
    }

    /// Serialize the logical line (its name, parameters and value), with no
    /// line ending and no wire shape. This is the byte string the wire offsets
    /// index.
    fn write_logical(&self, out: &mut Vec<u8>) {
        out.extend_from_slice(self.name.get().as_bytes());

        for param in &self.params {
            out.push(b';');
            param.write_bytes(out);
        }

        out.push(b':');
        self.value.write_bytes(out);
    }

    /// The first parameter of type `P`, decoded.
    pub fn param<P: VcardParamLens>(&self) -> Option<P::Target<'_>> {
        self.params
            .iter()
            .find(|param| param.name.get().eq_ignore_ascii_case(&P::KIND))
            .map(|param| P::decode(param))
    }

    /// The first parameter of type `P`, mutably (raw, for editing its leaves).
    pub fn param_mut<P: VcardParamLens>(&mut self) -> Option<&mut VcardParamNode<'a>> {
        self.params
            .iter_mut()
            .find(|param| param.name.get().eq_ignore_ascii_case(&P::KIND))
    }

    /// Split one logical line into a typed line at the colon, separating the
    /// name, its parameters and the value. The head (name and parameters) must
    /// be valid UTF-8, as every version's grammar guarantees; only the value
    /// may carry a foreign charset, so it is kept as raw bytes.
    fn parse<'b>(content: &'b [u8], eol: &'b [u8]) -> Result<VcardLine<'b>, VcardParseError> {
        let Some(colon) = value_colon(content) else {
            return Err(VcardParseError::MissingPropertyColon(lossy(content)));
        };

        let head = str::from_utf8(&content[..colon])
            .map_err(|_| VcardParseError::NonUtf8Header(lossy(&content[..colon])))?;
        let (name, params) = split_head(head);

        let mut value = &content[colon + 1..];
        let mut wire = VcardWire::default();

        // NOTE: A trailing `=` on a QUOTED-PRINTABLE value is always a
        // dangling soft-break marker, real content encoding `=` as `=3D`. Left
        // in, it would re-trigger the join on reparse and swallow the next
        // line, so the logical line drops it and the wire shape keeps it.
        if head_is_quoted_printable(content) {
            let full = value.len();
            while value.last() == Some(&b'=') {
                value = &value[..value.len() - 1];
            }
            if value.len() < full {
                let end = colon + 1 + value.len();
                wire.skipped(end, ascii(&content[end..colon + 1 + full]));
            }
        }

        wire.seal(colon + 1 + value.len());

        Ok(VcardLine {
            name: VcardLeaf::from(name),
            params,
            value: VcardValueNode::parse(value),
            eol: VcardLeaf::from(str::from_utf8(eol).unwrap_or("")),
            wire,
        })
    }
}

impl fmt::Display for VcardLine<'_> {
    /// The line as text, wire shape included, lossily for a non-UTF-8 value.
    /// `VcardLine::write_bytes` is the byte-faithful path.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.wire.is_empty() {
            f.write_str(self.name.get())?;

            for param in &self.params {
                write!(f, ";{param}")?;
            }

            return write!(f, ":{}{}", self.value, self.eol.get());
        }

        let mut bytes = Vec::new();
        self.write_bytes(&mut bytes);
        f.write_str(&String::from_utf8_lossy(&bytes))
    }
}

/// Append a continuation's content to the logical line, recording the rest.
///
/// A logical line still empty here came from a whitespace-only physical line,
/// so a leading whitespace on the continuation is a wire artifact rather than
/// part of the name.
fn push_content<'a>(logical: &mut Vec<u8>, wire: &mut VcardWire<'a>, content: &'a [u8]) {
    let kept = if logical.is_empty() {
        strip_leading_wsp(content)
    } else {
        content
    };

    if kept.len() < content.len() {
        wire.skipped(logical.len(), ascii(&content[..content.len() - kept.len()]));
    }

    logical.extend_from_slice(kept);
}

/// Split a head into its name and its `;`-separated parameters.
fn split_head(head: &str) -> (&str, Vec<VcardParamNode<'_>>) {
    let (name, mut rest) = match param_semicolon(head) {
        Some(semi) => (&head[..semi], &head[semi..]),
        None => return (head, Vec::new()),
    };

    let mut params = Vec::new();

    while let Some(after) = rest.strip_prefix(';') {
        let (param, tail) = match param_semicolon(after) {
            Some(semi) => (&after[..semi], &after[semi..]),
            None => (after, ""),
        };

        params.push(VcardParamNode::parse(param));
        rest = tail;
    }

    (name, params)
}

/// The index of the `:` separating a line's head from its value.
///
/// It is the first colon outside a double-quoted parameter value, which RFC
/// 6350 3.3 lets carry one. An unbalanced quote would swallow the rest of the
/// line, so with no colon outside quotes the scan falls back to the first.
fn value_colon(content: &[u8]) -> Option<usize> {
    let mut quoted = false;

    for (i, &byte) in content.iter().enumerate() {
        match byte {
            b'"' => quoted = !quoted,
            b':' if !quoted => return Some(i),
            _ => {}
        }
    }

    memchr::memchr(b':', content)
}

/// The byte index of the first `;` of a head that sits outside a double-quoted
/// parameter value, the one separating one parameter from the next.
fn param_semicolon(head: &str) -> Option<usize> {
    let mut quoted = false;

    for (i, byte) in head.bytes().enumerate() {
        match byte {
            b'"' => quoted = !quoted,
            b';' if !quoted => return Some(i),
            _ => {}
        }
    }

    None
}

/// Split the first physical line off `rest`: its content (without the line
/// ending), its line ending, and the remaining input. A final line with no
/// trailing break is taken whole, with an empty ending.
fn physical_line(rest: &[u8]) -> (&[u8], &[u8], &[u8]) {
    let Some(lf) = memchr::memchr(b'\n', rest) else {
        return (rest, b"", b"");
    };

    let tail = &rest[lf + 1..];

    let (content, eol) = if lf > 0 && rest[lf - 1] == b'\r' {
        (&rest[..lf - 1], &rest[lf - 1..lf + 1])
    } else {
        (&rest[..lf], &rest[lf..lf + 1])
    };

    (content, eol, tail)
}

/// Whether `rest` begins with a folding whitespace (space or tab).
fn starts_with_wsp(rest: &[u8]) -> bool {
    matches!(rest.first(), Some(b' ' | b'\t'))
}

/// Strip any leading folding whitespace (space, tab) or stray line-break byte
/// (`\r`, `\n`) from a line's content, so its name never begins with a byte
/// that another layer (folding, blank-line skipping) would re-strip on reparse.
fn strip_leading_wsp(mut bytes: &[u8]) -> &[u8] {
    while matches!(bytes.first(), Some(b' ' | b'\t' | b'\r' | b'\n')) {
        bytes = &bytes[1..];
    }
    bytes
}

/// Whether a line's head (its name and parameters, before the `:`) declares the
/// `QUOTED-PRINTABLE` encoding, as an `ENCODING=` parameter or a bare token.
fn head_is_quoted_printable(line: &[u8]) -> bool {
    let head = match value_colon(line) {
        Some(colon) => &line[..colon],
        None => return false,
    };

    head.split(|&b| b == b';').any(|token| {
        token.eq_ignore_ascii_case(b"QUOTED-PRINTABLE")
            || token.eq_ignore_ascii_case(b"ENCODING=QUOTED-PRINTABLE")
    })
}

/// An owned line-ending leaf from raw bytes (always an ASCII `\r\n` / `\n`).
fn eol_leaf(bytes: &[u8]) -> VcardLeaf<'static> {
    VcardLeaf::from(String::from_utf8_lossy(bytes).into_owned())
}

/// Whether a line ending is a `\r\n` rather than a bare `\n`.
fn is_crlf(eol: &[u8]) -> bool {
    eol.starts_with(b"\r")
}

/// Bytes the tokeniser resolved away, as text. Every one of them is a line
/// break, a space, a tab or an `=`, so the conversion never fails; a lone `""`
/// on the impossible path keeps this total rather than panicking.
fn ascii(bytes: &[u8]) -> &str {
    str::from_utf8(bytes).unwrap_or("")
}

/// A lossy owned string of raw bytes, for error diagnostics.
fn lossy(bytes: &[u8]) -> String {
    String::from_utf8_lossy(bytes).into_owned()
}

#[cfg(test)]
mod tests {
    use alloc::string::ToString;

    use crate::tree::{line::VcardLine, value::node::VcardValueNode};

    #[test]
    fn takes_one_line_and_leaves_the_rest() {
        let (line, rest) = VcardLine::take(b"FN:John\r\nEND:VCARD\r\n").unwrap();
        assert_eq!(line.name.get(), "FN");
        assert_eq!(line.to_string(), "FN:John\r\n");
        assert_eq!(rest, b"END:VCARD\r\n");
    }

    #[test]
    fn splits_parameters_off_the_head_then_round_trips() {
        let (line, _) = VcardLine::take(b"TEL;TYPE=work,home:123\r\n").unwrap();
        assert_eq!(line.params.len(), 1);
        assert_eq!(line.to_string(), "TEL;TYPE=work,home:123\r\n");
    }

    /// RFC 6350 section 3.3 lets a quoted parameter value carry a colon and a
    /// semicolon, and section 6.3.1 uses both in its ADR example.
    #[test]
    fn keeps_a_quoted_parameter_value_whole() {
        let raw = b"ADR;GEO=\"geo:12.3457,78.910\";TYPE=work:;;123 Main Street\r\n";
        let (line, _) = VcardLine::take(raw).unwrap();

        assert_eq!(line.params.len(), 2);
        assert_eq!(line.params[0].name.get(), "GEO");
        assert_eq!(line.params[0].values[0].get(), "\"geo:12.3457,78.910\"");
        assert_eq!(line.params[1].name.get(), "TYPE");
        assert_eq!(line.value.component_count(), 3);
        assert_eq!(line.to_string(), str::from_utf8(raw).unwrap());
    }

    /// Quote tracking alone would swallow the rest of the line, so with no
    /// colon outside quotes the scan falls back to the first one.
    #[test]
    fn an_unbalanced_quote_still_parses() {
        let (line, _) = VcardLine::take(b"TEL;TYPE=\"work:+1\r\n").unwrap();

        assert_eq!(line.name.get(), "TEL");
        assert_eq!(line.to_string(), "TEL;TYPE=\"work:+1\r\n");
    }

    #[test]
    fn accepts_a_bare_lf_ending() {
        let (line, _) = VcardLine::take(b"FN:John\n").unwrap();
        assert_eq!(line.to_string(), "FN:John\n");
    }

    #[test]
    fn unfolds_space_and_tab_continuations() {
        let (line, rest) = VcardLine::take(b"NOTE:foo\r\n bar\r\n\tbaz\r\nEND:VCARD\r\n").unwrap();
        assert_eq!(line.name.get(), "NOTE");
        assert_eq!(line.raw_value_str(), "foobarbaz");
        assert_eq!(rest, b"END:VCARD\r\n");
    }

    #[test]
    fn serializes_a_folded_line_back_folded() {
        let (line, _) = VcardLine::take(b"NOTE:foo\r\n bar\r\n").unwrap();
        assert_eq!(line.raw_value_str(), "foobar");
        assert_eq!(line.to_string(), "NOTE:foo\r\n bar\r\n");
    }

    #[test]
    fn keeps_the_folding_whitespace_and_the_break_it_arrived_with() {
        let (line, _) = VcardLine::take(b"NOTE:foo\n\tbar\r\n").unwrap();
        assert_eq!(line.to_string(), "NOTE:foo\n\tbar\r\n");
    }

    #[test]
    fn serializes_a_skipped_blank_line_back() {
        let (line, _) = VcardLine::take(b"\r\n\r\nFN:John\r\n").unwrap();
        assert_eq!(line.to_string(), "\r\n\r\nFN:John\r\n");
    }

    /// The old offsets index bytes that are no longer there, so the edited
    /// line goes out unfolded rather than folded in the wrong places.
    #[test]
    fn drops_the_fold_points_once_the_value_is_edited() {
        let (mut line, _) = VcardLine::take(b"NOTE:foo\r\n bar\r\n").unwrap();
        line.value = VcardValueNode::parse(b"something else entirely");
        assert_eq!(line.to_string(), "NOTE:something else entirely\r\n");
    }

    /// The edit keeps the length, so every offset still indexes what it did
    /// and the line is folded exactly where it was.
    #[test]
    fn keeps_the_fold_points_when_an_edit_keeps_the_length() {
        let (mut line, _) = VcardLine::take(b"NOTE:foo\r\n bar\r\n").unwrap();
        line.value = VcardValueNode::parse(b"BARFOO");
        assert_eq!(line.to_string(), "NOTE:BAR\r\n FOO\r\n");
    }

    /// Only the first space of a continuation is the fold marker, so a
    /// whitespace-only line followed by a doubly-indented one leaves the
    /// leftover space in front of the name. Left there, the line folds back
    /// into its predecessor on reparse and the card is not a fixpoint.
    #[test]
    fn a_continuation_of_a_blank_line_does_not_keep_its_whitespace() {
        let (line, _) = VcardLine::take(b"   \r\n  A:b\r\n").unwrap();

        assert_eq!(line.name.get(), "A");
        assert_eq!(line.to_string(), "   \r\n  A:b\r\n");
    }

    /// Only the first space is the fold marker; the rest is value content.
    #[test]
    fn keeps_whitespace_beyond_the_single_fold_indicator() {
        let (line, _) = VcardLine::take(b"NOTE:foo\r\n  bar\r\n").unwrap();
        assert_eq!(line.raw_value_str(), "foo bar");
    }

    #[test]
    fn skips_blank_lines_before_the_next_line() {
        let (line, rest) = VcardLine::take(b"\r\n\r\nFN:John\r\nEND:VCARD\r\n").unwrap();
        assert_eq!(line.name.get(), "FN");
        assert_eq!(rest, b"END:VCARD\r\n");
    }

    #[test]
    fn tolerates_a_missing_final_line_break() {
        let (line, rest) = VcardLine::take(b"END:VCARD").unwrap();
        assert_eq!(line.name.get(), "END");
        assert_eq!(line.to_string(), "END:VCARD");
        assert_eq!(rest, b"");
    }

    /// Two soft breaks, so both join arms run: the first continuation itself
    /// ends with `=`, the second does not.
    #[test]
    fn joins_a_quoted_printable_soft_broken_line() {
        let raw = b"NOTE;ENCODING=QUOTED-PRINTABLE:caf=\r\n=C3=\r\n=A9\r\n";
        let (line, _) = VcardLine::take(raw).unwrap();
        assert_eq!(line.name.get(), "NOTE");
        assert_eq!(line.raw_value_str(), "caf=C3=A9");
        assert_eq!(line.raw_value(), b"caf=C3=A9");
        assert_eq!(line.to_string(), str::from_utf8(raw).unwrap());
    }

    #[test]
    fn errors_when_there_is_no_content_line() {
        assert!(VcardLine::take(b"").is_err());
        assert!(VcardLine::take(b"\r\n\r\n").is_err());
    }

    #[test]
    fn rejects_a_non_utf8_head() {
        let mut raw = b"X-".to_vec();
        raw.push(0xff);
        raw.extend_from_slice(b":v\r\n");
        assert!(VcardLine::take(&raw).is_err());
    }

    #[test]
    fn finds_a_parameter_mutably() {
        use crate::tree::param::r#type::TYPE;

        let (mut line, _) = VcardLine::take(b"TEL;TYPE=home:123\r\n").unwrap();
        assert!(line.param_mut::<TYPE>().is_some());
    }

    /// `abc=` ends with `=` but has no colon, so the QUOTED-PRINTABLE
    /// soft-break check bails and the line then fails for want of a value
    /// separator.
    #[test]
    fn a_trailing_equals_without_a_colon_is_not_quoted_printable() {
        assert!(VcardLine::take(b"abc=\r\n").is_err());
    }

    /// The final continuation ends with `=` and nothing follows, so the join
    /// loop exits through the empty-tail guard rather than a non-`=` line.
    #[test]
    fn quoted_printable_join_stops_at_an_empty_tail() {
        let raw = b"NOTE;ENCODING=QUOTED-PRINTABLE:a=\r\nb=\r\n";
        let (line, rest) = VcardLine::take(raw).unwrap();
        assert_eq!(line.raw_value_str(), "ab");
        assert_eq!(rest, b"");
        assert_eq!(line.to_string(), str::from_utf8(raw).unwrap());
    }
}