vcard-rs 0.2.1

vCard parser, validator, editor and builder library for Rust
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
//! # Value node
//!
//! The raw value of a content line, on the syntax side.
//!
//! [`VcardValueNode`] is the syntactic peer of the decoded
//! [`VcardValue`](crate::value::VcardValue): the bytes after a line's colon,
//! read as `;`-separated components of `,`-separated
//! [`crate::tree::leaf::VcardValueLeaf`] values (raw bytes, so a foreign
//! charset survives). Straight from parse the value stays one unsplit slice
//! walked on demand; an edit or a model encode splits it into owned components,
//! which then become the source of truth. The splitting is generic, counting
//! and preserving separators so the value round-trips; what the components
//! *mean* is the lens's business.
//!
//! The codec that unescapes components into decoded values and re-escapes edits
//! back lives on this type, applying the rules of the sibling
//! [`mode`](crate::tree::codec::mode) codec.

use core::fmt;

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

use crate::tree::{
    codec::{
        encode::{encode_component, encode_leaf},
        escape::escape_with,
        mode::VcardEscaper,
        unescape::{unescape_bytes, unescape_with},
    },
    leaf::VcardValueLeaf,
};

/// A raw value: `;`-separated components, each a list of `,`-separated raw
/// value leaves.
///
/// From parse it is one unsplit `raw` slice, walked lazily, so a parse that
/// never decodes and a byte-faithful reserialize split nothing. The first edit
/// (or a model encode) splits it into owned `components`, which then take over.
/// A write touches only the leaf or component it names, so everything else
/// keeps its parsed bytes. `escaper` records which version's escaping rules to
/// apply, stamped from the card version after parsing.
#[derive(Clone, Debug, Default)]
pub struct VcardValueNode<'a> {
    /// The unsplit value bytes, straight from parse and authoritative until an
    /// edit or a model encode replaces them; `None` once `components` is the
    /// source of truth.
    raw: Option<Cow<'a, [u8]>>,
    /// The split components, authoritative when `raw` is `None`; while `raw` is
    /// `Some` this stays empty and reads split `raw` on demand.
    components: Vec<Vec<VcardValueLeaf<'a>>>,
    /// The escaping rules to read and write this value with.
    pub escaper: VcardEscaper,
}

impl<'a> VcardValueNode<'a> {
    /// Wrap a raw value, unsplit and borrowed, to be walked lazily. The colon,
    /// name and eol are the line's business; this is only the bytes after the
    /// colon.
    pub fn parse(value: &'a [u8]) -> Self {
        Self {
            raw: Some(Cow::Borrowed(value)),
            components: Vec::new(),
            escaper: VcardEscaper::default(),
        }
    }

    /// Build a value node from already-split components (the model encode
    /// path); there is no `raw`, so the components are the source of truth.
    pub(crate) fn from_components(
        components: Vec<Vec<VcardValueLeaf<'a>>>,
        escaper: VcardEscaper,
    ) -> Self {
        Self {
            raw: None,
            components,
            escaper,
        }
    }

    /// The number of `;`-separated components (at least one, since an empty
    /// value is one empty component).
    pub fn component_count(&self) -> usize {
        match &self.raw {
            Some(raw) => {
                let mut count = 0;
                split_on(raw, b';', |_| count += 1);
                count
            }
            None => self.components.len(),
        }
    }

