xmlity 0.0.9

A (de)serialization library for 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
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
//! This module contains some utility types and visitors that can be reused.

use core::fmt::{self, Debug};
use std::{borrow::Cow, marker::PhantomData, str::FromStr};

use crate::{
    de::{
        self, Visitor, XmlCData, XmlComment, XmlDeclaration, XmlDoctype, XmlProcessingInstruction,
        XmlText,
    },
    value::{self, XmlDecl},
    Deserialize, Deserializer, Serialize, Serializer,
};

/// This utility type represents an XML root document.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct XmlRoot<T> {
    /// The declaration of the XML document.
    pub decl: Option<XmlDecl>,
    /// The top-level elements of the XML document.
    pub elements: Vec<XmlRootTop<T>>,
}

impl<T: Serialize> crate::Serialize for XmlRoot<T> {
    fn serialize<S>(
        &self,
        serializer: S,
    ) -> Result<<S as crate::Serializer>::Ok, <S as crate::Serializer>::Error>
    where
        S: crate::Serializer,
    {
        let mut __elements = crate::Serializer::serialize_seq(serializer)?;
        crate::ser::SerializeSeq::serialize_element(&mut __elements, &self.decl)?;
        crate::ser::SerializeSeq::serialize_element(&mut __elements, &self.elements)?;
        crate::ser::SerializeSeq::end(__elements)
    }
}

impl<'__deserialize, T: Deserialize<'__deserialize> + Debug> Deserialize<'__deserialize>
    for XmlRoot<T>
{
    fn deserialize<D>(__deserializer: D) -> Result<Self, <D as Deserializer<'__deserialize>>::Error>
    where
        D: Deserializer<'__deserialize>,
    {
        struct __XmlRootVisitor<'__visitor, T> {
            marker: ::core::marker::PhantomData<XmlRoot<T>>,
            lifetime: ::core::marker::PhantomData<&'__visitor ()>,
        }
        impl<'__visitor, T: Deserialize<'__visitor> + Debug> crate::de::Visitor<'__visitor>
            for __XmlRootVisitor<'__visitor, T>
        {
            type Value = XmlRoot<T>;
            fn expecting(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
                ::core::fmt::Formatter::write_str(formatter, "struct XmlRoot")
            }

            fn visit_seq<S>(self, mut sequence: S) -> Result<Self::Value, S::Error>
            where
                S: de::SeqAccess<'__visitor>,
            {
                Ok(Self::Value {
                    decl: crate::de::SeqAccess::next_element::<XmlDecl>(&mut sequence)
                        .ok()
                        .flatten(),
                    elements: crate::de::SeqAccess::next_element_seq::<Vec<XmlRootTop<T>>>(
                        &mut sequence,
                    )?
                    .unwrap_or_default(),
                })
            }
        }
        Deserializer::deserialize_seq(
            __deserializer,
            __XmlRootVisitor {
                lifetime: ::core::marker::PhantomData,
                marker: ::core::marker::PhantomData,
            },
        )
    }
}

/// A top-level element of the XML document.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum XmlRootTop<T> {
    /// An element of the XML document.
    Value(T),
    /// A comment in the XML document.
    Comment(value::XmlComment),
    /// A processing instructions in the XML document.
    PI(value::XmlProcessingInstruction),
    /// A doctype declarations in the XML document.
    Doctype(value::XmlDoctype),
}

impl<T> From<value::XmlComment> for XmlRootTop<T> {
    fn from(value: value::XmlComment) -> Self {
        XmlRootTop::Comment(value)
    }
}

impl<T> From<value::XmlProcessingInstruction> for XmlRootTop<T> {
    fn from(value: value::XmlProcessingInstruction) -> Self {
        XmlRootTop::PI(value)
    }
}

impl<T> From<value::XmlDoctype> for XmlRootTop<T> {
    fn from(value: value::XmlDoctype) -> Self {
        XmlRootTop::Doctype(value)
    }
}

