vcard-rs 0.3.1

vCard parser, validator, editor, merger and builder library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! # Value cursor
//!
//! The generic in-place edit cursor, shared by every property lens without a
//! bespoke one.
//!
//! A cursor borrows a content line mutably and reads and writes its value
//! through the codec: getters decode (unescape), setters encode (escape) and
//! write through to the syntax node.
//!
//! A setter only rewrites the component it touches, so every other leaf (and
//! every parameter) of a parsed line stays byte for byte intact.
//!
//! [`VcardValueCursor`] offers convenience accessors for the common
//! single-value and list shapes plus raw component-level access; the
//! structured properties (`N`, `ADR`, `GENDER`, `CLIENTPIDMAP`) carry a cursor
//! naming their own components instead.
//!
//! Beside the UTF-8 text accessors it offers a raw byte hatch
//! ([`bytes`](VcardValueCursor::bytes) /
//! [`set_bytes`](VcardValueCursor::set_bytes)) for a value in a foreign
//! charset.
//!
//! Behind the content-encoding features sit the
//! [`quoted_printable`](VcardValueCursor::quoted_printable) and
//! [`charset`](VcardValueCursor::charset) decoders.

#[cfg(feature = "encoding")]
use alloc::string::String;
use alloc::{borrow::Cow, vec::Vec};

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

/// A typed cursor over a content line's value, editing in place and byte
/// preserving for the components it does not touch.
pub struct VcardValueCursor<'c, 'a> {
    /// The borrowed content line.
    pub line: &'c mut VcardLine<'a>,
}

impl<'a> VcardValueCursor<'_, 'a> {
    /// The whole value as a single decoded text, its `;` and `,` kept literal.
    pub fn text(&self) -> Cow<'_, str> {
        self.line.value.decode()
    }

    /// Set the whole value to a single text, escaping it. Writes UTF-8; to keep
    /// a foreign charset, transcode yourself and use
    /// [`set_bytes`](Self::set_bytes).
    pub fn set_text(&mut self, value: impl AsRef<str>) {
        self.line.value.set(&[value]);
    }

    /// The whole value's raw bytes, unescaped but not otherwise decoded.
    ///
    /// For a value carrying a foreign charset. To resolve `QUOTED-PRINTABLE`
    /// or a `CHARSET`, use the [`quoted_printable`](Self::quoted_printable) /
    /// [`charset`](Self::charset) feature helpers.
    pub fn bytes(&self) -> Cow<'_, [u8]> {
        self.line.value.decode_bytes()
    }

    /// Set the whole value to raw bytes (the foreign-charset escape hatch),
    /// escaping structural separators but writing the bytes verbatim. The
    /// card's `CHARSET` parameter is left untouched: it is the caller's to keep
    /// consistent.
    pub fn set_bytes(&mut self, value: impl AsRef<[u8]>) {
        self.line.value.set_bytes(&[value]);
    }

    /// Decode the value's `QUOTED-PRINTABLE` `=XX` octets to raw bytes.
    ///
    /// The raw [`bytes`](Self::bytes) when the line declares no such encoding.
    /// Still in the value's own (possibly foreign) charset, so pair with
    /// [`charset`](Self::charset) for text. Requires `quoted-printable`.
    #[cfg(feature = "quoted-printable")]
    pub fn quoted_printable(&self) -> Vec<u8> {
        let raw = self.bytes();

        if self.line.is_quoted_printable() {
            quoted_printable::decode(raw.as_ref(), quoted_printable::ParseMode::Robust)
                .unwrap_or_else(|_| raw.into_owned())
        } else {
            raw.into_owned()
        }
    }

    /// Transcode the value to text using its `CHARSET` parameter (defaulting to
    /// UTF-8 when absent or unrecognised). When the `quoted-printable` feature
    /// is also on, `QUOTED-PRINTABLE` octets are resolved first. Requires the
    /// `encoding` feature.
    #[cfg(feature = "encoding")]
    pub fn charset(&self) -> String {
        #[cfg(feature = "quoted-printable")]
        let bytes = self.quoted_printable();
        #[cfg(not(feature = "quoted-printable"))]
        let bytes = self.bytes().into_owned();

        let encoding = self
            .line
            .charset_label()
            .and_then(|label| encoding_rs::Encoding::for_label(label.as_bytes()))
            .unwrap_or(encoding_rs::UTF_8);

        encoding.decode_without_bom_handling(&bytes).0.into_owned()
    }

    /// The whole value as a decoded list (its `,`-separated values), its `;`
    /// kept literal.
    pub fn list(&self) -> Vec<Cow<'_, str>> {
        self.line.value.decode_list()
    }

    /// Set the whole value to a list, escaping each value.
    pub fn set_list<S: AsRef<str>>(&mut self, values: &[S]) {
        self.line.value.set(values);
    }

    /// The `i`th component as a decoded list, for structured values.
    pub fn component(&self, i: usize) -> Vec<Cow<'_, str>> {
        self.line.value.decode_component_list(i)
    }

    /// Set the `i`th component, escaping each value and preserving the rest.
    pub fn set_component<S: AsRef<str>>(&mut self, i: usize, values: &[S]) {
        self.line.value.set_component(i, values);
    }

    /// Walk into the `i`th component to edit its `,`-separated values one at a
    /// time, splicing a single leaf per edit.
    pub fn list_at(&mut self, i: usize) -> VcardListCursor<'_, 'a> {
        VcardListCursor {
            node: &mut self.line.value,
            component: i,
        }
    }

    /// Walk into the first component's list (the flat `,`-list shape), the
    /// common case of [`list_at`](Self::list_at).
    pub fn list_mut(&mut self) -> VcardListCursor<'_, 'a> {
        self.list_at(0)
    }

    /// The first parameter of type `P` on this line, decoded.
    pub fn param<P: VcardParamLens>(&self) -> Option<P::Target<'_>> {
        self.line.param::<P>()
    }
}

