xmlity-quick-xml 0.0.9

XMLity implementation of quick-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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
use core::str;
use std::borrow::{Borrow, Cow};
use std::collections::BTreeMap;
use std::io::Write;
use std::ops::DerefMut;

use quick_xml::events::{BytesCData, BytesDecl, BytesEnd, BytesPI, BytesStart, BytesText, Event};
use quick_xml::writer::Writer as QuickXmlWriter;

use xmlity::{
    ser::{self, Error as _, IncludePrefix, Unexpected},
    ExpandedName, Prefix, QName, Serialize, XmlNamespace,
};
use xmlity::{ExpandedNameBuf, NoopDeSerializer, PrefixBuf, QNameBuf, XmlNamespaceBuf};

use crate::{OwnedQuickName, XmlnsDeclaration};

/// Errors that can occur when using this crate.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// Error from the `quick-xml` crate.
    #[error("Quick XML error: {0}")]
    QuickXml(#[from] quick_xml::Error),
    /// Error from the `quick-xml` crate when handling attributes.
    #[error("Attribute error: {0}")]
    AttrError(#[from] quick_xml::events::attributes::AttrError),
    /// IO errors.
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    /// Custom errors from [`Serialize`] implementations.
    #[error("Custom: {0}")]
    Custom(String),
    /// Invalid UTF-8 when serializing.
    #[error("Invalid UTF-8: {0}")]
    InvalidUtf8(#[from] std::string::FromUtf8Error),
}

impl xmlity::ser::Error for Error {
    fn unexpected_serialize(unexpected: ser::Unexpected) -> Self {
        Error::Custom(format!("Unexpected serialize: {unexpected:?}"))
    }

    fn custom<T: ToString>(msg: T) -> Self {
        Error::Custom(msg.to_string())
    }
}

fn serializer_to_string<T>(serializer: QuickXmlWriter<Vec<u8>>, value: &T) -> Result<String, Error>
where
    T: Serialize,
{
    let mut serializer = Serializer::from(serializer);
    value.serialize(&mut serializer)?;
    let bytes = serializer.into_inner();

    String::from_utf8(bytes).map_err(Error::InvalidUtf8)
}

/// Serialize a value into a string.
pub fn to_string<T>(value: &T) -> Result<String, Error>
where
    T: Serialize,
{
    serializer_to_string(QuickXmlWriter::new(Vec::new()), value)
}

/// Serialize a value into a string with pretty printing.
pub fn to_string_pretty<T>(value: &T, indentation: usize) -> Result<String, Error>
where
    T: Serialize,
{
    serializer_to_string(
        QuickXmlWriter::new_with_indent(Vec::new(), b' ', indentation),
        value,
    )
}

struct NamespaceScope {
    pub defined_namespaces: BTreeMap<Cow<'static, Prefix>, Cow<'static, XmlNamespace>>,
}

impl NamespaceScope {
    pub fn new() -> Self {
        Self {
            defined_namespaces: BTreeMap::new(),
        }
    }

    const XML_PREFIX: &'static Prefix = unsafe { Prefix::new_unchecked("xml") };
    const XML_NAMESPACE: &'static XmlNamespace =
        unsafe { XmlNamespace::new_unchecked("http://www.w3.org/XML/1998/namespace") };

    pub fn top_scope() -> Self {
        let mut scope = Self::new();
        scope.defined_namespaces.insert(
            Cow::Borrowed(Self::XML_PREFIX),
            Cow::Borrowed(Self::XML_NAMESPACE),
        );
        scope
    }

    pub fn get_namespace<'b>(&'b self, prefix: &'b Prefix) -> Option<&'b XmlNamespace> {
        self.defined_namespaces.get(prefix).map(|v| &**v)
    }
}

struct NamespaceScopeContainer {
    scopes: Vec<NamespaceScope>,
    prefix_generator: PrefixGenerator,
}

struct PrefixGenerator {
    count: usize,
}

impl PrefixGenerator {
    pub fn index_to_name(index: usize) -> PrefixBuf {
        // 0 = a0
        // 1 = a1
        // 26 = b0
        // 27 = b1
        // 52 = c0
        // 53 = c1
        // ...

        let letter = (index / 26) as u8 + b'a';
        let number = (index % 26) as u8 + b'0';
        let mut name = String::with_capacity(2);
        name.push(letter as char);
        name.push(number as char);
        PrefixBuf::new(name).expect("Invalid prefix generated")
    }

    pub fn new() -> Self {
        Self { count: 0 }
    }

    pub fn new_prefix(&mut self) -> PrefixBuf {
        let name = Self::index_to_name(self.count);
        self.count += 1;
        name
    }
}

impl NamespaceScopeContainer {
    pub fn new() -> Self {
        Self {
            scopes: vec![NamespaceScope::top_scope()],
            prefix_generator: PrefixGenerator::new(),
        }
    }

    pub fn push_scope(&mut self) {
        self.scopes.push(NamespaceScope::new())
    }

    pub fn pop_scope(&mut self) -> Option<NamespaceScope> {
        self.scopes.pop()
    }

    pub fn get_namespace<'b>(&'b self, prefix: &'b Prefix) -> Option<&'b XmlNamespace> {
        self.scopes
            .iter()
            .rev()
            .find_map(|a| a.get_namespace(prefix))
    }

    /// Find matching prefix
    pub fn find_matching_namespace<'b>(&'b self, namespace: &XmlNamespace) -> Option<&'b Prefix> {
        self.scopes.iter().rev().find_map(|a| {
            a.defined_namespaces
                .iter()
                .find(|(_, found_namespace)| *namespace == ***found_namespace)
                .map(|(prefix, _)| &**prefix)
        })
    }

    /// This function takes in a namespace and tries to resolve it in different ways depending on the options provided. Unless `always_declare` is true, it will try to use an existing declaration. Otherwise, or if the namespace has not yet been declared, it will provide a declaration.
    pub fn resolve_namespace<'b>(
        &'b mut self,
        namespace: &'_ XmlNamespace,
        preferred_prefix: Option<&Prefix>,
        always_declare: IncludePrefix,
    ) -> (&'b Prefix, Option<XmlnsDeclaration<'b>>) {
        if always_declare != IncludePrefix::Always {
            let existing_prefix = self.find_matching_namespace(namespace);

            if let Some(existing_prefix) = existing_prefix {
                if (always_declare == IncludePrefix::WhenNecessaryForPreferredPrefix
                    && preferred_prefix
                        .is_none_or(|preferred_prefix| preferred_prefix == existing_prefix))
                    || always_declare == IncludePrefix::Never
                {
                    let existing_prefix = self.find_matching_namespace(namespace).unwrap();
                    return (existing_prefix, None);
                }
            }
        }

        // If the namespace is not declared, use the specifically requested preferred prefix...
        // ...if it is not already used and not the same as the existing prefix.
        let prefix = preferred_prefix
            .filter(|p| self.get_namespace(p).is_none_or(|n| n == namespace))
            // If the preferred prefix is not available, use the preferred namespace prefix from the serializer...
            .or_else(|| {
                preferred_prefix
                    // ...if it is not already used and not the same as the existing prefix.
                    .filter(|p| self.get_namespace(p).is_none_or(|n| n == namespace))
            })
            .map(|p| p.to_owned())
            // If the preferred namespace prefix is not available, use a random prefix.
            .unwrap_or_else(|| self.prefix_generator.new_prefix());

        let scope = self
            .scopes
            .last_mut()
            .expect("There should be at least one scope");

        //TODO: This currently requires one more allocation than necessary. It requires https://github.com/rust-lang/rust/issues/65225 to be stabilized.
        scope
            .defined_namespaces
            .insert(Cow::Owned(prefix.clone()), Cow::Owned(namespace.to_owned()));

        let (prefix, namespace) = scope
            .defined_namespaces
            .get_key_value(Borrow::<Prefix>::borrow(&prefix))
            .expect("The namespace should be defined as it was just added");

        let xmlns = XmlnsDeclaration::new(prefix.as_ref(), namespace.as_ref());

        (prefix.as_ref(), Some(xmlns))
    }

    pub fn resolve_name<'a>(
        &'a mut self,
        local_name: ExpandedName<'a>,
        preferred_prefix: Option<&'a Prefix>,
        always_declare: IncludePrefix,
    ) -> (QName<'a>, Option<XmlnsDeclaration<'a>>) {
        let (local_name, namespace) = local_name.into_parts();

        let (prefix, declaration) = namespace
            .as_ref()
            .map(|namespace| self.resolve_namespace(namespace, preferred_prefix, always_declare))
            .unzip();

        let declaration = declaration.flatten();

        let name = QName::new(prefix, local_name);
        (name, declaration)
    }
}