impl<T: Serialize> crate::Serialize for XmlRootTop<T> {
    fn serialize<S>(
        &self,
        serializer: S,
    ) -> Result<<S as crate::Serializer>::Ok, <S as crate::Serializer>::Error>
    where
        S: crate::Serializer,
    {
        match self {
            XmlRootTop::Value(__v) => crate::Serialize::serialize(&__v, serializer),
            XmlRootTop::Comment(__v) => crate::Serialize::serialize(&__v, serializer),
            XmlRootTop::PI(__v) => crate::Serialize::serialize(&__v, serializer),
            XmlRootTop::Doctype(__v) => crate::Serialize::serialize(&__v, serializer),
        }
    }
}

impl<'__deserialize, T: Deserialize<'__deserialize>> Deserialize<'__deserialize> for XmlRootTop<T> {
    fn deserialize<D>(__deserializer: D) -> Result<Self, <D as Deserializer<'__deserialize>>::Error>
    where
        D: Deserializer<'__deserialize>,
    {
        struct __XmlRootTopVisitor<'__visitor, T> {
            marker: ::core::marker::PhantomData<XmlRootTop<T>>,
            lifetime: ::core::marker::PhantomData<&'__visitor ()>,
        }
        impl<'__visitor, T: Deserialize<'__visitor>> crate::de::Visitor<'__visitor>
            for __XmlRootTopVisitor<'__visitor, T>
        {
            type Value = XmlRootTop<T>;
            fn expecting(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
                ::core::fmt::Formatter::write_str(formatter, "enum XmlRootTop")
            }
            fn visit_seq<S>(
                self,
                mut __sequence: S,
            ) -> Result<Self::Value, <S as crate::de::SeqAccess<'__visitor>>::Error>
            where
                S: crate::de::SeqAccess<'__visitor>,
            {
                if let ::core::result::Result::Ok(::core::option::Option::Some(_v)) =
                    crate::de::SeqAccess::next_element::<T>(&mut __sequence)
                {
                    return ::core::result::Result::Ok(XmlRootTop::Value(_v));
                }
                if let ::core::result::Result::Ok(::core::option::Option::Some(_v)) =
                    crate::de::SeqAccess::next_element::<value::XmlComment>(&mut __sequence)
                {
                    return ::core::result::Result::Ok(XmlRootTop::Comment(_v));
                }
                if let ::core::result::Result::Ok(::core::option::Option::Some(_v)) =
                    crate::de::SeqAccess::next_element::<value::XmlProcessingInstruction>(
                        &mut __sequence,
                    )
                {
                    return ::core::result::Result::Ok(XmlRootTop::PI(_v));
                }
                if let ::core::result::Result::Ok(::core::option::Option::Some(_v)) =
                    crate::de::SeqAccess::next_element::<value::XmlDoctype>(&mut __sequence)
                {
                    return ::core::result::Result::Ok(XmlRootTop::Doctype(_v));
                }
                ::core::result::Result::Err(crate::de::Error::no_possible_variant("XmlRootTop"))
            }
        }
        Deserializer::deserialize_seq(
            __deserializer,
            __XmlRootTopVisitor {
                lifetime: ::core::marker::PhantomData,
                marker: ::core::marker::PhantomData,
            },
        )
    }
}

impl<T> XmlRoot<T> {
    /// Creates a new `XmlRoot` with the given value.
    pub fn new() -> Self {
        Self {
            decl: None,
            elements: Vec::new(),
        }
    }

    /// Adds a declaration to the XML document.
    pub fn with_decl<U: Into<XmlDecl>>(mut self, decl: U) -> Self {
        let decl: XmlDecl = decl.into();
        self.decl = Some(decl);
        self
    }

    /// Adds an element to the XML document.
    pub fn with_element<U: Into<T>>(mut self, element: U) -> Self {
        let element: T = element.into();
        self.elements.push(XmlRootTop::Value(element));
        self
    }

    /// Adds multiple elements to the XML document.
    pub fn with_elements<U: Into<T>, I: IntoIterator<Item = U>>(mut self, elements: I) -> Self {
        self.elements.extend(
            elements
                .into_iter()
                .map(Into::<T>::into)
                .map(XmlRootTop::Value),
        );
        self
    }

