ical-rs 0.5.0

iCalendar 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
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
//! # Concrete syntax tree
//!
//! The core representation: a whole calendar as generic, byte-faithful syntax.
//!
//! [`IcalCst`] is the hub of the crate. It models a component (the
//! `VCALENDAR` and every nested `VEVENT`, `VALARM`, `VTIMEZONE`, ...) as a
//! `BEGIN` / `END` envelope wrapping an ordered body of
//! [`items`](IcalCst::items): property lines and nested components.
//!
//! They are kept in source order, so anything round-trips byte for byte even
//! when a producer interleaves them. The tree itself knows nothing about what
//! a property or component *means*.
//!
//! It is filled from bytes ([`parse`](IcalCst::parse)) or from typed items,
//! and exports its bytes byte-faithfully ([`to_bytes`](IcalCst::to_bytes), or
//! the lossy-for-non-UTF-8 [`Display`](core::fmt::Display)).
//!
//! Typed access goes by lens ([`prop`](IcalCst::prop),
//! [`prop_mut`](IcalCst::prop_mut), [`component`](IcalCst::component)).
//!
//! The semantic projection ([`decode`](IcalCst::decode)) and the codec live
//! in the [`decode`](crate::tree::codec::decode) /
//! [`encode`](crate::tree::codec::encode) siblings.
//!
//! # Examples
//!
//! ```rust
//! use ical::tree::cst::IcalCst;
//! use ical::component::vevent::VEVENT;
//! use ical::prop::summary::SUMMARY;
//!
//! let raw = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//x//EN\r\nBEGIN:VEVENT\r\nUID:1\r\nDTSTAMP:20260101T000000Z\r\nSUMMARY:Lunch\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
//! let mut cst = IcalCst::parse(raw).unwrap();
//! assert_eq!(cst.to_string(), raw);
//!
//! cst.component_mut::<VEVENT>()
//!     .unwrap()
//!     .prop_mut::<SUMMARY>()
//!     .unwrap()
//!     .set_text("Dinner");
//! assert!(cst.to_string().contains("SUMMARY:Dinner\r\n"));
//! ```

use core::{fmt, iter, mem};

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

use crate::{
    component::spec::IcalComponentSpec,
    prop::IcalProp,
    tree::{codec::mode::Escaper, error::IcalParseError, line::IcalLine, prop::lens::IcalPropLens},
    version::IcalVersion,
};