/// The [`xmlity::Deserializer`] for the `quick-xml` crate.
pub struct Serializer<W: Write> {
    writer: QuickXmlWriter<W>,
    preferred_namespace_prefixes: BTreeMap<XmlNamespaceBuf, PrefixBuf>,
    namespace_scopes: NamespaceScopeContainer,
    buffered_bytes_start: BytesStart<'static>,
    buffered_bytes_start_empty: bool,
}

impl<W: Write> Serializer<W> {
    /// Create a new serializer.
    pub fn new(writer: QuickXmlWriter<W>) -> Self {
        Self::new_with_namespaces(writer, BTreeMap::new())
    }

    /// Create a new serializer with preferred namespace prefixes.
    pub fn new_with_namespaces(
        writer: QuickXmlWriter<W>,
        preferred_namespace_prefixes: BTreeMap<XmlNamespaceBuf, PrefixBuf>,
    ) -> Self {
        Self {
            writer,
            preferred_namespace_prefixes,
            namespace_scopes: NamespaceScopeContainer::new(),
            buffered_bytes_start: BytesStart::new(""),
            buffered_bytes_start_empty: true,
        }
    }

    /// Consume the serializer and return the underlying writer.
    pub fn into_inner(self) -> W {
        self.writer.into_inner()
    }

