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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
// Copyright 2023 Hugo Osvaldo Barrera
//
// SPDX-License-Identifier: ISC

//! See [`Parser`] as the main entry point to this library.
#![no_std]
#![deny(clippy::pedantic)]

extern crate alloc;

use core::{
    iter::{Enumerate, Peekable},
    str::Bytes,
};

use alloc::{
    borrow::{Cow, ToOwned},
    string::ToString,
};

/// A valid content line.
///
/// Continuation lines may be wrapped and separated by a CRLF immediately followed by a single
/// linear white-space character (i.e., SPACE or HTAB).
#[derive(Debug, PartialEq, Clone)]
pub struct ContentLine<'input> {
    // TODO: use indeces instead; they're half the size and slightly simpler.
    /// The entire raw line, unaltered.
    raw: &'input str,
    /// Everything before the first colon or semicolon.
    name: &'input str,
    /// Everything before the first colon and after the first semicolon.
    params: &'input str,
    /// Everything after the first unquoted colon.
    value: &'input str,
}

impl<'input> ContentLine<'input> {
    /// Return the raw line without any unfolding.
    #[must_use]
    pub fn raw(&self) -> &'input str {
        self.raw
    }

    /// Return this line's name, with continuation lines unfolded.
    #[must_use]
    pub fn name(&self) -> Cow<'input, str> {
        unfold_lines(self.name)
    }

    /// Return this line's parameter(s), with continuation lines unfolded.
    #[must_use]
    pub fn params(&self) -> Cow<'input, str> {
        unfold_lines(self.params)
    }

    /// Return this line's value, with continuation lines unfolded.
    #[must_use]
    pub fn value(&self) -> Cow<'input, str> {
        unfold_lines(self.value)
    }

    /// Return the entire line unfolded.
    ///
    /// Note that the line may exceed the maximum length, making it technically invalid. This is
    /// however, suitable for comparing equality between to lines.
    #[must_use]
    pub fn unfolded(&self) -> Cow<'input, str> {
        unfold_lines(self.raw)
    }

    /// Return this content line with normalised folds
    ///
    /// The returned line shall be semantically equivalent to the input line. It will be folded
    /// making each logical line as long as possible (e.g.: no more than 75 octets, excluding the
    /// line jump).
    #[must_use]
    // INVARIANT: content lines only have valid continuation lines.
    #[allow(clippy::missing_panics_doc)]
    pub fn normalise_folds(&self) -> Cow<'input, str> {
        let mut result = Cow::Borrowed(self.raw);
        // Index where current portion begins.
        let mut cur = 0;
        // No strictly where the line started; this is also shifted to compensate for unfolds.
        let mut line_start = 0;

        let mut chars = self.raw.char_indices().peekable();
        while let Some((i, c)) = chars.next() {
            if c == '\r' && matches!(chars.peek(), Some((_, '\n'))) {
                chars.next(); // Advance the peeked LF.

                assert!(
                    matches!(chars.next(), Some((_, ' ' | '\t'))),
                    "continuation line must start with a space or tab",
                );

                let next = chars.peek().map(|(_, c)| c.len_utf8()).unwrap_or(1);
                if i - line_start + next >= 75 {
                    // In this case we don't need to mutate anything; the whole line and CRLF
                    // stay they same.

                    // Note that the space already counts towards the following line.
                    line_start = i + 2;
                } else {
                    let portion = &self.raw[cur..i];
                    match result {
                        Cow::Borrowed(_) => {
                            result = Cow::Owned(portion.to_owned());
                        }
                        Cow::Owned(ref mut s) => {
                            s.push_str(portion);
                        }
                    }
                    // Shift by three to avoid counting CRLF<SPACE>.
                    line_start += 3;
                    cur = i + 3;
                }
            } else if (i - line_start) + c.len_utf8() >= 75 {
                let portion = &self.raw[cur..i];
                match result {
                    Cow::Borrowed(_) => {
                        result = Cow::Owned(portion.to_string() + "\r\n " + &c.to_string());
                    }
                    Cow::Owned(ref mut s) => {
                        s.push_str(portion);
                        s.push_str("\r\n ");
                        s.push(c);
                    }
                }
                cur = i + c.len_utf8();
                line_start = i - 1; // -1 to account for the inserted space.
            }
        }

        if let Cow::Owned(ref mut s) = result {
            let portion = &self.raw[cur..];
            s.push_str(portion);
        }

        result
    }
}