    /// Decode the `i`th component into a clean (unescaped) value list.
    pub fn decode_at(&self, i: usize) -> Vec<Cow<'_, str>> {
        match self.component_at(i) {
            Some(Component::Raw(bytes)) => {
                let mut values = Vec::new();
                split_on(bytes, b',', |value| {
                    values.push(unescape_with(value, self.escaper))
                });
                values
            }
            Some(Component::Split(leaves)) => leaves
                .iter()
                .map(|leaf| unescape_with(leaf.as_bytes(), self.escaper))
                .collect(),
            None => Vec::new(),
        }
    }

    /// The `i`th component's first value as raw unescaped bytes, not
    /// transcoded, for a value carrying a foreign charset.
    pub fn decode_bytes_at(&self, i: usize) -> Cow<'_, [u8]> {
        match self.component_at(i) {
            Some(Component::Raw(bytes)) => unescape_bytes(first_value(bytes), self.escaper),
            Some(Component::Split(leaves)) => leaves
                .first()
                .map(|leaf| unescape_bytes(leaf.as_bytes(), self.escaper))
                .unwrap_or(Cow::Borrowed(b"")),
            None => Cow::Borrowed(b""),
        }
    }

    /// Decode the `i`th component's first value (empty when there is none).
    pub fn decode_scalar_at(&self, i: usize) -> Cow<'_, str> {
        match self.component_at(i) {
            Some(Component::Raw(bytes)) => unescape_with(first_value(bytes), self.escaper),
            Some(Component::Split(leaves)) => leaves
                .first()
                .map(|leaf| unescape_with(leaf.as_bytes(), self.escaper))
                .unwrap_or(Cow::Borrowed("")),
            None => Cow::Borrowed(""),
        }
    }

    /// Decode the `i`th component as a single value, keeping its `,`-separated
    /// pieces joined. For values like URIs whose comma is a literal part of the
    /// value, not a list separator (so they must not be truncated).
    pub fn decode_joined_at(&self, i: usize) -> Cow<'_, str> {
        match self.component_at(i) {
            // NOTE: The whole component slice already has the commas in place,
            // so unescaping it verbatim keeps them literal.
            Some(Component::Raw(bytes)) => unescape_with(bytes, self.escaper),
            Some(Component::Split(leaves)) => {
                if leaves.len() <= 1 {
                    return leaves
                        .first()
                        .map(|leaf| unescape_with(leaf.as_bytes(), self.escaper))
                        .unwrap_or(Cow::Borrowed(""));
                }

                let mut raw = Vec::new();
                for (j, leaf) in leaves.iter().enumerate() {
                    if j > 0 {
                        raw.push(b',');
                    }
                    raw.extend_from_slice(leaf.as_bytes());
                }

                Cow::Owned(unescape_with(&raw, self.escaper).into_owned())
            }
            None => Cow::Borrowed(""),
        }
    }

    /// The raw (still-escaped) bytes of the first component's first value, for
    /// the simple single-value lines (the envelope values and diagnostics).
    pub(crate) fn first_value_bytes(&self) -> &[u8] {
        match self.component_at(0) {
            Some(Component::Raw(bytes)) => first_value(bytes),
            Some(Component::Split(leaves)) => {
                leaves.first().map(|leaf| leaf.as_bytes()).unwrap_or(b"")
            }
            None => b"",
        }
    }

    /// Set the `i`th component, escaping each value and padding with empty
    /// components when needed.
    pub fn set_at<S: AsRef<str>>(&mut self, i: usize, values: &[S]) {
        self.materialize();

        while self.components.len() <= i {
            self.components.push(Vec::new());
        }

        self.components[i] = encode_component(values, self.escaper);
    }

    /// Set the `i`th component from raw value bytes (the foreign-charset escape
    /// hatch), escaping structural separators but writing the bytes verbatim.
    pub fn set_bytes_at<B: AsRef<[u8]>>(&mut self, i: usize, values: &[B]) {
        self.materialize();

        while self.components.len() <= i {
            self.components.push(Vec::new());
        }

        self.components[i] = values
            .iter()
            .map(|v| VcardValueLeaf::from(escape_with(v.as_ref(), self.escaper).into_owned()))
            .collect();
    }

    /// The number of `,`-separated values in the `i`th component (zero when the
    /// component does not exist).
    pub fn value_count(&self, i: usize) -> usize {
        match self.component_at(i) {
            Some(Component::Raw(bytes)) => {
                let mut count = 0;
                split_on(bytes, b',', |_| count += 1);
                count
            }
            Some(Component::Split(leaves)) => leaves.len(),
            None => 0,
        }
    }

    /// Replace the `j`th value of the `i`th component in place, re-escaping only
    /// that leaf. Pads with empty values when `j` is past the end.
    pub fn set_value_at<S: AsRef<str>>(&mut self, i: usize, j: usize, value: S) {
        let escaper = self.escaper;
        let component = self.component_mut(i);

        while component.len() <= j {
            component.push(encode_leaf("", escaper));
        }

        component[j] = encode_leaf(value, escaper);
    }

    /// Insert a value at position `j` of the `i`th component (clamped to the
    /// end), escaping only the new leaf.
    pub fn insert_value_at<S: AsRef<str>>(&mut self, i: usize, j: usize, value: S) {
        let escaper = self.escaper;
        let component = self.component_mut(i);
        let at = j.min(component.len());

        component.insert(at, encode_leaf(value, escaper));
    }

    /// Append a value to the `i`th component, escaping only the new leaf.
    pub fn push_value<S: AsRef<str>>(&mut self, i: usize, value: S) {
        let escaper = self.escaper;
        let component = self.component_mut(i);

        component.push(encode_leaf(value, escaper));
    }

    /// Remove the `j`th value of the `i`th component, splicing it out; a no-op
    /// when either index is out of range.
    pub fn remove_value_at(&mut self, i: usize, j: usize) {
        self.materialize();

        if let Some(component) = self.components.get_mut(i)
            && j < component.len()
        {
            component.remove(j);
        }
    }

    /// Serialize the raw value bytes (name, colon and eol are the line's job)
    /// into `out`, exactly as parsed. An untouched value emits its `raw` slice
    /// with no reassembly.
    pub(crate) fn write_bytes(&self, out: &mut Vec<u8>) {
        if let Some(raw) = &self.raw {
            out.extend_from_slice(raw);
            return;
        }

        for (i, component) in self.components.iter().enumerate() {
            if i > 0 {
                out.push(b';');
            }

            for (j, leaf) in component.iter().enumerate() {
                if j > 0 {
                    out.push(b',');
                }

                out.extend_from_slice(leaf.as_bytes());
            }
        }
    }

    /// Convert into an owned value node (`'static`), keeping it lazy: an
    /// unsplit value stays unsplit, only its bytes become owned.
    pub(crate) fn into_static(self) -> VcardValueNode<'static> {
        match self.raw {
            Some(raw) => VcardValueNode {
                raw: Some(Cow::Owned(raw.into_owned())),
                components: Vec::new(),
                escaper: self.escaper,
            },
            None => VcardValueNode {
                raw: None,
                components: self
                    .components
                    .into_iter()
                    .map(|component| {
                        component
                            .into_iter()
                            .map(VcardValueLeaf::into_static)
                            .collect()
                    })
                    .collect(),
                escaper: self.escaper,
            },
        }
    }

    /// Locate the `i`th component, either as a raw slice of the unsplit value
    /// or as the already-split leaves.
    fn component_at(&self, i: usize) -> Option<Component<'_, 'a>> {
        match &self.raw {
            Some(raw) => {
                let mut found = None;
                let mut index = 0;
                split_on(raw, b';', |component| {
                    if index == i {
                        found = Some(component);
                    }
                    index += 1;
                });
                found.map(Component::Raw)
            }
            None => self
                .components
                .get(i)
                .map(|leaves| Component::Split(leaves)),
        }
    }

    /// Borrow the `i`th component's leaves for in-place editing, splitting the
    /// value first and padding with empty components up to `i`.
    fn component_mut(&mut self, i: usize) -> &mut Vec<VcardValueLeaf<'a>> {
        self.materialize();

        while self.components.len() <= i {
            self.components.push(Vec::new());
        }

        &mut self.components[i]
    }

    /// Split the unsplit `raw` value into owned components so it can be edited
    /// in place; a no-op once already split. Only edits pay this cost.
    fn materialize(&mut self) {
        let Some(raw) = self.raw.take() else {
            return;
        };

        self.components = match raw {
            Cow::Borrowed(bytes) => split_all(bytes),
            Cow::Owned(bytes) => split_all_owned(&bytes),
        };
    }
}