    fn push_namespace_scope(&mut self) {
        self.namespace_scopes.push_scope()
    }

    fn pop_namespace_scope(&mut self) {
        self.namespace_scopes.pop_scope();
    }
}

impl<W: Write> From<QuickXmlWriter<W>> for Serializer<W> {
    fn from(writer: QuickXmlWriter<W>) -> Self {
        Self::new(writer)
    }
}

impl<W: Write> From<W> for Serializer<W> {
    fn from(writer: W) -> Self {
        Self::new(QuickXmlWriter::new(writer))
    }
}

/// The main element serializer for the `quick-xml` crate.
pub struct SerializeElement<'s, W: Write> {
    serializer: &'s mut Serializer<W>,
    name: ExpandedNameBuf,
    include_prefix: IncludePrefix,
    preferred_prefix: Option<PrefixBuf>,
}

/// The attribute serializer for the `quick-xml` crate.
pub struct AttributeSerializer<'t, W: Write> {
    name: ExpandedNameBuf,
    serializer: &'t mut Serializer<W>,
    preferred_prefix: Option<PrefixBuf>,
    enforce_prefix: IncludePrefix,
}

/// The text serializer for the `quick-xml` crate. Used when serializing to an attribute value.
pub struct TextSerializer {
    value: Option<String>,
}

impl ser::SerializeSeq for &mut TextSerializer {
    type Ok = ();
    type Error = Error;

    fn serialize_element<V: Serialize>(&mut self, value: &V) -> Result<Self::Ok, Self::Error> {
        if self.value.is_some() {
            return Err(Error::unexpected_serialize(Unexpected::Text));
        }

        let mut text_ser = TextSerializer { value: None };
        value.serialize(&mut text_ser)?;

        if let Some(value) = text_ser.value {
            self.value = Some(value);
        } else {
            return Err(Error::unexpected_serialize(Unexpected::None));
        }

        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

impl<'a> ser::Serializer for &'a mut TextSerializer {
    type Ok = ();
    type Error = Error;

    type SerializeElement = NoopDeSerializer<Self::Ok, Self::Error>;

    type SerializeSeq = &'a mut TextSerializer;

    fn serialize_text<S: AsRef<str>>(self, text: S) -> Result<(), Self::Error> {
        if self.value.is_some() {
            return Err(Error::unexpected_serialize(Unexpected::Text));
        }

        self.value = Some(text.as_ref().to_string());

        Ok(())
    }

    fn serialize_cdata<S: AsRef<str>>(self, text: S) -> Result<Self::Ok, Self::Error> {
        let _ = text;

        Err(Error::unexpected_serialize(Unexpected::CData))
    }

    fn serialize_element(
        self,
        name: &'_ ExpandedName<'_>,
    ) -> Result<Self::SerializeElement, Self::Error> {
        let _ = name;

        Err(Error::unexpected_serialize(Unexpected::Element))
    }

    fn serialize_seq(self) -> Result<Self::SerializeSeq, Self::Error> {
        Ok(self)
    }

    fn serialize_decl<S: AsRef<str>>(
        self,
        version: S,
        encoding: Option<S>,
        standalone: Option<S>,
    ) -> Result<Self::Ok, Self::Error> {
        let _ = (version, encoding, standalone);

        Err(Error::unexpected_serialize(Unexpected::Decl))
    }

    fn serialize_pi<S: AsRef<[u8]>>(self, target: S, content: S) -> Result<Self::Ok, Self::Error> {
        let _ = (target, content);

        Err(Error::unexpected_serialize(Unexpected::PI))
    }

    fn serialize_comment<S: AsRef<[u8]>>(self, text: S) -> Result<Self::Ok, Self::Error> {
        let _ = text;

        Err(Error::unexpected_serialize(Unexpected::Comment))
    }

    fn serialize_doctype<S: AsRef<[u8]>>(self, text: S) -> Result<Self::Ok, Self::Error> {
        let _ = text;

        Err(Error::unexpected_serialize(Unexpected::DocType))
    }

    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
        Err(Error::unexpected_serialize(Unexpected::None))
    }
}

impl<W: Write> ser::SerializeAttributeAccess for AttributeSerializer<'_, W> {
    type Ok = ();
    type Error = Error;