/// One item in a component body: a property line, or a nested component.
#[derive(Clone, Debug)]
pub enum IcalItem<'a> {
    /// A property line.
    Prop(IcalLine<'a>),
    /// A nested component (its own `BEGIN` / `END` subtree). Boxed, since a
    /// component is recursive and a property line is not.
    Component(Box<IcalCst<'a>>),
    /// One physical line that could not be structured, kept verbatim (its
    /// ending included) so it still round-trips. Only
    /// [`parse_recovering`](IcalCst::parse_recovering) ever produces one: the
    /// strict entry points refuse the calendar instead.
    Opaque(Cow<'a, [u8]>),
}

/// A component as raw syntax: an optional envelope and its ordered body.
///
/// The `BEGIN` / `END` envelope wraps property lines and nested components, in
/// source order. Used for the `VCALENDAR` root and every subcomponent alike;
/// it is absent only for a bare record parsed by [`parse`](IcalCst::parse).
#[derive(Clone, Debug)]
pub struct IcalCst<'a> {
    /// The `BEGIN` line, or `None` for a bare record parsed without an
    /// envelope.
    pub begin: Option<IcalLine<'a>>,
    /// The body items (property lines and nested components), in source order.
    pub items: Vec<IcalItem<'a>>,
    /// The `END` line, absent exactly when [`begin`](Self::begin) is.
    pub end: Option<IcalLine<'a>>,
    /// The blank lines after `END`, kept so a file ending in one round-trips.
    /// Only ever set on a root calendar, and only when nothing but whitespace
    /// follows it.
    pub trailing: Cow<'a, str>,
}

impl<'a> IcalCst<'a> {
    /// Start an empty iCalendar 2.0 calendar, BEGIN/VERSION/END seeded, ready
    /// for properties and components.
    pub fn v2() -> Self {
        Self {
            begin: Some(IcalLine::text("BEGIN", "VCALENDAR")),
            items: vec![IcalItem::Prop(IcalLine::text(
                "VERSION",
                &*IcalVersion::V2_0,
            ))],
            end: Some(IcalLine::text("END", "VCALENDAR")),
            trailing: Cow::Borrowed(""),
        }
    }

    /// Parse the first calendar from raw text, borrowed for the Cst lifetime.
    ///
    /// A bare, envelope-less record (every line a property) is also accepted,
    /// so a lone component fragment round-trips. Anything after the first
    /// calendar is dropped, except trailing blank lines, which are kept: use
    /// [`parse_many`](Self::parse_many) to read a multi-calendar file whole.
    pub fn parse<T: AsRef<[u8]> + ?Sized>(input: &'a T) -> Result<Self, IcalParseError> {
        let input = input.as_ref();
        let (first, _rest) = IcalLine::take(input)?;

        if first.name.get().eq_ignore_ascii_case("BEGIN") {
            let (mut cst, rest) = Self::take_component(input)?;
            cst.take_trailing(rest);
            let escaper = Escaper::for_version_str(&cst.version_str());
            cst.stamp_escaper(escaper);
            Ok(cst)
        } else {
            Self::parse_bare(input)
        }
    }

    /// Parse a bare, envelope-less record: every line becomes a property.
    fn parse_bare(input: &'a [u8]) -> Result<Self, IcalParseError> {
        let mut items: Vec<IcalItem<'a>> = Vec::new();
        let mut rest = input;

        while !is_blank(rest) {
            let (line, tail) = IcalLine::take(rest)?;
            items.push(IcalItem::Prop(line));
            rest = tail;
        }

        let mut cst = Self {
            begin: None,
            items,
            end: None,
            trailing: Cow::Borrowed(""),
        };
        cst.take_trailing(rest);
        let escaper = Escaper::for_version_str(&cst.version_str());
        cst.stamp_escaper(escaper);
        Ok(cst)
    }

    /// Parse every top-level calendar in the input, lazily, one item each.
    ///
    /// An item is a calendar or the parse error that stopped iteration. Blank
    /// lines between calendars belong to the calendar that follows them, and
    /// those after the last one to the last calendar, so concatenating what
    /// this yields reproduces the file byte for byte.
    pub fn parse_many<T: AsRef<[u8]> + ?Sized>(
        input: &'a T,
    ) -> impl Iterator<Item = Result<Self, IcalParseError>> {
        let mut rest = input.as_ref();

        iter::from_fn(move || {
            if is_blank(rest) {
                return None;
            }

            match Self::take_component(rest) {
                Ok((mut cst, tail)) => {
                    rest = cst.take_trailing(tail);
                    let escaper = Escaper::for_version_str(&cst.version_str());
                    cst.stamp_escaper(escaper);
                    Some(Ok(cst))
                }
                Err(error) => {
                    rest = b"";
                    Some(Err(error))
                }
            }
        })
    }

    /// Parse the whole input, recovering from anything that cannot be
    /// structured instead of refusing the calendar.
    ///
    /// A physical line with no colon, or whose name is not UTF-8, is kept as
    /// an [`Opaque`](IcalItem::Opaque) item and parsing carries on, and a
    /// component left open at end of input is closed with no `END`. The bytes
    /// survive either way, so the recovered calendars serialize back unchanged.
    ///
    /// Every problem is reported in [`IcalRecovery::problems`]. The strict
    /// [`parse`](Self::parse) and [`parse_many`](Self::parse_many) stay the
    /// default: use this when a calendar from the wild matters more than the
    /// guarantee it was well formed.
    pub fn parse_recovering<T: AsRef<[u8]> + ?Sized>(input: &'a T) -> IcalRecovery<'a> {
        let mut rest = input.as_ref();
        let mut recovery = IcalRecovery::default();

        // NOTE: Items outside any BEGIN, which is where a bare record's
        // properties and any stray line land.
        let mut loose: Vec<IcalItem<'a>> = Vec::new();

        while !is_blank(rest) {
            match IcalLine::take(rest) {
                Ok((line, _tail)) if line.name.get().eq_ignore_ascii_case("BEGIN") => {
                    recovery.close_loose(&mut loose);

                    let (mut cst, tail) = Self::take_component_recovering(rest, &mut recovery);
                    rest = tail;
                    let escaper = Escaper::for_version_str(&cst.version_str());
                    cst.stamp_escaper(escaper);
                    recovery.calendars.push(cst);
                }
                Ok((line, tail)) => {
                    loose.push(IcalItem::Prop(line));
                    rest = tail;
                }
                Err(error) => {
                    let (opaque, tail) = IcalLine::take_physical(rest);
                    loose.push(IcalItem::Opaque(Cow::Borrowed(opaque)));
                    recovery.problems.push(error);
                    rest = tail;
                }
            }
        }

        recovery.close_loose(&mut loose);

        if let Some(last) = recovery.calendars.last_mut() {
            last.take_trailing(rest);
        } else {
            let mut bare = Self::bare(Vec::new());
            bare.take_trailing(rest);
            recovery.calendars.push(bare);
        }

        recovery
    }

    /// Take one component recovering from what it cannot structure: an
    /// unstructurable line becomes an opaque item, and an unclosed component is
    /// closed at end of input.
    fn take_component_recovering(
        input: &'a [u8],
        recovery: &mut IcalRecovery<'a>,
    ) -> (Self, &'a [u8]) {
        // NOTE: The caller only ever enters here on a line that tokenised as
        // BEGIN.
        let (begin, mut rest) = IcalLine::take(input).expect("a BEGIN line");
        let name = begin.raw_value_str().into_owned();

        let mut items: Vec<IcalItem<'a>> = Vec::new();

        loop {
            if is_blank(rest) {
                recovery.problems.push(IcalParseError::MissingEnd(name));
                return (
                    Self {
                        begin: Some(begin),
                        items,
                        end: None,
                        trailing: Cow::Borrowed(""),
                    },
                    rest,
                );
            }

            match IcalLine::take(rest) {
                Ok((line, tail)) => {
                    let line_name = line.name.get();

                    if line_name.eq_ignore_ascii_case("END") {
                        return (
                            Self {
                                begin: Some(begin),
                                items,
                                end: Some(line),
                                trailing: Cow::Borrowed(""),
                            },
                            tail,
                        );
                    }

                    if line_name.eq_ignore_ascii_case("BEGIN") {
                        let (child, next) = Self::take_component_recovering(rest, recovery);
                        items.push(IcalItem::Component(Box::new(child)));
                        rest = next;
                        continue;
                    }

                    items.push(IcalItem::Prop(line));
                    rest = tail;
                }
                Err(error) => {
                    let (opaque, tail) = IcalLine::take_physical(rest);
                    items.push(IcalItem::Opaque(Cow::Borrowed(opaque)));
                    recovery.problems.push(error);
                    rest = tail;
                }
            }
        }
    }

    /// A bare, envelope-less calendar around `items`.
    fn bare(items: Vec<IcalItem<'a>>) -> Self {
        Self {
            begin: None,
            items,
            end: None,
            trailing: Cow::Borrowed(""),
        }
    }

    /// Keep `rest` as this calendar's trailing blank lines when nothing but
    /// whitespace follows, and report what is left to parse.
    fn take_trailing(&mut self, rest: &'a [u8]) -> &'a [u8] {
        if !is_blank(rest) {
            return rest;
        }

        self.trailing = Cow::Borrowed(str::from_utf8(rest).unwrap_or(""));
        b""
    }

    /// Take one component (recursively) off the front of `input`, returning it
    /// and the unconsumed rest. A nested `BEGIN` recurses; the matching `END`
    /// closes this component.
    fn take_component(input: &'a [u8]) -> Result<(Self, &'a [u8]), IcalParseError> {
        let (begin, mut rest) = IcalLine::take(input)?;

        if !begin.name.get().eq_ignore_ascii_case("BEGIN") {
            return Err(IcalParseError::ExpectedBegin(begin.name.get().to_string()));
        }

        let mut items: Vec<IcalItem<'a>> = Vec::new();

        loop {
            if rest.is_empty() {
                // NOTE: The component's name, not the whole input: an error
                // that carries a megabyte of calendar is not a diagnostic.
                return Err(IcalParseError::MissingEnd(
                    begin.raw_value_str().into_owned(),
                ));
            }

            let (line, tail) = IcalLine::take(rest)?;
            let name = line.name.get();

            if name.eq_ignore_ascii_case("END") {
                return Ok((
                    Self {
                        begin: Some(begin),
                        items,
                        end: Some(line),
                        trailing: Cow::Borrowed(""),
                    },
                    tail,
                ));
            }

            if name.eq_ignore_ascii_case("BEGIN") {
                let (child, next) = Self::take_component(rest)?;
                items.push(IcalItem::Component(Box::new(child)));
                rest = next;
                continue;
            }

            items.push(IcalItem::Prop(line));
            rest = tail;
        }
    }

    /// Stamp the escaping mode onto every value and parameter node in the
    /// subtree, once the root `VERSION` is known (it can only be determined for
    /// the whole tree).
    fn stamp_escaper(&mut self, escaper: Escaper) {
        for item in &mut self.items {
            match item {
                IcalItem::Prop(line) => {
                    line.value.escaper = escaper;
                    for param in &mut line.params {
                        param.escaper = escaper;
                    }
                }
                IcalItem::Component(child) => child.stamp_escaper(escaper),
                IcalItem::Opaque(_) => {}
            }
        }
    }

    /// The `VERSION` line among this component's direct properties, if any.
    fn version_str(&self) -> Cow<'_, str> {
        self.items
            .iter()
            .find_map(|item| match item {
                IcalItem::Prop(line) if line.name.get().eq_ignore_ascii_case("VERSION") => {
                    Some(line.raw_value_str())
                }
                _ => None,
            })
            .unwrap_or(Cow::Borrowed(""))
    }

    /// The calendar's version indicator, read from its `VERSION` line. An
    /// unrecognised or missing version normalises to
    /// [`V2_0`](IcalVersion::V2_0).
    pub fn version(&self) -> IcalVersion {
        self.version_str().parse().unwrap_or(IcalVersion::V2_0)
    }

    /// Append a typed property to this component, encoding it into a line.
    pub fn push(&mut self, prop: IcalProp<'a>) -> &mut Self {
        let escaper = Escaper::for_version_str(&self.version_str());
        self.items.push(IcalItem::Prop(prop.encode(escaper)));
        self
    }

    /// Append a nested component to this one.
    pub fn push_component(&mut self, component: IcalCst<'a>) -> &mut Self {
        self.items.push(IcalItem::Component(Box::new(component)));
        self
    }

    /// Remove every property of type `L` from this component's direct
    /// properties.
    pub fn remove<L: IcalPropLens>(&mut self) -> &mut Self {
        self.items.retain(|item| match item {
            IcalItem::Prop(line) => !line.name.get().eq_ignore_ascii_case(&L::KIND),
            IcalItem::Component(_) => true,
            IcalItem::Opaque(_) => true,
        });
        self
    }

    /// The first direct property of type `L`, decoded into a borrowed snapshot.
    pub fn prop<L: IcalPropLens>(&self) -> Option<L::Target<'_>> {
        let version = self.version();
        self.items.iter().find_map(|item| match item {
            IcalItem::Prop(line) if line.name.get().eq_ignore_ascii_case(&L::KIND) => {
                Some(L::decode(line, version))
            }
            _ => None,
        })
    }

    /// The first direct property of type `L`, as a typed cursor for in-place
    /// editing.
    pub fn prop_mut<L: IcalPropLens>(&mut self) -> Option<L::Cursor<'_, 'a>> {
        self.items.iter_mut().find_map(|item| match item {
            IcalItem::Prop(line) if line.name.get().eq_ignore_ascii_case(&L::KIND) => {
                Some(L::cursor(line))
            }
            _ => None,
        })
    }

    /// The first direct child component of type `C`, as a borrowed subtree.
    pub fn component<C: IcalComponentSpec>(&self) -> Option<&IcalCst<'a>> {
        self.items.iter().find_map(|item| match item {
            IcalItem::Component(child) if child.is_kind::<C>() => Some(&**child),
            _ => None,
        })
    }

    /// The first direct child component of type `C`, mutably.
    pub fn component_mut<C: IcalComponentSpec>(&mut self) -> Option<&mut IcalCst<'a>> {
        self.items.iter_mut().find_map(|item| match item {
            IcalItem::Component(child) if child.is_kind::<C>() => Some(&mut **child),
            _ => None,
        })
    }

    /// Every direct child component of type `C`, in source order.
    pub fn components<C: IcalComponentSpec>(&self) -> impl Iterator<Item = &IcalCst<'a>> {
        self.items.iter().filter_map(|item| match item {
            IcalItem::Component(child) if child.is_kind::<C>() => Some(&**child),
            _ => None,
        })
    }

    /// Whether this component's `BEGIN` name matches the component marker `C`.
    fn is_kind<C: IcalComponentSpec>(&self) -> bool {
        self.begin
            .as_ref()
            .map(|begin| begin.raw_value_str().eq_ignore_ascii_case(&C::KIND))
            .unwrap_or(false)
    }

    /// The wire name of this component (its `BEGIN` value), or `""` for a bare
    /// record.
    pub(crate) fn component_name(&self) -> Cow<'_, str> {
        self.begin
            .as_ref()
            .map(|begin| begin.raw_value_str())
            .unwrap_or(Cow::Borrowed(""))
    }

    /// Own every borrowed leaf, detaching the calendar from the source bytes so
    /// it can outlive them.
    pub fn into_static(self) -> IcalCst<'static> {
        IcalCst {
            begin: self.begin.map(IcalLine::into_static),
            items: self
                .items
                .into_iter()
                .map(|item| match item {
                    IcalItem::Prop(line) => IcalItem::Prop(line.into_static()),
                    IcalItem::Component(child) => {
                        IcalItem::Component(Box::new(child.into_static()))
                    }
                    IcalItem::Opaque(bytes) => IcalItem::Opaque(Cow::Owned(bytes.into_owned())),
                })
                .collect(),
            end: self.end.map(IcalLine::into_static),
            trailing: Cow::Owned(self.trailing.into_owned()),
        }
    }

    /// Serialize the calendar to raw bytes, exactly as parsed.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = Vec::new();
        self.write_bytes(&mut out);
        out
    }

    fn write_bytes(&self, out: &mut Vec<u8>) {
        if let Some(begin) = &self.begin {
            begin.write_bytes(out);
        }
        for item in &self.items {
            match item {
                IcalItem::Prop(line) => line.write_bytes(out),
                IcalItem::Opaque(bytes) => out.extend_from_slice(bytes),
                IcalItem::Component(child) => child.write_bytes(out),
            }
        }
        if let Some(end) = &self.end {
            end.write_bytes(out);
        }
        out.extend_from_slice(self.trailing.as_bytes());
    }
}

