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
// Copyright 2023 Hugo Osvaldo Barrera
//
// SPDX-License-Identifier: ISC

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

use std::{borrow::Cow, iter::Peekable, str::CharIndices};

/// A valid content line.
///
/// Continuatoin 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)]
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 folded.
    #[must_use]
    pub fn name(&self) -> Cow<'input, str> {
        fold_lines(self.name)
    }

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

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

    /// Normalise wrapping by extending each line to be as long as possible.
    ///
    /// # Panics
    ///
    /// Not implemented.
    #[must_use]
    pub fn re_wrapped(&self) -> Cow<'input, str> {
        todo!()
    }
}

/// 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<CharIndices<'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.char_indices().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, ';')) => loop {
                    match self.characters.next() {
                        Some((colon, ':')) => loop {
                            match self.characters.next() {
                                Some((cr, '\r')) => {
                                    if !matches!(self.characters.peek(), Some((_, '\n'))) {
                                        continue; // Not CRLF.
                                    };
                                    self.characters.next(); // Advance the peeked LF.
                                    if matches!(self.characters.peek(), Some((_, ' ' | '\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((_, '"')) => loop {
                            match self.characters.next() {
                                Some((_, '"')) => 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, '\r')) => {
                            if !matches!(self.characters.peek(), Some((_, '\n'))) {
                                continue; // Not CRLF.
                            };
                            self.characters.next(); // Advance the peeked LF.
                            if matches!(self.characters.peek(), Some((_, ' ' | '\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, ':')) => loop {
                    match self.characters.next() {
                        Some((cr, '\r')) => {
                            if !matches!(self.characters.peek(), Some((_, '\n'))) {
                                continue; // Not CRLF.
                            };
                            self.characters.next(); // Advance the peeked LF.
                            if matches!(self.characters.peek(), Some((_, ' ' | '\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, '\r')) => {
                    if !matches!(self.characters.peek(), Some((_, '\n'))) {
                        continue; // Not CRLF.
                    };
                    self.characters.next(); // Advance the peeked LF.
                    if matches!(self.characters.peek(), Some((_, ' ' | '\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::{ContentLine, Parser};

    #[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);
    }
}

/// Fold multiple continuation lines into a single line.
///
/// # Panics
///
/// If the input string has multiple non-continuation lines.
fn fold_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 !matches!(chars.peek(), Some((_, '\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;
    }

    result
}