ical-rs 0.5.1

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
//! # Decode (syntax to model)
//!
//! The read side of the structural bridge: project a raw syntax tree onto the
//! decoded model.
//!
//! A [`IcalValueNode`] decodes its components, a [`IcalParamNode`] decodes
//! into an [`IcalParam`], an [`IcalLine`] decodes into an [`IcalProp`], and an
//! [`IcalCst`] decodes into a whole [`Ical`], recursively, walking every
//! nested component.
//!
//! A property's value kind is resolved through its spec, not a name match:
//! [`IcalLine::decode`] maps the name to an [`IcalPropKind`], asks the spec
//! for the in-force value kind (version plus any declared `VALUE`), then
//! routes to that kind's decoder.
//!
//! The parameter name dispatch is the match in [`IcalParamNode::decode`].

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

use crate::{
    component::{IcalComponent, IcalComponentName},
    ical::Ical,
    param::{IcalParam, IcalParamKind},
    prop::{IcalProp, IcalPropKind, IcalPropName, spec::prop_spec},
    tree::{
        codec::{Codec, unescape::unescape_param},
        cst::{IcalCst, IcalItem},
        line::IcalLine,
        param::node::IcalParamNode,
        value::node::IcalValueNode,
    },
    value::{
        IcalUnknownValue, IcalValue, IcalValueKind,
        binary::IcalBinary,
        boolean::IcalBoolean,
        cal_address::IcalCalAddress,
        datetime::{IcalDate, IcalDateTime, IcalDateTimeList, IcalTime},
        duration::IcalDuration,
        float::IcalFloat,
        geo::IcalGeo,
        integer::IcalInteger,
        period::IcalPeriod,
        recur::IcalRecur,
        request_status::IcalRequestStatus,
        text::{IcalText, IcalTextList},
        uri::IcalUri,
        utc_offset::IcalUtcOffset,
    },
    version::IcalVersion,
};

impl IcalCst<'_> {
    /// Decode the whole calendar into the semantic [`Ical`] model. `VERSION` is
    /// held as the calendar's indicator, not as a free property.
    pub fn decode(&self) -> Ical<'_> {
        let version = self.version();
        let mut props = Vec::new();
        let mut components = Vec::new();

        for item in &self.items {
            match item {
                IcalItem::Prop(line) if line.name.get().eq_ignore_ascii_case("VERSION") => {}
                IcalItem::Prop(line) => props.push(line.decode(version)),
                IcalItem::Component(child) => components.push(child.decode_component(version)),
                // NOTE: An opaque line carried no structure to decode.
                IcalItem::Opaque(_) => {}
            }
        }

        Ical {
            version,
            props,
            components,
        }
    }

    /// Decode a nested component into the recursive [`IcalComponent`] model.
    fn decode_component(&self, version: IcalVersion) -> IcalComponent<'_> {
        let mut props = Vec::new();
        let mut components = Vec::new();

        for item in &self.items {
            match item {
                IcalItem::Prop(line) => props.push(line.decode(version)),
                IcalItem::Component(child) => components.push(child.decode_component(version)),
                // NOTE: An opaque line carried no structure to decode.
                IcalItem::Opaque(_) => {}
            }
        }

        IcalComponent {
            name: IcalComponentName::from(self.component_name()),
            props,
            components,
        }
    }
}

impl IcalLine<'_> {
    /// Decode the line into a typed property. A known property dispatches its
    /// value through the spec (see `decode_value`); an unknown one keeps its
    /// raw components so it round-trips.
    pub fn decode(&self, version: IcalVersion) -> IcalProp<'_> {
        let name = self.name.get();
        let params = self.params.iter().map(IcalParamNode::decode).collect();

        let value = match name.parse::<IcalPropKind>() {
            Ok(prop) => self.decode_value(prop, version),
            // NOTE: A name outside the vocabulary has no spec to consult, but a
            // line that declares its own VALUE has said what to read it as
            // (RFC 5545 3.2.20), and that holds for an X- name as much as for a
            // registered one.
            Err(_) => match self.declared_value_kind() {
                Some(kind) => decode_value_kind(kind, &self.value),
                None => IcalValue::Unknown(IcalUnknownValue::decode(&self.value)),
            },
        };

        IcalProp {
            name: IcalPropName::from(name),
            params,
            value,
        }
    }

    /// Decode a known property's value through its spec: resolve the in-force
    /// value kind from the calendar version and any declared `VALUE`, then run
    /// that kind's decoder over the value node.
    pub(crate) fn decode_value(&self, prop: IcalPropKind, version: IcalVersion) -> IcalValue<'_> {
        let declared = self.declared_value_kind();
        let kind = (prop_spec(prop).value)(version, declared);
        decode_value_kind(kind, &self.value)
    }

    /// The value kind named by this line's `VALUE` parameter, if any.
    fn declared_value_kind(&self) -> Option<IcalValueKind> {
        self.params
            .iter()
            .find(|param| matches!(param.name.get().parse(), Ok(IcalParamKind::Value)))
            .and_then(|param| param.values.first())
            .and_then(|value| value.get().parse::<IcalValueKind>().ok())
    }

    /// Whether the line declares the `QUOTED-PRINTABLE` encoding, as an
    /// `ENCODING=` parameter or a bare token (the 1.0 short form).
    #[cfg(feature = "quoted-printable")]
    pub(crate) fn is_quoted_printable(&self) -> bool {
        self.params.iter().any(param_is_quoted_printable)
    }

    /// The value of this line's `CHARSET` parameter, if any.
    #[cfg(feature = "encoding")]
    pub(crate) fn charset_label(&self) -> Option<&str> {
        self.params
            .iter()
            .find(|param| param.name.get().eq_ignore_ascii_case("CHARSET"))
            .and_then(|param| param.values.first())
            .map(|value| value.get())
    }
}