impl fmt::Display for VcardValueNode<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(raw) = &self.raw {
            return f.write_str(&String::from_utf8_lossy(raw));
        }

        for (i, component) in self.components.iter().enumerate() {
            if i > 0 {
                f.write_str(";")?;
            }

            for (j, leaf) in component.iter().enumerate() {
                if j > 0 {
                    f.write_str(",")?;
                }

                f.write_str(&String::from_utf8_lossy(leaf.as_bytes()))?;
            }
        }

        Ok(())
    }
}

/// One located component: a slice of the still-unsplit value, or its leaves
/// once the value has been split for editing.
enum Component<'s, 'a> {
    /// The component's bytes, still `,`-joined, borrowed from the unsplit
    /// value.
    Raw(&'s [u8]),
    /// The component's already-split leaves.
    Split(&'s [VcardValueLeaf<'a>]),
}

/// The first `,`-separated value of a component (escape-aware): the bytes up to
/// the first unescaped comma, or the whole component when it has none.
fn first_value(component: &[u8]) -> &[u8] {
    let mut first = None;
    split_on(component, b',', |value| {
        first.get_or_insert(value);
    });
    first.unwrap_or(component)
}

/// Split a value into its `;`-separated components, each a list of its
/// `,`-separated leaves, borrowing from `bytes`.
fn split_all(bytes: &[u8]) -> Vec<Vec<VcardValueLeaf<'_>>> {
    let mut components = Vec::new();
    split_on(bytes, b';', |component| {
        let mut values = Vec::new();
        split_on(component, b',', |value| {
            values.push(VcardValueLeaf::from(value));
        });
        components.push(values);
    });
    components
}