/// A flexible parser for icalendar/vcard.
///
/// This parser is designed to allow malformed input as much as possible for vdirsyncer's
/// specific use case.
///
/// It should be used via its [`Iterator`] implementation which iterates over [`ContentLine`]
/// instances.
///
/// # Known issues
///
/// - A trailing empty line is lost.
pub struct Parser<'data> {
    data: &'data str,
    characters: Peekable<Enumerate<Bytes<'data>>>,
}

impl<'data> Parser<'data> {
    /// Create a new parser with the given input data.
    ///
    /// The input data MAY have unfolded continuation lines.
    #[must_use]
    pub fn new(data: &'data str) -> Parser<'data> {
        Parser {
            data,
            characters: data.bytes().enumerate().peekable(),
        }
    }

    /// Returns the unparsed portion of the input data.
    ///
    /// Does not affect advance the position of this iterator.
    #[must_use]
    pub fn remainder(&mut self) -> &str {
        &self.data[self
            .characters
            .peek()
            .map_or_else(|| self.data.len(), |(i, _)| *i)..]
    }
}

impl<'data> Iterator for Parser<'data> {
    type Item = ContentLine<'data>;

    /// Returns the next content line from the inner data.
    ///
    /// Returns `None` after the last line has been returned. Returns `None` if called after the
    /// iterator has been exhausted.
    #[allow(clippy::too_many_lines)]
    fn next(&mut self) -> Option<ContentLine<'data>> {
        let (start, _) = *self.characters.peek()?;
        loop {
            match self.characters.next() {
                Some((semicolon, b';')) => loop {
                    match self.characters.next() {
                        Some((colon, b':')) => loop {
                            match self.characters.next() {
                                Some((cr, b'\r')) => {
                                    if !self.characters.peek().is_some_and(|(_, c)| *c == b'\n') {
                                        continue; // Not CRLF.
                                    };
                                    self.characters.next(); // Advance the peeked LF.
                                    if matches!(self.characters.peek(), Some((_, b' ' | b'\t'))) {
                                        continue; // Continuation line
                                    }
                                    return Some(ContentLine {
                                        raw: &self.data[start..cr],
                                        name: &self.data[start..semicolon],
                                        params: &self.data[semicolon + 1..colon],
                                        value: &self.data[colon + 1..cr],
                                    });
                                }
                                Some((_, _)) => {}
                                None => {
                                    return Some(ContentLine {
                                        raw: &self.data[start..],
                                        name: &self.data[start..semicolon],
                                        params: &self.data[semicolon + 1..colon],
                                        value: &self.data[colon + 1..],
                                    })
                                }
                            }
                        },
                        Some((_, b'"')) => loop {
                            match self.characters.next() {
                                Some((_, b'"')) => break,
                                Some((_, _)) => {}
                                None => {
                                    // WARN: reached EOF, expected closing quote
                                    return Some(ContentLine {
                                        raw: &self.data[start..],
                                        name: &self.data[start..semicolon],
                                        params: &self.data[semicolon + 1..],
                                        value: &self.data[semicolon..semicolon],
                                    });
                                }
                            }
                        },
                        Some((cr, b'\r')) => {
                            if !self.characters.peek().is_some_and(|(_, c)| *c == b'\n') {
                                continue; // Not CRLF.
                            };
                            self.characters.next(); // Advance the peeked LF.
                            if matches!(self.characters.peek(), Some((_, b' ' | b'\t'))) {
                                continue; // Continuation line
                            }
                            return Some(ContentLine {
                                raw: &self.data[start..cr],
                                name: &self.data[start..semicolon],
                                params: &self.data[semicolon + 1..],
                                value: &self.data[semicolon..semicolon],
                            });
                        }
                        Some((_, _)) => {}
                        None => {
                            return Some(ContentLine {
                                raw: &self.data[start..],
                                name: &self.data[start..semicolon],
                                params: &self.data[semicolon + 1..],
                                value: &self.data[semicolon..semicolon],
                            });
                        }
                    };
                },
                // Begin value
                Some((colon, b':')) => loop {
                    match self.characters.next() {
                        Some((cr, b'\r')) => {
                            if !self.characters.peek().is_some_and(|(_, c)| *c == b'\n') {
                                continue; // Not CRLF.
                            };
                            self.characters.next(); // Advance the peeked LF.
                            if matches!(self.characters.peek(), Some((_, b' ' | b'\t'))) {
                                continue; // Continuation line
                            }
                            return Some(ContentLine {
                                raw: &self.data[start..cr],
                                name: &self.data[start..colon],
                                params: &self.data[colon..colon],
                                value: &self.data[colon + 1..cr],
                            });
                        }
                        Some((_, _)) => {}
                        None => {
                            return Some(ContentLine {
                                raw: &self.data[start..],
                                name: &self.data[start..colon],
                                params: &self.data[colon..colon],
                                value: &self.data[colon + 1..],
                            });
                        }
                    }
                },
                Some((cr, b'\r')) => {
                    if !self.characters.peek().is_some_and(|(_, c)| *c == b'\n') {
                        continue; // Not CRLF.
                    };
                    self.characters.next(); // Advance the peeked LF.
                    if matches!(self.characters.peek(), Some((_, b' ' | b'\t'))) {
                        continue; // Continuation line
                    }
                    return Some(ContentLine {
                        raw: &self.data[start..cr],
                        name: &self.data[start..cr],
                        params: &self.data[start..start],
                        value: &self.data[start..start],
                    });
                }
                Some((_, _)) => {}
                None => {
                    return Some(ContentLine {
                        raw: &self.data[start..],
                        name: &self.data[start..],
                        params: &self.data[start..start],
                        value: &self.data[start..start],
                    });
                }
            }
        }
    }
}

