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
|
//! Deserializer.
use std::convert::Infallible;
use crate::tagged::TagStart;
use crate::util::{feature_alternate, trait_alias};
use crate::DeserializeTagged;
pub mod buffered;
/// XML deserializer.
pub trait Deserializer
{
/// Deserializes a tagged element.
///
/// # Errors
/// Returns `Err` if deserialization fails.
fn de_tag<De: DeserializeTagged>(
&mut self,
tag_name: &str,
ignore_end: IgnoreEnd,
) -> Result<De, Error<De::Error>>;
/// Deserializes a tagged element using the given function.
///
/// # Errors
/// Returns `Err` if deserialization fails.
fn de_tag_with<Output, Err, Func>(
&mut self,
tag_name: &str,
ignore_end: IgnoreEnd,
deserialize: Func,
) -> Result<Output, Error<Err>>
where
Output: MaybeStatic,
Err: std::error::Error + Send + Sync + 'static,
Func: FnOnce(&TagStart, &mut Self) -> Result<Output, Err> + MaybeStatic;
/// Deserializes a list of tagged elements.
///
/// # Errors
/// Returns `Err` if deserialization fails.
fn de_tag_list<De, TagName>(
&mut self,
tag_name: Option<TagName>,
) -> Result<Vec<De>, Error<De::Error>>
where
De: DeserializeTagged,
TagName: AsRef<str> + MaybeStatic;
/// Deserializes a text element.
///
/// # Errors
/// Returns `Err` if deserialization fails.
fn de_text(&mut self) -> Result<String, Error<Infallible>>;
/// Skips past all elements until a tagged element with the name `tag_name` is
/// reached.
///
/// # Errors
/// Returns `Err` if unsuccessful.
fn skip_to_tag_start(&mut self, tag_name: &str) -> Result<(), Error<Infallible>>;
/// Skips past all elements until the end of a tagged element with the name `tag_name`
/// is reached.
///
/// # Errors
/// Returns `Err` if unsuccessful.
fn skip_to_tag_end(&mut self, tag_name: &str) -> Result<(), Error<Infallible>>;
}
macro_rules! maybe_static_doc {
() => {
"Bound to `'static` if the `deserializer-static-generics` feature is enabled."
};
}
#[cfg(any(not(feature = "deserializer-static-generics"), doc))]
trait_alias! {
#[doc = maybe_static_doc!()]
pub MaybeStatic;
}
#[cfg(all(feature = "deserializer-static-generics", not(doc)))]
trait_alias! {
#[doc = maybe_static_doc!()]
pub MaybeStatic: 'static;
}
/// Whether or not to skip the end tag of a tagged element.
///
/// **Should be `No`**.
#[derive(Debug, Default, PartialEq, Eq)]
pub enum IgnoreEnd
{
/// Skip the end tag.
///
/// **Will cause problems in most cases and should be used very carefully**.
Yes,
/// Don't skip the end tag.
#[default]
No,
}
/// [`Deserializer`] error.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error<DeError>
{
/// A XML error occurred.
#[error("A XML error occurred")]
XMLError(#[source] XMLError),
/// Failed to deserialize.
#[error("Failed to deserialize")]
DeserializeFailed(#[from] DeError),
/// Unexpected event.
#[error("Expected {expected_event_name} event. Found {found_event}")]
UnexpectedEvent
{
/// The name of the expected event.
expected_event_name: String,
/// The found event.
found_event: String,
},
/// Unexpected end of file.
#[error("Unexpected end of file")]
UnexpectedEndOfFile,
}
impl<DeError> Error<DeError>
{
/// Returns `Self` with `DeError` as [`Infallible`].
///
/// # Panics
/// Will panic if `Self` is the `DeserializeFailed` variant.
pub fn into_never_de_err(self) -> Error<Infallible>
{
match self {
Self::XMLError(xml_err) => Error::XMLError(xml_err),
Self::DeserializeFailed(_) => {
panic!("is a deserialization error");
}
Self::UnexpectedEvent {
expected_event_name,
found_event,
} => Error::UnexpectedEvent {
expected_event_name,
found_event,
},
Self::UnexpectedEndOfFile => Error::UnexpectedEndOfFile,
}
}
}
impl Error<Infallible>
{
fn into_with_de_error<DeError>(self) -> Error<DeError>
{
match self {
Self::XMLError(xml_err) => Error::XMLError(xml_err),
Self::DeserializeFailed(_) => {
unreachable!();
}
Self::UnexpectedEvent {
expected_event_name,
found_event,
} => Error::UnexpectedEvent {
expected_event_name,
found_event,
},
Self::UnexpectedEndOfFile => Error::UnexpectedEndOfFile,
}
}
}
impl From<Error<Error<Infallible>>> for Error<Infallible>
{
fn from(err: Error<Error<Infallible>>) -> Self
{
match err {
Error::XMLError(xml_err) => Self::XMLError(xml_err),
Error::DeserializeFailed(de_err) => de_err,
Error::UnexpectedEvent {
expected_event_name,
found_event,
} => Self::UnexpectedEvent {
expected_event_name,
found_event,
},
Error::UnexpectedEndOfFile => Self::UnexpectedEndOfFile,
}
}
}
impl<DeError> Error<DeError>
{
/// Converts `Self` into `Err`.
pub fn into_error<Err>(self) -> Err
where
Err: From<DeError> + From<Error<Infallible>>,
{
if let Error::DeserializeFailed(de_err) = self {
return de_err.into();
}
self.into_never_de_err().into()
}
}
/// XML error.
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct XMLError(#[from] quick_xml::Error);
/// Implements conversion from [`Error`] with [`From`] for the given error type.
///
/// Allows for custom error types with source error types to easily be converted into with
/// `?`.
///
/// The given error type should implement `From<Error<Infallible>>`.
///
/// # Examples
/// ```
/// use std::convert::Infallible;
///
/// use xml_stinks::deserializer::Error as DeserializerError;
/// use xml_stinks::impl_from_deserializer_error;
///
/// #[derive(Debug, thiserror::Error)]
/// enum FooError
/// {
/// #[error("Deserialization failed")]
/// DeserializeFailed(#[from] DeserializerError<Infallible>),
///
/// #[error("Invalid bar")]
/// InvalidBar(#[from] BarError),
/// }
///
/// impl_from_deserializer_error!(FooError);
///
/// #[derive(Debug, thiserror::Error)]
/// enum BarError
/// {
/// #[error("Oops")]
/// Oops,
/// }
///
/// let err_a: FooError = DeserializerError::<Infallible>::UnexpectedEndOfFile.into();
///
/// assert!(matches!(
/// err_a,
/// FooError::DeserializeFailed(DeserializerError::UnexpectedEndOfFile)
/// ));
///
/// let err_b: FooError = DeserializerError::DeserializeFailed(BarError::Oops).into();
///
/// assert!(matches!(err_b, FooError::InvalidBar(BarError::Oops)));
/// ```
#[macro_export]
macro_rules! impl_from_deserializer_error {
($err: path) => {
impl<DeError: Into<Self>> From<::xml_stinks::deserializer::Error<DeError>>
for $err
{
fn from(err: ::xml_stinks::deserializer::Error<DeError>) -> Self
{
if let ::xml_stinks::deserializer::Error::DeserializeFailed(de_err) = err
{
return de_err.into();
}
err.into_never_de_err().into()
}
}
};
}
feature_alternate!(
feature = "deserializer-static-generics",
/// Conditional compilation based on whether or not the `deserializer-static-generics`
/// feature is enabled.
///
/// # Examples
/// ```
/// use std::io::Cursor;
///
/// use xml_stinks::xml_stinks_if_deserializer_static_generics;
/// use xml_stinks::deserializer::buffered::Buffered as BufferedDeserializer;
/// use xml_stinks::deserializer::Deserializer;
///
/// fn do_something(bytes: &[u8])
/// {
/// let deserializer = xml_stinks_if_deserializer_static_generics!(then {
/// BufferedDeserializer::new(Cursor::new(bytes.to_vec()));
/// } else {
/// // This wouldn't compile if the deserializer-static-generics feature was
/// // enabled
/// BufferedDeserializer::new(bytes);
/// });
///
/// // ...
/// }
/// ```
when_enabled =
#[macro_export]
macro_rules! xml_stinks_if_deserializer_static_generics {
(then { $($then: tt)* }$(else { $($else: tt)* })?) => {
$($then)*
};
},
when_disabled =
#[macro_export]
macro_rules! xml_stinks_if_deserializer_static_generics {
(then { $($then: tt)* }$(else { $($else: tt)* })?) => {
$($($else)*)?
};
}
);
|