/// Decode a value node as the given value kind, routing to that value type's
/// [`Codec`].
fn decode_value_kind<'v>(kind: IcalValueKind, node: &'v IcalValueNode<'_>) -> IcalValue<'v> {
    match kind {
        IcalValueKind::Binary => IcalValue::Binary(IcalBinary::decode(node)),
        IcalValueKind::Boolean => IcalValue::Boolean(IcalBoolean::decode(node)),
        IcalValueKind::CalAddress => IcalValue::CalAddress(IcalCalAddress::decode(node)),
        IcalValueKind::Date => IcalValue::Date(IcalDate::decode(node)),
        IcalValueKind::DateTime => IcalValue::DateTime(IcalDateTime::decode(node)),
        IcalValueKind::DateTimeList => IcalValue::DateTimeList(IcalDateTimeList::decode(node)),
        IcalValueKind::Duration => IcalValue::Duration(IcalDuration::decode(node)),
        IcalValueKind::Float => IcalValue::Float(IcalFloat::decode(node)),
        IcalValueKind::Geo => IcalValue::Geo(IcalGeo::decode(node)),
        IcalValueKind::Integer => IcalValue::Integer(IcalInteger::decode(node)),
        IcalValueKind::Period => IcalValue::Period(IcalPeriod::decode(node)),
        IcalValueKind::Recur => IcalValue::Recur(IcalRecur::decode(node)),
        IcalValueKind::RequestStatus => IcalValue::RequestStatus(IcalRequestStatus::decode(node)),
        IcalValueKind::Text => IcalValue::Text(IcalText::decode(node)),
        IcalValueKind::TextList => IcalValue::TextList(IcalTextList::decode(node)),
        IcalValueKind::Time => IcalValue::Time(IcalTime::decode(node)),
        IcalValueKind::Uri => IcalValue::Uri(IcalUri::decode(node)),
        IcalValueKind::UtcOffset => IcalValue::UtcOffset(IcalUtcOffset::decode(node)),
    }
}