    /// Adds a comment to the XML document.
    pub fn with_comment<U: Into<value::XmlComment>>(mut self, comment: U) -> Self {
        let comment: value::XmlComment = comment.into();
        self.elements.push(comment.into());
        self
    }

    /// Adds multiple attributes to the element.
    pub fn with_comments<U: Into<value::XmlComment>, I: IntoIterator<Item = U>>(
        mut self,
        comments: I,
    ) -> Self {
        self.elements.extend(
            comments
                .into_iter()
                .map(Into::<value::XmlComment>::into)
                .map(Into::into),
        );
        self
    }

    /// Adds a processing instruction to the XML document.
    pub fn with_pi<U: Into<value::XmlProcessingInstruction>>(mut self, pi: U) -> Self {
        let pi: value::XmlProcessingInstruction = pi.into();
        self.elements.push(pi.into());
        self
    }

    /// Adds multiple processing instructions to the XML document.
    pub fn with_pis<U: Into<value::XmlProcessingInstruction>, I: IntoIterator<Item = U>>(
        mut self,
        pis: I,
    ) -> Self {
        self.elements.extend(
            pis.into_iter()
                .map(Into::<value::XmlProcessingInstruction>::into)
                .map(Into::into),
        );
        self
    }

    /// Adds a doctype declaration to the XML document.
    pub fn with_doctype<U: Into<value::XmlDoctype>>(mut self, doctype: U) -> Self {
        let doctype: value::XmlDoctype = doctype.into();
        self.elements.push(doctype.into());
        self
    }

    /// Adds multiple doctype declarations to the XML document.
    pub fn with_doctypes<U: Into<value::XmlDoctype>, I: IntoIterator<Item = U>>(
        mut self,
        doctypes: I,
    ) -> Self {
        self.elements.extend(
            doctypes
                .into_iter()
                .map(Into::<value::XmlDoctype>::into)
                .map(Into::into),
        );
        self
    }
}

impl<T> Default for XmlRoot<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// A visitor for deserializing a string from a CDATA section.
pub struct FromCDataVisitor<T> {
    _marker: PhantomData<fn() -> T>,
}

impl<T> Default for FromCDataVisitor<T> {
    fn default() -> Self {
        Self {
            _marker: PhantomData,
        }
    }
}

impl<'de, T: Deserialize<'de>> Visitor<'de> for FromCDataVisitor<T>
where
    T: FromStr,
{
    type Value = T;
    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "a string")
    }

    fn visit_cdata<E, V: XmlCData<'de>>(self, v: V) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        v.as_str().parse().map_err(|_| E::custom("invalid value"))
    }
}

/// A wrapper type for CDATA sections.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CData<S>(pub S);

impl<'de, S: FromStr + Deserialize<'de>> Deserialize<'de> for CData<S> {
    fn deserialize<D: Deserializer<'de>>(reader: D) -> Result<Self, D::Error> {
        reader
            .deserialize_any(FromCDataVisitor::default())
            .map(CData)
    }
}

impl<S: AsRef<str>> Serialize for CData<S> {
    fn serialize<Ser: Serializer>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error> {
        serializer.serialize_cdata(self.0.as_ref())
    }
}

/// A type that ignores that uses the value that visits it, but results in nothing. Useful for skipping over values.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Whitespace<'a>(pub std::borrow::Cow<'a, str>);