/// Split like [`split_all`] but copying each leaf, for the owned bytes an
/// edit-after-`into_static` value carries (which no slice can borrow from).
fn split_all_owned(bytes: &[u8]) -> Vec<Vec<VcardValueLeaf<'static>>> {
    let mut components = Vec::new();
    split_on(bytes, b';', |component| {
        let mut values = Vec::new();
        split_on(component, b',', |value| {
            values.push(VcardValueLeaf::from(value.to_vec()));
        });
        components.push(values);
    });
    components
}

/// Call `piece` for each span between unescaped `sep` bytes, always at least
/// once. A backslash escapes the next byte (so `\;` / `\,` do not split), and
/// `memchr` skips straight to the next `sep` or backslash instead of scanning
/// byte by byte, so a large separator-free value (e.g. base64) is skipped in
/// one pass.
fn split_on<'b>(bytes: &'b [u8], sep: u8, mut piece: impl FnMut(&'b [u8])) {
    let mut start = 0;
    let mut i = 0;

    while let Some(offset) = memchr::memchr2(b'\\', sep, &bytes[i..]) {
        let pos = i + offset;
        if bytes[pos] == b'\\' {
            i = (pos + 2).min(bytes.len());
        } else {
            piece(&bytes[start..pos]);
            start = pos + 1;
            i = pos + 1;
        }
    }

    piece(&bytes[start..]);
}

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

    use crate::tree::value::node::VcardValueNode;

    #[test]
    fn splits_components_and_values_then_round_trips() {
        let node = VcardValueNode::parse(b"a;b,c;");
        assert_eq!(node.component_count(), 3);
        assert_eq!(
            node.decode_at(1),
            vec![Cow::Borrowed("b"), Cow::Borrowed("c")]
        );
        assert_eq!(node.to_string(), "a;b,c;");
    }

    #[test]
    fn keeps_escaped_separators_inside_one_value() {
        let node = VcardValueNode::parse(br"a\,b\;c;d");
        assert_eq!(node.component_count(), 2);
        assert_eq!(node.decode_at(0).len(), 1);
        assert_eq!(node.to_string(), r"a\,b\;c;d");
    }

    #[test]
    fn an_edit_splits_and_preserves_untouched_components() {
        let mut node = VcardValueNode::parse(b"a;b;c");
        node.set_at(1, &["X"]);
        assert_eq!(node.to_string(), "a;X;c");
    }

    /// Every reader answers the same before and after the node materializes.
    ///
    /// A node holds its value as raw bytes until the first edit splits it into
    /// components, and each reader has a branch per state. A parse-and-read
    /// exercises the lazy branches; these are the other half, and a
    /// disagreement between the two would surface as a value that changes
    /// shape the moment an unrelated component is written.
    fn assert_readers_agree(node: &VcardValueNode<'_>, components: usize) {
        assert_eq!(node.component_count(), components);
        assert_eq!(node.value_count(1), 2);
        assert_eq!(node.decode_scalar_at(0), "a");
        assert_eq!(
            node.decode_at(1),
            vec![Cow::Borrowed("b"), Cow::Borrowed("c")],
        );
        assert_eq!(node.decode_joined_at(1), "b,c");
        assert_eq!(node.decode_bytes_at(2).as_ref(), b"d");
    }

    #[test]
    fn readers_agree_before_and_after_an_edit_materializes_the_node() {
        let mut node = VcardValueNode::parse(b"a;b,c;d");
        assert_readers_agree(&node, 3);

        // NOTE: Writing component 3 leaves the read components alone, but it is
        // what moves the node off its raw bytes.
        node.set_at(3, &["e"]);
        assert_readers_agree(&node, 4);
        assert_eq!(node.to_string(), "a;b,c;d;e");
    }

    #[test]
    fn readers_agree_after_an_owned_node_is_edited() {
        let mut node = VcardValueNode::parse(b"a;b,c;d").into_static();
        assert_readers_agree(&node, 3);

        node.set_at(3, &["e"]);
        assert_readers_agree(&node, 4);
        assert_eq!(node.to_string(), "a;b,c;d;e");
    }
}