Skip to content

Commit

Permalink
Merge a79da97 into 389077e
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcAntoine-Arnaud committed Feb 24, 2020
2 parents 389077e + a79da97 commit e7cf38c
Show file tree
Hide file tree
Showing 8 changed files with 151 additions and 30 deletions.
3 changes: 3 additions & 0 deletions yaserde/src/de/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
//! Generic data structure deserialization framework.
//!

use std::io::Read;
use xml::name::OwnedName;
use xml::reader::{EventReader, ParserConfig, XmlEvent};
Expand Down
9 changes: 9 additions & 0 deletions yaserde/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
//! # YaSerDe
//!
//! YaSerDe is a framework for ***ser***ializing and ***de***serializing Rust data
//! structures efficiently and generically from and into XML.

#[macro_use]
extern crate log;
extern crate xml;
Expand All @@ -12,14 +17,18 @@ use xml::writer::XmlEvent;
pub mod de;
pub mod ser;

/// A **data structure** that can be deserialized from any data format supported by YaSerDe.
pub trait YaDeserialize: Sized {
fn deserialize<R: Read>(reader: &mut de::Deserializer<R>) -> Result<Self, String>;
}

/// A **data structure** that can be serialized into any data format supported by YaSerDe.
pub trait YaSerialize: Sized {
fn serialize<W: Write>(&self, writer: &mut ser::Serializer<W>) -> Result<(), String>;
}


/// A **visitor** that can be implemented to retrieve information from source file.
pub trait Visitor<'de>: Sized {
/// The value produced by this visitor.
type Value;
Expand Down
3 changes: 3 additions & 0 deletions yaserde/src/ser/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
//! Generic data structure serialization framework.
//!

use std::io::{Cursor, Write};
use std::str;
use xml;
Expand Down
21 changes: 21 additions & 0 deletions yaserde/tests/se_namespace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,27 @@ fn ser_struct_default_namespace() {
convert_and_validate!(model, content);
}

#[test]
fn ser_struct_default_namespace_via_attribute() {
#[derive(YaSerialize, PartialEq, Debug)]
#[yaserde(
root = "tt",
default_namespace = "ttml",
namespace = "ttml: http://www.w3.org/ns/ttml",
namespace = "ttm: http://www.w3.org/ns/ttml#metadata"
)]
pub struct XmlStruct {
item: String,
}

let model = XmlStruct {
item: "something".to_string(),
};

let content = "<?xml version=\"1.0\" encoding=\"utf-8\"?><tt xmlns=\"http://www.w3.org/ns/ttml\" xmlns:ttm=\"http://www.w3.org/ns/ttml#metadata\"><item>something</item></tt>";
convert_and_validate!(model, content);
}

