Add support for serializing newtype structs

This enables formats like JSON to serialize newtype wrapper
structs without the normal object wrapper. Consider types like:

```rust
struct Point {
    x: u32,
    y: u32,
}

stuct MyPoint(Point);
```

Before this patch, `MyPoint(1,2)` would get serialized as
`[{"x":1,"y":2}]`, but now it gets serialized as `{"x":1,"y"2}`.
This commit is contained in:
Erick Tryzelaar
2015-07-30 09:38:09 -07:00
parent 6715fb6652
commit 97528b59cf
7 changed files with 180 additions and 41 deletions
+19 -2
View File
@@ -208,8 +208,8 @@ pub trait Deserializer {
self.visit(visitor)
}
/// This method hints that the `Deserialize` type is expecting a named unit. This allows
/// deserializers to a named unit that aren't tagged as a named unit.
/// This method hints that the `Deserialize` type is expecting a unit struct. This allows
/// deserializers to a unit struct that aren't tagged as a unit struct.
#[inline]
fn visit_unit_struct<V>(&mut self,
_name: &'static str,
@@ -219,6 +219,17 @@ pub trait Deserializer {
self.visit_unit(visitor)
}
/// This method hints that the `Deserialize` type is expecting a newtype struct. This allows
/// deserializers to a newtype struct that aren't tagged as a newtype struct.
#[inline]
fn visit_newtype_struct<V>(&mut self,
name: &'static str,
visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor,
{
self.visit_tuple_struct(name, 1, visitor)
}
/// This method hints that the `Deserialize` type is expecting a tuple struct. This allows
/// deserializers to parse sequences that aren't tagged as sequences.
#[inline]
@@ -415,6 +426,12 @@ pub trait Visitor {
Err(Error::syntax_error())
}
fn visit_newtype_struct<D>(&mut self, _deserializer: &mut D) -> Result<Self::Value, D::Error>
where D: Deserializer,
{
Err(Error::syntax_error())
}
fn visit_seq<V>(&mut self, _visitor: V) -> Result<Self::Value, V::Error>
where V: SeqVisitor,
{
+12
View File
@@ -125,6 +125,18 @@ pub trait Serializer {
self.visit_unit()
}
/// The `visit_newtype_struct` allows a tuple struct with a single element, also known as a
/// newtyped value, to be more efficiently serialized than a tuple struct with multiple items.
/// By default it just serializes the value as a tuple struct sequence.
#[inline]
fn visit_newtype_struct<T>(&mut self,
name: &'static str,
value: T) -> Result<(), Self::Error>
where T: Serialize,
{
self.visit_tuple_struct(name, Some(value))
}
/// The `visit_newtype_variant` allows a variant with a single item to be more efficiently
/// serialized than a variant with multiple items. By default it just serializes the value as a
/// tuple variant sequence.