impl<'de> Deserialize<'de> for Whitespace<'de> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct __Visitor<'v> {
            lifetime: ::core::marker::PhantomData<&'v ()>,
        }

        impl<'v> crate::de::Visitor<'v> for __Visitor<'v> {
            type Value = Whitespace<'v>;

            fn expecting(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
                formatter.write_str("ignored any value")
            }

            fn visit_text<E, V: XmlText<'v>>(self, text: V) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                let text = text.into_string();
                if text.trim().is_empty() {
                    Ok(Whitespace(text))
                } else {
                    Err(E::custom("expected whitespace"))
                }
            }
        }

        deserializer.deserialize_any(__Visitor {
            lifetime: ::core::marker::PhantomData,
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// Utility type for a type that can either be whitespace or a specific value
pub enum ValueOrWhitespace<'a, T> {
    /// Whitespace
    Whitespace(Cow<'a, str>),
    /// Value
    Value(T),
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for ValueOrWhitespace<'de, T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct __Visitor<'v, T> {
            marker: ::core::marker::PhantomData<T>,
            lifetime: ::core::marker::PhantomData<&'v ()>,
        }

        impl<'v, T: Deserialize<'v>> crate::de::Visitor<'v> for __Visitor<'v, T> {
            type Value = ValueOrWhitespace<'v, T>;

            fn expecting(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
                formatter.write_str("ignored any value")
            }

            fn visit_seq<S>(self, mut sequence: S) -> Result<Self::Value, S::Error>
            where
                S: de::SeqAccess<'v>,
            {
                if let Ok(Some(text)) = sequence.next_element::<Whitespace>() {
                    Ok(ValueOrWhitespace::Whitespace(text.0))
                } else {
                    sequence
                        .next_element_seq::<T>()?
                        .ok_or_else(de::Error::missing_data)
                        .map(ValueOrWhitespace::Value)
                }
            }

            fn visit_none<E>(self) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                T::deserialize_seq(crate::types::utils::NoneDeserializer::new())
                    .map(ValueOrWhitespace::Value)
            }
        }

        deserializer.deserialize_seq(__Visitor {
            lifetime: ::core::marker::PhantomData,
            marker: ::core::marker::PhantomData,
        })
    }
}

/// A type that ignores that uses the value that visits it, but results in nothing. Useful for skipping over values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct IgnoredAny;

impl<'de> Deserialize<'de> for IgnoredAny {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct __Visitor<'v> {
            marker: ::core::marker::PhantomData<IgnoredAny>,
            lifetime: ::core::marker::PhantomData<&'v ()>,
        }

        impl<'v> crate::de::Visitor<'v> for __Visitor<'v> {
            type Value = IgnoredAny;

            fn expecting(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
                formatter.write_str("ignored any value")
            }

            fn visit_seq<S>(self, _sequence: S) -> Result<Self::Value, S::Error>
            where
                S: crate::de::SeqAccess<'v>,
            {
                Ok(IgnoredAny)
            }

            fn visit_text<E, V: XmlText<'v>>(self, _value: V) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(IgnoredAny)
            }

            fn visit_cdata<E, V: XmlCData<'v>>(self, _value: V) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(IgnoredAny)
            }

            fn visit_element<A>(self, _element: A) -> Result<Self::Value, A::Error>
            where
                A: de::ElementAccess<'v>,
            {
                Ok(IgnoredAny)
            }

            fn visit_attribute<A>(self, _attribute: A) -> Result<Self::Value, A::Error>
            where
                A: de::AttributeAccess<'v>,
            {
                Ok(IgnoredAny)
            }

            fn visit_pi<E, V: XmlProcessingInstruction>(self, _pi: V) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(IgnoredAny)
            }

            fn visit_decl<E, V: XmlDeclaration>(self, _declaration: V) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(IgnoredAny)
            }

            fn visit_comment<E, V: XmlComment<'v>>(self, _comment: V) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(IgnoredAny)
            }

            fn visit_doctype<E, V: XmlDoctype<'v>>(self, _doctype: V) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(IgnoredAny)
            }

            fn visit_none<E>(self) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(IgnoredAny)
            }
        }

        deserializer.deserialize_any(__Visitor {
            lifetime: ::core::marker::PhantomData,
            marker: ::core::marker::PhantomData,
        })
    }
}

/// A deserializer that always runs [`Visitor::visit_none`].
pub struct NoneDeserializer<E: de::Error> {
    _marker: PhantomData<E>,
}

impl<E: de::Error> NoneDeserializer<E> {
    /// Creates a new [`NoneDeserializer`].
    pub fn new() -> Self {
        Self {
            _marker: PhantomData,
        }
    }
}

impl<E: de::Error> Default for NoneDeserializer<E> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'de, E: de::Error> Deserializer<'de> for NoneDeserializer<E> {
    type Error = E;

    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_none()
    }

    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_none()
    }
}