robinson 0.5.21

For when you go to a lonely island and survival depends on parsing XML.
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
use std::borrow::Cow;
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::iter::{Enumerate, from_fn};
use std::num::NonZeroU32;
use std::slice::Iter;

use crate::{
    Document, Name, NameData,
    error::{ErrorKind, Result},
};

impl<'input> Document<'input> {
    pub fn root<'doc>(&'doc self) -> Node<'doc, 'input> {
        self.node(NodeId::ROOT).unwrap()
    }

    pub fn root_element<'doc>(&'doc self) -> Node<'doc, 'input> {
        self.root().first_child_element().unwrap()
    }

    pub fn node<'doc>(&'doc self, id: NodeId) -> Option<Node<'doc, 'input>> {
        self.nodes.get(id.get()).map(|data| Node {
            id,
            data,
            doc: self,
        })
    }
}

#[derive(Clone, Copy)]
pub struct Node<'doc, 'input> {
    pub(crate) id: NodeId,
    pub(crate) data: &'doc NodeData,
    pub(crate) doc: &'doc Document<'input>,
}

impl PartialEq for Node<'_, '_> {
    fn eq(&self, other: &Self) -> bool {
        let doc = self.doc as *const Document;
        let other_doc = other.doc as *const Document;

        (self.id, doc) == (other.id, other_doc)
    }
}

impl Eq for Node<'_, '_> {}

impl PartialOrd for Node<'_, '_> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Node<'_, '_> {
    fn cmp(&self, other: &Self) -> Ordering {
        let doc = self.doc as *const Document;
        let other_doc = other.doc as *const Document;

        (self.id, doc).cmp(&(other.id, other_doc))
    }
}

impl Hash for Node<'_, '_> {
    fn hash<H>(&self, hasher: &mut H)
    where
        H: Hasher,
    {
        let doc = self.doc as *const Document;

        (self.id, doc).hash(hasher);
    }
}

impl<'doc, 'input> Node<'doc, 'input> {
    pub fn document(self) -> &'doc Document<'input> {
        self.doc
    }

    pub fn id(self) -> NodeId {
        self.id
    }

    pub fn is_root(&self) -> bool {
        self.id == NodeId::ROOT
    }

    pub fn is_element(&self) -> bool {
        self.data.element.is_some()
    }

    pub(crate) fn element_data(self) -> Option<&'doc ElementData<'input>> {
        self.data
            .element
            .map(|element| &self.doc.elements[element.get()])
    }

    pub fn is_text(&self) -> bool {
        self.data.text.is_some()
    }

    fn other(self, id: NodeId) -> Self {
        self.doc.node(id).unwrap()
    }

    fn iter<F>(self, f: F) -> impl Iterator<Item = Self> + Clone
    where
        F: Fn(Self) -> Option<Self> + Clone,
    {
        let mut next = Some(self);

        from_fn(move || match next {
            Some(next1) => {
                next = f(next1);

                Some(next1)
            }
            None => None,
        })
    }

    pub fn parent(self) -> Option<Self> {
        self.data.parent.map(|id| self.other(id))
    }

    pub fn ancestors(self) -> impl Iterator<Item = Self> + Clone {
        self.iter(Self::parent)
    }

    pub fn prev_sibling(self) -> Option<Self> {
        self.data.prev_sibling.map(|id| self.other(id))
    }

    pub fn prev_siblings(self) -> impl Iterator<Item = Self> + Clone {
        self.iter(Self::prev_sibling)
    }

    pub fn prev_sibling_element(self) -> Option<Self> {
        self.prev_siblings().find(Self::is_element)
    }

    pub fn next_sibling(self) -> Option<Self> {
        self.data
            .next_subtree
            .filter(|id| self.doc.nodes[id.get()].prev_sibling == Some(self.id))
            .map(|id| self.other(id))
    }

    pub fn next_siblings(self) -> impl Iterator<Item = Self> + Clone {
        self.iter(Self::next_sibling)
    }

    pub fn next_sibling_element(self) -> Option<Self> {
        self.next_siblings().find(Self::is_element)
    }

