xmlity/
ser.rs

1//! This module contains the [`Serialize`], [`SerializeAttribute`], [`Serializer`] and [`SerializationGroup`] traits and associated types.
2use std::fmt::Display;
3
4use crate::{ExpandedName, Prefix};
5
6/// A trait for errors that can be returned by serializer after a serialization attempt.
7pub trait Error {
8    /// Creates an error with a custom message.
9    fn custom<T>(msg: T) -> Self
10    where
11        T: Display;
12}
13
14/// A trait for serializing attributes.
15pub trait SerializeAttributes: Sized {
16    /// The type of the value that is returned when serialization is successful.
17    type Ok;
18    /// The type of the error that is returned when serialization fails.
19    type Error: Error;
20
21    /// Serializes an attribute.
22    fn serialize_attribute<A: SerializeAttribute>(
23        &mut self,
24        a: &A,
25    ) -> Result<Self::Ok, Self::Error>;
26}
27
28impl<T: SerializeAttributes> SerializeAttributes for &mut T {
29    type Ok = T::Ok;
30    type Error = T::Error;
31
32    fn serialize_attribute<A: SerializeAttribute>(
33        &mut self,
34        a: &A,
35    ) -> Result<Self::Ok, Self::Error> {
36        SerializeAttributes::serialize_attribute(*self, a)
37    }
38}
39
40/// A trait for serializing attributes of an element.
41pub trait SerializeElementAttributes: SerializeAttributes {
42    /// The type of the value that is returned when serialization is successful.
43    type ChildrenSerializeSeq: SerializeSeq<Ok = Self::Ok, Error = Self::Error>;
44
45    /// Serialize the children of this element.
46    fn serialize_children(self) -> Result<Self::ChildrenSerializeSeq, Self::Error>;
47
48    /// End the serialization of this element with no children.
49    fn end(self) -> Result<Self::Ok, Self::Error>;
50}
51
52/// A trait for serializing elements.
53#[must_use = "Serializers could be lazy and must be consumed to guarantee serialization. Try calling `.serialize_children()` or `.end()` on the serializer."]
54pub trait SerializeElement {
55    /// The type of the value that is returned when serialization is successful.
56    type Ok;
57    /// The type of the error that is returned when serialization fails.
58    type Error: Error;
59
60    /// The type of the serializer that is returned when serializing the children of this element.
61    type ChildrenSerializeSeq: SerializeSeq<Ok = Self::Ok, Error = Self::Error>;
62
63    /// The type of the serializer that is returned when serializing the attributes of this element.
64    type SerializeElementAttributes: SerializeElementAttributes<Ok = Self::Ok, Error = Self::Error>;
65
66    /// Always serialize this element with the given prefix.
67    fn include_prefix(&mut self, should_enforce: IncludePrefix) -> Result<Self::Ok, Self::Error>;
68
69    /// Set the preferred prefix for this element.
70    fn preferred_prefix(
71        &mut self,
72        preferred_prefix: Option<Prefix<'_>>,
73    ) -> Result<Self::Ok, Self::Error>;
74
75    /// Serialize the attributes of this element.
76    fn serialize_attributes(self) -> Result<Self::SerializeElementAttributes, Self::Error>;
77
78    /// Serialize the children of this element.
79    fn serialize_children(self) -> Result<Self::ChildrenSerializeSeq, Self::Error>;
80
81    /// End the serialization of this element with no children.
82    fn end(self) -> Result<Self::Ok, Self::Error>;
83}
84
85/// A trait for serializing a sequence of elements.
86#[must_use = "Serializers could be lazy and must be consumed to guarantee serialization. Try calling `.end()` on the serializer."]
87pub trait SerializeSeq {
88    /// The type of the value that is returned when serialization is successful.
89    type Ok;
90    /// The type of the error that is returned when serialization fails.
91    type Error: Error;
92
93    /// Serialize an element in the sequence.
94    fn serialize_element<V: Serialize>(&mut self, v: &V) -> Result<Self::Ok, Self::Error>;
95
96    /// End the serialization of the sequence.
97    fn end(self) -> Result<Self::Ok, Self::Error>;
98}
99
100/// A serializer receives serialization instructions from a [`Serialize`] implementation and produces serialized output.
101pub trait Serializer: Sized {
102    /// The type of the value that is returned when serialization is successful.
103    type Ok;
104    /// The type of the error that is returned when serialization fails.
105    type Error: Error;
106    /// The type of the serializer that is used to serialize an element with children.
107    type SerializeElement: SerializeElement<Ok = Self::Ok, Error = Self::Error>;
108    /// The type of the serializer that is used to serialize a sequence of elements.
109    type SerializeSeq: SerializeSeq<Ok = Self::Ok, Error = Self::Error>;
110
111    /// Serialize a text node.
112    fn serialize_text<S: AsRef<str>>(self, text: S) -> Result<Self::Ok, Self::Error>;
113
114    /// Serialize a CDATA section.
115    fn serialize_cdata<S: AsRef<str>>(self, text: S) -> Result<Self::Ok, Self::Error>;
116
117    /// Serialize an element with children.
118    fn serialize_element(
119        self,
120        name: &'_ ExpandedName<'_>,
121    ) -> Result<Self::SerializeElement, Self::Error>;
122
123    /// Serialize a sequence of elements.
124    fn serialize_seq(self) -> Result<Self::SerializeSeq, Self::Error>;
125
126    /// Serialize an XML declaration.
127    fn serialize_decl<S: AsRef<str>>(
128        self,
129        version: S,
130        encoding: Option<S>,
131        standalone: Option<S>,
132    ) -> Result<Self::Ok, Self::Error>;
133
134    /// Serialize a processing instruction.
135    fn serialize_pi<S: AsRef<[u8]>>(self, target: S, content: S) -> Result<Self::Ok, Self::Error>;
136
137    /// Serialize a comment.
138    fn serialize_comment<S: AsRef<[u8]>>(self, text: S) -> Result<Self::Ok, Self::Error>;
139
140    /// Serialize a doctype declaration.
141    fn serialize_doctype<S: AsRef<[u8]>>(self, text: S) -> Result<Self::Ok, Self::Error>;
142
143    /// Serialize nothing.
144    fn serialize_none(self) -> Result<Self::Ok, Self::Error>;
145}
146
147/// A type that can serialize attributes. Works in a similar way to [`Serializer`].
148pub trait AttributeSerializer: Sized {
149    /// The type of the value that is returned when serialization is successful.
150    type Ok;
151    /// The type of the error that is returned when serialization fails.
152    type Error: Error;
153    /// The type returned when serializing an attribute.
154    type SerializeAttribute<'a>: SerializeAttributeAccess<Ok = Self::Ok, Error = Self::Error>
155    where
156        Self: 'a;
157
158    /// Serialize an attribute.
159    fn serialize_attribute(
160        &mut self,
161        name: &'_ ExpandedName<'_>,
162    ) -> Result<Self::SerializeAttribute<'_>, Self::Error>;
163
164    /// Serialize nothing.
165    fn serialize_none(&mut self) -> Result<Self::Ok, Self::Error>;
166}
167
168/// A type that can be serialized. To serialize, you provide it with a [`Serializer`] that then gets instructions from the type on how to serialize itself.
169///
170/// To see the documentation for the derive macro, see [`xmlity_derive::Serialize`].
171pub trait Serialize {
172    /// Serialize the type.
173    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>;
174}
175
176impl<T: Serialize> Serialize for &T {
177    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
178        T::serialize(*self, serializer)
179    }
180}
181
182impl<T: Serialize> Serialize for &mut T {
183    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
184        T::serialize(*self, serializer)
185    }
186}
187
188/// Setting for whether to enforce a prefix when serializing.
189#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
190pub enum IncludePrefix {
191    /// Always enforce the prefix.
192    Always,
193    /// Only when the preferred prefix is not the used prefix.
194    WhenNecessaryForPreferredPrefix,
195    /// Only use the prefix when it is absolutely necessary.
196    #[default]
197    Never,
198}
199
200/// A type that can be used to serialize an attribute.
201pub trait SerializeAttributeAccess: Sized {
202    /// The type of the value that is returned when serialization is successful.
203    type Ok;
204    /// The type of the error that is returned when serialization fails.
205    type Error: Error;
206
207    /// Set whether to enforce a prefix when serializing.
208    fn include_prefix(&mut self, should_include: IncludePrefix) -> Result<Self::Ok, Self::Error>;
209
210    /// Set the preferred prefix to use when serializing.
211    fn preferred_prefix(
212        &mut self,
213        preferred_prefix: Option<Prefix<'_>>,
214    ) -> Result<Self::Ok, Self::Error>;
215
216    /// Serialize the attribute.
217    fn end<S: AsRef<str>>(self, value: S) -> Result<Self::Ok, Self::Error>;
218}
219
220/// A type that can be serialized as an attribute. Since this is a separate trait from [`Serialize`], it is possible to choose between serializing a type as an attribute or as an element.
221///
222/// To see the documentation for the derive macro, see [`xmlity_derive::SerializeAttribute`].
223pub trait SerializeAttribute: Sized {
224    /// Serialize the attribute.
225    fn serialize_attribute<S: AttributeSerializer>(&self, serializer: S)
226        -> Result<S::Ok, S::Error>;
227}
228
229/// A trait for serializing sub-elements/sub-attributes of a type. This can be used to more easily include common attributes/elements in multiple types, instead of repeating the same code.
230///
231/// To see the documentation for the derive macro, see [`xmlity_derive::SerializationGroup`].
232pub trait SerializationGroup: Sized {
233    /// Serialize the attributes of the type.
234    fn serialize_attributes<S: SerializeAttributes>(
235        &self,
236        serializer: &mut S,
237    ) -> Result<(), S::Error> {
238        let _ = serializer;
239
240        Ok(())
241    }
242
243    /// Serialize the children of the type.
244    fn serialize_children<S: SerializeSeq>(&self, serializer: &mut S) -> Result<(), S::Error> {
245        let _ = serializer;
246
247        Ok(())
248    }
249}