/// What a recovering parse read: the calendars it could structure, and every
/// problem it worked around.
///
/// The bytes are never lost, whatever the problems: serializing the calendars
/// in order reproduces the input.
#[derive(Clone, Debug, Default)]
pub struct IcalRecovery<'a> {
    /// Every top-level calendar, in source order. A run of lines outside any
    /// `BEGIN` becomes a bare, envelope-less calendar of its own.
    pub calendars: Vec<IcalCst<'a>>,
    /// What could not be structured, in the order it was met.
    pub problems: Vec<IcalParseError>,
}

impl<'a> IcalRecovery<'a> {
    /// Whether the input parsed with nothing to work around, in which case a
    /// strict parse would have accepted it too.
    pub fn is_clean(&self) -> bool {
        self.problems.is_empty()
    }

    /// Serialize every calendar, in order: the input, byte for byte.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = Vec::new();

        for cst in &self.calendars {
            cst.write_bytes(&mut out);
        }

        out
    }

    /// Close a run of loose items into a bare calendar, if there is one.
    fn close_loose(&mut self, loose: &mut Vec<IcalItem<'a>>) {
        if loose.is_empty() {
            return;
        }

        self.calendars.push(IcalCst::bare(mem::take(loose)));
    }
}

/// Whether nothing but blank-line bytes (`\r` / `\n`) is left.
fn is_blank(bytes: &[u8]) -> bool {
    bytes.iter().all(|byte| matches!(byte, b'\r' | b'\n'))
}

