From f0e17be1a9b51570debd8e93e3aeb11ad274b06e Mon Sep 17 00:00:00 2001 From: RedPhoenixQ Date: Sun, 29 Sep 2024 11:24:04 +0200 Subject: [PATCH] Split SeError from DeError This is needed for a larger change of error return values in Writer Refs: #227 --- src/errors.rs | 97 ++++++++++++++++++++++++++++++++----------- src/lib.rs | 2 +- src/se/content.rs | 31 +++++++------- src/se/element.rs | 51 +++++++++++------------ src/se/key.rs | 30 ++++++------- src/se/mod.rs | 62 +++++++++++++-------------- src/se/simple_type.rs | 61 +++++++++++++-------------- src/se/text.rs | 14 +++---- src/writer.rs | 8 ++-- tests/serde-se.rs | 8 ++-- 10 files changed, 205 insertions(+), 159 deletions(-) diff --git a/src/errors.rs b/src/errors.rs index 53e0e21f..e22c9509 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -159,7 +159,7 @@ impl std::error::Error for IllFormedError {} /// The error type used by this crate. #[derive(Clone, Debug)] pub enum Error { - /// XML document cannot be read from or written to underlying source. + /// XML document cannot be read from underlying source. /// /// Contains the reference-counted I/O error to make the error type `Clone`able. Io(Arc), @@ -318,8 +318,6 @@ pub mod serialize { pub enum DeError { /// Serde custom error Custom(String), - /// IO error from Writer - Io(Arc), /// Xml parsing error InvalidXml(Error), /// Cannot parse to integer @@ -351,13 +349,6 @@ pub mod serialize { /// store at current position, for example, attempt to deserialize `struct` /// from attribute or attempt to deserialize binary data. /// - /// Serialized type cannot be represented in an XML due to violation of the - /// XML rules in the final XML document. For example, attempt to serialize - /// a `HashMap<{integer}, ...>` would cause this error because [XML name] - /// cannot start from a digit or a hyphen (minus sign). The same result - /// would occur if map key is a complex type that cannot be serialized as - /// a primitive type (i.e. string, char, bool, unit struct or unit variant). - /// /// [XML name]: https://www.w3.org/TR/xml11/#sec-common-syn Unsupported(Cow<'static, str>), /// Too many events were skipped while deserializing a sequence, event limit @@ -370,7 +361,6 @@ pub mod serialize { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { DeError::Custom(s) => write!(f, "{}", s), - DeError::Io(e) => write!(f, "{}", e), DeError::InvalidXml(e) => write!(f, "{}", e), DeError::InvalidInt(e) => write!(f, "{}", e), DeError::InvalidFloat(e) => write!(f, "{}", e), @@ -406,19 +396,6 @@ pub mod serialize { } } - impl serde::ser::Error for DeError { - fn custom(msg: T) -> Self { - DeError::Custom(msg.to_string()) - } - } - - impl From for DeError { - #[inline] - fn from(e: IoError) -> Self { - Self::Io(Arc::new(e)) - } - } - impl From for DeError { #[inline] fn from(e: Error) -> Self { @@ -474,4 +451,76 @@ pub mod serialize { Self::Custom(e.to_string()) } } + + /// Serialization error + #[derive(Clone, Debug)] + pub enum SeError { + /// Serde custom error + Custom(String), + /// XML document cannot be written to underlying source. + /// + /// Contains the reference-counted I/O error to make the error type `Clone`able. + Io(Arc), + /// Some value could not be formatted + Fmt(std::fmt::Error), + /// Serialized type cannot be represented in an XML due to violation of the + /// XML rules in the final XML document. For example, attempt to serialize + /// a `HashMap<{integer}, ...>` would cause this error because [XML name] + /// cannot start from a digit or a hyphen (minus sign). The same result + /// would occur if map key is a complex type that cannot be serialized as + /// a primitive type (i.e. string, char, bool, unit struct or unit variant). + /// + /// [XML name]: https://www.w3.org/TR/xml11/#sec-common-syn + Unsupported(Cow<'static, str>), + /// Some value could not be turned to UTF-8 + NonEncodable(Utf8Error), + } + + impl fmt::Display for SeError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + SeError::Custom(s) => write!(f, "{}", s), + SeError::Io(e) => write!(f, "I/O error: {}", e), + SeError::Fmt(e) => write!(f, "Formatting error: {}", e), + SeError::Unsupported(s) => write!(f, "Unsupported value: {}", s), + SeError::NonEncodable(e) => write!(f, "Malformed UTF-8: {}", e), + } + } + } + + impl ::std::error::Error for SeError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + SeError::Io(e) => Some(e), + _ => None, + } + } + } + + impl serde::ser::Error for SeError { + fn custom(msg: T) -> Self { + SeError::Custom(msg.to_string()) + } + } + + impl From for SeError { + #[inline] + fn from(e: IoError) -> Self { + Self::Io(Arc::new(e)) + } + } + + impl From for SeError { + #[inline] + fn from(e: Utf8Error) -> Self { + Self::NonEncodable(e) + } + } + + impl From for SeError { + #[inline] + fn from(e: fmt::Error) -> Self { + Self::Fmt(e) + } + } } diff --git a/src/lib.rs b/src/lib.rs index b0f37f50..afc4c149 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -73,7 +73,7 @@ pub mod writer; // reexports pub use crate::encoding::Decoder; #[cfg(feature = "serialize")] -pub use crate::errors::serialize::DeError; +pub use crate::errors::serialize::{DeError, SeError}; pub use crate::errors::{Error, Result}; pub use crate::reader::{NsReader, Reader}; pub use crate::writer::{ElementWriter, Writer}; diff --git a/src/se/content.rs b/src/se/content.rs index 91e02880..50f3b92d 100644 --- a/src/se/content.rs +++ b/src/se/content.rs @@ -1,10 +1,9 @@ //! Contains serializer for content of an XML element use crate::de::TEXT_KEY; -use crate::errors::serialize::DeError; use crate::se::element::{ElementSerializer, Struct, Tuple}; use crate::se::simple_type::{QuoteTarget, SimpleTypeSerializer}; -use crate::se::{Indent, QuoteLevel, XmlName}; +use crate::se::{Indent, QuoteLevel, SeError, XmlName}; use serde::ser::{ Impossible, Serialize, SerializeSeq, SerializeTuple, SerializeTupleStruct, Serializer, }; @@ -36,7 +35,7 @@ macro_rules! write_primitive { /// - units (`()`) and unit structs does not write anything; /// - sequences, tuples and tuple structs are serialized without delimiters. /// `[1, 2, 3]` would be serialized as `123` (if not using indent); -/// - structs and maps are not supported ([`DeError::Unsupported`] is returned); +/// - structs and maps are not supported ([`SeError::Unsupported`] is returned); /// - enums: /// - unit variants are serialized as self-closed ``; /// - newtype variants are serialized as inner value wrapped in `...`; @@ -108,7 +107,7 @@ impl<'w, 'i, W: Write> ContentSerializer<'w, 'i, W> { /// Writes `name` as self-closed tag #[inline] - pub(super) fn write_empty(mut self, name: XmlName) -> Result<(), DeError> { + pub(super) fn write_empty(mut self, name: XmlName) -> Result<(), SeError> { self.write_indent()?; if self.expand_empty_elements { self.writer.write_char('<')?; @@ -125,9 +124,9 @@ impl<'w, 'i, W: Write> ContentSerializer<'w, 'i, W> { } /// Writes simple type content between `name` tags - pub(super) fn write_wrapped(mut self, name: XmlName, serialize: S) -> Result<(), DeError> + pub(super) fn write_wrapped(mut self, name: XmlName, serialize: S) -> Result<(), SeError> where - S: for<'a> FnOnce(SimpleTypeSerializer<'i, &'a mut W>) -> Result<&'a mut W, DeError>, + S: for<'a> FnOnce(SimpleTypeSerializer<'i, &'a mut W>) -> Result<&'a mut W, SeError>, { self.write_indent()?; self.writer.write_char('<')?; @@ -142,7 +141,7 @@ impl<'w, 'i, W: Write> ContentSerializer<'w, 'i, W> { Ok(()) } - pub(super) fn write_indent(&mut self) -> Result<(), DeError> { + pub(super) fn write_indent(&mut self) -> Result<(), SeError> { if self.write_indent { self.indent.write_indent(&mut self.writer)?; self.write_indent = false; @@ -153,7 +152,7 @@ impl<'w, 'i, W: Write> ContentSerializer<'w, 'i, W> { impl<'w, 'i, W: Write> Serializer for ContentSerializer<'w, 'i, W> { type Ok = (); - type Error = DeError; + type Error = SeError; type SerializeSeq = Self; type SerializeTuple = Self; @@ -310,7 +309,7 @@ impl<'w, 'i, W: Write> Serializer for ContentSerializer<'w, 'i, W> { } fn serialize_map(self, _len: Option) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( "serialization of map types is not supported in `$value` field".into(), )) } @@ -321,7 +320,7 @@ impl<'w, 'i, W: Write> Serializer for ContentSerializer<'w, 'i, W> { name: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!("serialization of struct `{name}` is not supported in `$value` field").into(), )) } @@ -345,7 +344,7 @@ impl<'w, 'i, W: Write> Serializer for ContentSerializer<'w, 'i, W> { len: usize, ) -> Result { if variant == TEXT_KEY { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!("cannot serialize `$text` struct variant of `{}` enum", name).into(), )) } else { @@ -360,7 +359,7 @@ impl<'w, 'i, W: Write> Serializer for ContentSerializer<'w, 'i, W> { impl<'w, 'i, W: Write> SerializeSeq for ContentSerializer<'w, 'i, W> { type Ok = (); - type Error = DeError; + type Error = SeError; fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> where @@ -380,7 +379,7 @@ impl<'w, 'i, W: Write> SerializeSeq for ContentSerializer<'w, 'i, W> { impl<'w, 'i, W: Write> SerializeTuple for ContentSerializer<'w, 'i, W> { type Ok = (); - type Error = DeError; + type Error = SeError; #[inline] fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> @@ -398,7 +397,7 @@ impl<'w, 'i, W: Write> SerializeTuple for ContentSerializer<'w, 'i, W> { impl<'w, 'i, W: Write> SerializeTupleStruct for ContentSerializer<'w, 'i, W> { type Ok = (); - type Error = DeError; + type Error = SeError; #[inline] fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> @@ -573,7 +572,7 @@ pub(super) mod tests { }; match $data.serialize(ser).unwrap_err() { - DeError::$kind(e) => assert_eq!(e, $reason), + SeError::$kind(e) => assert_eq!(e, $reason), e => panic!( "Expected `Err({}({}))`, but got `{:?}`", stringify!($kind), @@ -1013,7 +1012,7 @@ pub(super) mod tests { }; match $data.serialize(ser).unwrap_err() { - DeError::$kind(e) => assert_eq!(e, $reason), + SeError::$kind(e) => assert_eq!(e, $reason), e => panic!( "Expected `Err({}({}))`, but got `{:?}`", stringify!($kind), diff --git a/src/se/element.rs b/src/se/element.rs index 35aa28f4..4121817f 100644 --- a/src/se/element.rs +++ b/src/se/element.rs @@ -1,12 +1,11 @@ //! Contains serializer for an XML element use crate::de::{TEXT_KEY, VALUE_KEY}; -use crate::errors::serialize::DeError; use crate::se::content::ContentSerializer; use crate::se::key::QNameSerializer; use crate::se::simple_type::{QuoteTarget, SimpleSeq, SimpleTypeSerializer}; use crate::se::text::TextSerializer; -use crate::se::{Indent, XmlName}; +use crate::se::{Indent, SeError, XmlName}; use serde::ser::{ Impossible, Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, Serializer, @@ -53,7 +52,7 @@ macro_rules! write_primitive { /// In particular, the empty map is serialized as ``; /// - enums: /// - unit variants are serialized as `variant`; -/// - other variants are not supported ([`DeError::Unsupported`] is returned); +/// - other variants are not supported ([`SeError::Unsupported`] is returned); /// /// Usage of empty tags depends on the [`ContentSerializer::expand_empty_elements`] setting. pub struct ElementSerializer<'w, 'k, W: Write> { @@ -65,7 +64,7 @@ pub struct ElementSerializer<'w, 'k, W: Write> { impl<'w, 'k, W: Write> Serializer for ElementSerializer<'w, 'k, W> { type Ok = (); - type Error = DeError; + type Error = SeError; type SerializeSeq = Self; type SerializeTuple = Self; @@ -162,7 +161,7 @@ impl<'w, 'k, W: Write> Serializer for ElementSerializer<'w, 'k, W> { value.serialize(self) } - /// Always returns [`DeError::Unsupported`]. Newtype variants can be serialized + /// Always returns [`SeError::Unsupported`]. Newtype variants can be serialized /// only in `$value` fields, which is serialized using [`ContentSerializer`]. #[inline] fn serialize_newtype_variant( @@ -172,7 +171,7 @@ impl<'w, 'k, W: Write> Serializer for ElementSerializer<'w, 'k, W> { variant: &'static str, _value: &T, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize enum newtype variant `{}::{}`", name, variant @@ -200,7 +199,7 @@ impl<'w, 'k, W: Write> Serializer for ElementSerializer<'w, 'k, W> { self.serialize_tuple(len) } - /// Always returns [`DeError::Unsupported`]. Tuple variants can be serialized + /// Always returns [`SeError::Unsupported`]. Tuple variants can be serialized /// only in `$value` fields, which is serialized using [`ContentSerializer`]. #[inline] fn serialize_tuple_variant( @@ -210,7 +209,7 @@ impl<'w, 'k, W: Write> Serializer for ElementSerializer<'w, 'k, W> { variant: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize enum tuple variant `{}::{}`", name, variant @@ -243,7 +242,7 @@ impl<'w, 'k, W: Write> Serializer for ElementSerializer<'w, 'k, W> { }) } - /// Always returns [`DeError::Unsupported`]. Struct variants can be serialized + /// Always returns [`SeError::Unsupported`]. Struct variants can be serialized /// only in `$value` fields, which is serialized using [`ContentSerializer`]. #[inline] fn serialize_struct_variant( @@ -253,7 +252,7 @@ impl<'w, 'k, W: Write> Serializer for ElementSerializer<'w, 'k, W> { variant: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize enum struct variant `{}::{}`", name, variant @@ -265,7 +264,7 @@ impl<'w, 'k, W: Write> Serializer for ElementSerializer<'w, 'k, W> { impl<'w, 'k, W: Write> SerializeSeq for ElementSerializer<'w, 'k, W> { type Ok = (); - type Error = DeError; + type Error = SeError; fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> where @@ -288,7 +287,7 @@ impl<'w, 'k, W: Write> SerializeSeq for ElementSerializer<'w, 'k, W> { impl<'w, 'k, W: Write> SerializeTuple for ElementSerializer<'w, 'k, W> { type Ok = (); - type Error = DeError; + type Error = SeError; #[inline] fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> @@ -306,7 +305,7 @@ impl<'w, 'k, W: Write> SerializeTuple for ElementSerializer<'w, 'k, W> { impl<'w, 'k, W: Write> SerializeTupleStruct for ElementSerializer<'w, 'k, W> { type Ok = (); - type Error = DeError; + type Error = SeError; #[inline] fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> @@ -336,7 +335,7 @@ pub enum Tuple<'w, 'k, W: Write> { impl<'w, 'k, W: Write> SerializeTupleVariant for Tuple<'w, 'k, W> { type Ok = (); - type Error = DeError; + type Error = SeError; #[inline] fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> @@ -378,7 +377,7 @@ pub struct Struct<'w, 'k, W: Write> { impl<'w, 'k, W: Write> Struct<'w, 'k, W> { #[inline] - fn write_field(&mut self, key: &str, value: &T) -> Result<(), DeError> + fn write_field(&mut self, key: &str, value: &T) -> Result<(), SeError> where T: ?Sized + Serialize, { @@ -393,7 +392,7 @@ impl<'w, 'k, W: Write> Struct<'w, 'k, W> { /// Writes `value` as an attribute #[inline] - fn write_attribute(&mut self, key: XmlName, value: &T) -> Result<(), DeError> + fn write_attribute(&mut self, key: XmlName, value: &T) -> Result<(), SeError> where T: ?Sized + Serialize, { @@ -426,7 +425,7 @@ impl<'w, 'k, W: Write> Struct<'w, 'k, W> { /// /// [simple type]: SimpleTypeSerializer /// [content]: ContentSerializer - fn write_element(&mut self, key: &str, value: &T) -> Result<(), DeError> + fn write_element(&mut self, key: &str, value: &T) -> Result<(), SeError> where T: ?Sized + Serialize, { @@ -454,7 +453,7 @@ impl<'w, 'k, W: Write> Struct<'w, 'k, W> { impl<'w, 'k, W: Write> SerializeStruct for Struct<'w, 'k, W> { type Ok = (); - type Error = DeError; + type Error = SeError; fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> where @@ -490,7 +489,7 @@ impl<'w, 'k, W: Write> SerializeStruct for Struct<'w, 'k, W> { impl<'w, 'k, W: Write> SerializeStructVariant for Struct<'w, 'k, W> { type Ok = (); - type Error = DeError; + type Error = SeError; #[inline] fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> @@ -516,7 +515,7 @@ pub struct Map<'w, 'k, W: Write> { } impl<'w, 'k, W: Write> Map<'w, 'k, W> { - fn make_key(&mut self, key: &T) -> Result + fn make_key(&mut self, key: &T) -> Result where T: ?Sized + Serialize, { @@ -528,14 +527,14 @@ impl<'w, 'k, W: Write> Map<'w, 'k, W> { impl<'w, 'k, W: Write> SerializeMap for Map<'w, 'k, W> { type Ok = (); - type Error = DeError; + type Error = SeError; fn serialize_key(&mut self, key: &T) -> Result<(), Self::Error> where T: ?Sized + Serialize, { if let Some(_) = self.key.take() { - return Err(DeError::Custom( + return Err(SeError::Custom( "calling `serialize_key` twice without `serialize_value`".to_string(), )); } @@ -550,7 +549,7 @@ impl<'w, 'k, W: Write> SerializeMap for Map<'w, 'k, W> { if let Some(key) = self.key.take() { return self.ser.write_field(&key, value); } - Err(DeError::Custom( + Err(SeError::Custom( "calling `serialize_value` without call of `serialize_key`".to_string(), )) } @@ -566,7 +565,7 @@ impl<'w, 'k, W: Write> SerializeMap for Map<'w, 'k, W> { fn end(mut self) -> Result { if let Some(key) = self.key.take() { - return Err(DeError::Custom(format!( + return Err(SeError::Custom(format!( "calling `end` without call of `serialize_value` for key `{key}`" ))); } @@ -649,7 +648,7 @@ mod tests { }; match $data.serialize(ser).unwrap_err() { - DeError::$kind(e) => assert_eq!(e, $reason), + SeError::$kind(e) => assert_eq!(e, $reason), e => panic!( "Expected `Err({}({}))`, but got `{:?}`", stringify!($kind), @@ -1352,7 +1351,7 @@ mod tests { }; match $data.serialize(ser).unwrap_err() { - DeError::$kind(e) => assert_eq!(e, $reason), + SeError::$kind(e) => assert_eq!(e, $reason), e => panic!( "Expected `Err({}({}))`, but got `{:?}`", stringify!($kind), diff --git a/src/se/key.rs b/src/se/key.rs index c260f4e5..55c0db9a 100644 --- a/src/se/key.rs +++ b/src/se/key.rs @@ -1,4 +1,4 @@ -use crate::errors::serialize::DeError; +use crate::errors::serialize::SeError; use serde::ser::{Impossible, Serialize, Serializer}; use serde::serde_if_integer128; use std::fmt::Write; @@ -18,14 +18,14 @@ pub struct QNameSerializer { impl QNameSerializer { #[inline] - fn write_str(&mut self, value: &str) -> Result<(), DeError> { + fn write_str(&mut self, value: &str) -> Result<(), SeError> { Ok(self.writer.write_str(value)?) } } impl Serializer for QNameSerializer { type Ok = W; - type Error = DeError; + type Error = SeError; type SerializeSeq = Impossible; type SerializeTuple = Impossible; @@ -45,7 +45,7 @@ impl Serializer for QNameSerializer { /// Because unit type can be represented only by empty string which is not /// a valid XML name, serialization of unit returns `Err(Unsupported)` fn serialize_unit(self) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( "cannot serialize unit type `()` as an XML tag name".into(), )) } @@ -53,7 +53,7 @@ impl Serializer for QNameSerializer { /// Because unit struct can be represented only by empty string which is not /// a valid XML name, serialization of unit struct returns `Err(Unsupported)` fn serialize_unit_struct(self, name: &'static str) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!("cannot serialize unit struct `{}` as an XML tag name", name).into(), )) } @@ -66,8 +66,8 @@ impl Serializer for QNameSerializer { _variant_index: u32, variant: &'static str, _value: &T, - ) -> Result { - Err(DeError::Unsupported( + ) -> Result { + Err(SeError::Unsupported( format!( "cannot serialize enum newtype variant `{}::{}` as an XML tag name", name, variant @@ -77,13 +77,13 @@ impl Serializer for QNameSerializer { } fn serialize_seq(self, _len: Option) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( "cannot serialize sequence as an XML tag name".into(), )) } fn serialize_tuple(self, _len: usize) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( "cannot serialize tuple as an XML tag name".into(), )) } @@ -93,7 +93,7 @@ impl Serializer for QNameSerializer { name: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize tuple struct `{}` as an XML tag name", name @@ -109,7 +109,7 @@ impl Serializer for QNameSerializer { variant: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize enum tuple variant `{}::{}` as an XML tag name", name, variant @@ -119,7 +119,7 @@ impl Serializer for QNameSerializer { } fn serialize_map(self, _len: Option) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( "cannot serialize map as an XML tag name".into(), )) } @@ -129,7 +129,7 @@ impl Serializer for QNameSerializer { name: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!("cannot serialize struct `{}` as an XML tag name", name).into(), )) } @@ -141,7 +141,7 @@ impl Serializer for QNameSerializer { variant: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize enum struct variant `{}::{}` as an XML tag name", name, variant @@ -214,7 +214,7 @@ mod tests { }; match $data.serialize(ser).unwrap_err() { - DeError::$kind(e) => assert_eq!(e, $reason), + SeError::$kind(e) => assert_eq!(e, $reason), e => panic!( "Expected `Err({}({}))`, but got `{:?}`", stringify!($kind), diff --git a/src/se/mod.rs b/src/se/mod.rs index 719c89fa..b8c09a09 100644 --- a/src/se/mod.rs +++ b/src/se/mod.rs @@ -39,7 +39,7 @@ macro_rules! write_primitive { fn serialize_bytes(self, _value: &[u8]) -> Result { //TODO: customization point - allow user to decide how to encode bytes - Err(DeError::Unsupported( + Err(Self::Error::Unsupported( "`serialize_bytes` not supported yet".into(), )) } @@ -82,7 +82,7 @@ mod text; use self::content::ContentSerializer; use self::element::{ElementSerializer, Map, Struct, Tuple}; use crate::de::TEXT_KEY; -use crate::errors::serialize::DeError; +pub use crate::errors::serialize::SeError; use crate::writer::Indentation; use serde::ser::{self, Serialize}; use serde::serde_if_integer128; @@ -124,7 +124,7 @@ use std::str::from_utf8; /// " /// ); /// ``` -pub fn to_writer(mut writer: W, value: &T) -> Result<(), DeError> +pub fn to_writer(mut writer: W, value: &T) -> Result<(), SeError> where W: Write, T: ?Sized + Serialize, @@ -165,7 +165,7 @@ where /// " /// ); /// ``` -pub fn to_string(value: &T) -> Result +pub fn to_string(value: &T) -> Result where T: ?Sized + Serialize, { @@ -210,7 +210,7 @@ where /// ``` /// /// [XML name]: https://www.w3.org/TR/xml11/#NT-Name -pub fn to_writer_with_root(mut writer: W, root_tag: &str, value: &T) -> Result<(), DeError> +pub fn to_writer_with_root(mut writer: W, root_tag: &str, value: &T) -> Result<(), SeError> where W: Write, T: ?Sized + Serialize, @@ -252,7 +252,7 @@ where /// ``` /// /// [XML name]: https://www.w3.org/TR/xml11/#NT-Name -pub fn to_string_with_root(root_tag: &str, value: &T) -> Result +pub fn to_string_with_root(root_tag: &str, value: &T) -> Result where T: ?Sized + Serialize, { @@ -372,15 +372,15 @@ impl<'n> XmlName<'n> { /// Checks correctness of the XML name according to [XML 1.1 specification] /// /// [XML 1.1 specification]: https://www.w3.org/TR/xml11/#NT-Name - pub fn try_from(name: &'n str) -> Result, DeError> { + pub fn try_from(name: &'n str) -> Result, SeError> { //TODO: Customization point: allow user to decide if he want to reject or encode the name match name.chars().next() { - Some(ch) if !is_xml11_name_start_char(ch) => Err(DeError::Unsupported( + Some(ch) if !is_xml11_name_start_char(ch) => Err(SeError::Unsupported( format!("character `{ch}` is not allowed at the start of an XML name `{name}`") .into(), )), _ => match name.matches(|ch| !is_xml11_name_char(ch)).next() { - Some(s) => Err(DeError::Unsupported( + Some(s) => Err(SeError::Unsupported( format!("character `{s}` is not allowed in an XML name `{name}`").into(), )), None => Ok(XmlName(name)), @@ -426,7 +426,7 @@ impl<'i> Indent<'i> { } } - pub fn write_indent(&mut self, mut writer: W) -> Result<(), DeError> { + pub fn write_indent(&mut self, mut writer: W) -> Result<(), SeError> { match self { Self::None => {} Self::Owned(i) => { @@ -522,7 +522,7 @@ impl<'w, 'r, W: Write> Serializer<'w, 'r, W> { /// ``` /// /// [XML name]: https://www.w3.org/TR/xml11/#NT-Name - pub fn with_root(writer: &'w mut W, root_tag: Option<&'r str>) -> Result { + pub fn with_root(writer: &'w mut W, root_tag: Option<&'r str>) -> Result { Ok(Self { ser: ContentSerializer { writer, @@ -590,11 +590,11 @@ impl<'w, 'r, W: Write> Serializer<'w, 'r, W> { /// Creates actual serializer or returns an error if root tag is not defined. /// In that case `err` contains the name of type that cannot be serialized. - fn ser(self, err: &str) -> Result, DeError> { + fn ser(self, err: &str) -> Result, SeError> { if let Some(key) = self.root_tag { Ok(ElementSerializer { ser: self.ser, key }) } else { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!("cannot serialize {} without defined root tag", err).into(), )) } @@ -603,7 +603,7 @@ impl<'w, 'r, W: Write> Serializer<'w, 'r, W> { /// Creates actual serializer using root tag or a specified `key` if root tag /// is not defined. Returns an error if root tag is not defined and a `key` /// does not conform [XML rules](XmlName::try_from) for names. - fn ser_name(self, key: &'static str) -> Result, DeError> { + fn ser_name(self, key: &'static str) -> Result, SeError> { Ok(ElementSerializer { ser: self.ser, key: match self.root_tag { @@ -616,7 +616,7 @@ impl<'w, 'r, W: Write> Serializer<'w, 'r, W> { impl<'w, 'r, W: Write> ser::Serializer for Serializer<'w, 'r, W> { type Ok = (); - type Error = DeError; + type Error = SeError; type SerializeSeq = ElementSerializer<'w, 'r, W>; type SerializeTuple = ElementSerializer<'w, 'r, W>; @@ -650,19 +650,19 @@ impl<'w, 'r, W: Write> ser::Serializer for Serializer<'w, 'r, W> { forward!(serialize_str(&str)); forward!(serialize_bytes(&[u8])); - fn serialize_none(self) -> Result { + fn serialize_none(self) -> Result { Ok(()) } - fn serialize_some(self, value: &T) -> Result { + fn serialize_some(self, value: &T) -> Result { value.serialize(self) } - fn serialize_unit(self) -> Result { + fn serialize_unit(self) -> Result { self.ser("`()`")?.serialize_unit() } - fn serialize_unit_struct(self, name: &'static str) -> Result { + fn serialize_unit_struct(self, name: &'static str) -> Result { self.ser_name(name)?.serialize_unit_struct(name) } @@ -671,10 +671,10 @@ impl<'w, 'r, W: Write> ser::Serializer for Serializer<'w, 'r, W> { name: &'static str, _variant_index: u32, variant: &'static str, - ) -> Result { + ) -> Result { if variant == TEXT_KEY { // We should write some text but we don't known what text to write - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize enum unit variant `{}::$text` as text content value", name @@ -691,7 +691,7 @@ impl<'w, 'r, W: Write> ser::Serializer for Serializer<'w, 'r, W> { self, name: &'static str, value: &T, - ) -> Result { + ) -> Result { self.ser_name(name)?.serialize_newtype_struct(name, value) } @@ -701,7 +701,7 @@ impl<'w, 'r, W: Write> ser::Serializer for Serializer<'w, 'r, W> { _variant_index: u32, variant: &'static str, value: &T, - ) -> Result { + ) -> Result { if variant == TEXT_KEY { value.serialize(self.ser.into_simple_type_serializer())?; Ok(()) @@ -714,11 +714,11 @@ impl<'w, 'r, W: Write> ser::Serializer for Serializer<'w, 'r, W> { } } - fn serialize_seq(self, len: Option) -> Result { + fn serialize_seq(self, len: Option) -> Result { self.ser("sequence")?.serialize_seq(len) } - fn serialize_tuple(self, len: usize) -> Result { + fn serialize_tuple(self, len: usize) -> Result { self.ser("unnamed tuple")?.serialize_tuple(len) } @@ -726,7 +726,7 @@ impl<'w, 'r, W: Write> ser::Serializer for Serializer<'w, 'r, W> { self, name: &'static str, len: usize, - ) -> Result { + ) -> Result { self.ser_name(name)?.serialize_tuple_struct(name, len) } @@ -736,7 +736,7 @@ impl<'w, 'r, W: Write> ser::Serializer for Serializer<'w, 'r, W> { _variant_index: u32, variant: &'static str, len: usize, - ) -> Result { + ) -> Result { if variant == TEXT_KEY { self.ser .into_simple_type_serializer() @@ -751,7 +751,7 @@ impl<'w, 'r, W: Write> ser::Serializer for Serializer<'w, 'r, W> { } } - fn serialize_map(self, len: Option) -> Result { + fn serialize_map(self, len: Option) -> Result { self.ser("map")?.serialize_map(len) } @@ -759,7 +759,7 @@ impl<'w, 'r, W: Write> ser::Serializer for Serializer<'w, 'r, W> { self, name: &'static str, len: usize, - ) -> Result { + ) -> Result { self.ser_name(name)?.serialize_struct(name, len) } @@ -769,9 +769,9 @@ impl<'w, 'r, W: Write> ser::Serializer for Serializer<'w, 'r, W> { _variant_index: u32, variant: &'static str, len: usize, - ) -> Result { + ) -> Result { if variant == TEXT_KEY { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize enum struct variant `{}::$text` as text content value", name diff --git a/src/se/simple_type.rs b/src/se/simple_type.rs index 2ccb583f..dbdfe277 100644 --- a/src/se/simple_type.rs +++ b/src/se/simple_type.rs @@ -3,9 +3,8 @@ //! [simple types]: https://www.w3schools.com/xml/el_simpletype.asp //! [as defined]: https://www.w3.org/TR/xmlschema11-1/#Simple_Type_Definition -use crate::errors::serialize::DeError; use crate::escape::_escape; -use crate::se::{Indent, QuoteLevel}; +use crate::se::{Indent, QuoteLevel, SeError}; use serde::ser::{ Impossible, Serialize, SerializeSeq, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, Serializer, @@ -174,7 +173,7 @@ macro_rules! write_atomic { /// /// Identifiers represented as strings and serialized accordingly. /// -/// Serialization of all other types returns [`Unsupported`][DeError::Unsupported] error. +/// Serialization of all other types returns [`Unsupported`][SeError::Unsupported] error. /// /// This serializer returns `true` if something was written and `false` otherwise. /// @@ -192,7 +191,7 @@ pub struct AtomicSerializer<'i, W: Write> { } impl<'i, W: Write> AtomicSerializer<'i, W> { - fn write_str(&mut self, value: &str) -> Result<(), DeError> { + fn write_str(&mut self, value: &str) -> Result<(), SeError> { if let Some(indent) = self.indent.as_mut() { indent.write_indent(&mut self.writer)?; } else { @@ -205,7 +204,7 @@ impl<'i, W: Write> AtomicSerializer<'i, W> { impl<'i, W: Write> Serializer for AtomicSerializer<'i, W> { type Ok = bool; - type Error = DeError; + type Error = SeError; type SerializeSeq = Impossible; type SerializeTuple = Impossible; @@ -251,7 +250,7 @@ impl<'i, W: Write> Serializer for AtomicSerializer<'i, W> { fn serialize_bytes(self, _value: &[u8]) -> Result { //TODO: Customization point - allow user to decide how to encode bytes - Err(DeError::Unsupported( + Err(SeError::Unsupported( "`serialize_bytes` not supported yet".into(), )) } @@ -267,7 +266,7 @@ impl<'i, W: Write> Serializer for AtomicSerializer<'i, W> { /// We cannot store anything, so the absence of a unit and presence of it /// does not differ, so serialization of unit returns `Err(Unsupported)` fn serialize_unit(self) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( "cannot serialize unit type `()` as an `xs:list` item".into(), )) } @@ -275,7 +274,7 @@ impl<'i, W: Write> Serializer for AtomicSerializer<'i, W> { /// We cannot store anything, so the absence of a unit and presence of it /// does not differ, so serialization of unit returns `Err(Unsupported)` fn serialize_unit_struct(self, name: &'static str) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize unit struct `{}` as an `xs:list` item", name @@ -309,8 +308,8 @@ impl<'i, W: Write> Serializer for AtomicSerializer<'i, W> { _variant_index: u32, variant: &'static str, _value: &T, - ) -> Result { - Err(DeError::Unsupported( + ) -> Result { + Err(SeError::Unsupported( format!( "cannot serialize enum newtype variant `{}::{}` as an `xs:list` item", name, variant @@ -320,13 +319,13 @@ impl<'i, W: Write> Serializer for AtomicSerializer<'i, W> { } fn serialize_seq(self, _len: Option) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( "cannot serialize sequence as an `xs:list` item".into(), )) } fn serialize_tuple(self, _len: usize) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( "cannot serialize tuple as an `xs:list` item".into(), )) } @@ -336,7 +335,7 @@ impl<'i, W: Write> Serializer for AtomicSerializer<'i, W> { name: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize tuple struct `{}` as an `xs:list` item", name @@ -352,7 +351,7 @@ impl<'i, W: Write> Serializer for AtomicSerializer<'i, W> { variant: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize enum tuple variant `{}::{}` as an `xs:list` item", name, variant @@ -362,7 +361,7 @@ impl<'i, W: Write> Serializer for AtomicSerializer<'i, W> { } fn serialize_map(self, _len: Option) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( "cannot serialize map as an `xs:list` item".into(), )) } @@ -372,7 +371,7 @@ impl<'i, W: Write> Serializer for AtomicSerializer<'i, W> { name: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!("cannot serialize struct `{}` as an `xs:list` item", name).into(), )) } @@ -384,7 +383,7 @@ impl<'i, W: Write> Serializer for AtomicSerializer<'i, W> { variant: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize enum struct variant `{}::{}` as an `xs:list` item", name, variant @@ -414,7 +413,7 @@ pub struct SimpleTypeSerializer<'i, W: Write> { } impl<'i, W: Write> SimpleTypeSerializer<'i, W> { - fn write_str(&mut self, value: &str) -> Result<(), DeError> { + fn write_str(&mut self, value: &str) -> Result<(), SeError> { self.indent.write_indent(&mut self.writer)?; Ok(self.writer.write_str(value)?) } @@ -422,7 +421,7 @@ impl<'i, W: Write> SimpleTypeSerializer<'i, W> { impl<'i, W: Write> Serializer for SimpleTypeSerializer<'i, W> { type Ok = W; - type Error = DeError; + type Error = SeError; type SerializeSeq = SimpleSeq<'i, W>; type SerializeTuple = SimpleSeq<'i, W>; @@ -459,8 +458,8 @@ impl<'i, W: Write> Serializer for SimpleTypeSerializer<'i, W> { _variant_index: u32, variant: &'static str, _value: &T, - ) -> Result { - Err(DeError::Unsupported( + ) -> Result { + Err(SeError::Unsupported( format!("cannot serialize enum newtype variant `{}::{}` as an attribute or text content value", name, variant).into(), )) } @@ -497,13 +496,13 @@ impl<'i, W: Write> Serializer for SimpleTypeSerializer<'i, W> { variant: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!("cannot serialize enum tuple variant `{}::{}` as an attribute or text content value", name, variant).into(), )) } fn serialize_map(self, _len: Option) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( "cannot serialize map as an attribute or text content value".into(), )) } @@ -513,7 +512,7 @@ impl<'i, W: Write> Serializer for SimpleTypeSerializer<'i, W> { name: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize struct `{}` as an attribute or text content value", name @@ -529,7 +528,7 @@ impl<'i, W: Write> Serializer for SimpleTypeSerializer<'i, W> { variant: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!("cannot serialize enum struct variant `{}::{}` as an attribute or text content value", name, variant).into(), )) } @@ -548,7 +547,7 @@ pub struct SimpleSeq<'i, W: Write> { impl<'i, W: Write> SerializeSeq for SimpleSeq<'i, W> { type Ok = W; - type Error = DeError; + type Error = SeError; fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> where @@ -579,7 +578,7 @@ impl<'i, W: Write> SerializeSeq for SimpleSeq<'i, W> { impl<'i, W: Write> SerializeTuple for SimpleSeq<'i, W> { type Ok = W; - type Error = DeError; + type Error = SeError; #[inline] fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> @@ -597,7 +596,7 @@ impl<'i, W: Write> SerializeTuple for SimpleSeq<'i, W> { impl<'i, W: Write> SerializeTupleStruct for SimpleSeq<'i, W> { type Ok = W; - type Error = DeError; + type Error = SeError; #[inline] fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> @@ -615,7 +614,7 @@ impl<'i, W: Write> SerializeTupleStruct for SimpleSeq<'i, W> { impl<'i, W: Write> SerializeTupleVariant for SimpleSeq<'i, W> { type Ok = W; - type Error = DeError; + type Error = SeError; #[inline] fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> @@ -954,7 +953,7 @@ mod tests { }; match $data.serialize(ser).unwrap_err() { - DeError::$kind(e) => assert_eq!(e, $reason), + SeError::$kind(e) => assert_eq!(e, $reason), e => panic!( "Expected `Err({}({}))`, but got `{:?}`", stringify!($kind), @@ -1072,7 +1071,7 @@ mod tests { }; match $data.serialize(ser).unwrap_err() { - DeError::$kind(e) => assert_eq!(e, $reason), + SeError::$kind(e) => assert_eq!(e, $reason), e => panic!( "Expected `Err({}({}))`, but got `{:?}`", stringify!($kind), diff --git a/src/se/text.rs b/src/se/text.rs index 4dec138d..9dd30509 100644 --- a/src/se/text.rs +++ b/src/se/text.rs @@ -1,8 +1,8 @@ //! Contains serializer for a special `&text` field use crate::de::TEXT_KEY; -use crate::errors::serialize::DeError; use crate::se::simple_type::{SimpleSeq, SimpleTypeSerializer}; +use crate::se::SeError; use serde::ser::{Impossible, Serialize, Serializer}; use serde::serde_if_integer128; use std::fmt::Write; @@ -27,7 +27,7 @@ pub struct TextSerializer<'i, W: Write>(pub SimpleTypeSerializer<'i, W>); impl<'i, W: Write> Serializer for TextSerializer<'i, W> { type Ok = W; - type Error = DeError; + type Error = SeError; type SerializeSeq = SimpleSeq<'i, W>; type SerializeTuple = SimpleSeq<'i, W>; @@ -110,7 +110,7 @@ impl<'i, W: Write> Serializer for TextSerializer<'i, W> { variant: &'static str, _value: &T, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize enum newtype variant `{}::{}` as text content value", name, variant @@ -146,7 +146,7 @@ impl<'i, W: Write> Serializer for TextSerializer<'i, W> { variant: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize enum tuple variant `{}::{}` as text content value", name, variant @@ -157,7 +157,7 @@ impl<'i, W: Write> Serializer for TextSerializer<'i, W> { #[inline] fn serialize_map(self, _len: Option) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( "cannot serialize map as text content value".into(), )) } @@ -168,7 +168,7 @@ impl<'i, W: Write> Serializer for TextSerializer<'i, W> { name: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!("cannot serialize struct `{}` as text content value", name).into(), )) } @@ -181,7 +181,7 @@ impl<'i, W: Write> Serializer for TextSerializer<'i, W> { variant: &'static str, _len: usize, ) -> Result { - Err(DeError::Unsupported( + Err(SeError::Unsupported( format!( "cannot serialize enum struct variant `{}::{}` as text content value", name, variant diff --git a/src/writer.rs b/src/writer.rs index 0d5b1b56..d6aab1a3 100644 --- a/src/writer.rs +++ b/src/writer.rs @@ -11,7 +11,7 @@ mod async_tokio; /// XML writer. Writes XML [`Event`]s to a [`std::io::Write`] or [`tokio::io::AsyncWrite`] implementor. #[cfg(feature = "serialize")] -use {crate::de::DeError, serde::Serialize}; +use {crate::se::SeError, serde::Serialize}; /// XML writer. Writes XML [`Event`]s to a [`std::io::Write`] implementor. /// @@ -278,8 +278,8 @@ impl Writer { /// # use serde::Serialize; /// # use quick_xml::events::{BytesStart, Event}; /// # use quick_xml::writer::Writer; - /// # use quick_xml::DeError; - /// # fn main() -> Result<(), DeError> { + /// # use quick_xml::SeError; + /// # fn main() -> Result<(), SeError> { /// #[derive(Debug, PartialEq, Serialize)] /// struct MyData { /// question: String, @@ -318,7 +318,7 @@ impl Writer { &mut self, tag_name: &str, content: &T, - ) -> Result<(), DeError> { + ) -> Result<(), SeError> { use crate::se::{Indent, Serializer}; self.write_indent()?; diff --git a/tests/serde-se.rs b/tests/serde-se.rs index 39f6e66a..860372d2 100644 --- a/tests/serde-se.rs +++ b/tests/serde-se.rs @@ -1,7 +1,7 @@ use quick_xml::de::from_str; use quick_xml::se::Serializer; use quick_xml::utils::Bytes; -use quick_xml::DeError; +use quick_xml::SeError; use serde::{serde_if_integer128, Deserialize, Serialize}; use std::collections::BTreeMap; @@ -275,7 +275,7 @@ mod without_root { let ser = Serializer::new(&mut buffer); match $data.serialize(ser) { - Err(DeError::$kind(e)) => assert_eq!(e, $reason), + Err(SeError::$kind(e)) => assert_eq!(e, $reason), e => panic!( "Expected `Err({}({}))`, but got `{:?}`", stringify!($kind), @@ -1324,7 +1324,7 @@ mod without_root { let ser = Serializer::new(&mut buffer); match $data.serialize(ser) { - Err(DeError::$kind(e)) => assert_eq!(e, $reason), + Err(SeError::$kind(e)) => assert_eq!(e, $reason), e => panic!( "Expected `Err({}({}))`, but got `{:?}`", stringify!($kind), @@ -1883,7 +1883,7 @@ mod with_root { let ser = Serializer::with_root(&mut buffer, Some("root")).unwrap(); match $data.serialize(ser) { - Err(DeError::$kind(e)) => assert_eq!(e, $reason), + Err(SeError::$kind(e)) => assert_eq!(e, $reason), e => panic!( "Expected `Err({}({}))`, but got `{:?}`", stringify!($kind),