Merge pull request #249 from erickt/master

Rename error trait methods, optimize bytes, don't expose primitive
This commit is contained in:
Erick Tryzelaar
2016-02-23 20:51:59 -08:00
13 changed files with 588 additions and 554 deletions
+13 -13
View File
@@ -88,7 +88,7 @@ impl Visitor for BoolVisitor {
match s.trim() { match s.trim() {
"true" => Ok(true), "true" => Ok(true),
"false" => Ok(false), "false" => Ok(false),
_ => Err(Error::type_mismatch(Type::Bool)), _ => Err(Error::invalid_type(Type::Bool)),
} }
} }
} }
@@ -111,30 +111,30 @@ macro_rules! impl_deserialize_num_method {
{ {
match FromPrimitive::$from_method(v) { match FromPrimitive::$from_method(v) {
Some(v) => Ok(v), Some(v) => Ok(v),
None => Err(Error::type_mismatch($ty)), None => Err(Error::invalid_type($ty)),
} }
} }
} }
} }
/// A visitor that produces a primitive type. /// A visitor that produces a primitive type.
pub struct PrimitiveVisitor<T> { struct PrimitiveVisitor<T> {
marker: PhantomData<T>, marker: PhantomData<T>,
} }
impl<T> PrimitiveVisitor<T> { impl<T> PrimitiveVisitor<T> {
/// Construct a new `PrimitiveVisitor`. /// Construct a new `PrimitiveVisitor`.
#[inline] #[inline]
pub fn new() -> Self { fn new() -> Self {
PrimitiveVisitor { PrimitiveVisitor {
marker: PhantomData, marker: PhantomData,
} }
} }
} }
impl< impl<T> Visitor for PrimitiveVisitor<T>
T: Deserialize + FromPrimitive + str::FromStr where T: Deserialize + FromPrimitive + str::FromStr
> Visitor for PrimitiveVisitor<T> { {
type Value = T; type Value = T;
impl_deserialize_num_method!(isize, visit_isize, from_isize, Type::Isize); impl_deserialize_num_method!(isize, visit_isize, from_isize, Type::Isize);
@@ -155,7 +155,7 @@ impl<
where E: Error, where E: Error,
{ {
str::FromStr::from_str(v.trim()).or_else(|_| { str::FromStr::from_str(v.trim()).or_else(|_| {
Err(Error::type_mismatch(Type::Str)) Err(Error::invalid_type(Type::Str))
}) })
} }
} }
@@ -207,7 +207,7 @@ impl Visitor for CharVisitor {
let mut iter = v.chars(); let mut iter = v.chars();
if let Some(v) = iter.next() { if let Some(v) = iter.next() {
if iter.next().is_some() { if iter.next().is_some() {
Err(Error::type_mismatch(Type::Char)) Err(Error::invalid_type(Type::Char))
} else { } else {
Ok(v) Ok(v)
} }
@@ -250,7 +250,7 @@ impl Visitor for StringVisitor {
{ {
match str::from_utf8(v) { match str::from_utf8(v) {
Ok(s) => Ok(s.to_owned()), Ok(s) => Ok(s.to_owned()),
Err(_) => Err(Error::type_mismatch(Type::String)), Err(_) => Err(Error::invalid_type(Type::String)),
} }
} }
@@ -259,7 +259,7 @@ impl Visitor for StringVisitor {
{ {
match String::from_utf8(v) { match String::from_utf8(v) {
Ok(s) => Ok(s), Ok(s) => Ok(s),
Err(_) => Err(Error::type_mismatch(Type::String)), Err(_) => Err(Error::invalid_type(Type::String)),
} }
} }
} }
@@ -889,7 +889,7 @@ impl<T> Deserialize for NonZero<T> where T: Deserialize + PartialEq + Zeroable +
fn deserialize<D>(deserializer: &mut D) -> Result<NonZero<T>, D::Error> where D: Deserializer { fn deserialize<D>(deserializer: &mut D) -> Result<NonZero<T>, D::Error> where D: Deserializer {
let value = try!(Deserialize::deserialize(deserializer)); let value = try!(Deserialize::deserialize(deserializer));
if value == Zero::zero() { if value == Zero::zero() {
return Err(Error::syntax("expected a non-zero value")) return Err(Error::invalid_value("expected a non-zero value"))
} }
unsafe { unsafe {
Ok(NonZero::new(value)) Ok(NonZero::new(value))
@@ -941,7 +941,7 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
_ => { _ => {
match str::from_utf8(value) { match str::from_utf8(value) {
Ok(value) => Err(Error::unknown_field(value)), Ok(value) => Err(Error::unknown_field(value)),
Err(_) => Err(Error::type_mismatch(Type::String)), Err(_) => Err(Error::invalid_type(Type::String)),
} }
} }
} }
+44 -38
View File
@@ -12,44 +12,44 @@ mod from_primitive;
/// `Deserializer` error. /// `Deserializer` error.
pub trait Error: Sized + error::Error { pub trait Error: Sized + error::Error {
/// Raised when there is general error when deserializing a type. /// Raised when there is general error when deserializing a type.
fn syntax(msg: &str) -> Self; fn custom(msg: String) -> Self;
/// Raised when a fixed sized sequence or map was passed in the wrong amount of arguments.
fn length_mismatch(_len: usize) -> Self {
Error::syntax("incorrect length")
}
/// Raised when a `Deserialize` was passed an incorrect type.
fn type_mismatch(_type: Type) -> Self {
Error::syntax("incorrect type")
}
/// Raised when a `Deserialize` was passed an incorrect value.
fn invalid_value(msg: &str) -> Self {
Error::syntax(msg)
}
/// Raised when a `Deserialize` type unexpectedly hit the end of the stream. /// Raised when a `Deserialize` type unexpectedly hit the end of the stream.
fn end_of_stream() -> Self; fn end_of_stream() -> Self;
/// Raised when a `Deserialize` struct type received an unexpected struct field. /// Raised when a `Deserialize` was passed an incorrect type.
fn unknown_field(field: &str) -> Self { fn invalid_type(ty: Type) -> Self {
Error::syntax(&format!("Unknown field `{}`", field)) Error::custom(format!("Invalid type. Expected `{:?}`", ty))
}
/// Raised when a `Deserialize` was passed an incorrect value.
fn invalid_value(msg: &str) -> Self {
Error::custom(format!("Invalid value: {}", msg))
}
/// Raised when a fixed sized sequence or map was passed in the wrong amount of arguments.
fn invalid_length(len: usize) -> Self {
Error::custom(format!("Invalid length: {}", len))
} }
/// Raised when a `Deserialize` enum type received an unexpected variant. /// Raised when a `Deserialize` enum type received an unexpected variant.
fn unknown_variant(field: &str) -> Self { fn unknown_variant(field: &str) -> Self {
Error::syntax(&format!("Unknown variant `{}`", field)) Error::custom(format!("Unknown variant `{}`", field))
}
/// Raised when a `Deserialize` struct type received an unexpected struct field.
fn unknown_field(field: &str) -> Self {
Error::custom(format!("Unknown field `{}`", field))
} }
/// raised when a `deserialize` struct type did not receive a field. /// raised when a `deserialize` struct type did not receive a field.
fn missing_field(field: &'static str) -> Self { fn missing_field(field: &'static str) -> Self {
Error::syntax(&format!("Missing field `{}`", field)) Error::custom(format!("Missing field `{}`", field))
} }
} }
/// `Type` represents all the primitive types that can be deserialized. This is used by /// `Type` represents all the primitive types that can be deserialized. This is used by
/// `Error::kind_mismatch`. /// `Error::invalid_type`.
#[derive(Copy, Clone, PartialEq, Eq, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Type { pub enum Type {
/// Represents a `bool` type. /// Represents a `bool` type.
@@ -124,12 +124,18 @@ pub enum Type {
/// Represents a struct type. /// Represents a struct type.
Struct, Struct,
/// Represents a struct field name.
FieldName,
/// Represents a tuple type. /// Represents a tuple type.
Tuple, Tuple,
/// Represents an `enum` type. /// Represents an `enum` type.
Enum, Enum,
/// Represents an enum variant name.
VariantName,
/// Represents a struct variant. /// Represents a struct variant.
StructVariant, StructVariant,
@@ -416,7 +422,7 @@ pub trait Deserializer {
_visitor: V) -> Result<V::Value, Self::Error> _visitor: V) -> Result<V::Value, Self::Error>
where V: EnumVisitor, where V: EnumVisitor,
{ {
Err(Error::syntax("expected an enum")) Err(Error::invalid_type(Type::Enum))
} }
/// This method hints that the `Deserialize` type is expecting a `Vec<u8>`. This allows /// This method hints that the `Deserialize` type is expecting a `Vec<u8>`. This allows
@@ -460,7 +466,7 @@ pub trait Visitor {
fn visit_bool<E>(&mut self, _v: bool) -> Result<Self::Value, E> fn visit_bool<E>(&mut self, _v: bool) -> Result<Self::Value, E>
where E: Error, where E: Error,
{ {
Err(Error::type_mismatch(Type::Bool)) Err(Error::invalid_type(Type::Bool))
} }
/// `visit_isize` deserializes a `isize` into a `Value`. /// `visit_isize` deserializes a `isize` into a `Value`.
@@ -495,7 +501,7 @@ pub trait Visitor {
fn visit_i64<E>(&mut self, _v: i64) -> Result<Self::Value, E> fn visit_i64<E>(&mut self, _v: i64) -> Result<Self::Value, E>
where E: Error, where E: Error,
{ {
Err(Error::type_mismatch(Type::I64)) Err(Error::invalid_type(Type::I64))
} }
/// `visit_usize` deserializes a `usize` into a `Value`. /// `visit_usize` deserializes a `usize` into a `Value`.
@@ -530,7 +536,7 @@ pub trait Visitor {
fn visit_u64<E>(&mut self, _v: u64) -> Result<Self::Value, E> fn visit_u64<E>(&mut self, _v: u64) -> Result<Self::Value, E>
where E: Error, where E: Error,
{ {
Err(Error::type_mismatch(Type::U64)) Err(Error::invalid_type(Type::U64))
} }
/// `visit_f32` deserializes a `f32` into a `Value`. /// `visit_f32` deserializes a `f32` into a `Value`.
@@ -544,7 +550,7 @@ pub trait Visitor {
fn visit_f64<E>(&mut self, _v: f64) -> Result<Self::Value, E> fn visit_f64<E>(&mut self, _v: f64) -> Result<Self::Value, E>
where E: Error, where E: Error,
{ {
Err(Error::type_mismatch(Type::F64)) Err(Error::invalid_type(Type::F64))
} }
/// `visit_char` deserializes a `char` into a `Value`. /// `visit_char` deserializes a `char` into a `Value`.
@@ -561,7 +567,7 @@ pub trait Visitor {
fn visit_str<E>(&mut self, _v: &str) -> Result<Self::Value, E> fn visit_str<E>(&mut self, _v: &str) -> Result<Self::Value, E>
where E: Error, where E: Error,
{ {
Err(Error::type_mismatch(Type::Str)) Err(Error::invalid_type(Type::Str))
} }
/// `visit_string` deserializes a `String` into a `Value`. This allows a deserializer to avoid /// `visit_string` deserializes a `String` into a `Value`. This allows a deserializer to avoid
@@ -578,7 +584,7 @@ pub trait Visitor {
fn visit_unit<E>(&mut self) -> Result<Self::Value, E> fn visit_unit<E>(&mut self) -> Result<Self::Value, E>
where E: Error, where E: Error,
{ {
Err(Error::type_mismatch(Type::Unit)) Err(Error::invalid_type(Type::Unit))
} }
/// `visit_unit_struct` deserializes a unit struct into a `Value`. /// `visit_unit_struct` deserializes a unit struct into a `Value`.
@@ -593,42 +599,42 @@ pub trait Visitor {
fn visit_none<E>(&mut self) -> Result<Self::Value, E> fn visit_none<E>(&mut self) -> Result<Self::Value, E>
where E: Error, where E: Error,
{ {
Err(Error::type_mismatch(Type::Option)) Err(Error::invalid_type(Type::Option))
} }
/// `visit_some` deserializes a value into a `Value`. /// `visit_some` deserializes a value into a `Value`.
fn visit_some<D>(&mut self, _deserializer: &mut D) -> Result<Self::Value, D::Error> fn visit_some<D>(&mut self, _deserializer: &mut D) -> Result<Self::Value, D::Error>
where D: Deserializer, where D: Deserializer,
{ {
Err(Error::type_mismatch(Type::Option)) Err(Error::invalid_type(Type::Option))
} }
/// `visit_newtype_struct` deserializes a value into a `Value`. /// `visit_newtype_struct` deserializes a value into a `Value`.
fn visit_newtype_struct<D>(&mut self, _deserializer: &mut D) -> Result<Self::Value, D::Error> fn visit_newtype_struct<D>(&mut self, _deserializer: &mut D) -> Result<Self::Value, D::Error>
where D: Deserializer, where D: Deserializer,
{ {
Err(Error::type_mismatch(Type::NewtypeStruct)) Err(Error::invalid_type(Type::NewtypeStruct))
} }
/// `visit_bool` deserializes a `SeqVisitor` into a `Value`. /// `visit_bool` deserializes a `SeqVisitor` into a `Value`.
fn visit_seq<V>(&mut self, _visitor: V) -> Result<Self::Value, V::Error> fn visit_seq<V>(&mut self, _visitor: V) -> Result<Self::Value, V::Error>
where V: SeqVisitor, where V: SeqVisitor,
{ {
Err(Error::type_mismatch(Type::Seq)) Err(Error::invalid_type(Type::Seq))
} }
/// `visit_map` deserializes a `MapVisitor` into a `Value`. /// `visit_map` deserializes a `MapVisitor` into a `Value`.
fn visit_map<V>(&mut self, _visitor: V) -> Result<Self::Value, V::Error> fn visit_map<V>(&mut self, _visitor: V) -> Result<Self::Value, V::Error>
where V: MapVisitor, where V: MapVisitor,
{ {
Err(Error::type_mismatch(Type::Map)) Err(Error::invalid_type(Type::Map))
} }
/// `visit_bytes` deserializes a `&[u8]` into a `Value`. /// `visit_bytes` deserializes a `&[u8]` into a `Value`.
fn visit_bytes<E>(&mut self, _v: &[u8]) -> Result<Self::Value, E> fn visit_bytes<E>(&mut self, _v: &[u8]) -> Result<Self::Value, E>
where E: Error, where E: Error,
{ {
Err(Error::type_mismatch(Type::Bytes)) Err(Error::invalid_type(Type::Bytes))
} }
/// `visit_byte_buf` deserializes a `Vec<u8>` into a `Value`. /// `visit_byte_buf` deserializes a `Vec<u8>` into a `Value`.
@@ -799,7 +805,7 @@ pub trait VariantVisitor {
/// `visit_unit` is called when deserializing a variant with no values. /// `visit_unit` is called when deserializing a variant with no values.
fn visit_unit(&mut self) -> Result<(), Self::Error> { fn visit_unit(&mut self) -> Result<(), Self::Error> {
Err(Error::type_mismatch(Type::UnitVariant)) Err(Error::invalid_type(Type::UnitVariant))
} }
/// `visit_newtype` is called when deserializing a variant with a single value. By default this /// `visit_newtype` is called when deserializing a variant with a single value. By default this
@@ -818,7 +824,7 @@ pub trait VariantVisitor {
_visitor: V) -> Result<V::Value, Self::Error> _visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor where V: Visitor
{ {
Err(Error::type_mismatch(Type::TupleVariant)) Err(Error::invalid_type(Type::TupleVariant))
} }
/// `visit_struct` is called when deserializing a struct-like variant. /// `visit_struct` is called when deserializing a struct-like variant.
@@ -827,7 +833,7 @@ pub trait VariantVisitor {
_visitor: V) -> Result<V::Value, Self::Error> _visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor where V: Visitor
{ {
Err(Error::type_mismatch(Type::StructVariant)) Err(Error::invalid_type(Type::StructVariant))
} }
} }
+28 -14
View File
@@ -24,18 +24,24 @@ use bytes;
/// This represents all the possible errors that can occur using the `ValueDeserializer`. /// This represents all the possible errors that can occur using the `ValueDeserializer`.
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub enum Error { pub enum Error {
/// The value had some syntatic error. /// The value had some custom error.
Syntax(String), Custom(String),
/// The value had an incorrect type. /// The value had an incorrect type.
Type(de::Type), InvalidType(de::Type),
/// The value had an invalid length. /// The value had an invalid length.
Length(usize), InvalidLength(usize),
/// The value is invalid and cannot be deserialized.
InvalidValue(String),
/// EOF while deserializing a value. /// EOF while deserializing a value.
EndOfStream, EndOfStream,
/// Unknown variant in enum.
UnknownVariant(String),
/// Unknown field in struct. /// Unknown field in struct.
UnknownField(String), UnknownField(String),
@@ -44,10 +50,12 @@ pub enum Error {
} }
impl de::Error for Error { impl de::Error for Error {
fn syntax(msg: &str) -> Self { Error::Syntax(String::from(msg)) } fn custom(msg: String) -> Self { Error::Custom(msg) }
fn type_mismatch(type_: de::Type) -> Self { Error::Type(type_) }
fn length_mismatch(len: usize) -> Self { Error::Length(len) }
fn end_of_stream() -> Self { Error::EndOfStream } fn end_of_stream() -> Self { Error::EndOfStream }
fn invalid_type(ty: de::Type) -> Self { Error::InvalidType(ty) }
fn invalid_value(msg: &str) -> Self { Error::InvalidValue(msg.to_owned()) }
fn invalid_length(len: usize) -> Self { Error::InvalidLength(len) }
fn unknown_variant(variant: &str) -> Self { Error::UnknownVariant(String::from(variant)) }
fn unknown_field(field: &str) -> Self { Error::UnknownField(String::from(field)) } fn unknown_field(field: &str) -> Self { Error::UnknownField(String::from(field)) }
fn missing_field(field: &'static str) -> Self { Error::MissingField(field) } fn missing_field(field: &'static str) -> Self { Error::MissingField(field) }
} }
@@ -55,10 +63,14 @@ impl de::Error for Error {
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self { match *self {
Error::Syntax(ref s) => write!(formatter, "Syntax error: {}", s), Error::Custom(ref s) => write!(formatter, "{}", s),
Error::Type(ty) => write!(formatter, "Invalid type: {:?}", ty), Error::EndOfStream => formatter.write_str("End of stream"),
Error::Length(len) => write!(formatter, "Invalid length: {}", len), Error::InvalidType(ty) => write!(formatter, "Invalid type, expected `{:?}`", ty),
Error::EndOfStream => formatter.write_str("EndOfStreamError"), Error::InvalidValue(ref value) => write!(formatter, "Invalid value: {}", value),
Error::InvalidLength(len) => write!(formatter, "Invalid length: {}", len),
Error::UnknownVariant(ref variant) => {
write!(formatter, "Unknown variant: {}", variant)
}
Error::UnknownField(ref field) => write!(formatter, "Unknown field: {}", field), Error::UnknownField(ref field) => write!(formatter, "Unknown field: {}", field),
Error::MissingField(ref field) => write!(formatter, "Missing field: {}", field), Error::MissingField(ref field) => write!(formatter, "Missing field: {}", field),
} }
@@ -338,7 +350,7 @@ impl<I, T, E> de::SeqVisitor for SeqDeserializer<I, E>
if self.len == 0 { if self.len == 0 {
Ok(()) Ok(())
} else { } else {
Err(de::Error::length_mismatch(self.len)) Err(de::Error::invalid_length(self.len))
} }
} }
@@ -494,7 +506,9 @@ impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
let mut de = value.into_deserializer(); let mut de = value.into_deserializer();
de::Deserialize::deserialize(&mut de) de::Deserialize::deserialize(&mut de)
} }
None => Err(de::Error::syntax("expected a map value")) None => {
Err(de::Error::end_of_stream())
}
} }
} }
@@ -502,7 +516,7 @@ impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
if self.len == 0 { if self.len == 0 {
Ok(()) Ok(())
} else { } else {
Err(de::Error::length_mismatch(self.len)) Err(de::Error::invalid_length(self.len))
} }
} }
+2 -2
View File
@@ -10,11 +10,11 @@ pub mod impls;
/// `Serializer` error. /// `Serializer` error.
pub trait Error: Sized + error::Error { pub trait Error: Sized + error::Error {
/// Raised when there is general error when deserializing a type. /// Raised when there is general error when deserializing a type.
fn syntax(msg: &str) -> Self; fn custom(msg: String) -> Self;
/// Raised when a `Serialize` was passed an incorrect value. /// Raised when a `Serialize` was passed an incorrect value.
fn invalid_value(msg: &str) -> Self { fn invalid_value(msg: &str) -> Self {
Error::syntax(msg) Error::custom(format!("invalid value: {}", msg))
} }
} }
+99 -98
View File
@@ -5,7 +5,7 @@ use syntax::codemap::Span;
use syntax::ext::base::ExtCtxt; use syntax::ext::base::ExtCtxt;
use syntax::fold::Folder; use syntax::fold::Folder;
use syntax::parse::parser::PathParsingMode; use syntax::parse::parser::PathParsingMode;
use syntax::parse::token; use syntax::parse::token::{self, InternedString};
use syntax::parse; use syntax::parse;
use syntax::print::pprust::{lit_to_string, meta_item_to_string}; use syntax::print::pprust::{lit_to_string, meta_item_to_string};
use syntax::ptr::P; use syntax::ptr::P;
@@ -14,22 +14,66 @@ use aster::AstBuilder;
use error::Error; use error::Error;
#[derive(Debug)]
pub struct Name {
ident: ast::Ident,
serialize_name: Option<InternedString>,
deserialize_name: Option<InternedString>,
}
impl Name {
fn new(ident: ast::Ident) -> Self {
Name {
ident: ident,
serialize_name: None,
deserialize_name: None,
}
}
/// Return the string expression of the field ident.
pub fn ident_expr(&self) -> P<ast::Expr> {
AstBuilder::new().expr().str(self.ident)
}
/// Return the container name for the container when serializing.
pub fn serialize_name(&self) -> InternedString {
match self.serialize_name {
Some(ref name) => name.clone(),
None => self.ident.name.as_str(),
}
}
/// Return the container name expression for the container when deserializing.
pub fn serialize_name_expr(&self) -> P<ast::Expr> {
AstBuilder::new().expr().str(self.serialize_name())
}
/// Return the container name for the container when deserializing.
pub fn deserialize_name(&self) -> InternedString {
match self.deserialize_name {
Some(ref name) => name.clone(),
None => self.ident.name.as_str(),
}
}
/// Return the container name expression for the container when deserializing.
pub fn deserialize_name_expr(&self) -> P<ast::Expr> {
AstBuilder::new().expr().str(self.deserialize_name())
}
}
/// Represents container (e.g. struct) attribute information /// Represents container (e.g. struct) attribute information
#[derive(Debug)] #[derive(Debug)]
pub struct ContainerAttrs { pub struct ContainerAttrs {
ident: ast::Ident, name: Name,
serialize_name: Option<ast::Lit>,
deserialize_name: Option<ast::Lit>,
deny_unknown_fields: bool, deny_unknown_fields: bool,
} }
impl ContainerAttrs { impl ContainerAttrs {
/// Extract out the `#[serde(...)]` attributes from an item. /// Extract out the `#[serde(...)]` attributes from an item.
pub fn from_item(cx: &ExtCtxt, item: &ast::Item) -> Result<ContainerAttrs, Error> { pub fn from_item(cx: &ExtCtxt, item: &ast::Item) -> Result<Self, Error> {
let mut container_attrs = ContainerAttrs { let mut container_attrs = ContainerAttrs {
ident: item.ident, name: Name::new(item.ident),
serialize_name: None,
deserialize_name: None,
deny_unknown_fields: false, deny_unknown_fields: false,
}; };
@@ -38,15 +82,18 @@ impl ContainerAttrs {
match meta_item.node { match meta_item.node {
// Parse `#[serde(rename="foo")]` // Parse `#[serde(rename="foo")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => { ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
container_attrs.serialize_name = Some(lit.clone()); let s = try!(get_str_from_lit(cx, name, lit));
container_attrs.deserialize_name = Some(lit.clone());
container_attrs.name.serialize_name = Some(s.clone());
container_attrs.name.deserialize_name = Some(s);
} }
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]` // Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => { ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
let (ser_name, de_name) = try!(get_renames(cx, meta_items)); let (ser_name, de_name) = try!(get_renames(cx, meta_items));
container_attrs.serialize_name = ser_name;
container_attrs.deserialize_name = de_name; container_attrs.name.serialize_name = ser_name;
container_attrs.name.deserialize_name = de_name;
} }
// Parse `#[serde(deny_unknown_fields)]` // Parse `#[serde(deny_unknown_fields)]`
@@ -69,25 +116,8 @@ impl ContainerAttrs {
Ok(container_attrs) Ok(container_attrs)
} }
/// Return the string expression of the field ident. pub fn name(&self) -> &Name {
pub fn ident_expr(&self) -> P<ast::Expr> { &self.name
AstBuilder::new().expr().str(self.ident)
}
/// Return the field name for the field when serializing.
pub fn serialize_name_expr(&self) -> P<ast::Expr> {
match self.serialize_name {
Some(ref name) => AstBuilder::new().expr().build_lit(P(name.clone())),
None => self.ident_expr(),
}
}
/// Return the field name for the field when serializing.
pub fn deserialize_name_expr(&self) -> P<ast::Expr> {
match self.deserialize_name {
Some(ref name) => AstBuilder::new().expr().build_lit(P(name.clone())),
None => self.ident_expr(),
}
} }
pub fn deny_unknown_fields(&self) -> bool { pub fn deny_unknown_fields(&self) -> bool {
@@ -98,17 +128,13 @@ impl ContainerAttrs {
/// Represents variant attribute information /// Represents variant attribute information
#[derive(Debug)] #[derive(Debug)]
pub struct VariantAttrs { pub struct VariantAttrs {
ident: ast::Ident, name: Name,
serialize_name: Option<ast::Lit>,
deserialize_name: Option<ast::Lit>,
} }
impl VariantAttrs { impl VariantAttrs {
pub fn from_variant(cx: &ExtCtxt, variant: &ast::Variant) -> Result<Self, Error> { pub fn from_variant(cx: &ExtCtxt, variant: &ast::Variant) -> Result<Self, Error> {
let mut variant_attrs = VariantAttrs { let mut variant_attrs = VariantAttrs {
ident: variant.node.name, name: Name::new(variant.node.name),
serialize_name: None,
deserialize_name: None,
}; };
for meta_items in variant.node.attrs.iter().filter_map(get_serde_meta_items) { for meta_items in variant.node.attrs.iter().filter_map(get_serde_meta_items) {
@@ -116,15 +142,18 @@ impl VariantAttrs {
match meta_item.node { match meta_item.node {
// Parse `#[serde(rename="foo")]` // Parse `#[serde(rename="foo")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => { ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
variant_attrs.serialize_name = Some(lit.clone()); let s = try!(get_str_from_lit(cx, name, lit));
variant_attrs.deserialize_name = Some(lit.clone());
variant_attrs.name.serialize_name = Some(s.clone());
variant_attrs.name.deserialize_name = Some(s);
} }
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]` // Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => { ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
let (ser_name, de_name) = try!(get_renames(cx, meta_items)); let (ser_name, de_name) = try!(get_renames(cx, meta_items));
variant_attrs.serialize_name = ser_name;
variant_attrs.deserialize_name = de_name; variant_attrs.name.serialize_name = ser_name;
variant_attrs.name.deserialize_name = de_name;
} }
_ => { _ => {
@@ -142,34 +171,15 @@ impl VariantAttrs {
Ok(variant_attrs) Ok(variant_attrs)
} }
/// Return the string expression of the field ident. pub fn name(&self) -> &Name {
pub fn ident_expr(&self) -> P<ast::Expr> { &self.name
AstBuilder::new().expr().str(self.ident)
}
/// Return the field name for the field when serializing.
pub fn serialize_name_expr(&self) -> P<ast::Expr> {
match self.serialize_name {
Some(ref name) => AstBuilder::new().expr().build_lit(P(name.clone())),
None => self.ident_expr(),
}
}
/// Return the field name for the field when serializing.
pub fn deserialize_name_expr(&self) -> P<ast::Expr> {
match self.deserialize_name {
Some(ref name) => AstBuilder::new().expr().build_lit(P(name.clone())),
None => self.ident_expr(),
}
} }
} }
/// Represents field attribute information /// Represents field attribute information
#[derive(Debug)] #[derive(Debug)]
pub struct FieldAttrs { pub struct FieldAttrs {
ident: ast::Ident, name: Name,
serialize_name: Option<ast::Lit>,
deserialize_name: Option<ast::Lit>,
skip_serializing_field: bool, skip_serializing_field: bool,
skip_serializing_field_if: Option<P<ast::Expr>>, skip_serializing_field_if: Option<P<ast::Expr>>,
default_expr_if_missing: Option<P<ast::Expr>>, default_expr_if_missing: Option<P<ast::Expr>>,
@@ -192,9 +202,7 @@ impl FieldAttrs {
}; };
let mut field_attrs = FieldAttrs { let mut field_attrs = FieldAttrs {
ident: field_ident, name: Name::new(field_ident),
serialize_name: None,
deserialize_name: None,
skip_serializing_field: false, skip_serializing_field: false,
skip_serializing_field_if: None, skip_serializing_field_if: None,
default_expr_if_missing: None, default_expr_if_missing: None,
@@ -207,15 +215,18 @@ impl FieldAttrs {
match meta_item.node { match meta_item.node {
// Parse `#[serde(rename="foo")]` // Parse `#[serde(rename="foo")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => { ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
field_attrs.serialize_name = Some(lit.clone()); let s = try!(get_str_from_lit(cx, name, lit));
field_attrs.deserialize_name = Some(lit.clone());
field_attrs.name.serialize_name = Some(s.clone());
field_attrs.name.deserialize_name = Some(s);
} }
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]` // Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => { ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
let (ser_name, de_name) = try!(get_renames(cx, meta_items)); let (ser_name, de_name) = try!(get_renames(cx, meta_items));
field_attrs.serialize_name = ser_name;
field_attrs.deserialize_name = de_name; field_attrs.name.serialize_name = ser_name;
field_attrs.name.deserialize_name = de_name;
} }
// Parse `#[serde(default)]` // Parse `#[serde(default)]`
@@ -290,25 +301,8 @@ impl FieldAttrs {
Ok(field_attrs) Ok(field_attrs)
} }
/// Return the string expression of the field ident. pub fn name(&self) -> &Name {
pub fn ident_expr(&self) -> P<ast::Expr> { &self.name
AstBuilder::new().expr().str(self.ident)
}
/// Return the field name for the field when serializing.
pub fn serialize_name_expr(&self) -> P<ast::Expr> {
match self.serialize_name {
Some(ref name) => AstBuilder::new().expr().build_lit(P(name.clone())),
None => self.ident_expr(),
}
}
/// Return the field name for the field when deserializing.
pub fn deserialize_name_expr(&self) -> P<ast::Expr> {
match self.deserialize_name {
Some(ref name) => AstBuilder::new().expr().build_lit(P(name.clone())),
None => self.ident_expr(),
}
} }
/// Predicate for using a field's default value /// Predicate for using a field's default value
@@ -316,7 +310,7 @@ impl FieldAttrs {
match self.default_expr_if_missing { match self.default_expr_if_missing {
Some(ref expr) => expr.clone(), Some(ref expr) => expr.clone(),
None => { None => {
let name = self.ident_expr(); let name = self.name.ident_expr();
AstBuilder::new().expr() AstBuilder::new().expr()
.try() .try()
.method_call("missing_field").id("visitor") .method_call("missing_field").id("visitor")
@@ -357,18 +351,21 @@ pub fn get_struct_field_attrs(cx: &ExtCtxt,
} }
fn get_renames(cx: &ExtCtxt, fn get_renames(cx: &ExtCtxt,
items: &[P<ast::MetaItem>]) -> Result<(Option<ast::Lit>, Option<ast::Lit>), Error> { items: &[P<ast::MetaItem>],
)-> Result<(Option<InternedString>, Option<InternedString>), Error> {
let mut ser_name = None; let mut ser_name = None;
let mut de_name = None; let mut de_name = None;
for item in items { for item in items {
match item.node { match item.node {
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"serialize" => { ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"serialize" => {
ser_name = Some(lit.clone()); let s = try!(get_str_from_lit(cx, name, lit));
ser_name = Some(s);
} }
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"deserialize" => { ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"deserialize" => {
de_name = Some(lit.clone()); let s = try!(get_str_from_lit(cx, name, lit));
de_name = Some(s);
} }
_ => { _ => {
@@ -442,9 +439,9 @@ impl<'a, 'b> Folder for Respanner<'a, 'b> {
} }
} }
fn parse_lit_into_path(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<ast::Path, Error> { fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<InternedString, Error> {
let source: &str = match lit.node { match lit.node {
ast::LitKind::Str(ref source, _) => &source, ast::LitKind::Str(ref s, _) => Ok(s.clone()),
_ => { _ => {
cx.span_err( cx.span_err(
lit.span, lit.span,
@@ -454,7 +451,11 @@ fn parse_lit_into_path(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<ast::
return Err(Error); return Err(Error);
} }
}; }
}
fn parse_lit_into_path(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<ast::Path, Error> {
let source = try!(get_str_from_lit(cx, name, lit));
// If we just parse the string into an expression, any syntax errors in the source will only // If we just parse the string into an expression, any syntax errors in the source will only
// have spans that point inside the string, and not back to the attribute. So to have better // have spans that point inside the string, and not back to the attribute. So to have better
@@ -463,7 +464,7 @@ fn parse_lit_into_path(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<ast::
// and then finally parse them into an expression. // and then finally parse them into an expression.
let tts = parse::parse_tts_from_source_str( let tts = parse::parse_tts_from_source_str(
format!("<serde {} expansion>", name), format!("<serde {} expansion>", name),
source.to_owned(), (*source).to_owned(),
cx.cfg(), cx.cfg(),
cx.parse_sess()); cx.parse_sess());
+60 -26
View File
@@ -10,6 +10,7 @@ use syntax::ast::{
use syntax::codemap::Span; use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ext::build::AstBuilder; use syntax::ext::build::AstBuilder;
use syntax::parse::token::InternedString;
use syntax::ptr::P; use syntax::ptr::P;
use attr; use attr;
@@ -266,7 +267,7 @@ fn deserialize_unit_struct(
type_ident: Ident, type_ident: Ident,
container_attrs: &attr::ContainerAttrs, container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> { ) -> Result<P<ast::Expr>, Error> {
let type_name = container_attrs.deserialize_name_expr(); let type_name = container_attrs.name().deserialize_name_expr();
Ok(quote_expr!(cx, { Ok(quote_expr!(cx, {
struct __Visitor; struct __Visitor;
@@ -318,7 +319,7 @@ fn deserialize_newtype_struct(
1, 1,
); );
let type_name = container_attrs.deserialize_name_expr(); let type_name = container_attrs.name().deserialize_name_expr();
Ok(quote_expr!(cx, { Ok(quote_expr!(cx, {
$visitor_item $visitor_item
@@ -371,7 +372,7 @@ fn deserialize_tuple_struct(
fields, fields,
); );
let type_name = container_attrs.deserialize_name_expr(); let type_name = container_attrs.name().deserialize_name_expr();
Ok(quote_expr!(cx, { Ok(quote_expr!(cx, {
$visitor_item $visitor_item
@@ -510,7 +511,7 @@ fn deserialize_struct(
false, false,
)); ));
let type_name = container_attrs.deserialize_name_expr(); let type_name = container_attrs.name().deserialize_name_expr();
Ok(quote_expr!(cx, { Ok(quote_expr!(cx, {
$field_visitor $field_visitor
@@ -552,7 +553,7 @@ fn deserialize_item_enum(
) -> Result<P<ast::Expr>, Error> { ) -> Result<P<ast::Expr>, Error> {
let where_clause = &impl_generics.where_clause; let where_clause = &impl_generics.where_clause;
let type_name = container_attrs.deserialize_name_expr(); let type_name = container_attrs.name().deserialize_name_expr();
let variant_visitor = deserialize_field_visitor( let variant_visitor = deserialize_field_visitor(
cx, cx,
@@ -561,7 +562,7 @@ fn deserialize_item_enum(
enum_def.variants.iter() enum_def.variants.iter()
.map(|variant| { .map(|variant| {
let attrs = try!(attr::VariantAttrs::from_variant(cx, variant)); let attrs = try!(attr::VariantAttrs::from_variant(cx, variant));
Ok(attrs.deserialize_name_expr()) Ok(attrs.name().deserialize_name())
}) })
.collect() .collect()
), ),
@@ -806,12 +807,12 @@ fn deserialize_struct_variant(
fn deserialize_field_visitor( fn deserialize_field_visitor(
cx: &ExtCtxt, cx: &ExtCtxt,
builder: &aster::AstBuilder, builder: &aster::AstBuilder,
field_names: Vec<P<ast::Expr>>, field_names: Vec<InternedString>,
container_attrs: &attr::ContainerAttrs, container_attrs: &attr::ContainerAttrs,
is_variant: bool, is_variant: bool,
) -> Vec<P<ast::Item>> { ) -> Vec<P<ast::Item>> {
// Create the field names for the fields. // Create the field names for the fields.
let field_idents: Vec<ast::Ident> = (0 .. field_names.len()) let field_idents: Vec<_> = (0 .. field_names.len())
.map(|i| builder.id(format!("__field{}", i))) .map(|i| builder.id(format!("__field{}", i)))
.collect(); .collect();
@@ -846,22 +847,34 @@ fn deserialize_field_visitor(
(builder.expr().str("expected a field"), builder.id("unknown_field")) (builder.expr().str("expected a field"), builder.id("unknown_field"))
}; };
let fallthrough_index_arm_expr = if !is_variant && !container_attrs.deny_unknown_fields() {
quote_expr!(cx, Ok(__Field::__ignore))
} else {
quote_expr!(cx, {
Err(::serde::de::Error::invalid_value($index_error_msg))
})
};
let index_body = quote_expr!(cx, let index_body = quote_expr!(cx,
match value { match value {
$index_field_arms $index_field_arms
_ => { Err(::serde::de::Error::syntax($index_error_msg)) } _ => $fallthrough_index_arm_expr
} }
); );
// Convert the field names into byte strings.
let str_field_names: Vec<_> = field_names.iter()
.map(|name| builder.expr().lit().str(&name))
.collect();
// Match arms to extract a field from a string // Match arms to extract a field from a string
let default_field_arms: Vec<_> = field_idents.iter() let str_field_arms: Vec<_> = field_idents.iter().zip(str_field_names.iter())
.zip(field_names.iter())
.map(|(field_ident, field_name)| { .map(|(field_ident, field_name)| {
quote_arm!(cx, $field_name => { Ok(__Field::$field_ident) }) quote_arm!(cx, $field_name => { Ok(__Field::$field_ident) })
}) })
.collect(); .collect();
let fallthrough_arm_expr = if !is_variant && !container_attrs.deny_unknown_fields() { let fallthrough_str_arm_expr = if !is_variant && !container_attrs.deny_unknown_fields() {
quote_expr!(cx, Ok(__Field::__ignore)) quote_expr!(cx, Ok(__Field::__ignore))
} else { } else {
quote_expr!(cx, Err(::serde::de::Error::$unknown_ident(value))) quote_expr!(cx, Err(::serde::de::Error::$unknown_ident(value)))
@@ -869,8 +882,39 @@ fn deserialize_field_visitor(
let str_body = quote_expr!(cx, let str_body = quote_expr!(cx,
match value { match value {
$default_field_arms $str_field_arms
_ => $fallthrough_arm_expr _ => $fallthrough_str_arm_expr
}
);
// Convert the field names into byte strings.
let bytes_field_names: Vec<_> = field_names.iter()
.map(|name| {
let name: &str = name;
builder.expr().lit().byte_str(name)
})
.collect();
// Match arms to extract a field from a string
let bytes_field_arms: Vec<_> = field_idents.iter().zip(bytes_field_names.iter())
.map(|(field_ident, field_name)| {
quote_arm!(cx, $field_name => { Ok(__Field::$field_ident) })
})
.collect();
let fallthrough_bytes_arm_expr = if !is_variant && !container_attrs.deny_unknown_fields() {
quote_expr!(cx, Ok(__Field::__ignore))
} else {
quote_expr!(cx, {
let value = ::std::string::String::from_utf8_lossy(value);
Err(::serde::de::Error::$unknown_ident(&value))
})
};
let bytes_body = quote_expr!(cx,
match value {
$bytes_field_arms
_ => $fallthrough_bytes_arm_expr
} }
); );
@@ -906,17 +950,7 @@ fn deserialize_field_visitor(
fn visit_bytes<E>(&mut self, value: &[u8]) -> ::std::result::Result<__Field, E> fn visit_bytes<E>(&mut self, value: &[u8]) -> ::std::result::Result<__Field, E>
where E: ::serde::de::Error, where E: ::serde::de::Error,
{ {
// TODO: would be better to generate a byte string literal match $bytes_body
match ::std::str::from_utf8(value) {
Ok(s) => self.visit_str(s),
_ => {
Err(
::serde::de::Error::syntax(
"could not convert a byte string to a String"
)
)
}
}
} }
} }
@@ -947,7 +981,7 @@ fn deserialize_struct_visitor(
field, field,
is_enum) is_enum)
); );
Ok(field_attrs.deserialize_name_expr()) Ok(field_attrs.name().deserialize_name())
}) })
.collect(); .collect();
+8 -8
View File
@@ -185,7 +185,7 @@ fn serialize_unit_struct(
cx: &ExtCtxt, cx: &ExtCtxt,
container_attrs: &attr::ContainerAttrs, container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> { ) -> Result<P<ast::Expr>, Error> {
let type_name = container_attrs.serialize_name_expr(); let type_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx, Ok(quote_expr!(cx,
serializer.serialize_unit_struct($type_name) serializer.serialize_unit_struct($type_name)
@@ -196,7 +196,7 @@ fn serialize_newtype_struct(
cx: &ExtCtxt, cx: &ExtCtxt,
container_attrs: &attr::ContainerAttrs, container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> { ) -> Result<P<ast::Expr>, Error> {
let type_name = container_attrs.serialize_name_expr(); let type_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx, Ok(quote_expr!(cx,
serializer.serialize_newtype_struct($type_name, &self.0) serializer.serialize_newtype_struct($type_name, &self.0)
@@ -224,7 +224,7 @@ fn serialize_tuple_struct(
impl_generics, impl_generics,
); );
let type_name = container_attrs.serialize_name_expr(); let type_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx, { Ok(quote_expr!(cx, {
$visitor_struct $visitor_struct
@@ -259,7 +259,7 @@ fn serialize_struct(
false, false,
)); ));
let type_name = container_attrs.serialize_name_expr(); let type_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx, { Ok(quote_expr!(cx, {
$visitor_struct $visitor_struct
@@ -316,11 +316,11 @@ fn serialize_variant(
variant_index: usize, variant_index: usize,
container_attrs: &attr::ContainerAttrs, container_attrs: &attr::ContainerAttrs,
) -> Result<ast::Arm, Error> { ) -> Result<ast::Arm, Error> {
let type_name = container_attrs.serialize_name_expr(); let type_name = container_attrs.name().serialize_name_expr();
let variant_ident = variant.node.name; let variant_ident = variant.node.name;
let variant_attrs = try!(attr::VariantAttrs::from_variant(cx, variant)); let variant_attrs = try!(attr::VariantAttrs::from_variant(cx, variant));
let variant_name = variant_attrs.serialize_name_expr(); let variant_name = variant_attrs.name().serialize_name_expr();
match variant.node.data { match variant.node.data {
ast::VariantData::Unit(_) => { ast::VariantData::Unit(_) => {
@@ -551,7 +551,7 @@ fn serialize_struct_variant(
true, true,
)); ));
let container_name = container_attrs.serialize_name_expr(); let container_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx, { Ok(quote_expr!(cx, {
$variant_struct $variant_struct
@@ -658,7 +658,7 @@ fn serialize_struct_visitor(
.map(|(i, (ref field, ref field_attr))| { .map(|(i, (ref field, ref field_attr))| {
let name = field.node.ident().expect("struct has unnamed field"); let name = field.node.ident().expect("struct has unnamed field");
let key_expr = field_attr.serialize_name_expr(); let key_expr = field_attr.name().serialize_name_expr();
let stmt = if let Some(expr) = field_attr.skip_serializing_field_if() { let stmt = if let Some(expr) = field_attr.skip_serializing_field_if() {
Some(quote_stmt!(cx, if $expr { continue; })) Some(quote_stmt!(cx, if $expr { continue; }))
+70 -71
View File
@@ -17,18 +17,18 @@ pub enum Animal {
#[derive(Debug)] #[derive(Debug)]
pub enum Error { pub enum Error {
EndOfStreamError, EndOfStream,
SyntaxError, Syntax,
} }
impl serde::de::Error for Error { impl serde::de::Error for Error {
fn syntax(_: &str) -> Error { Error::SyntaxError } fn custom(_: String) -> Error { Error::Syntax }
fn end_of_stream() -> Error { Error::EndOfStreamError } fn end_of_stream() -> Error { Error::EndOfStream }
fn unknown_field(_: &str) -> Error { Error::SyntaxError } fn unknown_field(_: &str) -> Error { Error::Syntax }
fn missing_field(_: &'static str) -> Error { Error::SyntaxError } fn missing_field(_: &'static str) -> Error { Error::Syntax }
} }
impl fmt::Display for Error { impl fmt::Display for Error {
@@ -54,12 +54,11 @@ mod decoder {
use super::{Animal, Error}; use super::{Animal, Error};
use super::Animal::{Dog, Frog}; use super::Animal::{Dog, Frog};
use self::State::{AnimalState, IsizeState, StringState};
enum State { enum State {
AnimalState(Animal), Animal(Animal),
IsizeState(isize), Isize(isize),
StringState(String), String(String),
} }
pub struct AnimalDecoder { pub struct AnimalDecoder {
@@ -71,7 +70,7 @@ mod decoder {
#[inline] #[inline]
pub fn new(animal: Animal) -> AnimalDecoder { pub fn new(animal: Animal) -> AnimalDecoder {
AnimalDecoder { AnimalDecoder {
stack: vec!(AnimalState(animal)), stack: vec!(State::Animal(animal)),
} }
} }
} }
@@ -79,35 +78,35 @@ mod decoder {
impl Decoder for AnimalDecoder { impl Decoder for AnimalDecoder {
type Error = Error; type Error = Error;
fn error(&mut self, _: &str) -> Error { Error::SyntaxError } fn error(&mut self, _: &str) -> Error { Error::Syntax }
// Primitive types: // Primitive types:
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::SyntaxError) } fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::SyntaxError) } fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::Syntax) }
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) } fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) } fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) } fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::SyntaxError) } fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
#[inline] #[inline]
fn read_isize(&mut self) -> Result<isize, Error> { fn read_isize(&mut self) -> Result<isize, Error> {
match self.stack.pop() { match self.stack.pop() {
Some(IsizeState(x)) => Ok(x), Some(State::Isize(x)) => Ok(x),
_ => Err(Error::SyntaxError), _ => Err(Error::Syntax),
} }
} }
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) } fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) } fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) } fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) } fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) } fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) } fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) } fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
fn read_char(&mut self) -> Result<char, Error> { Err(Error::SyntaxError) } fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
#[inline] #[inline]
fn read_str(&mut self) -> Result<String, Error> { fn read_str(&mut self) -> Result<String, Error> {
match self.stack.pop() { match self.stack.pop() {
Some(StringState(x)) => Ok(x), Some(State::String(x)) => Ok(x),
_ => Err(Error::SyntaxError), _ => Err(Error::Syntax),
} }
} }
@@ -117,15 +116,15 @@ mod decoder {
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>, F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{ {
match self.stack.pop() { match self.stack.pop() {
Some(AnimalState(animal)) => { Some(State::Animal(animal)) => {
self.stack.push(AnimalState(animal)); self.stack.push(State::Animal(animal));
if name == "Animal" { if name == "Animal" {
f(self) f(self)
} else { } else {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
} }
_ => Err(Error::SyntaxError) _ => Err(Error::Syntax)
} }
} }
@@ -134,18 +133,18 @@ mod decoder {
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>, F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
{ {
let name = match self.stack.pop() { let name = match self.stack.pop() {
Some(AnimalState(Dog)) => "Dog", Some(State::Animal(Dog)) => "Dog",
Some(AnimalState(Frog(x0, x1))) => { Some(State::Animal(Frog(x0, x1))) => {
self.stack.push(IsizeState(x1)); self.stack.push(State::Isize(x1));
self.stack.push(StringState(x0)); self.stack.push(State::String(x0));
"Frog" "Frog"
} }
_ => { return Err(Error::SyntaxError); } _ => { return Err(Error::Syntax); }
}; };
let idx = match names.iter().position(|n| *n == name) { let idx = match names.iter().position(|n| *n == name) {
Some(idx) => idx, Some(idx) => idx,
None => { return Err(Error::SyntaxError); } None => { return Err(Error::Syntax); }
}; };
f(self, idx) f(self, idx)
@@ -161,56 +160,56 @@ mod decoder {
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>, F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>, F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>, F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>, F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>, F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>, F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>, F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>, F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
// Specialized types: // Specialized types:
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder, bool) -> Result<T, Error>, F: FnOnce(&mut AnimalDecoder, bool) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
#[inline] #[inline]
@@ -230,19 +229,19 @@ mod decoder {
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>, F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>, F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>, F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
} }
} }
@@ -256,10 +255,10 @@ mod deserializer {
#[derive(Debug)] #[derive(Debug)]
enum State { enum State {
AnimalState(Animal), Animal(Animal),
IsizeState(isize), Isize(isize),
StrState(&'static str), Str(&'static str),
StringState(String), String(String),
UnitState, UnitState,
} }
@@ -271,7 +270,7 @@ mod deserializer {
#[inline] #[inline]
pub fn new(animal: Animal) -> AnimalDeserializer { pub fn new(animal: Animal) -> AnimalDeserializer {
AnimalDeserializer { AnimalDeserializer {
stack: vec!(State::AnimalState(animal)), stack: vec!(State::Animal(animal)),
} }
} }
} }
@@ -284,23 +283,23 @@ mod deserializer {
where V: de::Visitor, where V: de::Visitor,
{ {
match self.stack.pop() { match self.stack.pop() {
Some(State::IsizeState(value)) => { Some(State::Isize(value)) => {
visitor.visit_isize(value) visitor.visit_isize(value)
} }
Some(State::StringState(value)) => { Some(State::String(value)) => {
visitor.visit_string(value) visitor.visit_string(value)
} }
Some(State::StrState(value)) => { Some(State::Str(value)) => {
visitor.visit_str(value) visitor.visit_str(value)
} }
Some(State::UnitState) => { Some(State::UnitState) => {
visitor.visit_unit() visitor.visit_unit()
} }
Some(_) => { Some(_) => {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
None => { None => {
Err(Error::EndOfStreamError) Err(Error::EndOfStream)
} }
} }
} }
@@ -313,27 +312,27 @@ mod deserializer {
where V: de::EnumVisitor, where V: de::EnumVisitor,
{ {
match self.stack.pop() { match self.stack.pop() {
Some(State::AnimalState(Animal::Dog)) => { Some(State::Animal(Animal::Dog)) => {
self.stack.push(State::UnitState); self.stack.push(State::UnitState);
self.stack.push(State::StrState("Dog")); self.stack.push(State::Str("Dog"));
visitor.visit(DogVisitor { visitor.visit(DogVisitor {
de: self, de: self,
}) })
} }
Some(State::AnimalState(Animal::Frog(x0, x1))) => { Some(State::Animal(Animal::Frog(x0, x1))) => {
self.stack.push(State::IsizeState(x1)); self.stack.push(State::Isize(x1));
self.stack.push(State::StringState(x0)); self.stack.push(State::String(x0));
self.stack.push(State::StrState("Frog")); self.stack.push(State::Str("Frog"));
visitor.visit(FrogVisitor { visitor.visit(FrogVisitor {
de: self, de: self,
state: 0, state: 0,
}) })
} }
Some(_) => { Some(_) => {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
None => { None => {
Err(Error::EndOfStreamError) Err(Error::EndOfStream)
} }
} }
} }
@@ -405,7 +404,7 @@ mod deserializer {
if self.state == 2 { if self.state == 2 {
Ok(()) Ok(())
} else { } else {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
} }
+56 -57
View File
@@ -14,16 +14,16 @@ use serde::de::{Deserializer, Deserialize};
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
pub enum Error { pub enum Error {
EndOfStream, EndOfStream,
SyntaxError, Syntax,
MissingField, MissingField,
} }
impl serde::de::Error for Error { impl serde::de::Error for Error {
fn syntax(_: &str) -> Error { Error::SyntaxError } fn custom(_: String) -> Error { Error::Syntax }
fn end_of_stream() -> Error { Error::EndOfStream } fn end_of_stream() -> Error { Error::EndOfStream }
fn unknown_field(_: &str) -> Error { Error::SyntaxError } fn unknown_field(_: &str) -> Error { Error::Syntax }
fn missing_field(_: &'static str) -> Error { fn missing_field(_: &'static str) -> Error {
Error::MissingField Error::MissingField
@@ -53,11 +53,10 @@ mod decoder {
use rustc_serialize; use rustc_serialize;
use super::Error; use super::Error;
use self::Value::{StringValue, IsizeValue};
enum Value { enum Value {
StringValue(String), String(String),
IsizeValue(isize), Isize(isize),
} }
pub struct IsizeDecoder { pub struct IsizeDecoder {
@@ -81,37 +80,37 @@ mod decoder {
type Error = Error; type Error = Error;
fn error(&mut self, _msg: &str) -> Error { fn error(&mut self, _msg: &str) -> Error {
Error::SyntaxError Error::Syntax
} }
// Primitive types: // Primitive types:
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::SyntaxError) } fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::SyntaxError) } fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::Syntax) }
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) } fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) } fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) } fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::SyntaxError) } fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
#[inline] #[inline]
fn read_isize(&mut self) -> Result<isize, Error> { fn read_isize(&mut self) -> Result<isize, Error> {
match self.stack.pop() { match self.stack.pop() {
Some(IsizeValue(x)) => Ok(x), Some(Value::Isize(x)) => Ok(x),
Some(_) => Err(Error::SyntaxError), Some(_) => Err(Error::Syntax),
None => Err(Error::EndOfStream), None => Err(Error::EndOfStream),
} }
} }
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) } fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) } fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) } fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) } fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) } fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) } fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) } fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
fn read_char(&mut self) -> Result<char, Error> { Err(Error::SyntaxError) } fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
#[inline] #[inline]
fn read_str(&mut self) -> Result<String, Error> { fn read_str(&mut self) -> Result<String, Error> {
match self.stack.pop() { match self.stack.pop() {
Some(StringValue(x)) => Ok(x), Some(Value::String(x)) => Ok(x),
Some(_) => Err(Error::SyntaxError), Some(_) => Err(Error::Syntax),
None => Err(Error::EndOfStream), None => Err(Error::EndOfStream),
} }
} }
@@ -120,86 +119,86 @@ mod decoder {
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>, F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>, F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
// Specialized types: // Specialized types:
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder, bool) -> Result<T, Error>, F: FnOnce(&mut IsizeDecoder, bool) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_seq<T, F>(&mut self, _f: F) -> Result<T, Error> where fn read_seq<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>, F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_seq_elt<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where fn read_seq_elt<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
#[inline] #[inline]
@@ -215,12 +214,12 @@ mod decoder {
{ {
match self.iter.next() { match self.iter.next() {
Some((key, value)) => { Some((key, value)) => {
self.stack.push(IsizeValue(value)); self.stack.push(Value::Isize(value));
self.stack.push(StringValue(key)); self.stack.push(Value::String(key));
f(self) f(self)
} }
None => { None => {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
} }
} }
@@ -247,8 +246,8 @@ mod deserializer {
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
enum State { enum State {
StartState, StartState,
KeyState(String), Key(String),
ValueState(isize), Value(isize),
} }
pub struct IsizeDeserializer { pub struct IsizeDeserializer {
@@ -276,10 +275,10 @@ mod deserializer {
Some(State::StartState) => { Some(State::StartState) => {
visitor.visit_map(self) visitor.visit_map(self)
} }
Some(State::KeyState(key)) => { Some(State::Key(key)) => {
visitor.visit_string(key) visitor.visit_string(key)
} }
Some(State::ValueState(value)) => { Some(State::Value(value)) => {
visitor.visit_isize(value) visitor.visit_isize(value)
} }
None => { None => {
@@ -297,8 +296,8 @@ mod deserializer {
{ {
match self.iter.next() { match self.iter.next() {
Some((key, value)) => { Some((key, value)) => {
self.stack.push(State::ValueState(value)); self.stack.push(State::Value(value));
self.stack.push(State::KeyState(key)); self.stack.push(State::Key(key));
Ok(Some(try!(de::Deserialize::deserialize(self)))) Ok(Some(try!(de::Deserialize::deserialize(self))))
} }
None => { None => {
@@ -315,7 +314,7 @@ mod deserializer {
fn end(&mut self) -> Result<(), Error> { fn end(&mut self) -> Result<(), Error> {
match self.iter.next() { match self.iter.next() {
Some(_) => Err(Error::SyntaxError), Some(_) => Err(Error::Syntax),
None => Ok(()), None => Ok(()),
} }
} }
@@ -332,14 +331,14 @@ mod deserializer {
#[inline] #[inline]
fn next(&mut self) -> Option<Result<de::Token, Error>> { fn next(&mut self) -> Option<Result<de::Token, Error>> {
match self.stack.pop() { match self.stack.pop() {
Some(StartState) => { Some(State::StartState) => {
self.stack.push(KeyOrEndState); self.stack.push(KeyOrEndState);
Some(Ok(de::Token::MapStart(self.len))) Some(Ok(de::Token::MapStart(self.len)))
} }
Some(KeyOrEndState) => { Some(State::KeyOrEndState) => {
match self.iter.next() { match self.iter.next() {
Some((key, value)) => { Some((key, value)) => {
self.stack.push(ValueState(value)); self.stack.push(Value(value));
Some(Ok(de::Token::String(key))) Some(Ok(de::Token::String(key)))
} }
None => { None => {
@@ -348,7 +347,7 @@ mod deserializer {
} }
} }
} }
Some(ValueState(x)) => { Some(State::Value(x)) => {
self.stack.push(KeyOrEndState); self.stack.push(KeyOrEndState);
Some(Ok(de::Token::Isize(x))) Some(Ok(de::Token::Isize(x)))
} }
@@ -370,24 +369,24 @@ mod deserializer {
#[inline] #[inline]
fn syntax(&mut self, _token: de::Token, _expected: &[de::TokenKind]) -> Error { fn syntax(&mut self, _token: de::Token, _expected: &[de::TokenKind]) -> Error {
SyntaxError Syntax
} }
#[inline] #[inline]
fn unexpected_name(&mut self, _token: de::Token) -> Error { fn unexpected_name(&mut self, _token: de::Token) -> Error {
SyntaxError Syntax
} }
#[inline] #[inline]
fn conversion_error(&mut self, _token: de::Token) -> Error { fn conversion_error(&mut self, _token: de::Token) -> Error {
SyntaxError Syntax
} }
#[inline] #[inline]
fn missing_field< fn missing_field<
T: de::Deserialize<IsizeDeserializer, Error> T: de::Deserialize<IsizeDeserializer, Error>
>(&mut self, _field: &'static str) -> Result<T, Error> { >(&mut self, _field: &'static str) -> Result<T, Error> {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
} }
*/ */
+114 -127
View File
@@ -29,17 +29,17 @@ pub struct Outer {
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum Error { pub enum Error {
EndOfStream, EndOfStream,
SyntaxError, Syntax,
MissingField, MissingField,
OtherError, OtherError,
} }
impl serde::de::Error for Error { impl serde::de::Error for Error {
fn syntax(_: &str) -> Error { Error::SyntaxError } fn custom(_: String) -> Error { Error::Syntax }
fn end_of_stream() -> Error { Error::EndOfStream } fn end_of_stream() -> Error { Error::EndOfStream }
fn unknown_field(_: &str) -> Error { Error::SyntaxError } fn unknown_field(_: &str) -> Error { Error::Syntax }
fn missing_field(_: &'static str) -> Error { fn missing_field(_: &'static str) -> Error {
Error::MissingField Error::MissingField
@@ -68,31 +68,18 @@ mod decoder {
use super::{Outer, Inner, Error}; use super::{Outer, Inner, Error};
use self::State::{
OuterState,
InnerState,
NullState,
UsizeState,
CharState,
StringState,
FieldState,
VecState,
MapState,
OptionState,
};
#[derive(Debug)] #[derive(Debug)]
enum State { enum State {
OuterState(Outer), Outer(Outer),
InnerState(Inner), Inner(Inner),
NullState, Null,
UsizeState(usize), Usize(usize),
CharState(char), Char(char),
StringState(String), String(String),
FieldState(&'static str), Field(&'static str),
VecState(Vec<Inner>), Vec(Vec<Inner>),
MapState(HashMap<String, Option<char>>), Map(HashMap<String, Option<char>>),
OptionState(bool), Option(bool),
} }
pub struct OuterDecoder { pub struct OuterDecoder {
@@ -104,7 +91,7 @@ mod decoder {
#[inline] #[inline]
pub fn new(animal: Outer) -> OuterDecoder { pub fn new(animal: Outer) -> OuterDecoder {
OuterDecoder { OuterDecoder {
stack: vec!(OuterState(animal)), stack: vec!(State::Outer(animal)),
} }
} }
} }
@@ -120,41 +107,41 @@ mod decoder {
#[inline] #[inline]
fn read_nil(&mut self) -> Result<(), Error> { fn read_nil(&mut self) -> Result<(), Error> {
match self.stack.pop() { match self.stack.pop() {
Some(NullState) => Ok(()), Some(State::Null) => Ok(()),
_ => Err(Error::SyntaxError), _ => Err(Error::Syntax),
} }
} }
#[inline] #[inline]
fn read_usize(&mut self) -> Result<usize, Error> { fn read_usize(&mut self) -> Result<usize, Error> {
match self.stack.pop() { match self.stack.pop() {
Some(UsizeState(value)) => Ok(value), Some(State::Usize(value)) => Ok(value),
_ => Err(Error::SyntaxError), _ => Err(Error::Syntax),
} }
} }
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) } fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) } fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) } fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::SyntaxError) } fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::SyntaxError) } fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::Syntax) }
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) } fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) } fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) } fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) } fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) } fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) } fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) } fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
#[inline] #[inline]
fn read_char(&mut self) -> Result<char, Error> { fn read_char(&mut self) -> Result<char, Error> {
match self.stack.pop() { match self.stack.pop() {
Some(CharState(c)) => Ok(c), Some(State::Char(c)) => Ok(c),
_ => Err(Error::SyntaxError), _ => Err(Error::Syntax),
} }
} }
#[inline] #[inline]
fn read_str(&mut self) -> Result<String, Error> { fn read_str(&mut self) -> Result<String, Error> {
match self.stack.pop() { match self.stack.pop() {
Some(StringState(value)) => Ok(value), Some(State::String(value)) => Ok(value),
_ => Err(Error::SyntaxError), _ => Err(Error::Syntax),
} }
} }
@@ -162,31 +149,31 @@ mod decoder {
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>, F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>, F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>, F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>, F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>, F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
#[inline] #[inline]
@@ -194,31 +181,31 @@ mod decoder {
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>, F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{ {
match self.stack.pop() { match self.stack.pop() {
Some(OuterState(Outer { inner })) => { Some(State::Outer(Outer { inner })) => {
if s_name == "Outer" { if s_name == "Outer" {
self.stack.push(VecState(inner)); self.stack.push(State::Vec(inner));
self.stack.push(FieldState("inner")); self.stack.push(State::Field("inner"));
f(self) f(self)
} else { } else {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
} }
Some(InnerState(Inner { a: (), b, c })) => { Some(State::Inner(Inner { a: (), b, c })) => {
if s_name == "Inner" { if s_name == "Inner" {
self.stack.push(MapState(c)); self.stack.push(State::Map(c));
self.stack.push(FieldState("c")); self.stack.push(State::Field("c"));
self.stack.push(UsizeState(b)); self.stack.push(State::Usize(b));
self.stack.push(FieldState("b")); self.stack.push(State::Field("b"));
self.stack.push(NullState); self.stack.push(State::Null);
self.stack.push(FieldState("a")); self.stack.push(State::Field("a"));
f(self) f(self)
} else { } else {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
} }
_ => Err(Error::SyntaxError), _ => Err(Error::Syntax),
} }
} }
#[inline] #[inline]
@@ -226,39 +213,39 @@ mod decoder {
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>, F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{ {
match self.stack.pop() { match self.stack.pop() {
Some(FieldState(name)) => { Some(State::Field(name)) => {
if f_name == name { if f_name == name {
f(self) f(self)
} else { } else {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
} }
_ => Err(Error::SyntaxError) _ => Err(Error::Syntax)
} }
} }
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>, F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>, F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>, F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>, F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
// Specialized types: // Specialized types:
@@ -267,8 +254,8 @@ mod decoder {
F: FnOnce(&mut OuterDecoder, bool) -> Result<T, Error>, F: FnOnce(&mut OuterDecoder, bool) -> Result<T, Error>,
{ {
match self.stack.pop() { match self.stack.pop() {
Some(OptionState(b)) => f(self, b), Some(State::Option(b)) => f(self, b),
_ => Err(Error::SyntaxError), _ => Err(Error::Syntax),
} }
} }
@@ -277,14 +264,14 @@ mod decoder {
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>, F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
{ {
match self.stack.pop() { match self.stack.pop() {
Some(VecState(value)) => { Some(State::Vec(value)) => {
let len = value.len(); let len = value.len();
for inner in value.into_iter().rev() { for inner in value.into_iter().rev() {
self.stack.push(InnerState(inner)); self.stack.push(State::Inner(inner));
} }
f(self, len) f(self, len)
} }
_ => Err(Error::SyntaxError) _ => Err(Error::Syntax)
} }
} }
#[inline] #[inline]
@@ -299,23 +286,23 @@ mod decoder {
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>, F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
{ {
match self.stack.pop() { match self.stack.pop() {
Some(MapState(map)) => { Some(State::Map(map)) => {
let len = map.len(); let len = map.len();
for (key, value) in map { for (key, value) in map {
match value { match value {
Some(c) => { Some(c) => {
self.stack.push(CharState(c)); self.stack.push(State::Char(c));
self.stack.push(OptionState(true)); self.stack.push(State::Option(true));
} }
None => { None => {
self.stack.push(OptionState(false)); self.stack.push(State::Option(false));
} }
} }
self.stack.push(StringState(key)); self.stack.push(State::String(key));
} }
f(self, len) f(self, len)
} }
_ => Err(Error::SyntaxError), _ => Err(Error::Syntax),
} }
} }
#[inline] #[inline]
@@ -346,16 +333,16 @@ mod deserializer {
#[derive(Debug)] #[derive(Debug)]
enum State { enum State {
OuterState(Outer), Outer(Outer),
InnerState(Inner), Inner(Inner),
StrState(&'static str), Str(&'static str),
NullState, Null,
UsizeState(usize), Usize(usize),
CharState(char), Char(char),
StringState(String), String(String),
OptionState(bool), Option(bool),
VecState(Vec<Inner>), Vec(Vec<Inner>),
MapState(HashMap<String, Option<char>>), Map(HashMap<String, Option<char>>),
} }
pub struct OuterDeserializer { pub struct OuterDeserializer {
@@ -366,7 +353,7 @@ mod deserializer {
#[inline] #[inline]
pub fn new(outer: Outer) -> OuterDeserializer { pub fn new(outer: Outer) -> OuterDeserializer {
OuterDeserializer { OuterDeserializer {
stack: vec!(State::OuterState(outer)), stack: vec!(State::Outer(outer)),
} }
} }
} }
@@ -378,40 +365,40 @@ mod deserializer {
where V: de::Visitor, where V: de::Visitor,
{ {
match self.stack.pop() { match self.stack.pop() {
Some(State::VecState(value)) => { Some(State::Vec(value)) => {
visitor.visit_seq(OuterSeqVisitor { visitor.visit_seq(OuterSeqVisitor {
de: self, de: self,
iter: value.into_iter(), iter: value.into_iter(),
}) })
} }
Some(State::MapState(value)) => { Some(State::Map(value)) => {
visitor.visit_map(MapVisitor { visitor.visit_map(MapVisitor {
de: self, de: self,
iter: value.into_iter(), iter: value.into_iter(),
}) })
} }
Some(State::NullState) => { Some(State::Null) => {
visitor.visit_unit() visitor.visit_unit()
} }
Some(State::UsizeState(x)) => { Some(State::Usize(x)) => {
visitor.visit_usize(x) visitor.visit_usize(x)
} }
Some(State::CharState(x)) => { Some(State::Char(x)) => {
visitor.visit_char(x) visitor.visit_char(x)
} }
Some(State::StrState(x)) => { Some(State::Str(x)) => {
visitor.visit_str(x) visitor.visit_str(x)
} }
Some(State::StringState(x)) => { Some(State::String(x)) => {
visitor.visit_string(x) visitor.visit_string(x)
} }
Some(State::OptionState(false)) => { Some(State::Option(false)) => {
visitor.visit_none() visitor.visit_none()
} }
Some(State::OptionState(true)) => { Some(State::Option(true)) => {
visitor.visit_some(self) visitor.visit_some(self)
} }
Some(_) => Err(Error::SyntaxError), Some(_) => Err(Error::Syntax),
None => Err(Error::EndOfStream), None => Err(Error::EndOfStream),
} }
} }
@@ -423,32 +410,32 @@ mod deserializer {
where V: de::Visitor, where V: de::Visitor,
{ {
match self.stack.pop() { match self.stack.pop() {
Some(State::OuterState(Outer { inner })) => { Some(State::Outer(Outer { inner })) => {
if name != "Outer" { if name != "Outer" {
return Err(Error::SyntaxError); return Err(Error::Syntax);
} }
self.stack.push(State::VecState(inner)); self.stack.push(State::Vec(inner));
self.stack.push(State::StrState("inner")); self.stack.push(State::Str("inner"));
visitor.visit_map(OuterMapVisitor { visitor.visit_map(OuterMapVisitor {
de: self, de: self,
state: 0, state: 0,
}) })
} }
Some(State::InnerState(Inner { a: (), b, c })) => { Some(State::Inner(Inner { a: (), b, c })) => {
if name != "Inner" { if name != "Inner" {
return Err(Error::SyntaxError); return Err(Error::Syntax);
} }
self.stack.push(State::MapState(c)); self.stack.push(State::Map(c));
self.stack.push(State::StrState("c")); self.stack.push(State::Str("c"));
self.stack.push(State::UsizeState(b)); self.stack.push(State::Usize(b));
self.stack.push(State::StrState("b")); self.stack.push(State::Str("b"));
self.stack.push(State::NullState); self.stack.push(State::Null);
self.stack.push(State::StrState("a")); self.stack.push(State::Str("a"));
visitor.visit_map(InnerMapVisitor { visitor.visit_map(InnerMapVisitor {
de: self, de: self,
@@ -456,7 +443,7 @@ mod deserializer {
}) })
} }
_ => { _ => {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
} }
} }
@@ -494,7 +481,7 @@ mod deserializer {
if self.state == 1 { if self.state == 1 {
Ok(()) Ok(())
} else { } else {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
} }
@@ -517,7 +504,7 @@ mod deserializer {
{ {
match self.iter.next() { match self.iter.next() {
Some(value) => { Some(value) => {
self.de.stack.push(State::InnerState(value)); self.de.stack.push(State::Inner(value));
Ok(Some(try!(de::Deserialize::deserialize(self.de)))) Ok(Some(try!(de::Deserialize::deserialize(self.de))))
} }
None => { None => {
@@ -528,7 +515,7 @@ mod deserializer {
fn end(&mut self) -> Result<(), Error> { fn end(&mut self) -> Result<(), Error> {
match self.iter.next() { match self.iter.next() {
Some(_) => Err(Error::SyntaxError), Some(_) => Err(Error::Syntax),
None => Ok(()), None => Ok(()),
} }
} }
@@ -570,7 +557,7 @@ mod deserializer {
if self.state == 3 { if self.state == 3 {
Ok(()) Ok(())
} else { } else {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
} }
@@ -593,14 +580,14 @@ mod deserializer {
{ {
match self.iter.next() { match self.iter.next() {
Some((key, Some(value))) => { Some((key, Some(value))) => {
self.de.stack.push(State::CharState(value)); self.de.stack.push(State::Char(value));
self.de.stack.push(State::OptionState(true)); self.de.stack.push(State::Option(true));
self.de.stack.push(State::StringState(key)); self.de.stack.push(State::String(key));
Ok(Some(try!(de::Deserialize::deserialize(self.de)))) Ok(Some(try!(de::Deserialize::deserialize(self.de))))
} }
Some((key, None)) => { Some((key, None)) => {
self.de.stack.push(State::OptionState(false)); self.de.stack.push(State::Option(false));
self.de.stack.push(State::StringState(key)); self.de.stack.push(State::String(key));
Ok(Some(try!(de::Deserialize::deserialize(self.de)))) Ok(Some(try!(de::Deserialize::deserialize(self.de))))
} }
None => { None => {
@@ -617,7 +604,7 @@ mod deserializer {
fn end(&mut self) -> Result<(), Error> { fn end(&mut self) -> Result<(), Error> {
match self.iter.next() { match self.iter.next() {
Some(_) => Err(Error::SyntaxError), Some(_) => Err(Error::Syntax),
None => Ok(()), None => Ok(()),
} }
} }
+90 -90
View File
@@ -12,18 +12,18 @@ use serde::de::{Deserializer, Deserialize};
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
pub enum Error { pub enum Error {
EndOfStreamError, EndOfStream,
SyntaxError, Syntax,
} }
impl serde::de::Error for Error { impl serde::de::Error for Error {
fn syntax(_: &str) -> Error { Error::SyntaxError } fn custom(_: String) -> Error { Error::Syntax }
fn end_of_stream() -> Error { Error::EndOfStreamError } fn end_of_stream() -> Error { Error::EndOfStream }
fn unknown_field(_: &str) -> Error { Error::SyntaxError } fn unknown_field(_: &str) -> Error { Error::Syntax }
fn missing_field(_: &'static str) -> Error { Error::SyntaxError } fn missing_field(_: &'static str) -> Error { Error::Syntax }
} }
impl fmt::Display for Error { impl fmt::Display for Error {
@@ -67,104 +67,104 @@ mod decoder {
impl rustc_serialize::Decoder for UsizeDecoder { impl rustc_serialize::Decoder for UsizeDecoder {
type Error = Error; type Error = Error;
fn error(&mut self, _: &str) -> Error { Error::SyntaxError } fn error(&mut self, _: &str) -> Error { Error::Syntax }
// Primitive types: // Primitive types:
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::SyntaxError) } fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
#[inline] #[inline]
fn read_usize(&mut self) -> Result<usize, Error> { fn read_usize(&mut self) -> Result<usize, Error> {
match self.iter.next() { match self.iter.next() {
Some(value) => Ok(value), Some(value) => Ok(value),
None => Err(Error::EndOfStreamError), None => Err(Error::EndOfStream),
} }
} }
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) } fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) } fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) } fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::SyntaxError) } fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::SyntaxError) } fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::Syntax) }
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) } fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) } fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) } fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) } fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) } fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) } fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) } fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
fn read_char(&mut self) -> Result<char, Error> { Err(Error::SyntaxError) } fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
fn read_str(&mut self) -> Result<String, Error> { Err(Error::SyntaxError) } fn read_str(&mut self) -> Result<String, Error> { Err(Error::Syntax) }
// Compound types: // Compound types:
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
// Specialized types: // Specialized types:
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder, bool) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder, bool) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
#[inline] #[inline]
@@ -184,19 +184,19 @@ mod decoder {
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>, F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
} }
@@ -219,105 +219,105 @@ mod decoder {
impl rustc_serialize::Decoder for U8Decoder { impl rustc_serialize::Decoder for U8Decoder {
type Error = Error; type Error = Error;
fn error(&mut self, _: &str) -> Error { Error::SyntaxError } fn error(&mut self, _: &str) -> Error { Error::Syntax }
// Primitive types: // Primitive types:
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::SyntaxError) } fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::SyntaxError) } fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::Syntax) }
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) } fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) } fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) } fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
#[inline] #[inline]
fn read_u8(&mut self) -> Result<u8, Error> { fn read_u8(&mut self) -> Result<u8, Error> {
match self.iter.next() { match self.iter.next() {
Some(value) => Ok(value), Some(value) => Ok(value),
None => Err(Error::EndOfStreamError), None => Err(Error::EndOfStream),
} }
} }
#[inline] #[inline]
fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::SyntaxError) } fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::Syntax) }
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) } fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) } fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) } fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) } fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) } fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) } fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) } fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
fn read_char(&mut self) -> Result<char, Error> { Err(Error::SyntaxError) } fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
fn read_str(&mut self) -> Result<String, Error> { Err(Error::SyntaxError) } fn read_str(&mut self) -> Result<String, Error> { Err(Error::Syntax) }
// Compound types: // Compound types:
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>, F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>, F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>, F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>, F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>, F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>, F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>, F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>, F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>, F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>, F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>, F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
// Specialized types: // Specialized types:
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder, bool) -> Result<T, Error>, F: FnOnce(&mut U8Decoder, bool) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
#[inline] #[inline]
@@ -337,19 +337,19 @@ mod decoder {
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>, F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>, F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>, F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{ {
Err(Error::SyntaxError) Err(Error::Syntax)
} }
} }
} }
@@ -366,9 +366,9 @@ mod deserializer {
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
enum State { enum State {
StartState, Start,
SepOrEndState, SepOrEnd,
EndState, End,
} }
pub struct Deserializer<A> { pub struct Deserializer<A> {
@@ -383,7 +383,7 @@ mod deserializer {
pub fn new(values: Vec<A>) -> Deserializer<A> { pub fn new(values: Vec<A>) -> Deserializer<A> {
let len = values.len(); let len = values.len();
Deserializer { Deserializer {
state: State::StartState, state: State::Start,
iter: values.into_iter(), iter: values.into_iter(),
len: len, len: len,
value: None, value: None,
@@ -399,15 +399,15 @@ mod deserializer {
where V: de::Visitor, where V: de::Visitor,
{ {
match self.state { match self.state {
State::StartState => { State::Start => {
self.state = State::SepOrEndState; self.state = State::SepOrEnd;
visitor.visit_seq(self) visitor.visit_seq(self)
} }
State::SepOrEndState => { State::SepOrEnd => {
visitor.visit_usize(self.value.take().unwrap()) visitor.visit_usize(self.value.take().unwrap())
} }
State::EndState => { State::End => {
Err(Error::EndOfStreamError) Err(Error::EndOfStream)
} }
} }
} }
@@ -427,7 +427,7 @@ mod deserializer {
Ok(Some(try!(de::Deserialize::deserialize(self)))) Ok(Some(try!(de::Deserialize::deserialize(self))))
} }
None => { None => {
self.state = State::EndState; self.state = State::End;
Ok(None) Ok(None)
} }
} }
@@ -436,9 +436,9 @@ mod deserializer {
#[inline] #[inline]
fn end(&mut self) -> Result<(), Error> { fn end(&mut self) -> Result<(), Error> {
match self.iter.next() { match self.iter.next() {
Some(_) => Err(Error::SyntaxError), Some(_) => Err(Error::Syntax),
None => { None => {
self.state = State::EndState; self.state = State::End;
Ok(()) Ok(())
} }
} }
@@ -458,15 +458,15 @@ mod deserializer {
where V: de::Visitor, where V: de::Visitor,
{ {
match self.state { match self.state {
State::StartState => { State::Start => {
self.state = State::SepOrEndState; self.state = State::SepOrEnd;
visitor.visit_seq(self) visitor.visit_seq(self)
} }
State::SepOrEndState => { State::SepOrEnd => {
visitor.visit_u8(self.value.take().unwrap()) visitor.visit_u8(self.value.take().unwrap())
} }
State::EndState => { State::End => {
Err(Error::EndOfStreamError) Err(Error::EndOfStream)
} }
} }
} }
@@ -486,7 +486,7 @@ mod deserializer {
Ok(Some(try!(de::Deserialize::deserialize(self)))) Ok(Some(try!(de::Deserialize::deserialize(self))))
} }
None => { None => {
self.state = State::EndState; self.state = State::End;
Ok(None) Ok(None)
} }
} }
@@ -495,9 +495,9 @@ mod deserializer {
#[inline] #[inline]
fn end(&mut self) -> Result<(), Error> { fn end(&mut self) -> Result<(), Error> {
match self.iter.next() { match self.iter.next() {
Some(_) => Err(Error::SyntaxError), Some(_) => Err(Error::Syntax),
None => { None => {
self.state = State::EndState; self.state = State::End;
Ok(()) Ok(())
} }
} }
+2 -8
View File
@@ -10,19 +10,13 @@ use serde::bytes::{ByteBuf, Bytes};
struct Error; struct Error;
impl serde::ser::Error for Error { impl serde::ser::Error for Error {
fn syntax(_: &str) -> Error { Error } fn custom(_: String) -> Error { Error }
fn invalid_value(_field: &str) -> Error { Error }
} }
impl serde::de::Error for Error { impl serde::de::Error for Error {
fn syntax(_: &str) -> Error { Error } fn custom(_: String) -> Error { Error }
fn end_of_stream() -> Error { Error } fn end_of_stream() -> Error { Error }
fn unknown_field(_field: &str) -> Error { Error }
fn missing_field(_field: &'static str) -> Error { Error }
} }
impl fmt::Display for Error { impl fmt::Display for Error {
+2 -2
View File
@@ -416,7 +416,7 @@ pub enum Error {
} }
impl ser::Error for Error { impl ser::Error for Error {
fn syntax(_: &str) -> Error { Error::SyntaxError } fn custom(_: String) -> Error { Error::SyntaxError }
fn invalid_value(msg: &str) -> Error { fn invalid_value(msg: &str) -> Error {
Error::InvalidValue(msg.to_owned()) Error::InvalidValue(msg.to_owned())
@@ -424,7 +424,7 @@ impl ser::Error for Error {
} }
impl de::Error for Error { impl de::Error for Error {
fn syntax(_: &str) -> Error { Error::SyntaxError } fn custom(_: String) -> Error { Error::SyntaxError }
fn end_of_stream() -> Error { Error::EndOfStreamError } fn end_of_stream() -> Error { Error::EndOfStreamError }