    pub fn has_children(self) -> bool {
        self.data.last_child.is_some()
    }

    pub fn first_child(self) -> Option<Self> {
        if self.has_children() {
            Some(self.other(self.id.next()))
        } else {
            None
        }
    }

    pub fn first_child_element(self) -> Option<Self> {
        self.child_elements().next()
    }

    pub fn last_child(self) -> Option<Self> {
        self.data.last_child.map(|id| self.other(id))
    }

    pub fn last_child_element(self) -> Option<Self> {
        self.child_elements().next_back()
    }

    pub fn children(self) -> Children<'doc, 'input> {
        Children {
            front: self.first_child(),
            back: self.last_child(),
        }
    }

    pub fn child_elements(self) -> impl DoubleEndedIterator<Item = Self> + Clone {
        self.children().filter(Self::is_element)
    }

    /// ```
    /// # use robinson::{Document, Name};
    /// let doc = Document::parse(r#"<root><parent><child/></parent></root>"#).unwrap();
    ///
    /// let mut nodes = doc.root_element().descendants();
    ///
    /// let node = nodes.next().unwrap();
    /// assert_eq!(node.name(), Some(Name { namespace: None, local: "root" }));
    ///
    /// let node = nodes.next().unwrap();
    /// assert_eq!(node.name(), Some(Name { namespace: None, local: "parent" }));
    ///
    /// let node = nodes.next().unwrap();
    /// assert_eq!(node.name(), Some(Name { namespace: None, local: "child" }));
    ///
    /// assert_eq!(nodes.next(), None);
    pub fn descendants(self) -> Descendants<'doc, 'input> {
        let from = self.id.get();

        let until = self
            .data
            .next_subtree
            .map_or(self.doc.nodes.len(), |id| id.get());

        let nodes = self.doc.nodes[from..until].iter().enumerate();

        Descendants {
            from,
            nodes,
            doc: self.doc,
        }
    }

    pub fn name(self) -> Option<Name<'doc, 'input>> {
        self.element_data()
            .map(|element| element.name.get(self.doc))
    }

    pub fn has_name<N>(self, name: N) -> bool
    where
        Name<'doc, 'input>: PartialEq<N>,
    {
        self.name().is_some_and(|name1| name1 == name)
    }

    pub fn text(self) -> Option<&'doc str> {
        self.data.text.map(|text| self.doc.strings.get(text))
    }

    pub fn child_texts(self) -> impl Iterator<Item = &'doc str> + Clone {
        self.children().filter_map(Self::text)
    }

    /// ```
    /// # use std::borrow::Cow;
    /// # use robinson::Document;
    /// let doc = Document::parse(r#"<root>foo<child>bar</child>baz</root>"#).unwrap();
    ///
    /// let text = doc.root_element().child_text();
    ///
    /// assert_eq!(text, Some(Cow::Owned("foobaz".to_owned())));
    pub fn child_text(self) -> Option<Cow<'doc, str>> {
        collect_text(self.child_texts())
    }

    pub fn descedant_texts(self) -> impl Iterator<Item = &'doc str> + Clone {
        self.descendants().filter_map(Self::text)
    }

    /// ```
    /// # use std::borrow::Cow;
    /// # use robinson::Document;
    /// let doc = Document::parse(r#"<root>foo<child>bar</child>baz</root>"#).unwrap();
    ///
    /// let text = doc.root_element().descedant_text();
    ///
    /// assert_eq!(text, Some(Cow::Owned("foobarbaz".to_owned())));
    pub fn descedant_text(self) -> Option<Cow<'doc, str>> {
        collect_text(self.descedant_texts())
    }
}

fn collect_text<'doc>(mut iter: impl Iterator<Item = &'doc str> + Clone) -> Option<Cow<'doc, str>> {
    let mut cnt = 0;
    let mut len = 0;

    for text in iter.clone() {
        cnt += 1;
        len += text.len();
    }

    if cnt == 0 {
        return None;
    } else if cnt == 1 {
        let text = iter.next().unwrap();

        return Some(Cow::Borrowed(text));
    }

    let mut buf = String::with_capacity(len);

    for text in iter {
        buf.push_str(text);
    }

    Some(Cow::Owned(buf))
}

