Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix up unit variant ordering and support rendering them as string content #208

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,53 @@ fn main() {
assert_eq!(src, reserialized_item);
}
```

## Tuning the serialization

Since XML has multiple ways to represent "sub-values" of a node (attributes,
child nodes, contents) the serializer understands various special names for
fields to steer where and how their contents should be rendered.

```rust
#[derive(Serialize)]
struct Node {
// Fields with names starting with `@` are rendered as attributes (and must
therefore be primitive types)
#[serde(rename = "@my_attr")]
my_attr: String,

// Fields renamed to "$value" are rendered as content nodes of the structure
(and must also be primitive types)
#[serde(rename = "$value")]
content: String,

// Other fields are rendered as child nodes
child: String,
}
```

The above might get rendered as:

```xml
<Node my_attr="foo">
Hello World!
<child>And me too!</child>
</Node>
```

Unit-variant `enum` objects can also be rendered in two ways, either as a
self-closing node or as a string content by default they're rendered as nodes,
but this can also be tuned:

```rust
enum Options {
Live,
#[serde(rename = "@Laugh")]
Laugh,
#[serde(rename = "@LOVE")]
Love,
}
```

When an instance of this `enum` is serialized, `Options::Live` renders as
`<Live />` while `Laugh` renders as `Laugh` and `Love` renders as `LOVE`.
61 changes: 57 additions & 4 deletions src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,10 +297,18 @@ impl<'ser, W: Write> serde::ser::Serializer for &'ser mut Serializer<W> {
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok> {
debug!("Unit variant {}::{}", name, variant);
self.start_tag(variant, HashMap::new())?;
self.serialize_unit()?;
self.end_tag()?;
let need_outer_end = self.build_start_tag()?;
if let Some(stripped) = variant.strip_prefix("$") {
debug!("Unit variant (plain) {}", stripped);
self.characters(stripped)?;
} else {
debug!("Unit variant {}::{}", name, variant);
self.start_tag(variant, HashMap::new())?;
self.end_tag()?;
}
if need_outer_end {
self.end_tag()?
};
Ok(())
}

Expand Down Expand Up @@ -447,4 +455,49 @@ mod tests {
let got = String::from_utf8(buffer).unwrap();
assert_eq!(got, should_be);
}

#[test]
fn test_serialize_unit_enum() {
#[derive(Serialize)]
#[allow(dead_code)]
enum PlainValue {
#[serde(rename = "$FOO")]
Foo,
#[serde(rename = "$BAR")]
Bar,
#[serde(rename = "$BAZ")]
Baz,
}

#[derive(Serialize)]
#[allow(dead_code)]
enum Value {
Foo,
Bar,
Baz,
}

#[derive(Serialize)]
#[allow(dead_code)]
struct Outer {
plain_value: PlainValue,
value: Value,
}

let mut buffer = Vec::new();
let should_be =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><Outer><plain_value>FOO</plain_value><value><Foo /></value></Outer>";

{
let mut ser = Serializer::new(&mut buffer);
let outer = Outer {
plain_value: PlainValue::Foo,
value: Value::Foo,
};
outer.serialize(&mut ser).unwrap();
}

let got = String::from_utf8(buffer).unwrap();
assert_eq!(got, should_be);
}
}