/// A cursor over one component's `,`-separated values, editing them per item.
///
/// Every mutation touches a single leaf, so an untouched value keeps the exact
/// bytes it was parsed with, escaping and all. Obtained from
/// [`VcardValueCursor::list_at`] / [`list_mut`](VcardValueCursor::list_mut).
pub struct VcardListCursor<'c, 'a> {
    node: &'c mut VcardValueNode<'a>,
    component: usize,
}

impl VcardListCursor<'_, '_> {
    /// The number of values in the walked component.
    pub fn len(&self) -> usize {
        self.node.value_count(self.component)
    }

    /// Whether the walked component has no values.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The `j`th value, decoded, or `None` when the index is out of range.
    pub fn get(&self, j: usize) -> Option<Cow<'_, str>> {
        self.node
            .decode_component_list(self.component)
            .into_iter()
            .nth(j)
    }

    /// Replace the `j`th value in place, re-escaping only that leaf.
    pub fn set<S: AsRef<str>>(&mut self, j: usize, value: S) -> &mut Self {
        self.node.set_value_at(self.component, j, value);
        self
    }

    /// Insert a value at position `j` (clamped to the end), escaping only the
    /// new leaf.
    pub fn insert<S: AsRef<str>>(&mut self, j: usize, value: S) -> &mut Self {
        self.node.insert_value_at(self.component, j, value);
        self
    }

    /// Append a value, escaping only the new leaf.
    pub fn push<S: AsRef<str>>(&mut self, value: S) -> &mut Self {
        self.node.push_value(self.component, value);
        self
    }

    /// Remove the `j`th value, splicing it out; a no-op when out of range.
    pub fn remove(&mut self, j: usize) -> &mut Self {
        self.node.remove_value_at(self.component, j);
        self
    }
}

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

    use crate::{
        prop::{adr::ADR, r#fn::FN},
        tree::cst::VcardCst,
    };

    #[test]
    fn edits_a_scalar_value_in_place_escaping_it() {
        let mut card =
            VcardCst::parse("BEGIN:VCARD\r\nVERSION:4.0\r\nFN:John\r\nEND:VCARD\r\n").unwrap();
        card.prop_mut::<FN>().unwrap().set_text("Jane, Q");
        assert!(card.to_string().contains("FN:Jane\\, Q\r\n"));
    }

    #[test]
    fn writes_and_reads_a_foreign_charset_value_as_raw_bytes() {
        use crate::prop::note::NOTE;

        let mut card = VcardCst::parse(
            "BEGIN:VCARD\r\nVERSION:2.1\r\nNOTE;CHARSET=ISO-8859-1:x\r\nEND:VCARD\r\n",
        )
        .unwrap();

        // NOTE: "café" in ISO-8859-1: the trailing 0xE9 is not valid UTF-8.
        let latin1 = [b'c', b'a', b'f', 0xE9];
        card.prop_mut::<NOTE>().unwrap().set_bytes(latin1);

        assert_eq!(card.prop_mut::<NOTE>().unwrap().bytes().as_ref(), &latin1);
        assert!(card.to_bytes().windows(4).any(|window| window == latin1));
    }

    /// The core does not resolve QUOTED-PRINTABLE, so bytes() is the raw wire
    /// value.
    #[test]
    fn bytes_returns_the_raw_undecoded_value() {
        use crate::prop::note::NOTE;

        let mut card = VcardCst::parse(concat!(
            "BEGIN:VCARD\r\n",
            "VERSION:2.1\r\n",
            "NOTE;CHARSET=ISO-8859-1;ENCODING=QUOTED-PRINTABLE:caf=E9\r\n",
            "END:VCARD\r\n",
        ))
        .unwrap();

        assert_eq!(card.prop_mut::<NOTE>().unwrap().bytes().as_ref(), b"caf=E9");
    }

    #[cfg(feature = "quoted-printable")]
    /// `=E9` is the Latin-1 'é' octet, which the helper resolves to raw bytes.
    #[test]
    fn quoted_printable_helper_resolves_octets() {
        use crate::prop::note::NOTE;

        let mut card = VcardCst::parse(concat!(
            "BEGIN:VCARD\r\n",
            "VERSION:2.1\r\n",
            "NOTE;CHARSET=ISO-8859-1;ENCODING=QUOTED-PRINTABLE:caf=E9\r\n",
            "END:VCARD\r\n",
        ))
        .unwrap();

        assert_eq!(
            card.prop_mut::<NOTE>().unwrap().quoted_printable(),
            [b'c', b'a', b'f', 0xE9],
        );
    }

    #[cfg(all(feature = "encoding", feature = "quoted-printable"))]
    /// "café" as ISO-8859-1 quoted-printable: the charset helper, composing
    /// the QUOTED-PRINTABLE one, yields the UTF-8 string.
    #[test]
    fn charset_helper_transcodes_to_utf8() {
        use crate::prop::note::NOTE;

        let mut card = VcardCst::parse(concat!(
            "BEGIN:VCARD\r\n",
            "VERSION:2.1\r\n",
            "NOTE;CHARSET=ISO-8859-1;ENCODING=QUOTED-PRINTABLE:caf=E9\r\n",
            "END:VCARD\r\n",
        ))
        .unwrap();

        assert_eq!(card.prop_mut::<NOTE>().unwrap().charset(), "café");
    }

    #[test]
    fn edits_one_structured_component_preserving_the_rest() {
        let mut card =
            VcardCst::parse("BEGIN:VCARD\r\nVERSION:4.0\r\nADR:;;Old St;;;;\r\nEND:VCARD\r\n")
                .unwrap();
        card.prop_mut::<ADR>().unwrap().set_street(&["New St"]);
        assert!(card.to_string().contains("ADR:;;New St;;;;\r\n"));
    }

    /// `a\:b` is a redundant escape, `:` needing none. A whole-list rewrite
    /// would decode and normalise it to `a:b`, while a per-item edit of a
    /// different value leaves it byte for byte.
    #[test]
    fn walks_a_list_editing_items_without_reformatting_siblings() {
        use crate::prop::nickname::NICKNAME;

        let mut card = VcardCst::parse(concat!(
            "BEGIN:VCARD\r\n",
            "VERSION:4.0\r\n",
            "NICKNAME:a\\:b,middle,z\r\n",
            "END:VCARD\r\n",
        ))
        .unwrap();

        card.prop_mut::<NICKNAME>().unwrap().list_mut().remove(1);

        let out = card.to_string();
        assert!(out.contains("NICKNAME:a\\:b,z\r\n"), "got: {out}");
    }

    #[test]
    fn walks_a_list_setting_inserting_and_pushing() {
        use crate::prop::nickname::NICKNAME;

        let mut card =
            VcardCst::parse("BEGIN:VCARD\r\nVERSION:4.0\r\nNICKNAME:a,b,c\r\nEND:VCARD\r\n")
                .unwrap();

        {
            let mut cursor = card.prop_mut::<NICKNAME>().unwrap();
            let mut list = cursor.list_mut();
            assert_eq!(list.len(), 3);
            assert_eq!(list.get(1).as_deref(), Some("b"));

            list.set(1, "B").insert(0, "first").push("last");
        }

        let out = card.to_string();
        assert!(out.contains("NICKNAME:first,a,B,c,last\r\n"), "got: {out}");
    }

    /// The generic accessors read and write the value, not its first slot.
    ///
    /// A semicolon separates nothing in a text value, so a read stopping at
    /// one handed back a truncated value and a write rewriting only the first
    /// component left the old tail behind: read then write changed the value.
    #[test]
    fn reads_and_writes_the_whole_value_not_its_first_component() {
        use crate::prop::note::NOTE;

        let mut card =
            VcardCst::parse("BEGIN:VCARD\r\nVERSION:4.0\r\nNOTE:a;b\r\nEND:VCARD\r\n").unwrap();

        {
            let cursor = card.prop_mut::<NOTE>().unwrap();
            assert_eq!(cursor.text(), "a;b");
            assert_eq!(cursor.bytes().as_ref(), b"a;b");
            assert_eq!(cursor.list(), vec!["a;b"]);
        }

        let whole = card.prop_mut::<NOTE>().unwrap().text().into_owned();
        card.prop_mut::<NOTE>().unwrap().set_text(&whole);

        assert!(card.to_string().contains("NOTE:a\\;b\r\n"), "got: {card}");
        assert_eq!(card.prop_mut::<NOTE>().unwrap().text(), "a;b");
    }

    /// A named component of a structured value keeps the commas inside it.
    #[test]
    fn reads_a_structured_component_past_its_first_comma() {
        use crate::prop::client_pid_map::CLIENTPIDMAP;

        let mut card = VcardCst::parse(concat!(
            "BEGIN:VCARD\r\n",
            "VERSION:4.0\r\n",
            "CLIENTPIDMAP:1;urn:uuid:a,b\r\n",
            "END:VCARD\r\n",
        ))
        .unwrap();

        let cursor = card.prop_mut::<CLIENTPIDMAP>().unwrap();
        assert_eq!(cursor.id(), "1");
        assert_eq!(cursor.uri(), "urn:uuid:a,b");
    }

    #[test]
    fn exercises_every_generic_accessor() {
        use crate::prop::note::NOTE;

        let mut card =
            VcardCst::parse("BEGIN:VCARD\r\nVERSION:4.0\r\nNOTE:a,b\r\nEND:VCARD\r\n").unwrap();

        {
            let mut cursor = card.prop_mut::<NOTE>().unwrap();

            // NOTE: A text read takes the whole value and a list read splits it
            // on its commas, both keeping every `;` the value carries, while a
            // component read takes one `;`-separated slot.
            assert_eq!(cursor.text(), "a,b");
            assert_eq!(cursor.list(), vec!["a", "b"]);
            assert_eq!(cursor.component(0), vec!["a", "b"]);

            cursor.set_text("x");
            assert_eq!(cursor.text(), "x");

            cursor.set_list(&["a", "b"]);
            assert_eq!(cursor.list(), vec!["a", "b"]);

            // NOTE: a component past the last one extends the value rather
            // than dropping the write.
            cursor.set_component(1, &["y"]);
            assert_eq!(cursor.component(1), vec!["y"]);
        }

        assert!(card.to_string().contains("NOTE:a,b;y\r\n"), "got: {card}");
    }
}