#[test]
fn de_struct_namespace_nested() {
#[derive(YaSerialize, Default, PartialEq, Debug)]
Expand Down
109 changes: 85 additions & 24 deletions yaserde_derive/src/attribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ use syn::Attribute;

#[derive(Debug, PartialEq, Clone)]
pub struct YaSerdeAttribute {
pub root: Option<String>,
pub rename: Option<String>,
pub prefix: Option<String>,
pub attribute: bool,
pub default: Option<String>,
pub default_namespace: Option<String>,
pub flatten: bool,
pub namespaces: BTreeMap<String, String>,
pub attribute: bool,
pub prefix: Option<String>,
pub root: Option<String>,
pub rename: Option<String>,
pub text: bool,
pub flatten: bool,
}

fn get_value(iter: &mut IntoIter) -> Option<String> {
Expand All @@ -33,13 +34,14 @@ fn get_value(iter: &mut IntoIter) -> Option<String> {
impl YaSerdeAttribute {
pub fn parse(attrs: &[Attribute]) -> YaSerdeAttribute {
let mut attribute = false;
let mut flatten = false;
let mut default = None;
let mut default_namespace = None;
let mut namespaces = BTreeMap::new();
let mut prefix = None;
let mut rename = None;
let mut root = None;
let mut default = None;
let mut text = false;
let mut flatten = false;

for attr in attrs.iter() {
let mut attr_iter = attr.clone().tokens.into_iter();
Expand All @@ -54,6 +56,15 @@ impl YaSerdeAttribute {
"attribute" => {
attribute = true;
}
"default" => {
default = get_value(&mut attr_iter);
}
"default_namespace" => {
default_namespace = get_value(&mut attr_iter);
}
"flatten" => {
flatten = true;
}
"namespace" => {
if let Some(namespace) = get_value(&mut attr_iter) {
let splitted: Vec<&str> = namespace.split(": ").collect();
Expand All @@ -74,15 +85,9 @@ impl YaSerdeAttribute {
"root" => {
root = get_value(&mut attr_iter);
}
"default" => {
default = get_value(&mut attr_iter);
}
"text" => {
text = true;
}
"flatten" => {
flatten = true;
}
_ => {}
}
}
Expand All @@ -94,13 +99,14 @@ impl YaSerdeAttribute {

YaSerdeAttribute {
attribute,
default,
default_namespace,
flatten,
namespaces,
prefix,
rename,
root,
default,
text,
flatten,
}
}
}
Expand All @@ -112,14 +118,15 @@ fn parse_empty_attributes() {

assert_eq!(
YaSerdeAttribute {
root: None,
rename: None,
prefix: None,
attribute: false,
default: None,
default_namespace: None,
flatten: false,
namespaces: BTreeMap::new(),
attribute: false,
prefix: None,
root: None,
rename: None,
text: false,
flatten: false,
},
attrs
);
Expand Down Expand Up @@ -160,14 +167,68 @@ fn parse_attributes() {

assert_eq!(
YaSerdeAttribute {
root: None,
rename: None,
prefix: None,
attribute: true,
default: None,
default_namespace: None,
flatten: false,
namespaces: BTreeMap::new(),
prefix: None,
root: None,
rename: None,
text: false,
},
attrs
);
}

#[test]
fn parse_attributes_with_values() {
use proc_macro2::{Span, TokenStream};
use std::str::FromStr;
use syn::punctuated::Punctuated;
use syn::token::Bracket;
use syn::token::Pound;
use syn::AttrStyle::Outer;
use syn::{Ident, Path, PathArguments, PathSegment};

let mut punctuated = Punctuated::new();
punctuated.push(PathSegment {
ident: Ident::new("yaserde", Span::call_site()),
arguments: PathArguments::None,
});

// #[()]
let attributes = vec![Attribute {
pound_token: Pound {
spans: [Span::call_site()],
},
style: Outer,
bracket_token: Bracket {
span: Span::call_site(),
},
path: Path {
leading_colon: None,
segments: punctuated,
},
tokens: TokenStream::from_str("(attribute, flatten, default_namespace=\"example\", namespace=\"example: http://example.org\")").unwrap(),
}];

let attrs = YaSerdeAttribute::parse(&attributes);

let mut namespaces = BTreeMap::new();
namespaces.insert("example".to_string(), "http://example.org".to_string());

assert_eq!(
YaSerdeAttribute {
attribute: true,
default: None,
default_namespace: Some("example".to_string()),
flatten: true,
namespaces,
prefix: None,
root: None,
rename: None,
text: false,
flatten: false,
},
attrs
);
Expand Down
8 changes: 8 additions & 0 deletions yaserde_derive/src/ser/expand_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub fn serialize(
name: &Ident,
root: &str,
namespaces: &BTreeMap<String, String>,
default_namespace: &Option<String>,
) -> TokenStream {
let write_enum_content: TokenStream = data_enum
.variants
Expand Down Expand Up @@ -212,6 +213,13 @@ pub fn serialize(
let add_namespaces: TokenStream = namespaces
.iter()
.map(|(prefix, namespace)| {
if let Some(dn) = default_namespace {
if dn == prefix {
return Some(quote!(
.default_ns(#namespace)
));
}
}
Some(quote!(
.ns(#prefix, #namespace)
))
Expand Down
8 changes: 8 additions & 0 deletions yaserde_derive/src/ser/expand_struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ pub fn serialize(
name: &Ident,
root: &str,
namespaces: &BTreeMap<String, String>,
default_namespace: &Option<String>,
) -> TokenStream {
let build_attributes: TokenStream = data_struct
.fields
Expand Down Expand Up @@ -208,6 +209,13 @@ pub fn serialize(
let add_namespaces: TokenStream = namespaces
.iter()
.map(|(prefix, namespace)| {
if let Some(dn) = default_namespace {
if dn == prefix {
return Some(quote!(
.default_ns(#namespace)
));
}
}
Some(quote!(
.ns(#prefix, #namespace)
))
Expand Down
20 changes: 14 additions & 6 deletions yaserde_derive/src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,20 @@ pub fn expand_derive_serialize(ast: &syn::DeriveInput) -> Result<TokenStream, St
};

let impl_block = match *data {
syn::Data::Struct(ref data_struct) => {
expand_struct::serialize(data_struct, name, &root, &root_attrs.namespaces)
}
syn::Data::Enum(ref data_enum) => {
expand_enum::serialize(data_enum, name, &root, &root_attrs.namespaces)
}
syn::Data::Struct(ref data_struct) => expand_struct::serialize(
data_struct,
name,
&root,
&root_attrs.namespaces,
&root_attrs.default_namespace,
),
syn::Data::Enum(ref data_enum) => expand_enum::serialize(
data_enum,
name,
&root,
&root_attrs.namespaces,
&root_attrs.default_namespace,
),
syn::Data::Union(ref _data_union) => unimplemented!(),
};

Expand Down

0 comments on commit e7cf38c

Please sign in to comment.