#[cfg(test)]
mod test {
    use crate::{unfold_lines, ContentLine, Parser};
    use alloc::{borrow::Cow, vec};

    #[test]
    fn test_complete_example() {
        let data = vec![
            "BEGIN:VCALENDAR",
            "VERSION:2.0",
            "PRODID:nl.whynothugo.todoman",
            "BEGIN:VTODO",
            "DTSTAMP:20231126T095923Z",
            "DUE;TZID=Asia/Shanghai:20231128T090000",
            "SUMMARY:dummy todo for parser tests",
            "UID:565f48cb5b424815a2ba5e56555e2832@destiny.whynothugo.nl",
            "END:VTODO",
            "END:VCALENDAR",
            // Note: this calendar is not entirely semantically valid;
            // it is missing the timezone which is referred to in DUE.
        ]
        .join("\r\n");

        let mut parser = Parser::new(&data);
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "BEGIN:VCALENDAR",
                name: "BEGIN",
                params: "",
                value: "VCALENDAR"
            })
        );
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "VERSION:2.0",
                name: "VERSION",
                params: "",
                value: "2.0",
            })
        );
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "PRODID:nl.whynothugo.todoman",
                name: "PRODID",
                params: "",
                value: "nl.whynothugo.todoman",
            })
        );
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "BEGIN:VTODO",
                name: "BEGIN",
                params: "",
                value: "VTODO",
            })
        );
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "DTSTAMP:20231126T095923Z",
                name: "DTSTAMP",
                params: "",
                value: "20231126T095923Z",
            })
        );
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "DUE;TZID=Asia/Shanghai:20231128T090000",
                name: "DUE",
                params: "TZID=Asia/Shanghai",
                value: "20231128T090000",
            })
        );
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "SUMMARY:dummy todo for parser tests",
                name: "SUMMARY",
                params: "",
                value: "dummy todo for parser tests",
            })
        );
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "UID:565f48cb5b424815a2ba5e56555e2832@destiny.whynothugo.nl",
                name: "UID",
                params: "",
                value: "565f48cb5b424815a2ba5e56555e2832@destiny.whynothugo.nl",
            })
        );
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "END:VTODO",
                name: "END",
                params: "",
                value: "VTODO",
            })
        );
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "END:VCALENDAR",
                name: "END",
                params: "",
                value: "VCALENDAR",
            })
        );
        assert_eq!(parser.next(), None);
    }

    #[test]
    fn test_empty_data() {
        let data = "";
        let mut parser = Parser::new(&data);
        assert_eq!(parser.next(), None);
    }

    #[test]
    fn test_empty_lines() {
        // A line followed by CRLF is a different code-path than a line followed by EOF.
        let data = "\r\n";
        let mut parser = Parser::new(&data);
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "",
                name: "",
                params: "",
                value: "",
            })
        );
        // FIXME: trailing empty lines are swallowed.
        // assert_eq!(
        //     parser.next(),
        //     Some(ContentLine {
        //         raw: "",
        //         name: "",
        //         params: "",
        //         value: "",
        //     })
        // );
        assert_eq!(parser.next(), None);
    }

    #[test]
    fn test_line_with_params() {
        // A line with ending in CRLF is a different code-path than a line in EOF.
        let data = vec![
            "DTSTART;TZID=America/New_York:19970902T090000",
            "DTSTART;TZID=America/New_York:19970902T090000",
        ]
        .join("\r\n");
        let mut parser = Parser::new(&data);
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "DTSTART;TZID=America/New_York:19970902T090000",
                name: "DTSTART",
                params: "TZID=America/New_York",
                value: "19970902T090000",
            })
        );
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "DTSTART;TZID=America/New_York:19970902T090000",
                name: "DTSTART",
                params: "TZID=America/New_York",
                value: "19970902T090000",
            })
        );
        assert_eq!(parser.next(), None);
    }

    #[test]
    fn test_line_with_dquote() {
        // A line with ending in CRLF is a different code-path than a line in EOF.
        let data = vec![
            "SUMMARY:This has \"some quotes\"",
            "DTSTART;TZID=\"local;VALUE=DATE-TIME\":20150304T184500",
        ]
        .join("\r\n");
        let mut parser = Parser::new(&data);
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "SUMMARY:This has \"some quotes\"",
                name: "SUMMARY",
                params: "",
                value: "This has \"some quotes\"",
            })
        );
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "DTSTART;TZID=\"local;VALUE=DATE-TIME\":20150304T184500",
                name: "DTSTART",
                params: "TZID=\"local;VALUE=DATE-TIME\"",
                value: "20150304T184500",
            })
        );
        assert_eq!(parser.next(), None);
    }

    #[test]
    fn test_continuation_line() {
        // A line with ending in CRLF is a different code-path than a line in EOF.
        let data = vec![
            "X-JMAP-LOCATION;VALUE=TEXT;X-JMAP-GEO=\"geo:52.123456,4.123456\";",
            " X-JMAP-ID=03453afa-71fc-4893-ba70-a7436bb6d56c:Name of place",
            "X-JMAP-LOCATION;VALUE=TEXT;X-JMAP-GEO=\"geo:52.123456,4.123456\";",
            " X-JMAP-ID=03453afa-71fc-4893-ba70-a7436bb6d56c:Name of place",
        ]
        .join("\r\n");
        let mut parser = Parser::new(&data);
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: &vec![
                    "X-JMAP-LOCATION;VALUE=TEXT;X-JMAP-GEO=\"geo:52.123456,4.123456\";",
                    " X-JMAP-ID=03453afa-71fc-4893-ba70-a7436bb6d56c:Name of place"
                ]
                .join("\r\n"),
                name: "X-JMAP-LOCATION",
                params: "VALUE=TEXT;X-JMAP-GEO=\"geo:52.123456,4.123456\";\r\n X-JMAP-ID=03453afa-71fc-4893-ba70-a7436bb6d56c",
                value: "Name of place",
            })
        );
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: &vec![
                    "X-JMAP-LOCATION;VALUE=TEXT;X-JMAP-GEO=\"geo:52.123456,4.123456\";",
                    " X-JMAP-ID=03453afa-71fc-4893-ba70-a7436bb6d56c:Name of place"
                ]
                .join("\r\n"),
                name: "X-JMAP-LOCATION",
                params: "VALUE=TEXT;X-JMAP-GEO=\"geo:52.123456,4.123456\";\r\n X-JMAP-ID=03453afa-71fc-4893-ba70-a7436bb6d56c",
                value: "Name of place",
            })
        );
        assert_eq!(parser.next(), None);
    }

    #[test]
    fn test_invalid_lone_name() {
        let data = "BEGIN";
        let mut parser = Parser::new(&data);
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "BEGIN",
                name: "BEGIN",
                params: "",
                value: "",
            })
        );
        assert_eq!(parser.next(), None);
    }

    #[test]
    fn test_invalid_name_with_params() {
        let data = "DTSTART;TZID=America/New_York";
        let mut parser = Parser::new(&data);
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "DTSTART;TZID=America/New_York",
                name: "DTSTART",
                params: "TZID=America/New_York",
                value: "",
            })
        );
        assert_eq!(parser.next(), None);
    }

    #[test]
    fn test_invalid_name_with_trailing_semicolon() {
        let data = "DTSTART;";
        let mut parser = Parser::new(&data);
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "DTSTART;",
                name: "DTSTART",
                params: "",
                value: "",
            })
        );
        assert_eq!(parser.next(), None);
    }

    #[test]
    fn test_invalid_name_with_trailing_colon() {
        let data = "DTSTART:";
        let mut parser = Parser::new(&data);
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "DTSTART:",
                name: "DTSTART",
                params: "",
                value: "",
            })
        );
        assert_eq!(parser.next(), None);
    }

    #[test]
    fn test_remainder() {
        let data = vec!["BEGIN:VTODO", "SUMMARY:Do the thing"].join("\r\n");
        let mut parser = Parser::new(&data);
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "BEGIN:VTODO",
                name: "BEGIN",
                params: "",
                value: "VTODO",
            })
        );
        assert_eq!(parser.remainder(), "SUMMARY:Do the thing");
        assert_eq!(
            parser.next(),
            Some(ContentLine {
                raw: "SUMMARY:Do the thing",
                name: "SUMMARY",
                params: "",
                value: "Do the thing",
            })
        );
        assert_eq!(parser.next(), None);
    }

    #[test]
    fn test_fold_multiline() {
        assert_eq!(
            unfold_lines("UID:horrible-\r\n example"),
            "UID:horrible-example"
        );
        assert_eq!(unfold_lines("UID:X\r\n Y"), "UID:XY");
        assert_eq!(unfold_lines("UID:X\r\n "), "UID:X");
        assert_eq!(
            unfold_lines("UID:quite\r\n a\r\n few\r\n lines"),
            "UID:quiteafewlines"
        );
    }

    #[test]
    #[should_panic]
    fn test_fold_multiline_missing_whitespace() {
        unfold_lines("UID:two\r\nlines");
    }

    #[test]
    fn test_normalise_folds_short() {
        let data = "SUMMARY:Hello there";
        let mut parser = Parser::new(data);
        let line = parser.next().unwrap();
        assert_eq!(parser.next(), None);

        assert_eq!(line.normalise_folds(), data);
        assert!(matches!(line.normalise_folds(), Cow::Borrowed(_)));
    }

    #[test]
    fn test_normalise_folds_with_carrige_returns() {
        let data = "SUMMARY:Hello \rthere";
        let mut parser = Parser::new(data);
        let line = parser.next().unwrap();
        assert_eq!(parser.next(), None);

        assert_eq!(line.normalise_folds(), data);
        assert!(matches!(line.normalise_folds(), Cow::Borrowed(_)));
    }

    #[test]
    fn test_normalise_folds_with_newlines() {
        let data = "SUMMARY:Hello \nthere";
        let mut parser = Parser::new(data);
        let line = parser.next().unwrap();
        assert_eq!(parser.next(), None);

        assert_eq!(line.normalise_folds(), data);
        assert!(matches!(line.normalise_folds(), Cow::Borrowed(_)));
    }

    #[test]
    fn test_normalise_folds_too_many_folds() {
        let data = "SUMMARY:Hello \r\n \r\n there";
        let mut parser = Parser::new(data);
        let line = parser.next().unwrap();
        assert_eq!(parser.next(), None);

        let expected = "SUMMARY:Hello there";
        assert_eq!(line.normalise_folds(), expected);
    }

    #[test]
    fn test_normalise_folds_long() {
        let data = vec![
            "SUMMARY:Some really long text that nobody ",
            " cares about, but is wrapped in two lines.",
        ]
        .join("\r\n");
        let mut parser = Parser::new(&data);
        let line = parser.next().unwrap();
        assert_eq!(parser.next(), None);

        let expected = vec![
            "SUMMARY:Some really long text that nobody cares about, but is wrapped in t",
            " wo lines.",
        ]
        .join("\r\n");
        assert_eq!(line.normalise_folds(), expected);
    }

    #[test]
    fn test_normalise_folds_multibyte() {
        // This is 59 characters, 161 octets
        let data = vec![
            "SUMMARY:動千首看院波未假遠子到花,白六到星害,馬吃牠說衣欠去皮香收司意,青個話化汁喜視娘以男雪青土已升斤法兌。"
        ]
        .join("\r\n");
        let mut parser = Parser::new(&data);
        let line = parser.next().unwrap();
        assert_eq!(parser.next(), None);

        let expected = vec![
            // Keep in mind that CR counts, but LF does not.
            "SUMMARY:動千首看院波未假遠子到花,白六到星害,馬吃牠", // 74
            " 說衣欠去皮香收司意,青個話化汁喜視娘以男雪青土已",    // 73
            " 升斤法兌。",                                          // 16
        ]
        .join("\r\n");
        assert_eq!(line.normalise_folds(), expected);
    }

    #[test]
    fn test_normalise_folds_multibyte_noop() {
        // This is 59 characters, 161 octets
        let data = vec![
            // Keep in mind that CR counts, but LF does not.
            "SUMMARY:動千首看院波未假遠子到花,白六到星害,馬吃牠", // 74
            " 說衣欠去皮香收司意,青個話化汁喜視娘以男雪青土已",    // 73
            " 升斤法兌。",                                          // 16
        ]
        .join("\r\n");
        let mut parser = Parser::new(&data);
        let line = parser.next().unwrap();
        assert_eq!(parser.next(), None);

        assert_eq!(line.normalise_folds(), data);
        assert!(matches!(line.normalise_folds(), Cow::Borrowed(_)));
    }
}

/// Unfold multiple continuation lines into a single line.
///
/// # Panics
///
/// If the input string has multiple non-continuation lines.
fn unfold_lines(lines: &str) -> Cow<str> {
    let mut result = Cow::Borrowed(lines);
    let mut cur = 0;

    let mut chars = lines.char_indices().peekable();
    while let Some((i, c)) = chars.next() {
        if c != '\r' {
            continue;
        }
        if !chars.peek().is_some_and(|(_, c)| *c == '\n') {
            continue; // Not CRLF.
        };
        chars.next(); // Advance the peeked LF.

        assert!(
            matches!(chars.next(), Some((_, ' ' | '\t'))),
            "continuation line is not a continuation line",
        );

        let portion = &lines[cur..i];
        match result {
            Cow::Borrowed(_) => {
                result = Cow::Owned(portion.to_owned());
            }
            Cow::Owned(ref mut s) => {
                s.push_str(portion);
            }
        }
        cur = i + 3;
    }

    if let Cow::Owned(ref mut s) = result {
        let portion = &lines[cur..];
        s.push_str(portion);
    }

    result
}