    fn include_prefix(&mut self, should_enforce: IncludePrefix) -> Result<Self::Ok, Self::Error> {
        self.enforce_prefix = should_enforce;
        Ok(())
    }

    fn preferred_prefix(
        &mut self,
        preferred_prefix: Option<&Prefix>,
    ) -> Result<Self::Ok, Self::Error> {
        self.preferred_prefix = preferred_prefix.map(Prefix::to_owned);
        Ok(())
    }

    fn end<S: Serialize>(self, value: &S) -> Result<Self::Ok, Self::Error> {
        let preferred_prefix = self.preferred_prefix.as_deref().or_else(|| {
            self.name
                .namespace()
                .and_then(|a| self.serializer.preferred_namespace_prefixes.get(a))
                .map(|p| &**p)
        });

        let (qname, decl) = self.serializer.namespace_scopes.resolve_name(
            self.name.as_ref(),
            preferred_prefix,
            self.enforce_prefix,
        );

        if let Some(decl) = decl {
            self.serializer.buffered_bytes_start.push_declaration(decl);
        }

        let mut text_ser = TextSerializer { value: None };

        value.serialize(&mut text_ser)?;

        self.serializer.buffered_bytes_start.push_attribute_xmlity(
            qname,
            Cow::Owned(
                text_ser
                    .value
                    .expect("TextSerializer should have a value")
                    .into_bytes(),
            ),
        );

        Ok(())
    }
}

impl<W: Write> ser::AttributeSerializer for &mut SerializeElementAttributes<'_, W> {
    type Error = Error;

    type Ok = ();
    type SerializeAttribute<'a>
        = AttributeSerializer<'a, W>
    where
        Self: 'a;

    fn serialize_attribute(
        &mut self,
        name: &'_ ExpandedName,
    ) -> Result<Self::SerializeAttribute<'_>, Self::Error> {
        Ok(Self::SerializeAttribute {
            name: name.into_owned(),
            serializer: self.serializer.deref_mut(),
            preferred_prefix: None,
            enforce_prefix: IncludePrefix::default(),
        })
    }

    fn serialize_none(&mut self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

impl<'s, W: Write> SerializeElement<'s, W> {
    fn finish_start(self) -> (QNameBuf, &'s mut Serializer<W>) {
        let Self {
            name,
            include_prefix,
            preferred_prefix,
            serializer,
        } = self;

        assert!(
            serializer.buffered_bytes_start_empty,
            "Should have been emptied by the serializer"
        );

        serializer.buffered_bytes_start.clear_attributes();

        let preferred_prefix = preferred_prefix.as_deref().or_else(|| {
            name.as_ref()
                .namespace()
                .and_then(|a| serializer.preferred_namespace_prefixes.get(a))
                .map(|p| &**p)
        });

        let (qname, decl) = serializer.namespace_scopes.resolve_name(
            name.as_ref(),
            preferred_prefix,
            include_prefix,
        );
        let qname = qname.into_owned();

        serializer
            .buffered_bytes_start
            .set_name(qname.to_string().as_bytes());

        if let Some(decl) = decl {
            serializer.buffered_bytes_start.push_declaration(decl);
        }
        serializer.buffered_bytes_start_empty = false;

        (qname, serializer)
    }

    fn end_empty(serializer: &mut Serializer<W>) -> Result<(), Error> {
        assert!(
            !serializer.buffered_bytes_start_empty,
            "start should be buffered"
        );
        let start = serializer.buffered_bytes_start.borrow();

        serializer
            .writer
            .write_event(Event::Empty(start))
            .map_err(Error::Io)?;

        serializer.buffered_bytes_start_empty = true;

        Ok(())
    }
}

/// Provides the implementation of [`ser::SerializeElement`] for the `quick-xml` crate.
pub struct SerializeElementAttributes<'s, W: Write> {
    serializer: &'s mut Serializer<W>,
    end_name: QNameBuf,
}

