xml: Implement XmlDocument for tagged enums and fix small bug

This commit is contained in:
Lennart
2024-12-23 13:02:59 +01:00
parent 6721e876fa
commit 98ed1a3fc5
5 changed files with 65 additions and 1 deletions

View File

@@ -1,3 +1,5 @@
use core::panic;
use super::attrs::EnumAttrs;
use crate::de::attrs::VariantAttrs;
use darling::{FromDeriveInput, FromVariant};
@@ -219,4 +221,35 @@ impl Enum {
}
}
}
pub fn impl_xml_document(&self) -> proc_macro2::TokenStream {
if self.attrs.untagged.is_present() {
panic!("XmlDocument only supported for untagged enums");
}
let (impl_generics, type_generics, where_clause) = self.generics.split_for_impl();
let ident = &self.ident;
quote! {
impl #impl_generics ::rustical_xml::XmlDocument for #ident #type_generics #where_clause {
fn parse<R: ::std::io::BufRead>(mut reader: ::quick_xml::NsReader<R>) -> Result<Self, ::rustical_xml::XmlDeError>
where
Self: ::rustical_xml::XmlDeserialize
{
use ::quick_xml::events::Event;
let mut buf = Vec::new();
let event = reader.read_event_into(&mut buf)?;
let empty = matches!(event, Event::Empty(_));
match event {
Event::Start(start) | Event::Empty(start) => {
return Self::deserialize(&mut reader, &start, empty);
}
_ => {}
};
Err(::rustical_xml::XmlDeError::UnknownError)
}
}
}
}
}

View File

@@ -39,3 +39,15 @@ pub fn derive_xml_root_tag(input: proc_macro::TokenStream) -> proc_macro::TokenS
}
.into()
}
#[proc_macro_derive(XmlDocument, attributes(xml))]
pub fn derive_xml_document(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as DeriveInput);
match &input.data {
syn::Data::Struct(_) => panic!("Struct not supported, use XmlRootTag instead"),
syn::Data::Enum(e) => Enum::parse(&input, e).impl_xml_document(),
syn::Data::Union(_) => panic!("Union not supported as root"),
}
.into()
}