xso: add support for ignoring unknown attributes

This commit is contained in:
Jonas Schäfer 2024-10-03 12:29:10 +02:00 committed by Link Mauve
commit 290460ba9d
9 changed files with 185 additions and 23 deletions

View file

@ -47,6 +47,7 @@ such:
- *path*: A Rust path, like `some_crate::foo::Bar`. Note that `foo` on its own
is also a path.
- *identifier*: A single Rust identifier.
- *string literal*: A string literal, like `"hello world!"`.
- *type*: A Rust type.
- *expression*: A Rust expression.
@ -67,6 +68,7 @@ The following keys are defined on structs:
| `transparent` | *flag* | If present, declares the struct as *transparent* struct (see below) |
| `builder` | optional *ident* | The name to use for the generated builder type. |
| `iterator` | optional *ident* | The name to use for the generated iterator type. |
| `on_unknown_attribute` | *identifier* | Name of an [`UnknownAttributePolicy`] member, controlling how unknown attributes are handled. |
Note that the `name` value must be a valid XML element name, without colons.
The namespace prefix, if any, is assigned automatically at serialisation time
@ -146,6 +148,7 @@ documentation above.
| Key | Value type | Description |
| --- | --- | --- |
| `name` | *string literal* or *path* | The XML element name to match for this variant. If it is a *path*, it must point at a `&'static NcNameStr`. |
| `on_unknown_attribute` | *identifier* | Name of an [`UnknownAttributePolicy`] member, controlling how unknown attributes are handled. |
Note that the `name` value must be a valid XML element name, without colons.
The namespace prefix, if any, is assigned automatically at serialisation time

View file

@ -291,6 +291,38 @@ impl<T: AsXmlText> AsOptionalXmlText for Option<T> {
}
}
/// Control how unknown attributes are handled.
///
/// The variants of this enum are referenced in the
/// `#[xml(on_unknown_attribute = ..)]` which can be used on structs and
/// enum variants. The specified variant controls how attributes, which are
/// not handled by any member of the compound, are handled during parsing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub enum UnknownAttributePolicy {
/// All unknown attributes are discarded.
Discard,
/// The first unknown attribute which is encountered generates a fatal
/// parsing error.
///
/// This is the default policy.
#[default]
Fail,
}
impl UnknownAttributePolicy {
#[doc(hidden)]
/// Implementation of the policy.
///
/// This is an internal API and not subject to semver versioning.
pub fn apply_policy(&self, msg: &'static str) -> Result<(), self::error::Error> {
match self {
Self::Fail => Err(self::error::Error::Other(msg)),
Self::Discard => Ok(()),
}
}
}
/// Attempt to transform a type implementing [`AsXml`] into another
/// type which implements [`FromXml`].
pub fn transform<T: FromXml, F: AsXml>(from: F) -> Result<T, self::error::Error> {