impl<W: Write> ser::SerializeAttributes for SerializeElementAttributes<'_, W> {
    type Ok = ();
    type Error = Error;

    fn serialize_attribute<A: ser::SerializeAttribute>(
        &mut self,
        a: &A,
    ) -> Result<Self::Ok, Self::Error> {
        a.serialize_attribute(self)
    }
}

impl<'s, W: Write> ser::SerializeElementAttributes for SerializeElementAttributes<'s, W> {
    type ChildrenSerializeSeq = ChildrenSerializeSeq<'s, W>;

    fn serialize_children(self) -> Result<Self::ChildrenSerializeSeq, Self::Error> {
        Ok(ChildrenSerializeSeq {
            serializer: self.serializer,
            end_name: self.end_name,
        })
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        SerializeElement::end_empty(self.serializer)
    }
}

impl<'s, W: Write> ser::SerializeElement for SerializeElement<'s, W> {
    type Ok = ();
    type Error = Error;
    type ChildrenSerializeSeq = ChildrenSerializeSeq<'s, W>;
    type SerializeElementAttributes = SerializeElementAttributes<'s, W>;

    fn include_prefix(&mut self, should_enforce: IncludePrefix) -> Result<Self::Ok, Self::Error> {
        self.include_prefix = should_enforce;
        Ok(())
    }
    fn preferred_prefix(
        &mut self,
        preferred_prefix: Option<&Prefix>,
    ) -> Result<Self::Ok, Self::Error> {
        self.preferred_prefix = preferred_prefix.map(Prefix::to_owned);
        Ok(())
    }

    fn serialize_attributes(self) -> Result<Self::SerializeElementAttributes, Self::Error> {
        self.serializer.push_namespace_scope();
        let (end_name, serializer) = self.finish_start();
        Ok(SerializeElementAttributes {
            serializer,
            end_name,
        })
    }

    fn serialize_children(self) -> Result<Self::ChildrenSerializeSeq, Self::Error> {
        self.serializer.push_namespace_scope();
        let (end_name, serializer) = self.finish_start();

        Ok(ChildrenSerializeSeq {
            serializer,
            end_name,
        })
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.serializer.push_namespace_scope();
        let (_, serializer) = self.finish_start();

        SerializeElement::end_empty(serializer)?;

        serializer.pop_namespace_scope();

        Ok(())
    }
}

///Provides the implementation of `SerializeSeq` trait for element children for the `quick-xml` crate.
pub struct ChildrenSerializeSeq<'s, W: Write> {
    serializer: &'s mut Serializer<W>,
    end_name: QNameBuf,
}

impl<W: Write> ser::SerializeSeq for ChildrenSerializeSeq<'_, W> {
    type Ok = ();
    type Error = Error;

    fn serialize_element<V: Serialize>(&mut self, value: &V) -> Result<(), Self::Error> {
        value.serialize(self.serializer.deref_mut())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        // If we have a bytes_start, then we never wrote the start event, so we need to write an empty element instead.
        if !self.serializer.buffered_bytes_start_empty {
            self.serializer
                .writer
                .write_event(Event::Empty(self.serializer.buffered_bytes_start.borrow()))
                .map_err(Error::Io)?;
            self.serializer.buffered_bytes_start_empty = true;
        } else {
            let end_name = OwnedQuickName::new(&self.end_name.as_ref());

            let bytes_end = BytesEnd::from(end_name.as_ref());

            self.serializer
                .writer
                .write_event(Event::End(bytes_end))
                .map_err(Error::Io)?;
        }

        self.serializer.pop_namespace_scope();

        Ok(())
    }
}

/// Provides the implementation of `SerializeSeq` trait for any nodes for the `quick-xml` crate.
pub struct SerializeSeq<'e, W: Write> {
    serializer: &'e mut Serializer<W>,
}