pub(crate) struct NodeData {
    pub(crate) element: Option<NodeId>,
    pub(crate) text: Option<NodeId>,
    pub(crate) parent: Option<NodeId>,
    pub(crate) prev_sibling: Option<NodeId>,
    pub(crate) next_subtree: Option<NodeId>,
    pub(crate) last_child: Option<NodeId>,
}

const _SIZE_OF_NODE_DATA: () = assert!(size_of::<NodeData>() == 3 * size_of::<usize>());

#[repr(Rust, packed)]
pub(crate) struct ElementData<'input> {
    pub(crate) name: NameData<'input>,
    pub(crate) attributes_start: u32,
    pub(crate) attributes_len: u16,
}

const _SIZE_OF_ELEMENT_DATA: () = assert!(
    size_of::<ElementData<'static>>()
        == size_of::<u16>() + 2 * size_of::<usize>() + size_of::<u32>() + size_of::<u16>()
);

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NodeId(NonZeroU32);

impl NodeId {
    pub(crate) const ROOT: Self = Self(NonZeroU32::new(1).unwrap());

    pub(crate) fn new(id: usize) -> Result<Self> {
        if id >= u32::MAX as usize {
            return ErrorKind::TooManyNodes.into();
        }

        Ok(Self(NonZeroU32::new(id as u32 + 1).unwrap()))
    }

    pub(crate) fn get(self) -> usize {
        self.0.get() as usize - 1
    }

    fn next(self) -> Self {
        Self(self.0.checked_add(1).unwrap())
    }
}

#[derive(Clone)]
pub struct Children<'doc, 'input> {
    front: Option<Node<'doc, 'input>>,
    back: Option<Node<'doc, 'input>>,
}

impl<'doc, 'input> Iterator for Children<'doc, 'input> {
    type Item = Node<'doc, 'input>;

    fn next(&mut self) -> Option<Self::Item> {
        let is_last = self.front == self.back;

        let node = self.front.take();

        if is_last {
            self.back = None;
        } else {
            self.front = node.and_then(Node::next_sibling);
        }

        node
    }
}

impl DoubleEndedIterator for Children<'_, '_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        let is_last = self.front == self.back;

        let node = self.back.take();

        if is_last {
            self.front = None;
        } else {
            self.back = node.and_then(Node::prev_sibling);
        }

        node
    }
}

#[derive(Clone)]
pub struct Descendants<'doc, 'input> {
    from: usize,
    nodes: Enumerate<Iter<'doc, NodeData>>,
    doc: &'doc Document<'input>,
}

impl<'doc, 'input> Descendants<'doc, 'input> {
    fn get(&self, (idx, data): (usize, &'doc NodeData)) -> Node<'doc, 'input> {
        Node {
            id: NodeId::new(self.from + idx).unwrap(),
            data,
            doc: self.doc,
        }
    }
}

impl<'doc, 'input> Iterator for Descendants<'doc, 'input> {
    type Item = Node<'doc, 'input>;

    fn next(&mut self) -> Option<Self::Item> {
        self.nodes.next().map(|node| self.get(node))
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.nodes.nth(n).map(|node| self.get(node))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.nodes.size_hint()
    }
}

impl ExactSizeIterator for Descendants<'_, '_> {}

impl DoubleEndedIterator for Descendants<'_, '_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.nodes.next_back().map(|node| self.get(node))
    }
}

impl fmt::Debug for Node<'_, '_> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut fmt = fmt.debug_struct("Node");

        if let Some(name) = self.name() {
            fmt.field("name", &name);
        }

        if let Some(text) = self.text() {
            fmt.field("text", &text);
        }

        if self.has_attributes() {
            fmt.field("attributes", &self.attributes());
        }

        if self.has_children() {
            fmt.field("children", &self.children());
        }

        fmt.finish()
    }
}

impl fmt::Debug for Children<'_, '_> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_list().entries(self.clone()).finish()
    }
}

impl fmt::Debug for Descendants<'_, '_> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_list().entries(self.clone()).finish()
    }
}