impl IcalParamNode<'_> {
    /// Decode the parameter into a typed parameter, dispatching on the name.
    pub fn decode(&self) -> IcalParam<'_> {
        let Ok(kind) = self.name.get().parse::<IcalParamKind>() else {
            return IcalParam::Unknown {
                // NOTE: a parameter name is a token (RFC 5545 3.2), with no
                // encoding of any kind to resolve.
                name: Cow::Borrowed(self.name.get()),
                values: self.list(),
            };
        };

        match kind {
            IcalParamKind::AltRep => IcalParam::AltRep(self.scalar()),
            IcalParamKind::Cn => IcalParam::Cn(self.scalar()),
            IcalParamKind::CuType => IcalParam::CuType(self.scalar()),
            IcalParamKind::DelegatedFrom => IcalParam::DelegatedFrom(self.list()),
            IcalParamKind::DelegatedTo => IcalParam::DelegatedTo(self.list()),
            IcalParamKind::Dir => IcalParam::Dir(self.scalar()),
            IcalParamKind::Encoding => IcalParam::Encoding(self.scalar()),
            IcalParamKind::FmtType => IcalParam::FmtType(self.scalar()),
            IcalParamKind::FbType => IcalParam::FbType(self.scalar()),
            IcalParamKind::Language => IcalParam::Language(self.scalar()),
            IcalParamKind::Member => IcalParam::Member(self.list()),
            IcalParamKind::PartStat => IcalParam::PartStat(self.scalar()),
            IcalParamKind::Range => IcalParam::Range(self.scalar()),
            IcalParamKind::Related => IcalParam::Related(self.scalar()),
            IcalParamKind::RelType => IcalParam::RelType(self.scalar()),
            IcalParamKind::Role => IcalParam::Role(self.scalar()),
            IcalParamKind::Rsvp => IcalParam::Rsvp(self.scalar()),
            IcalParamKind::SentBy => IcalParam::SentBy(self.scalar()),
            IcalParamKind::TzId => IcalParam::TzId(self.scalar()),
            IcalParamKind::Value => IcalParam::Value(self.scalar()),
            IcalParamKind::Display => IcalParam::Display(self.scalar()),
            IcalParamKind::Email => IcalParam::Email(self.scalar()),
            IcalParamKind::Feature => IcalParam::Feature(self.list()),
            IcalParamKind::Label => IcalParam::Label(self.scalar()),
            IcalParamKind::Order => IcalParam::Order(self.scalar()),
            IcalParamKind::Schema => IcalParam::Schema(self.scalar()),
            IcalParamKind::Derived => IcalParam::Derived(self.scalar()),
            IcalParamKind::ScheduleAgent => IcalParam::ScheduleAgent(self.scalar()),
            IcalParamKind::ScheduleForceSend => IcalParam::ScheduleForceSend(self.scalar()),
            IcalParamKind::ScheduleStatus => IcalParam::ScheduleStatus(self.scalar()),
            IcalParamKind::LinkRel => IcalParam::LinkRel(self.scalar()),
            IcalParamKind::Gap => IcalParam::Gap(self.scalar()),
            IcalParamKind::Charset => IcalParam::Charset(self.scalar()),
        }
    }

    /// The parameter's first value, decoded by the RFC 6868 rules (empty when
    /// there is none).
    fn scalar(&self) -> Cow<'_, str> {
        self.values
            .first()
            .map(|v| unescape_param(v.get(), self.escaper))
            .unwrap_or(Cow::Borrowed(""))
    }

    /// The parameter's values, decoded by the RFC 6868 rules.
    fn list(&self) -> Vec<Cow<'_, str>> {
        self.values
            .iter()
            .map(|v| unescape_param(v.get(), self.escaper))
            .collect()
    }
}

/// Whether a parameter is `ENCODING=QUOTED-PRINTABLE` or the bare 1.0 token.
#[cfg(feature = "quoted-printable")]
fn param_is_quoted_printable(param: &IcalParamNode<'_>) -> bool {
    let name = param.name.get();

    (name.eq_ignore_ascii_case("ENCODING")
        && param
            .values
            .iter()
            .any(|v| v.get().eq_ignore_ascii_case("QUOTED-PRINTABLE")))
        || (param.values.is_empty() && name.eq_ignore_ascii_case("QUOTED-PRINTABLE"))
}

#[cfg(test)]
mod tests {
    use alloc::{borrow::Cow, vec};

    use crate::{
        param::IcalParam,
        tree::{
            codec::Codec, cst::IcalCst, param::node::IcalParamNode, value::node::IcalValueNode,
        },
        value::{
            IcalValue,
            binary::IcalBinary,
            boolean::IcalBoolean,
            cal_address::IcalCalAddress,
            datetime::{IcalDate, IcalDateTime, IcalDateTimeList, IcalTime},
            duration::IcalDuration,
            float::IcalFloat,
            integer::IcalInteger,
            period::IcalPeriod,
            recur::IcalRecur,
            request_status::IcalRequestStatus,
            text::{IcalText, IcalTextList},
            uri::IcalUri,
            utc_offset::IcalUtcOffset,
        },
        version::IcalVersion,
    };

    #[test]
    fn decodes_a_calendar_with_a_nested_event() {
        let input = concat!(
            "BEGIN:VCALENDAR\r\n",
            "VERSION:2.0\r\n",
            "PRODID:-//x//EN\r\n",
            "BEGIN:VEVENT\r\n",
            "UID:1\r\n",
            "DTSTART:20260101T120000Z\r\n",
            "SUMMARY:Lunch\r\n",
            "END:VEVENT\r\n",
            "END:VCALENDAR\r\n",
        );
        let cst = IcalCst::parse(input).unwrap();
        let cal = cst.decode();

        assert_eq!(cal.version, IcalVersion::V2_0);
        assert_eq!(cal.props.len(), 1);
        assert_eq!(&*cal.props[0].name, "PRODID");
        assert_eq!(cal.components.len(), 1);

        let event = &cal.components[0];
        assert_eq!(&*event.name, "VEVENT");
        assert_eq!(event.props.len(), 3);
        assert_eq!(
            event.props[1].value,
            IcalValue::DateTime(IcalDateTime(Cow::Borrowed("20260101T120000Z"))),
        );
        assert_eq!(
            event.props[2].value,
            IcalValue::Text(IcalText(Cow::Borrowed("Lunch"))),
        );
    }