impl fmt::Display for IcalCst<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(begin) = &self.begin {
            write!(f, "{begin}")?;
        }
        for item in &self.items {
            match item {
                IcalItem::Prop(line) => write!(f, "{line}")?,
                IcalItem::Opaque(bytes) => f.write_str(&String::from_utf8_lossy(bytes))?,
                IcalItem::Component(child) => write!(f, "{child}")?,
            }
        }
        if let Some(end) = &self.end {
            write!(f, "{end}")?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use alloc::{
        string::{String, ToString},
        vec::Vec,
    };

    use crate::{
        component::vevent::VEVENT,
        prop::{prodid::PRODID, summary::SUMMARY},
        tree::{cst::IcalCst, error::IcalParseError},
        version::IcalVersion,
    };

    const CAL: &str = concat!(
        "BEGIN:VCALENDAR\r\n",
        "VERSION:2.0\r\n",
        "PRODID:-//Example//EN\r\n",
        "BEGIN:VEVENT\r\n",
        "UID:1\r\n",
        "DTSTAMP:20260101T000000Z\r\n",
        "SUMMARY:Lunch\r\n",
        "BEGIN:VALARM\r\n",
        "ACTION:DISPLAY\r\n",
        "TRIGGER:-PT15M\r\n",
        "END:VALARM\r\n",
        "END:VEVENT\r\n",
        "END:VCALENDAR\r\n",
    );

    #[test]
    fn round_trips_a_nested_calendar_byte_for_byte() {
        let cst = IcalCst::parse(CAL).unwrap();
        assert_eq!(cst.to_string(), CAL);
    }

    #[test]
    fn reads_a_nested_property_through_component_and_prop_lenses() {
        let cst = IcalCst::parse(CAL).unwrap();
        let event = cst.component::<VEVENT>().expect("a VEVENT");
        assert_eq!(&*event.prop::<SUMMARY>().unwrap().0, "Lunch");
    }

    #[test]
    fn edits_a_nested_property_leaving_every_other_byte_intact() {
        let mut cst = IcalCst::parse(CAL).unwrap();
        cst.component_mut::<VEVENT>()
            .unwrap()
            .prop_mut::<SUMMARY>()
            .unwrap()
            .set_text("Dinner");
        assert_eq!(
            cst.to_string(),
            CAL.replace("SUMMARY:Lunch", "SUMMARY:Dinner")
        );
    }

    #[test]
    fn reports_the_version() {
        let cst = IcalCst::parse(CAL).unwrap();
        assert_eq!(cst.version(), IcalVersion::V2_0);
    }

    #[test]
    fn round_trips_a_folded_calendar_byte_for_byte() {
        // NOTE: What a real exporter emits: folded at a column, blank lines
        // between components, and a blank line at the end of the file.
        let raw = concat!(
            "BEGIN:VCALENDAR\r\n",
            "VERSION:2.0\r\n",
            "PRODID:-//Example//EN\r\n",
            "\r\n",
            "BEGIN:VEVENT\r\n",
            "UID:1\r\n",
            "DTSTAMP:20260101T000000Z\r\n",
            "DESCRIPTION:a very long description that an exporter would fold at s\r\n",
            " ome column\r\n",
            "END:VEVENT\r\n",
            "END:VCALENDAR\r\n",
            "\r\n",
        );

        let cst = IcalCst::parse(raw).unwrap();
        assert_eq!(String::from_utf8(cst.to_bytes()).unwrap(), raw);
    }

    #[test]
    fn round_trips_a_leading_blank_line() {
        let raw = "\r\nBEGIN:VCALENDAR\r\nVERSION:2.0\r\nEND:VCALENDAR\r\n";
        let cst = IcalCst::parse(raw).unwrap();
        assert_eq!(String::from_utf8(cst.to_bytes()).unwrap(), raw);
    }

    #[test]
    fn round_trips_a_quoted_printable_value_ending_on_two_equals() {
        // NOTE: The tokeniser records the soft break past the last logical
        // byte and the splitter the dangling `=` before it, so a wire shape
        // ordered by list rather than by offset emits `x=\r\n=` and the
        // reparse swallows the END line.
        let raw = concat!(
            "BEGIN:VCALENDAR\r\n",
            "VERSION:2.0\r\n",
            "NOTE;ENCODING=QUOTED-PRINTABLE:x==\r\n",
            "\r\n",
            "END:VCALENDAR\r\n",
        );

        let cst = IcalCst::parse(raw).unwrap();
        let bytes = cst.to_bytes();

        assert_eq!(String::from_utf8(bytes.clone()).unwrap(), raw);
        assert_eq!(IcalCst::parse(&bytes).unwrap().to_bytes(), bytes);
    }

    #[test]
    fn round_trips_a_whole_multi_calendar_file() {
        // NOTE: `parse` reads the first calendar and stops, so a file holding
        // several round-trips through `parse_many`, whose output concatenates
        // to the input, blank lines between calendars included.
        let raw = concat!(
            "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nEND:VCALENDAR\r\n",
            "\r\n",
            "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nEND:VCALENDAR\r\n",
        );

        let mut out = Vec::new();
        for cst in IcalCst::parse_many(raw) {
            out.extend_from_slice(&cst.unwrap().to_bytes());
        }

        assert_eq!(String::from_utf8(out).unwrap(), raw);
    }

    #[test]
    fn recovers_a_line_with_no_colon() {
        let raw = concat!(
            "BEGIN:VCALENDAR\r\nVERSION:2.0\r\n",
            "this line has no colon\r\n",
            "PRODID:-//Example//EN\r\nEND:VCALENDAR\r\n",
        );

        assert!(IcalCst::parse(raw).is_err());

        let recovery = IcalCst::parse_recovering(raw);
        assert_eq!(String::from_utf8(recovery.to_bytes()).unwrap(), raw);
        assert_eq!(recovery.calendars.len(), 1);
        assert!(matches!(
            recovery.problems.as_slice(),
            [IcalParseError::MissingPropertyColon(_)]
        ));

        let cal = &recovery.calendars[0];
        assert_eq!(&*cal.prop::<PRODID>().unwrap().0, "-//Example//EN");
    }

    #[test]
    fn recovers_a_component_with_no_end() {
        let raw = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:1\r\n";

        assert!(IcalCst::parse(raw).is_err());

        let recovery = IcalCst::parse_recovering(raw);
        assert_eq!(String::from_utf8(recovery.to_bytes()).unwrap(), raw);
        assert_eq!(
            recovery.problems,
            [
                IcalParseError::MissingEnd("VEVENT".into()),
                IcalParseError::MissingEnd("VCALENDAR".into()),
            ]
        );
        assert!(recovery.calendars[0].component::<VEVENT>().is_some());
    }

    #[test]
    fn reports_nothing_for_a_calendar_the_strict_parser_accepts() {
        let recovery = IcalCst::parse_recovering(CAL);
        assert!(recovery.is_clean());
        assert_eq!(String::from_utf8(recovery.to_bytes()).unwrap(), CAL);
    }

    #[test]
    fn refolds_nothing_once_a_value_is_edited() {
        let raw = concat!(
            "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\n",
            "SUMMARY:a summary long enough to have been fol\r\n ded by its exporter\r\n",
            "END:VEVENT\r\nEND:VCALENDAR\r\n",
        );

        let mut cst = IcalCst::parse(raw).unwrap();
        cst.component_mut::<VEVENT>()
            .unwrap()
            .prop_mut::<SUMMARY>()
            .unwrap()
            .set_text("Dinner");

        assert_eq!(
            String::from_utf8(cst.to_bytes()).unwrap(),
            concat!(
                "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\n",
                "SUMMARY:Dinner\r\n",
                "END:VEVENT\r\nEND:VCALENDAR\r\n",
            )
        );
    }
}