impl<W: Write> ser::SerializeSeq for SerializeSeq<'_, W> {
    type Ok = ();
    type Error = Error;

    fn serialize_element<V: Serialize>(&mut self, v: &V) -> Result<(), Self::Error> {
        v.serialize(self.serializer.deref_mut())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

trait BytesStartExt<'a> {
    fn push_attribute_xmlity(&mut self, qname: QName<'_>, value: Cow<'a, [u8]>);

    fn push_declaration(&mut self, decl: XmlnsDeclaration<'_>);
}

impl<'a> BytesStartExt<'a> for BytesStart<'a> {
    fn push_attribute_xmlity(&mut self, qname: QName<'_>, value: Cow<'a, [u8]>) {
        self.push_attribute(quick_xml::events::attributes::Attribute {
            key: quick_xml::name::QName(qname.to_string().as_bytes()),
            value,
        });
    }

    fn push_declaration(&mut self, decl: XmlnsDeclaration<'_>) {
        let XmlnsDeclaration { namespace, prefix } = decl;

        let key = XmlnsDeclaration::xmlns_qname(prefix);

        self.push_attribute_xmlity(key, Cow::Owned(namespace.as_str().as_bytes().to_vec()));
    }
}

impl<W: Write> Serializer<W> {
    fn try_start(&mut self) -> Result<(), Error> {
        if !self.buffered_bytes_start_empty {
            self.writer
                .write_event(Event::Start(self.buffered_bytes_start.borrow()))
                .map_err(Error::Io)?;
            self.buffered_bytes_start_empty = true;
        }
        Ok(())
    }
}

impl<'s, W: Write> xmlity::Serializer for &'s mut Serializer<W> {
    type Ok = ();
    type Error = Error;
    type SerializeElement = SerializeElement<'s, W>;
    type SerializeSeq = SerializeSeq<'s, W>;

    fn serialize_cdata<S: AsRef<str>>(self, text: S) -> Result<Self::Ok, Self::Error> {
        self.try_start()?;
        self.writer
            .write_event(Event::CData(BytesCData::new(text.as_ref())))
            .map_err(Error::Io)
    }

    fn serialize_text<S: AsRef<str>>(self, text: S) -> Result<Self::Ok, Self::Error> {
        self.try_start()?;
        self.writer
            .write_event(Event::Text(BytesText::from_escaped(text.as_ref())))
            .map_err(Error::Io)
    }

    fn serialize_element<'a>(
        self,
        name: &'a ExpandedName<'a>,
    ) -> Result<Self::SerializeElement, Self::Error> {
        self.try_start()?;

        Ok(SerializeElement {
            serializer: self,
            name: name.into_owned(),
            include_prefix: IncludePrefix::default(),
            preferred_prefix: None,
        })
    }

    fn serialize_seq(self) -> Result<Self::SerializeSeq, Self::Error> {
        Ok(SerializeSeq { serializer: self })
    }

    fn serialize_decl<S: AsRef<str>>(
        self,
        version: S,
        encoding: Option<S>,
        standalone: Option<S>,
    ) -> Result<Self::Ok, Self::Error> {
        self.try_start()?;
        self.writer
            .write_event(Event::Decl(BytesDecl::new(
                version.as_ref(),
                encoding.as_ref().map(|s| s.as_ref()),
                standalone.as_ref().map(|s| s.as_ref()),
            )))
            .map_err(Error::Io)
    }

    fn serialize_pi<S: AsRef<[u8]>>(self, target: S, content: S) -> Result<Self::Ok, Self::Error> {
        self.try_start()?;
        self.writer
            .write_event(Event::PI(BytesPI::new(format!(
                "{} {}",
                str::from_utf8(target.as_ref()).unwrap(),
                str::from_utf8(content.as_ref()).unwrap()
            ))))
            .map_err(Error::Io)
    }

    fn serialize_comment<S: AsRef<[u8]>>(self, text: S) -> Result<Self::Ok, Self::Error> {
        self.try_start()?;
        self.writer
            .write_event(Event::Comment(BytesText::from_escaped(
                str::from_utf8(text.as_ref()).unwrap(),
            )))
            .map_err(Error::Io)
    }

    fn serialize_doctype<S: AsRef<[u8]>>(self, text: S) -> Result<Self::Ok, Self::Error> {
        self.try_start()?;
        self.writer
            .write_event(Event::DocType(BytesText::from_escaped(
                str::from_utf8(text.as_ref()).unwrap(),
            )))
            .map_err(Error::Io)
    }

    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}