    #[test]
    fn an_unknown_property_round_trips_as_unknown() {
        let input = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nX-WR-CALNAME:Work\r\nEND:VCALENDAR\r\n";
        let cst = IcalCst::parse(input).unwrap();
        let cal = cst.decode();
        assert!(matches!(cal.props[0].value, IcalValue::Unknown(_)));
        assert_eq!(&*cal.props[0].name, "X-WR-CALNAME");
    }

    /// A kind with no `;`-structure of its own is decoded whole.
    ///
    /// RFC 5545 3.3.11 has a text value escape a semicolon it means literally
    /// and 3.3.13 gives a URI no structure, so an unescaped `;` is content in
    /// either, and reading component by component dropped everything past it.
    #[test]
    fn decodes_every_unstructured_kind_whole() {
        let node = IcalValueNode::parse(b"a;b,c");

        assert_eq!(IcalText::decode(&node).0, "a;b,c");
        assert_eq!(IcalUri::decode(&node).0, "a;b,c");
        assert_eq!(IcalCalAddress::decode(&node).0, "a;b,c");
        assert_eq!(IcalPeriod::decode(&node).0, "a;b,c");
        assert_eq!(IcalRecur::decode(&node).0, "a;b,c");
        assert_eq!(
            IcalBinary::decode(&node),
            IcalBinary::Base64(Cow::Borrowed("a;b,c")),
        );
        assert_eq!(IcalBoolean::decode(&node).0, "a;b,c");
        assert_eq!(IcalDate::decode(&node).0, "a;b,c");
        assert_eq!(IcalDateTime::decode(&node).0, "a;b,c");
        assert_eq!(IcalTime::decode(&node).0, "a;b,c");
        assert_eq!(IcalDuration::decode(&node).0, "a;b,c");
        assert_eq!(IcalFloat::decode(&node).0, "a;b,c");
        assert_eq!(IcalInteger::decode(&node).0, "a;b,c");
        assert_eq!(IcalUtcOffset::decode(&node).0, "a;b,c");

        // NOTE: A list value owns its commas and nothing else, so only they
        // separate.
        assert_eq!(
            IcalTextList::decode(&node).0,
            vec![Cow::Borrowed("a;b"), Cow::Borrowed("c")],
        );
        assert_eq!(
            IcalDateTimeList::decode(&node).0,
            vec![Cow::Borrowed("a;b"), Cow::Borrowed("c")],
        );
    }

    /// A structured value's component keeps the commas inside it.
    ///
    /// A `REQUEST-STATUS` description is a text, where a comma separates
    /// nothing, so reading only a component's first comma-piece truncated the
    /// status a caller reads.
    #[test]
    fn decodes_a_structured_component_past_its_first_comma() {
        let node = IcalValueNode::parse(br"2.0;Success\, welcome;rcpt,two");
        let status = IcalRequestStatus::decode(&node);

        assert_eq!(status.code, "2.0");
        assert_eq!(status.description, "Success, welcome");
        assert_eq!(status.extra, "rcpt,two");
    }

    #[test]
    fn decodes_the_rfc_6868_parameter_sequences() {
        // NOTE: RFC 6868 section 3.1 spells the three characters a parameter
        // value cannot carry raw.
        let node = IcalParamNode::parse("CN=a^nb^^c^'d");

        assert_eq!(node.decode(), IcalParam::Cn(Cow::Borrowed("a\nb^c\"d")));
    }

    #[test]
    fn keeps_an_unknown_caret_sequence_in_a_parameter() {
        // NOTE: RFC 6868 section 3.1 forbids reading any other caret sequence
        // as an error, so the caret and what follows stay literal, and so does
        // a trailing one.
        let node = IcalParamNode::parse("CN=a^xb^");

        assert_eq!(node.decode(), IcalParam::Cn(Cow::Borrowed("a^xb^")));
    }

    #[test]
    fn keeps_a_backslash_in_a_parameter() {
        // NOTE: RFC 6868 section 3.2 forbids backslash escaping in a parameter
        // value, so a Windows path keeps its separators.
        let node = IcalParamNode::parse(r"X-PATH=C:\temp\note.txt");

        assert_eq!(
            node.decode(),
            IcalParam::Unknown {
                name: Cow::Borrowed("X-PATH"),
                values: vec![Cow::Borrowed(r"C:\temp\note.txt")],
            },
        );
    }
}