mirror of
https://github.com/lennart-k/rustical.git
synced 2025-12-14 07:02:24 +00:00
xml: namespace serialization
This commit is contained in:
@@ -10,7 +10,8 @@ pub struct ContainerAttrs {
|
||||
pub struct TagAttrs {
|
||||
pub rename: Option<LitByteStr>,
|
||||
pub ns_strict: Flag,
|
||||
pub ns: Option<LitByteStr>,
|
||||
// pub ns: Option<LitByteStr>,
|
||||
pub ns: Option<syn::ExprPath>,
|
||||
}
|
||||
|
||||
#[derive(Default, FromVariant)]
|
||||
@@ -37,7 +38,7 @@ pub struct StructAttrs {
|
||||
pub container: ContainerAttrs,
|
||||
|
||||
pub root: Option<LitByteStr>,
|
||||
pub ns: Option<LitByteStr>,
|
||||
pub ns: Option<syn::ExprPath>,
|
||||
pub allow_invalid: Flag,
|
||||
}
|
||||
|
||||
|
||||
@@ -148,8 +148,8 @@ impl Field {
|
||||
}
|
||||
|
||||
let namespace_match = if self.ns_strict() {
|
||||
if let Some(ns) = &self.attrs.common.ns {
|
||||
quote! {quick_xml::name::ResolveResult::Bound(quick_xml::name::Namespace(#ns))}
|
||||
if self.attrs.common.ns.is_some() {
|
||||
quote! {quick_xml::name::ResolveResult::Bound(ns)}
|
||||
} else {
|
||||
quote! {quick_xml::name::ResolveResult::Unbound}
|
||||
}
|
||||
@@ -157,6 +157,16 @@ impl Field {
|
||||
quote! {_}
|
||||
};
|
||||
|
||||
let namespace_condition = if self.ns_strict() {
|
||||
self.attrs
|
||||
.common
|
||||
.ns
|
||||
.as_ref()
|
||||
.map(|ns| quote! { if ns == #ns })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let field_name = self.xml_name();
|
||||
let field_ident = self.field_ident();
|
||||
let deserializer = self.deserializer_type();
|
||||
@@ -170,7 +180,7 @@ impl Field {
|
||||
};
|
||||
|
||||
Some(quote! {
|
||||
(#namespace_match, #field_name) => { #assignment; }
|
||||
(#namespace_match, #field_name) #namespace_condition => { #assignment; }
|
||||
})
|
||||
}
|
||||
|
||||
@@ -256,6 +266,10 @@ impl Field {
|
||||
} else {
|
||||
quote! { ::rustical_xml::XmlSerialize::serialize }
|
||||
};
|
||||
let ns = match &self.attrs.common.ns {
|
||||
Some(ns) => quote! { Some(#ns) },
|
||||
None => quote! { None },
|
||||
};
|
||||
|
||||
match (&self.attrs.xml_ty, self.attrs.flatten.is_present()) {
|
||||
(FieldType::Attr, _) => None,
|
||||
@@ -269,19 +283,19 @@ impl Field {
|
||||
}),
|
||||
(FieldType::Tag, true) => Some(quote! {
|
||||
for item in self.#field_ident.iter() {
|
||||
#serializer(item, None, Some(#field_name), writer)?;
|
||||
#serializer(item, #ns, Some(#field_name), namespaces, writer)?;
|
||||
}
|
||||
}),
|
||||
(FieldType::Tag, false) => Some(quote! {
|
||||
#serializer(&self.#field_ident, None, Some(#field_name), writer)?;
|
||||
#serializer(&self.#field_ident, #ns, Some(#field_name), namespaces, writer)?;
|
||||
}),
|
||||
(FieldType::Untagged, true) => Some(quote! {
|
||||
for item in self.#field_ident.iter() {
|
||||
#serializer(item, None, None, writer)?;
|
||||
#serializer(item, None, None, namespaces, writer)?;
|
||||
}
|
||||
}),
|
||||
(FieldType::Untagged, false) => Some(quote! {
|
||||
#serializer(&self.#field_ident, None, None, writer)?;
|
||||
#serializer(&self.#field_ident, None, None, namespaces, writer)?;
|
||||
}),
|
||||
// TODO: Think about what to do here
|
||||
(FieldType::TagName | FieldType::Namespace, _) => None,
|
||||
|
||||
@@ -176,6 +176,10 @@ impl Variant {
|
||||
pub fn se_branch(&self) -> proc_macro2::TokenStream {
|
||||
let ident = self.ident();
|
||||
let variant_name = self.xml_name();
|
||||
let ns = match &self.attrs.common.ns {
|
||||
Some(ns) => quote! { Some(#ns) },
|
||||
None => quote! { None },
|
||||
};
|
||||
|
||||
match &self.variant.fields {
|
||||
Fields::Named(_) => {
|
||||
@@ -190,9 +194,9 @@ impl Variant {
|
||||
quote! {
|
||||
if let Self::#ident(val) = &self {
|
||||
if !enum_untagged {
|
||||
::rustical_xml::XmlSerialize::serialize(val, None, Some(#variant_name), writer)?;
|
||||
::rustical_xml::XmlSerialize::serialize(val, #ns, Some(#variant_name), namespaces, writer)?;
|
||||
} else {
|
||||
::rustical_xml::XmlSerialize::serialize(val, None, None, writer)?;
|
||||
::rustical_xml::XmlSerialize::serialize(val, None, None, namespaces, writer)?;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -201,9 +205,9 @@ impl Variant {
|
||||
quote! {
|
||||
if let Self::#ident = &self {
|
||||
if !enum_untagged {
|
||||
::rustical_xml::XmlSerialize::serialize(&(), None, Some(#variant_name), writer)?;
|
||||
::rustical_xml::XmlSerialize::serialize(&(), #ns, Some(#variant_name), namespaces, writer)?;
|
||||
} else {
|
||||
::rustical_xml::XmlSerialize::serialize(&(), None, None, writer)?;
|
||||
::rustical_xml::XmlSerialize::serialize(&(), None, None, namespaces, writer)?;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,24 +99,37 @@ impl Enum {
|
||||
impl #impl_generics ::rustical_xml::XmlSerialize for #ident #type_generics #where_clause {
|
||||
fn serialize<W: ::std::io::Write>(
|
||||
&self,
|
||||
ns: Option<&[u8]>,
|
||||
ns: Option<::quick_xml::name::Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &::std::collections::HashMap<::quick_xml::name::Namespace, &[u8]>,
|
||||
writer: &mut ::quick_xml::Writer<W>
|
||||
) -> ::std::io::Result<()> {
|
||||
use ::quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
|
||||
|
||||
let tag_str = tag.map(String::from_utf8_lossy);
|
||||
let prefix = ns
|
||||
.map(|ns| namespaces.get(&ns))
|
||||
.unwrap_or(None)
|
||||
.map(|prefix| [*prefix, b":"].concat());
|
||||
let has_prefix = prefix.is_some();
|
||||
let tagname = tag.map(|tag| [&prefix.unwrap_or_default(), tag].concat());
|
||||
let qname = tagname.as_ref().map(|tagname| ::quick_xml::name::QName(tagname));
|
||||
|
||||
const enum_untagged: bool = #enum_untagged;
|
||||
|
||||
if let Some(tag) = &tag_str {
|
||||
let bytes_start = BytesStart::new(tag.to_owned());
|
||||
if let Some(qname) = &qname {
|
||||
let mut bytes_start = BytesStart::from(qname.to_owned());
|
||||
if !has_prefix {
|
||||
if let Some(ns) = &ns {
|
||||
bytes_start.push_attribute((b"xmlns".as_ref(), ns.as_ref()));
|
||||
}
|
||||
}
|
||||
writer.write_event(Event::Start(bytes_start))?;
|
||||
}
|
||||
|
||||
#(#variant_serializers);*
|
||||
|
||||
if let Some(tag) = &tag_str {
|
||||
writer.write_event(Event::End(BytesEnd::new(tag.to_owned())))?;
|
||||
if let Some(qname) = &qname {
|
||||
writer.write_event(Event::End(BytesEnd::from(qname.to_owned())))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ impl NamedStruct {
|
||||
quote! {
|
||||
impl #impl_generics ::rustical_xml::XmlRootTag for #ident #type_generics #where_clause {
|
||||
fn root_tag() -> &'static [u8] { #root }
|
||||
fn root_ns() -> Option<&'static [u8]> { #ns }
|
||||
fn root_ns() -> Option<::quick_xml::name::Namespace<'static>> { #ns }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -217,7 +217,8 @@ impl NamedStruct {
|
||||
.map(|field| {
|
||||
let field_ident = field.field_ident();
|
||||
quote! {
|
||||
let tag_str = Some(tag_str.unwrap_or(self.#field_ident.to_string()));
|
||||
let tag_str = self.#field_ident.to_string();
|
||||
let tag = Some(tag.unwrap_or(tag_str.as_bytes()));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -227,17 +228,30 @@ impl NamedStruct {
|
||||
impl #impl_generics ::rustical_xml::XmlSerialize for #ident #type_generics #where_clause {
|
||||
fn serialize<W: ::std::io::Write>(
|
||||
&self,
|
||||
ns: Option<&[u8]>,
|
||||
ns: Option<::quick_xml::name::Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &::std::collections::HashMap<::quick_xml::name::Namespace, &[u8]>,
|
||||
writer: &mut ::quick_xml::Writer<W>
|
||||
) -> ::std::io::Result<()> {
|
||||
use ::quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
|
||||
|
||||
let tag_str = tag.map(|a| String::from_utf8_lossy(a).to_string());
|
||||
#tag_name_field;
|
||||
|
||||
if let Some(tag) = &tag_str {
|
||||
let mut bytes_start = BytesStart::new(tag.to_owned());
|
||||
let prefix = ns
|
||||
.map(|ns| namespaces.get(&ns))
|
||||
.unwrap_or(None)
|
||||
.map(|prefix| [*prefix, b":"].concat());
|
||||
let has_prefix = prefix.is_some();
|
||||
let tagname = tag.map(|tag| [&prefix.unwrap_or_default(), tag].concat());
|
||||
let qname = tagname.as_ref().map(|tagname| ::quick_xml::name::QName(tagname));
|
||||
|
||||
if let Some(qname) = &qname {
|
||||
let mut bytes_start = BytesStart::from(qname.to_owned());
|
||||
if !has_prefix {
|
||||
if let Some(ns) = &ns {
|
||||
bytes_start.push_attribute((b"xmlns".as_ref(), ns.as_ref()));
|
||||
}
|
||||
}
|
||||
if let Some(attrs) = self.attributes() {
|
||||
bytes_start.extend_attributes(attrs);
|
||||
}
|
||||
@@ -250,8 +264,8 @@ impl NamedStruct {
|
||||
}
|
||||
if !#is_empty {
|
||||
#(#tag_writers);*
|
||||
if let Some(tag) = &tag_str {
|
||||
writer.write_event(Event::End(BytesEnd::new(tag.to_owned())))?;
|
||||
if let Some(qname) = &qname {
|
||||
writer.write_event(Event::End(BytesEnd::from(qname.to_owned())))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -54,11 +54,7 @@ impl<T: XmlRootTag + XmlDeserialize> XmlDocument for T {
|
||||
// Wrong tag
|
||||
(_, _, name) if name.as_ref() != Self::root_tag() => false,
|
||||
// Wrong namespace
|
||||
(Some(root_ns), ns, _)
|
||||
if &ResolveResult::Bound(Namespace(root_ns)) != ns =>
|
||||
{
|
||||
false
|
||||
}
|
||||
(Some(root_ns), ns, _) if &ResolveResult::Bound(root_ns) != ns => false,
|
||||
_ => true,
|
||||
};
|
||||
if !matches {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use quick_xml::events::BytesEnd;
|
||||
use quick_xml::events::{BytesStart, Event};
|
||||
use quick_xml::name::{Namespace, QName};
|
||||
use std::collections::HashMap;
|
||||
use std::io::BufRead;
|
||||
|
||||
pub mod de;
|
||||
@@ -38,14 +39,26 @@ impl XmlDeserialize for () {
|
||||
impl XmlSerialize for () {
|
||||
fn serialize<W: std::io::Write>(
|
||||
&self,
|
||||
ns: Option<&[u8]>,
|
||||
ns: Option<Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
) -> std::io::Result<()> {
|
||||
let tag_str = tag.map(String::from_utf8_lossy);
|
||||
|
||||
if let Some(tag) = &tag_str {
|
||||
writer.write_event(Event::Empty(BytesStart::new(tag.clone())))?;
|
||||
let prefix = ns
|
||||
.map(|ns| namespaces.get(&ns))
|
||||
.unwrap_or(None)
|
||||
.map(|prefix| [*prefix, b":"].concat());
|
||||
let has_prefix = prefix.is_some();
|
||||
let tagname = tag.map(|tag| [&prefix.unwrap_or_default(), tag].concat());
|
||||
let qname = tagname.as_ref().map(|tagname| QName(tagname));
|
||||
if let Some(qname) = &qname {
|
||||
let mut bytes_start = BytesStart::from(qname.to_owned());
|
||||
if !has_prefix {
|
||||
if let Some(ns) = &ns {
|
||||
bytes_start.push_attribute((b"xmlns".as_ref(), ns.as_ref()));
|
||||
}
|
||||
}
|
||||
writer.write_event(Event::Empty(bytes_start))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -84,5 +97,5 @@ impl XmlDeserialize for Unparsed {
|
||||
|
||||
pub trait XmlRootTag {
|
||||
fn root_tag() -> &'static [u8];
|
||||
fn root_ns() -> Option<&'static [u8]>;
|
||||
fn root_ns() -> Option<Namespace<'static>>;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use quick_xml::events::attributes::Attribute;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use quick_xml::{events::attributes::Attribute, name::Namespace};
|
||||
pub use xml_derive::XmlSerialize;
|
||||
|
||||
use crate::XmlRootTag;
|
||||
@@ -6,8 +8,9 @@ use crate::XmlRootTag;
|
||||
pub trait XmlSerialize {
|
||||
fn serialize<W: std::io::Write>(
|
||||
&self,
|
||||
ns: Option<&[u8]>,
|
||||
ns: Option<Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
) -> std::io::Result<()>;
|
||||
|
||||
@@ -17,12 +20,13 @@ pub trait XmlSerialize {
|
||||
impl<T: XmlSerialize> XmlSerialize for Option<T> {
|
||||
fn serialize<W: std::io::Write>(
|
||||
&self,
|
||||
ns: Option<&[u8]>,
|
||||
ns: Option<Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
) -> std::io::Result<()> {
|
||||
if let Some(some) = self {
|
||||
some.serialize(ns, tag, writer)
|
||||
some.serialize(ns, tag, namespaces, writer)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
@@ -46,6 +50,7 @@ impl<T: XmlSerialize + XmlRootTag> XmlSerializeRoot for T {
|
||||
&self,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
) -> std::io::Result<()> {
|
||||
self.serialize(Self::root_ns(), Some(Self::root_tag()), writer)
|
||||
let namespaces = HashMap::new();
|
||||
self.serialize(Self::root_ns(), Some(Self::root_tag()), &namespaces, writer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
|
||||
use quick_xml::name::{Namespace, QName};
|
||||
use std::collections::HashMap;
|
||||
use std::num::{ParseFloatError, ParseIntError};
|
||||
use std::{convert::Infallible, io::BufRead};
|
||||
use thiserror::Error;
|
||||
@@ -93,19 +95,30 @@ impl<T: Value> XmlDeserialize for T {
|
||||
impl<T: Value> XmlSerialize for T {
|
||||
fn serialize<W: std::io::Write>(
|
||||
&self,
|
||||
ns: Option<&[u8]>,
|
||||
ns: Option<Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
) -> std::io::Result<()> {
|
||||
let tag_str = tag.map(String::from_utf8_lossy);
|
||||
|
||||
if let Some(tag) = &tag_str {
|
||||
writer.write_event(Event::Start(BytesStart::new(tag.clone())))?;
|
||||
let prefix = ns
|
||||
.map(|ns| namespaces.get(&ns))
|
||||
.unwrap_or(None)
|
||||
.map(|prefix| [*prefix, b":"].concat());
|
||||
let has_prefix = prefix.is_some();
|
||||
let tagname = tag.map(|tag| [&prefix.unwrap_or_default(), tag].concat());
|
||||
let qname = tagname.as_ref().map(|tagname| QName(tagname));
|
||||
if let Some(qname) = &qname {
|
||||
let mut bytes_start = BytesStart::from(qname.to_owned());
|
||||
if !has_prefix {
|
||||
if let Some(ns) = &ns {
|
||||
bytes_start.push_attribute((b"xmlns".as_ref(), ns.as_ref()));
|
||||
}
|
||||
}
|
||||
writer.write_event(Event::Start(bytes_start))?;
|
||||
}
|
||||
writer.write_event(Event::Text(BytesText::new(&self.serialize())))?;
|
||||
|
||||
if let Some(tag) = &tag_str {
|
||||
writer.write_event(Event::End(BytesEnd::new(tag.clone())))?;
|
||||
if let Some(qname) = &qname {
|
||||
writer.write_event(Event::End(BytesEnd::from(qname.to_owned())))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use quick_xml::name::Namespace;
|
||||
use rustical_xml::de::XmlDocument;
|
||||
use rustical_xml::XmlRootTag;
|
||||
use rustical_xml::{Unparsed, XmlDeserialize};
|
||||
use rustical_xml::{Unparsed, XmlDeserialize, XmlRootTag};
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[test]
|
||||
@@ -151,10 +151,12 @@ fn test_struct_set() {
|
||||
|
||||
#[test]
|
||||
fn test_struct_ns() {
|
||||
const NS_HELLO: Namespace = Namespace(b"hello");
|
||||
|
||||
#[derive(Debug, XmlDeserialize, XmlRootTag, PartialEq)]
|
||||
#[xml(root = b"document", ns_strict)]
|
||||
struct Document {
|
||||
#[xml(ns = b"hello")]
|
||||
#[xml(ns = "NS_HELLO")]
|
||||
child: (),
|
||||
}
|
||||
|
||||
@@ -164,10 +166,12 @@ fn test_struct_ns() {
|
||||
|
||||
#[test]
|
||||
fn test_struct_attr() {
|
||||
const NS_HELLO: Namespace = Namespace(b"hello");
|
||||
|
||||
#[derive(Debug, XmlDeserialize, XmlRootTag, PartialEq)]
|
||||
#[xml(root = b"document", ns_strict)]
|
||||
struct Document {
|
||||
#[xml(ns = b"hello")]
|
||||
#[xml(ns = "NS_HELLO")]
|
||||
child: (),
|
||||
#[xml(ty = "attr", default = "Default::default")]
|
||||
test: String,
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
use std::borrow::{Borrow, Cow};
|
||||
use std::{
|
||||
borrow::{Borrow, Cow},
|
||||
collections::HashMap,
|
||||
};
|
||||
|
||||
use quick_xml::name::Namespace;
|
||||
use quick_xml::Writer;
|
||||
use rustical_xml::{XmlDocument, XmlRootTag, XmlSerialize, XmlSerializeRoot};
|
||||
use xml_derive::XmlDeserialize;
|
||||
@@ -135,11 +139,12 @@ fn test_struct_serialize_with() {
|
||||
|
||||
fn serialize_href<W: ::std::io::Write>(
|
||||
val: &str,
|
||||
ns: Option<&[u8]>,
|
||||
ns: Option<Namespace>,
|
||||
tag: Option<&[u8]>,
|
||||
namespaces: &HashMap<Namespace, &[u8]>,
|
||||
writer: &mut Writer<W>,
|
||||
) -> std::io::Result<()> {
|
||||
val.to_uppercase().serialize(ns, tag, writer)
|
||||
val.to_uppercase().serialize(ns, tag, namespaces, writer)
|
||||
}
|
||||
|
||||
let mut buf = Vec::new();
|
||||
@@ -188,3 +193,26 @@ fn test_struct_tag_list() {
|
||||
let out = String::from_utf8(buf).unwrap();
|
||||
dbg!(out);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_struct_ns() {
|
||||
// const NS: Namespace = Namespace(b"TEST", quick_xml::name::Namespace(b"NS:TEST:"));
|
||||
const NS: Namespace = quick_xml::name::Namespace(b"NS:TEST:");
|
||||
|
||||
#[derive(Debug, XmlRootTag, XmlSerialize)]
|
||||
#[xml(root = b"document")]
|
||||
struct Document {
|
||||
#[xml(ns = "NS", rename = b"okay")]
|
||||
child: String,
|
||||
}
|
||||
|
||||
let mut buf = Vec::new();
|
||||
let mut writer = quick_xml::Writer::new(&mut buf);
|
||||
Document {
|
||||
child: "hello!".to_string(),
|
||||
}
|
||||
.serialize_root(&mut writer)
|
||||
.unwrap();
|
||||
let out = String::from_utf8(buf).unwrap();
|
||||
dbg!(out);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user