mirror of
https://github.com/pezkuwichain/serde.git
synced 2026-04-22 22:58:02 +00:00
Compare commits
74 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 017e6d304f | |||
| 89cbb81673 | |||
| c36743fa05 | |||
| 9a3c1243f4 | |||
| 599a1b6607 | |||
| 3d6e086d3e | |||
| ad480d2b04 | |||
| 7bee779514 | |||
| dff919a926 | |||
| bac593573c | |||
| 9444db5f19 | |||
| 3bf8cda994 | |||
| f98e7f6ba0 | |||
| 772b22b427 | |||
| 535ab1e04b | |||
| a3fe03c323 | |||
| 7dad6426da | |||
| 792a5f7502 | |||
| a4c738a9f3 | |||
| 4538143d00 | |||
| 7f08894a32 | |||
| adf7b086b5 | |||
| c590df13b9 | |||
| afa6dfbbe2 | |||
| f500db6e91 | |||
| 090c8a7049 | |||
| e8651a52e7 | |||
| 964a2dd4d1 | |||
| 8a21bbc720 | |||
| 4dba260ad7 | |||
| 1d3044fa28 | |||
| d1f0112bfb | |||
| 3f25cd9a7e | |||
| 45a36f1219 | |||
| 529a1cfedb | |||
| 219abd2e00 | |||
| 4bd10528a0 | |||
| b82bba2d0a | |||
| 17c175a1a6 | |||
| 763ab9c2a1 | |||
| 30b8036efa | |||
| 89bb16da6b | |||
| d00a895902 | |||
| 393b19ee8a | |||
| e68888d475 | |||
| d1306a78ec | |||
| ce230adf12 | |||
| 066c9a15cf | |||
| 6277079152 | |||
| d60fd84b7e | |||
| 02e6c04e9f | |||
| 9f04b9d6e7 | |||
| d298da0b4f | |||
| ff21d557c7 | |||
| faaa494579 | |||
| 661cdf4e00 | |||
| a55d812441 | |||
| b7ca574bb3 | |||
| d960571439 | |||
| 1ccc58e2aa | |||
| 34b39083bc | |||
| 48f4deac55 | |||
| 9a0f05d00d | |||
| b47e1a6dc3 | |||
| 39c7797633 | |||
| 368784949e | |||
| 74cf80989d | |||
| f0b4735781 | |||
| 297f373548 | |||
| 81f28da8e1 | |||
| d4bb687032 | |||
| f9bc5037f5 | |||
| 8624ca6f1d | |||
| a9b5cc4830 |
+6
-17
@@ -1,5 +1,6 @@
|
||||
sudo: false
|
||||
language: rust
|
||||
cache: cargo
|
||||
|
||||
# run builds for all the trains (and more)
|
||||
rust:
|
||||
@@ -8,21 +9,9 @@ rust:
|
||||
- beta
|
||||
- nightly
|
||||
|
||||
before_script:
|
||||
- pip install 'travis-cargo<0.2' --user
|
||||
- export PATH=$HOME/.local/bin:$PATH
|
||||
matrix:
|
||||
include:
|
||||
- rust: nightly
|
||||
env: CLIPPY=true
|
||||
|
||||
script:
|
||||
- (cd serde && travis-cargo build)
|
||||
- (cd serde && travis-cargo --only beta test)
|
||||
- (cd serde && travis-cargo --only nightly test -- --features unstable-testing)
|
||||
- (cd serde && travis-cargo build -- --no-default-features)
|
||||
- (cd serde && travis-cargo --only nightly build -- --no-default-features --features alloc)
|
||||
- (cd serde && travis-cargo --only nightly build -- --no-default-features --features collections)
|
||||
- (cd test_suite && travis-cargo --only beta test)
|
||||
- (cd test_suite/deps && travis-cargo --only nightly build && cd .. && travis-cargo --only nightly test -- --features unstable-testing)
|
||||
- (cd test_suite/no_std && travis-cargo --only nightly build)
|
||||
|
||||
env:
|
||||
global:
|
||||
- TRAVIS_CARGO_NIGHTLY_FEATURE=""
|
||||
script: ./travis.sh
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
[workspace]
|
||||
members = [
|
||||
"serde",
|
||||
"serde_codegen_internals",
|
||||
"serde_derive",
|
||||
"serde_test",
|
||||
"test_suite",
|
||||
"test_suite/no_std",
|
||||
]
|
||||
+9
-6
@@ -1,16 +1,16 @@
|
||||
[package]
|
||||
name = "serde"
|
||||
version = "0.9.2"
|
||||
version = "0.9.8"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "A generic serialization/deserialization framework"
|
||||
homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://docs.serde.rs/serde/"
|
||||
readme = "../README.md"
|
||||
keywords = ["serde", "serialization"]
|
||||
keywords = ["serde", "serialization", "no_std"]
|
||||
categories = ["encoding"]
|
||||
include = ["Cargo.toml", "src/**/*.rs"]
|
||||
readme = "../README.md"
|
||||
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "serde-rs/serde" }
|
||||
@@ -22,10 +22,13 @@ std = []
|
||||
unstable = []
|
||||
alloc = ["unstable"]
|
||||
collections = ["alloc"]
|
||||
unstable-testing = ["clippy", "unstable", "std"]
|
||||
unstable-testing = ["unstable", "std"]
|
||||
|
||||
# to get serde_derive picked up by play.integer32.com
|
||||
playground = ["serde_derive"]
|
||||
|
||||
[dependencies]
|
||||
clippy = { version = "0.*", optional = true }
|
||||
serde_derive = { version = "0.9", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_derive = "0.9"
|
||||
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../README.md
|
||||
+22
-17
@@ -60,9 +60,7 @@ pub struct Bytes<'a> {
|
||||
impl<'a> Bytes<'a> {
|
||||
/// Wrap an existing `&[u8]`.
|
||||
pub fn new(bytes: &'a [u8]) -> Self {
|
||||
Bytes {
|
||||
bytes: bytes,
|
||||
}
|
||||
Bytes { bytes: bytes }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,7 +96,9 @@ impl<'a> Into<&'a [u8]> for Bytes<'a> {
|
||||
impl<'a> ops::Deref for Bytes<'a> {
|
||||
type Target = [u8];
|
||||
|
||||
fn deref(&self) -> &[u8] { self.bytes }
|
||||
fn deref(&self) -> &[u8] {
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ser::Serialize for Bytes<'a> {
|
||||
@@ -114,6 +114,7 @@ impl<'a> ser::Serialize for Bytes<'a> {
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
mod bytebuf {
|
||||
use core::cmp;
|
||||
use core::ops;
|
||||
use core::fmt;
|
||||
use core::fmt::Write;
|
||||
@@ -161,9 +162,7 @@ mod bytebuf {
|
||||
|
||||
/// Wrap existing bytes in a `ByteBuf`.
|
||||
pub fn from<T: Into<Vec<u8>>>(bytes: T) -> Self {
|
||||
ByteBuf {
|
||||
bytes: bytes.into(),
|
||||
}
|
||||
ByteBuf { bytes: bytes.into() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,11 +215,15 @@ mod bytebuf {
|
||||
impl ops::Deref for ByteBuf {
|
||||
type Target = [u8];
|
||||
|
||||
fn deref(&self) -> &[u8] { &self.bytes[..] }
|
||||
fn deref(&self) -> &[u8] {
|
||||
&self.bytes[..]
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::DerefMut for ByteBuf {
|
||||
fn deref_mut(&mut self) -> &mut [u8] { &mut self.bytes[..] }
|
||||
fn deref_mut(&mut self) -> &mut [u8] {
|
||||
&mut self.bytes[..]
|
||||
}
|
||||
}
|
||||
|
||||
impl ser::Serialize for ByteBuf {
|
||||
@@ -243,16 +246,16 @@ mod bytebuf {
|
||||
|
||||
#[inline]
|
||||
fn visit_unit<E>(self) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
Ok(ByteBuf::new())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_seq<V>(self, mut visitor: V) -> Result<ByteBuf, V::Error>
|
||||
where V: de::SeqVisitor,
|
||||
where V: de::SeqVisitor
|
||||
{
|
||||
let (len, _) = visitor.size_hint();
|
||||
let len = cmp::min(visitor.size_hint().0, 4096);
|
||||
let mut values = Vec::with_capacity(len);
|
||||
|
||||
while let Some(value) = try!(visitor.visit()) {
|
||||
@@ -264,26 +267,26 @@ mod bytebuf {
|
||||
|
||||
#[inline]
|
||||
fn visit_bytes<E>(self, v: &[u8]) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, v: &str) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
|
||||
fn visit_string<E>(self, v: String) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
@@ -302,7 +305,9 @@ mod bytebuf {
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[inline]
|
||||
fn escape_bytestring<'a>(bytes: &'a [u8]) -> iter::FlatMap<slice::Iter<'a, u8>, char::EscapeDefault, fn(&u8) -> char::EscapeDefault> {
|
||||
fn escape_bytestring<'a>
|
||||
(bytes: &'a [u8])
|
||||
-> iter::FlatMap<slice::Iter<'a, u8>, char::EscapeDefault, fn(&u8) -> char::EscapeDefault> {
|
||||
fn f(b: &u8) -> char::EscapeDefault {
|
||||
char::from_u32(*b as u32).unwrap().escape_default()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,797 @@
|
||||
// This module is doc(hidden) and nothing here should be used outside of
|
||||
// generated code.
|
||||
//
|
||||
// We will iterate on the implementation for a few releases and only have to
|
||||
// worry about backward compatibility for the `untagged` and `tag` attributes
|
||||
// rather than for this entire mechanism.
|
||||
//
|
||||
// This issue is tracking making some of this stuff public:
|
||||
// https://github.com/serde-rs/serde/issues/741
|
||||
|
||||
#![doc(hidden)]
|
||||
|
||||
use core::cmp;
|
||||
use core::fmt;
|
||||
use core::marker::PhantomData;
|
||||
|
||||
#[cfg(all(not(feature = "std"), feature = "collections"))]
|
||||
use collections::{String, Vec};
|
||||
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
use alloc::boxed::Box;
|
||||
|
||||
use de::{self, Deserialize, DeserializeSeed, Deserializer, Visitor, SeqVisitor, MapVisitor,
|
||||
EnumVisitor, Unexpected};
|
||||
|
||||
/// Used from generated code to buffer the contents of the Deserializer when
|
||||
/// deserializing untagged enums and internally tagged enums.
|
||||
///
|
||||
/// Not public API. Use serde-value instead.
|
||||
#[derive(Debug)]
|
||||
pub enum Content {
|
||||
// Don't mind the PhantomData, just need to use E somewhere.
|
||||
Bool(bool),
|
||||
|
||||
U8(u8),
|
||||
U16(u16),
|
||||
U32(u32),
|
||||
U64(u64),
|
||||
|
||||
I8(i8),
|
||||
I16(i16),
|
||||
I32(i32),
|
||||
I64(i64),
|
||||
|
||||
F32(f32),
|
||||
F64(f64),
|
||||
|
||||
Char(char),
|
||||
String(String),
|
||||
Bytes(Vec<u8>),
|
||||
|
||||
None,
|
||||
Some(Box<Content>),
|
||||
|
||||
Unit,
|
||||
Newtype(Box<Content>),
|
||||
Seq(Vec<Content>),
|
||||
Map(Vec<(Content, Content)>),
|
||||
}
|
||||
|
||||
impl Deserialize for Content {
|
||||
fn deserialize<D: Deserializer>(deserializer: D) -> Result<Self, D::Error> {
|
||||
// Untagged and internally tagged enums are only supported in
|
||||
// self-describing formats.
|
||||
deserializer.deserialize(ContentVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
struct ContentVisitor;
|
||||
|
||||
impl Visitor for ContentVisitor {
|
||||
type Value = Content;
|
||||
|
||||
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
fmt.write_str("any value")
|
||||
}
|
||||
|
||||
fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::Bool(value))
|
||||
}
|
||||
|
||||
fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::I8(value))
|
||||
}
|
||||
|
||||
fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::I16(value))
|
||||
}
|
||||
|
||||
fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::I32(value))
|
||||
}
|
||||
|
||||
fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::I64(value))
|
||||
}
|
||||
|
||||
fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::U8(value))
|
||||
}
|
||||
|
||||
fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::U16(value))
|
||||
}
|
||||
|
||||
fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::U32(value))
|
||||
}
|
||||
|
||||
fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::U64(value))
|
||||
}
|
||||
|
||||
fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::F32(value))
|
||||
}
|
||||
|
||||
fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::F64(value))
|
||||
}
|
||||
|
||||
fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::Char(value))
|
||||
}
|
||||
|
||||
fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::String(value.into()))
|
||||
}
|
||||
|
||||
fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::String(value))
|
||||
}
|
||||
|
||||
fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::Bytes(value.into()))
|
||||
}
|
||||
|
||||
fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::Bytes(value))
|
||||
}
|
||||
|
||||
fn visit_unit<F>(self) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::Unit)
|
||||
}
|
||||
|
||||
fn visit_none<F>(self) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
Ok(Content::None)
|
||||
}
|
||||
|
||||
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
Deserialize::deserialize(deserializer).map(|v| Content::Some(Box::new(v)))
|
||||
}
|
||||
|
||||
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
Deserialize::deserialize(deserializer).map(|v| Content::Newtype(Box::new(v)))
|
||||
}
|
||||
|
||||
fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: SeqVisitor
|
||||
{
|
||||
let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096));
|
||||
while let Some(e) = try!(visitor.visit()) {
|
||||
vec.push(e);
|
||||
}
|
||||
Ok(Content::Seq(vec))
|
||||
}
|
||||
|
||||
fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: MapVisitor
|
||||
{
|
||||
let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096));
|
||||
while let Some(kv) = try!(visitor.visit()) {
|
||||
vec.push(kv);
|
||||
}
|
||||
Ok(Content::Map(vec))
|
||||
}
|
||||
|
||||
fn visit_enum<V>(self, _visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: EnumVisitor
|
||||
{
|
||||
Err(de::Error::custom("untagged and internally tagged enums do not support enum input"))
|
||||
}
|
||||
}
|
||||
|
||||
/// This is the type of the map keys in an internally tagged enum.
|
||||
///
|
||||
/// Not public API.
|
||||
pub enum TagOrContent {
|
||||
Tag,
|
||||
Content(Content),
|
||||
}
|
||||
|
||||
struct TagOrContentVisitor {
|
||||
name: &'static str,
|
||||
}
|
||||
|
||||
impl TagOrContentVisitor {
|
||||
fn new(name: &'static str) -> Self {
|
||||
TagOrContentVisitor { name: name }
|
||||
}
|
||||
}
|
||||
|
||||
impl DeserializeSeed for TagOrContentVisitor {
|
||||
type Value = TagOrContent;
|
||||
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
// Internally tagged enums are only supported in self-describing
|
||||
// formats.
|
||||
deserializer.deserialize(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Visitor for TagOrContentVisitor {
|
||||
type Value = TagOrContent;
|
||||
|
||||
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(fmt, "a type tag `{}` or any other value", self.name)
|
||||
}
|
||||
|
||||
fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_bool(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_i8(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_i16(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_i32(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_i64(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_u8(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_u16(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_u32(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_u64(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_f32(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_f64(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_char(value).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
if value == self.name {
|
||||
Ok(TagOrContent::Tag)
|
||||
} else {
|
||||
ContentVisitor.visit_str(value).map(TagOrContent::Content)
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
if value == self.name {
|
||||
Ok(TagOrContent::Tag)
|
||||
} else {
|
||||
ContentVisitor.visit_string(value).map(TagOrContent::Content)
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
if value == self.name.as_bytes() {
|
||||
Ok(TagOrContent::Tag)
|
||||
} else {
|
||||
ContentVisitor.visit_bytes(value).map(TagOrContent::Content)
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
if value == self.name.as_bytes() {
|
||||
Ok(TagOrContent::Tag)
|
||||
} else {
|
||||
ContentVisitor.visit_byte_buf(value).map(TagOrContent::Content)
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_unit<F>(self) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_unit().map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_none<F>(self) -> Result<Self::Value, F>
|
||||
where F: de::Error
|
||||
{
|
||||
ContentVisitor.visit_none().map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
ContentVisitor.visit_some(deserializer).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
ContentVisitor.visit_newtype_struct(deserializer).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: SeqVisitor
|
||||
{
|
||||
ContentVisitor.visit_seq(visitor).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: MapVisitor
|
||||
{
|
||||
ContentVisitor.visit_map(visitor).map(TagOrContent::Content)
|
||||
}
|
||||
|
||||
fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: EnumVisitor
|
||||
{
|
||||
ContentVisitor.visit_enum(visitor).map(TagOrContent::Content)
|
||||
}
|
||||
}
|
||||
|
||||
/// Used by generated code to deserialize an internally tagged enum.
|
||||
///
|
||||
/// Not public API.
|
||||
pub struct TaggedContent<T> {
|
||||
pub tag: T,
|
||||
pub content: Content,
|
||||
}
|
||||
|
||||
/// Not public API.
|
||||
pub struct TaggedContentVisitor<T> {
|
||||
tag_name: &'static str,
|
||||
tag: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> TaggedContentVisitor<T> {
|
||||
/// Visitor for the content of an internally tagged enum with the given tag
|
||||
/// name.
|
||||
pub fn new(name: &'static str) -> Self {
|
||||
TaggedContentVisitor {
|
||||
tag_name: name,
|
||||
tag: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DeserializeSeed for TaggedContentVisitor<T>
|
||||
where T: Deserialize
|
||||
{
|
||||
type Value = TaggedContent<T>;
|
||||
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
// Internally tagged enums are only supported in self-describing
|
||||
// formats.
|
||||
deserializer.deserialize(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Visitor for TaggedContentVisitor<T>
|
||||
where T: Deserialize
|
||||
{
|
||||
type Value = TaggedContent<T>;
|
||||
|
||||
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
fmt.write_str("any value")
|
||||
}
|
||||
|
||||
fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: MapVisitor
|
||||
{
|
||||
let mut tag = None;
|
||||
let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096));
|
||||
while let Some(k) = try!(visitor.visit_key_seed(TagOrContentVisitor::new(self.tag_name))) {
|
||||
match k {
|
||||
TagOrContent::Tag => {
|
||||
if tag.is_some() {
|
||||
return Err(de::Error::duplicate_field(self.tag_name));
|
||||
}
|
||||
tag = Some(try!(visitor.visit_value()));
|
||||
}
|
||||
TagOrContent::Content(k) => {
|
||||
let v = try!(visitor.visit_value());
|
||||
vec.push((k, v));
|
||||
}
|
||||
}
|
||||
}
|
||||
match tag {
|
||||
None => Err(de::Error::missing_field(self.tag_name)),
|
||||
Some(tag) => {
|
||||
Ok(TaggedContent {
|
||||
tag: tag,
|
||||
content: Content::Map(vec),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Used by generated code to deserialize an adjacently tagged enum.
|
||||
///
|
||||
/// Not public API.
|
||||
pub enum TagOrContentField {
|
||||
Tag,
|
||||
Content,
|
||||
}
|
||||
|
||||
/// Not public API.
|
||||
pub struct TagOrContentFieldVisitor {
|
||||
pub tag: &'static str,
|
||||
pub content: &'static str,
|
||||
}
|
||||
|
||||
impl DeserializeSeed for TagOrContentFieldVisitor {
|
||||
type Value = TagOrContentField;
|
||||
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
deserializer.deserialize_str(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Visitor for TagOrContentFieldVisitor {
|
||||
type Value = TagOrContentField;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "{:?} or {:?}", self.tag, self.content)
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, field: &str) -> Result<Self::Value, E>
|
||||
where E: de::Error
|
||||
{
|
||||
if field == self.tag {
|
||||
Ok(TagOrContentField::Tag)
|
||||
} else if field == self.content {
|
||||
Ok(TagOrContentField::Content)
|
||||
} else {
|
||||
Err(de::Error::invalid_value(Unexpected::Str(field), &self))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Not public API
|
||||
pub struct ContentDeserializer<E> {
|
||||
content: Content,
|
||||
err: PhantomData<E>,
|
||||
}
|
||||
|
||||
/// Used when deserializing an internally tagged enum because the content will
|
||||
/// be used exactly once.
|
||||
impl<E> Deserializer for ContentDeserializer<E>
|
||||
where E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match self.content {
|
||||
Content::Bool(v) => visitor.visit_bool(v),
|
||||
Content::U8(v) => visitor.visit_u8(v),
|
||||
Content::U16(v) => visitor.visit_u16(v),
|
||||
Content::U32(v) => visitor.visit_u32(v),
|
||||
Content::U64(v) => visitor.visit_u64(v),
|
||||
Content::I8(v) => visitor.visit_i8(v),
|
||||
Content::I16(v) => visitor.visit_i16(v),
|
||||
Content::I32(v) => visitor.visit_i32(v),
|
||||
Content::I64(v) => visitor.visit_i64(v),
|
||||
Content::F32(v) => visitor.visit_f32(v),
|
||||
Content::F64(v) => visitor.visit_f64(v),
|
||||
Content::Char(v) => visitor.visit_char(v),
|
||||
Content::String(v) => visitor.visit_string(v),
|
||||
Content::Unit => visitor.visit_unit(),
|
||||
Content::None => visitor.visit_none(),
|
||||
Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
|
||||
Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)),
|
||||
Content::Seq(v) => {
|
||||
let seq = v.into_iter().map(ContentDeserializer::new);
|
||||
let mut seq_visitor = de::value::SeqDeserializer::new(seq);
|
||||
let value = try!(visitor.visit_seq(&mut seq_visitor));
|
||||
try!(seq_visitor.end());
|
||||
Ok(value)
|
||||
}
|
||||
Content::Map(v) => {
|
||||
let map = v.into_iter()
|
||||
.map(|(k, v)| (ContentDeserializer::new(k), ContentDeserializer::new(v)));
|
||||
let mut map_visitor = de::value::MapDeserializer::new(map);
|
||||
let value = try!(visitor.visit_map(&mut map_visitor));
|
||||
try!(map_visitor.end());
|
||||
Ok(value)
|
||||
}
|
||||
Content::Bytes(v) => visitor.visit_byte_buf(v),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match self.content {
|
||||
Content::None => visitor.visit_none(),
|
||||
Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
|
||||
Content::Unit => visitor.visit_unit(),
|
||||
_ => visitor.visit_some(self),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor
|
||||
{
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
|
||||
forward_to_deserialize! {
|
||||
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
|
||||
seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
|
||||
struct_field tuple enum ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> ContentDeserializer<E> {
|
||||
/// private API, don't use
|
||||
pub fn new(content: Content) -> Self {
|
||||
ContentDeserializer {
|
||||
content: content,
|
||||
err: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Not public API.
|
||||
pub struct ContentRefDeserializer<'a, E> {
|
||||
content: &'a Content,
|
||||
err: PhantomData<E>,
|
||||
}
|
||||
|
||||
/// Used when deserializing an untagged enum because the content may need to be
|
||||
/// used more than once.
|
||||
impl<'a, E> Deserializer for ContentRefDeserializer<'a, E>
|
||||
where E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match *self.content {
|
||||
Content::Bool(v) => visitor.visit_bool(v),
|
||||
Content::U8(v) => visitor.visit_u8(v),
|
||||
Content::U16(v) => visitor.visit_u16(v),
|
||||
Content::U32(v) => visitor.visit_u32(v),
|
||||
Content::U64(v) => visitor.visit_u64(v),
|
||||
Content::I8(v) => visitor.visit_i8(v),
|
||||
Content::I16(v) => visitor.visit_i16(v),
|
||||
Content::I32(v) => visitor.visit_i32(v),
|
||||
Content::I64(v) => visitor.visit_i64(v),
|
||||
Content::F32(v) => visitor.visit_f32(v),
|
||||
Content::F64(v) => visitor.visit_f64(v),
|
||||
Content::Char(v) => visitor.visit_char(v),
|
||||
Content::String(ref v) => visitor.visit_str(v),
|
||||
Content::Unit => visitor.visit_unit(),
|
||||
Content::None => visitor.visit_none(),
|
||||
Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
|
||||
Content::Newtype(ref v) => visitor.visit_newtype_struct(ContentRefDeserializer::new(v)),
|
||||
Content::Seq(ref v) => {
|
||||
let seq = v.into_iter().map(ContentRefDeserializer::new);
|
||||
let mut seq_visitor = de::value::SeqDeserializer::new(seq);
|
||||
let value = try!(visitor.visit_seq(&mut seq_visitor));
|
||||
try!(seq_visitor.end());
|
||||
Ok(value)
|
||||
}
|
||||
Content::Map(ref v) => {
|
||||
let map = v.into_iter().map(|&(ref k, ref v)| {
|
||||
(ContentRefDeserializer::new(k), ContentRefDeserializer::new(v))
|
||||
});
|
||||
let mut map_visitor = de::value::MapDeserializer::new(map);
|
||||
let value = try!(visitor.visit_map(&mut map_visitor));
|
||||
try!(map_visitor.end());
|
||||
Ok(value)
|
||||
}
|
||||
Content::Bytes(ref v) => visitor.visit_bytes(v),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match *self.content {
|
||||
Content::None => visitor.visit_none(),
|
||||
Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
|
||||
Content::Unit => visitor.visit_unit(),
|
||||
_ => visitor.visit_some(self),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor
|
||||
{
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
|
||||
forward_to_deserialize! {
|
||||
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
|
||||
seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
|
||||
struct_field tuple enum ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, E> ContentRefDeserializer<'a, E> {
|
||||
/// private API, don't use
|
||||
pub fn new(content: &'a Content) -> Self {
|
||||
ContentRefDeserializer {
|
||||
content: content,
|
||||
err: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> de::value::ValueDeserializer<E> for ContentDeserializer<E>
|
||||
where E: de::Error
|
||||
{
|
||||
type Deserializer = Self;
|
||||
|
||||
fn into_deserializer(self) -> Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, E> de::value::ValueDeserializer<E> for ContentRefDeserializer<'a, E>
|
||||
where E: de::Error
|
||||
{
|
||||
type Deserializer = Self;
|
||||
|
||||
fn into_deserializer(self) -> Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Visitor for deserializing an internally tagged unit variant.
|
||||
///
|
||||
/// Not public API.
|
||||
pub struct InternallyTaggedUnitVisitor<'a> {
|
||||
type_name: &'a str,
|
||||
variant_name: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> InternallyTaggedUnitVisitor<'a> {
|
||||
/// Not public API.
|
||||
pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
|
||||
InternallyTaggedUnitVisitor {
|
||||
type_name: type_name,
|
||||
variant_name: variant_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Visitor for InternallyTaggedUnitVisitor<'a> {
|
||||
type Value = ();
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name)
|
||||
}
|
||||
|
||||
fn visit_map<V>(self, _: V) -> Result<(), V::Error>
|
||||
where V: MapVisitor
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Visitor for deserializing an untagged unit variant.
|
||||
///
|
||||
/// Not public API.
|
||||
pub struct UntaggedUnitVisitor<'a> {
|
||||
type_name: &'a str,
|
||||
variant_name: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> UntaggedUnitVisitor<'a> {
|
||||
/// Not public API.
|
||||
pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
|
||||
UntaggedUnitVisitor {
|
||||
type_name: type_name,
|
||||
variant_name: variant_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Visitor for UntaggedUnitVisitor<'a> {
|
||||
type Value = ();
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name)
|
||||
}
|
||||
|
||||
fn visit_unit<E>(self) -> Result<(), E>
|
||||
where E: de::Error
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+159
-171
@@ -6,32 +6,16 @@ use std::borrow::Cow;
|
||||
use collections::borrow::Cow;
|
||||
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
use collections::{
|
||||
BinaryHeap,
|
||||
BTreeMap,
|
||||
BTreeSet,
|
||||
LinkedList,
|
||||
VecDeque,
|
||||
Vec,
|
||||
String,
|
||||
};
|
||||
use collections::{BinaryHeap, BTreeMap, BTreeSet, LinkedList, VecDeque, Vec, String};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use std::collections::{
|
||||
HashMap,
|
||||
HashSet,
|
||||
BinaryHeap,
|
||||
BTreeMap,
|
||||
BTreeSet,
|
||||
LinkedList,
|
||||
VecDeque,
|
||||
};
|
||||
use std::collections::{HashMap, HashSet, BinaryHeap, BTreeMap, BTreeSet, LinkedList, VecDeque};
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
use collections::enum_set::{CLike, EnumSet};
|
||||
#[cfg(feature = "collections")]
|
||||
use collections::borrow::ToOwned;
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
use core::cmp;
|
||||
use core::fmt;
|
||||
#[cfg(feature = "std")]
|
||||
use core::hash::{Hash, BuildHasher};
|
||||
@@ -65,17 +49,8 @@ use core::nonzero::{NonZero, Zeroable};
|
||||
#[allow(deprecated)] // required for impl Deserialize for NonZero<T>
|
||||
use core::num::Zero;
|
||||
|
||||
use de::{
|
||||
Deserialize,
|
||||
Deserializer,
|
||||
EnumVisitor,
|
||||
Error,
|
||||
MapVisitor,
|
||||
SeqVisitor,
|
||||
Unexpected,
|
||||
VariantVisitor,
|
||||
Visitor,
|
||||
};
|
||||
use de::{Deserialize, Deserializer, EnumVisitor, Error, MapVisitor, SeqVisitor, Unexpected,
|
||||
VariantVisitor, Visitor};
|
||||
use de::from_primitive::FromPrimitive;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
@@ -91,13 +66,13 @@ impl Visitor for UnitVisitor {
|
||||
}
|
||||
|
||||
fn visit_unit<E>(self) -> Result<(), E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_seq<V>(self, _: V) -> Result<(), V::Error>
|
||||
where V: SeqVisitor,
|
||||
where V: SeqVisitor
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
@@ -105,7 +80,7 @@ impl Visitor for UnitVisitor {
|
||||
|
||||
impl Deserialize for () {
|
||||
fn deserialize<D>(deserializer: D) -> Result<(), D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
deserializer.deserialize_unit(UnitVisitor)
|
||||
}
|
||||
@@ -124,13 +99,13 @@ impl Visitor for BoolVisitor {
|
||||
}
|
||||
|
||||
fn visit_bool<E>(self, v: bool) -> Result<bool, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, s: &str) -> Result<bool, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
match s.trim_matches(::utils::Pattern_White_Space) {
|
||||
"true" => Ok(true),
|
||||
@@ -142,7 +117,7 @@ impl Visitor for BoolVisitor {
|
||||
|
||||
impl Deserialize for bool {
|
||||
fn deserialize<D>(deserializer: D) -> Result<bool, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
deserializer.deserialize_bool(BoolVisitor)
|
||||
}
|
||||
@@ -233,14 +208,14 @@ impl Visitor for CharVisitor {
|
||||
|
||||
#[inline]
|
||||
fn visit_char<E>(self, v: char) -> Result<char, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_str<E>(self, v: &str) -> Result<char, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
let mut iter = v.chars();
|
||||
match (iter.next(), iter.next()) {
|
||||
@@ -253,7 +228,7 @@ impl Visitor for CharVisitor {
|
||||
impl Deserialize for char {
|
||||
#[inline]
|
||||
fn deserialize<D>(deserializer: D) -> Result<char, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
deserializer.deserialize_char(CharVisitor)
|
||||
}
|
||||
@@ -273,25 +248,25 @@ impl Visitor for StringVisitor {
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, v: &str) -> Result<String, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Ok(v.to_owned())
|
||||
}
|
||||
|
||||
fn visit_string<E>(self, v: String) -> Result<String, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn visit_unit<E>(self) -> Result<String, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Ok(String::new())
|
||||
}
|
||||
|
||||
fn visit_bytes<E>(self, v: &[u8]) -> Result<String, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
match str::from_utf8(v) {
|
||||
Ok(s) => Ok(s.to_owned()),
|
||||
@@ -300,7 +275,7 @@ impl Visitor for StringVisitor {
|
||||
}
|
||||
|
||||
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<String, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
match String::from_utf8(v) {
|
||||
Ok(s) => Ok(s),
|
||||
@@ -312,7 +287,7 @@ impl Visitor for StringVisitor {
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl Deserialize for String {
|
||||
fn deserialize<D>(deserializer: D) -> Result<String, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
deserializer.deserialize_string(StringVisitor)
|
||||
}
|
||||
@@ -324,9 +299,7 @@ struct OptionVisitor<T> {
|
||||
marker: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<
|
||||
T: Deserialize,
|
||||
> Visitor for OptionVisitor<T> {
|
||||
impl<T: Deserialize> Visitor for OptionVisitor<T> {
|
||||
type Value = Option<T>;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
@@ -335,29 +308,31 @@ impl<
|
||||
|
||||
#[inline]
|
||||
fn visit_unit<E>(self) -> Result<Option<T>, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_none<E>(self) -> Result<Option<T>, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_some<D>(self, deserializer: D) -> Result<Option<T>, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
Ok(Some(try!(Deserialize::deserialize(deserializer))))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deserialize for Option<T> where T: Deserialize {
|
||||
impl<T> Deserialize for Option<T>
|
||||
where T: Deserialize
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Option<T>, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
deserializer.deserialize_option(OptionVisitor { marker: PhantomData })
|
||||
}
|
||||
@@ -379,7 +354,7 @@ impl<T> Visitor for PhantomDataVisitor<T> {
|
||||
|
||||
#[inline]
|
||||
fn visit_unit<E>(self) -> Result<PhantomData<T>, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Ok(PhantomData)
|
||||
}
|
||||
@@ -387,7 +362,7 @@ impl<T> Visitor for PhantomDataVisitor<T> {
|
||||
|
||||
impl<T> Deserialize for PhantomData<T> {
|
||||
fn deserialize<D>(deserializer: D) -> Result<PhantomData<T>, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
let visitor = PhantomDataVisitor { marker: PhantomData };
|
||||
deserializer.deserialize_unit_struct("PhantomData", visitor)
|
||||
@@ -469,7 +444,7 @@ seq_impl!(
|
||||
BinaryHeapVisitor<T: Deserialize + Ord>,
|
||||
visitor,
|
||||
BinaryHeap::new(),
|
||||
BinaryHeap::with_capacity(visitor.size_hint().0),
|
||||
BinaryHeap::with_capacity(cmp::min(visitor.size_hint().0, 4096)),
|
||||
BinaryHeap::push);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
@@ -481,15 +456,6 @@ seq_impl!(
|
||||
BTreeSet::new(),
|
||||
BTreeSet::insert);
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
seq_impl!(
|
||||
EnumSet<T>,
|
||||
EnumSetVisitor<T: Deserialize + CLike>,
|
||||
visitor,
|
||||
EnumSet::new(),
|
||||
EnumSet::new(),
|
||||
EnumSet::insert);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
seq_impl!(
|
||||
LinkedList<T>,
|
||||
@@ -506,7 +472,7 @@ seq_impl!(
|
||||
S: BuildHasher + Default>,
|
||||
visitor,
|
||||
HashSet::with_hasher(S::default()),
|
||||
HashSet::with_capacity_and_hasher(visitor.size_hint().0, S::default()),
|
||||
HashSet::with_capacity_and_hasher(cmp::min(visitor.size_hint().0, 4096), S::default()),
|
||||
HashSet::insert);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
@@ -515,7 +481,7 @@ seq_impl!(
|
||||
VecVisitor<T: Deserialize>,
|
||||
visitor,
|
||||
Vec::new(),
|
||||
Vec::with_capacity(visitor.size_hint().0),
|
||||
Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096)),
|
||||
Vec::push);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
@@ -524,7 +490,7 @@ seq_impl!(
|
||||
VecDequeVisitor<T: Deserialize>,
|
||||
visitor,
|
||||
VecDeque::new(),
|
||||
VecDeque::with_capacity(visitor.size_hint().0),
|
||||
VecDeque::with_capacity(cmp::min(visitor.size_hint().0, 4096)),
|
||||
VecDeque::push_back);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
@@ -535,13 +501,13 @@ struct ArrayVisitor<A> {
|
||||
|
||||
impl<A> ArrayVisitor<A> {
|
||||
pub fn new() -> Self {
|
||||
ArrayVisitor {
|
||||
marker: PhantomData,
|
||||
}
|
||||
ArrayVisitor { marker: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Visitor for ArrayVisitor<[T; 0]> where T: Deserialize {
|
||||
impl<T> Visitor for ArrayVisitor<[T; 0]>
|
||||
where T: Deserialize
|
||||
{
|
||||
type Value = [T; 0];
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
@@ -550,14 +516,14 @@ impl<T> Visitor for ArrayVisitor<[T; 0]> where T: Deserialize {
|
||||
|
||||
#[inline]
|
||||
fn visit_unit<E>(self) -> Result<[T; 0], E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Ok([])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_seq<V>(self, _: V) -> Result<[T; 0], V::Error>
|
||||
where V: SeqVisitor,
|
||||
where V: SeqVisitor
|
||||
{
|
||||
Ok([])
|
||||
}
|
||||
@@ -567,14 +533,14 @@ impl<T> Deserialize for [T; 0]
|
||||
where T: Deserialize
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<[T; 0], D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
deserializer.deserialize_seq_fixed_size(0, ArrayVisitor::<[T; 0]>::new())
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! array_impls {
|
||||
($($len:expr => ($($name:ident)+))+) => {
|
||||
($($len:expr => ($($n:tt $name:ident)+))+) => {
|
||||
$(
|
||||
impl<T> Visitor for ArrayVisitor<[T; $len]> where T: Deserialize {
|
||||
type Value = [T; $len];
|
||||
@@ -590,7 +556,7 @@ macro_rules! array_impls {
|
||||
$(
|
||||
let $name = match try!(visitor.visit()) {
|
||||
Some(val) => val,
|
||||
None => return Err(Error::invalid_length(0, &self)),
|
||||
None => return Err(Error::invalid_length($n, &self)),
|
||||
};
|
||||
)+
|
||||
|
||||
@@ -612,44 +578,44 @@ macro_rules! array_impls {
|
||||
}
|
||||
|
||||
array_impls! {
|
||||
1 => (a)
|
||||
2 => (a b)
|
||||
3 => (a b c)
|
||||
4 => (a b c d)
|
||||
5 => (a b c d e)
|
||||
6 => (a b c d e f)
|
||||
7 => (a b c d e f g)
|
||||
8 => (a b c d e f g h)
|
||||
9 => (a b c d e f g h i)
|
||||
10 => (a b c d e f g h i j)
|
||||
11 => (a b c d e f g h i j k)
|
||||
12 => (a b c d e f g h i j k l)
|
||||
13 => (a b c d e f g h i j k l m)
|
||||
14 => (a b c d e f g h i j k l m n)
|
||||
15 => (a b c d e f g h i j k l m n o)
|
||||
16 => (a b c d e f g h i j k l m n o p)
|
||||
17 => (a b c d e f g h i j k l m n o p q)
|
||||
18 => (a b c d e f g h i j k l m n o p q r)
|
||||
19 => (a b c d e f g h i j k l m n o p q r s)
|
||||
20 => (a b c d e f g h i j k l m n o p q r s t)
|
||||
21 => (a b c d e f g h i j k l m n o p q r s t u)
|
||||
22 => (a b c d e f g h i j k l m n o p q r s t u v)
|
||||
23 => (a b c d e f g h i j k l m n o p q r s t u v w)
|
||||
24 => (a b c d e f g h i j k l m n o p q r s t u v w x)
|
||||
25 => (a b c d e f g h i j k l m n o p q r s t u v w x y)
|
||||
26 => (a b c d e f g h i j k l m n o p q r s t u v w x y z)
|
||||
27 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa)
|
||||
28 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab)
|
||||
29 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac)
|
||||
30 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad)
|
||||
31 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae)
|
||||
32 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae af)
|
||||
1 => (0 a)
|
||||
2 => (0 a 1 b)
|
||||
3 => (0 a 1 b 2 c)
|
||||
4 => (0 a 1 b 2 c 3 d)
|
||||
5 => (0 a 1 b 2 c 3 d 4 e)
|
||||
6 => (0 a 1 b 2 c 3 d 4 e 5 f)
|
||||
7 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g)
|
||||
8 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h)
|
||||
9 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i)
|
||||
10 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j)
|
||||
11 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k)
|
||||
12 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l)
|
||||
13 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m)
|
||||
14 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n)
|
||||
15 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o)
|
||||
16 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p)
|
||||
17 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q)
|
||||
18 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r)
|
||||
19 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s)
|
||||
20 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t)
|
||||
21 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u)
|
||||
22 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v)
|
||||
23 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w)
|
||||
24 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x)
|
||||
25 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y)
|
||||
26 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z)
|
||||
27 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa)
|
||||
28 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab)
|
||||
29 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac)
|
||||
30 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad)
|
||||
31 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad 30 ae)
|
||||
32 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad 30 ae 31 af)
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! tuple_impls {
|
||||
($($len:expr => $visitor:ident => ($($name:ident)+))+) => {
|
||||
($($len:expr => $visitor:ident => ($($n:tt $name:ident)+))+) => {
|
||||
$(
|
||||
/// Construct a tuple visitor.
|
||||
pub struct $visitor<$($name,)+> {
|
||||
@@ -678,7 +644,7 @@ macro_rules! tuple_impls {
|
||||
$(
|
||||
let $name = match try!(visitor.visit()) {
|
||||
Some(value) => value,
|
||||
None => return Err(Error::invalid_length(0, &self)),
|
||||
None => return Err(Error::invalid_length($n, &self)),
|
||||
};
|
||||
)+
|
||||
|
||||
@@ -699,22 +665,22 @@ macro_rules! tuple_impls {
|
||||
}
|
||||
|
||||
tuple_impls! {
|
||||
1 => TupleVisitor1 => (T0)
|
||||
2 => TupleVisitor2 => (T0 T1)
|
||||
3 => TupleVisitor3 => (T0 T1 T2)
|
||||
4 => TupleVisitor4 => (T0 T1 T2 T3)
|
||||
5 => TupleVisitor5 => (T0 T1 T2 T3 T4)
|
||||
6 => TupleVisitor6 => (T0 T1 T2 T3 T4 T5)
|
||||
7 => TupleVisitor7 => (T0 T1 T2 T3 T4 T5 T6)
|
||||
8 => TupleVisitor8 => (T0 T1 T2 T3 T4 T5 T6 T7)
|
||||
9 => TupleVisitor9 => (T0 T1 T2 T3 T4 T5 T6 T7 T8)
|
||||
10 => TupleVisitor10 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9)
|
||||
11 => TupleVisitor11 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10)
|
||||
12 => TupleVisitor12 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11)
|
||||
13 => TupleVisitor13 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12)
|
||||
14 => TupleVisitor14 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13)
|
||||
15 => TupleVisitor15 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14)
|
||||
16 => TupleVisitor16 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15)
|
||||
1 => TupleVisitor1 => (0 T0)
|
||||
2 => TupleVisitor2 => (0 T0 1 T1)
|
||||
3 => TupleVisitor3 => (0 T0 1 T1 2 T2)
|
||||
4 => TupleVisitor4 => (0 T0 1 T1 2 T2 3 T3)
|
||||
5 => TupleVisitor5 => (0 T0 1 T1 2 T2 3 T3 4 T4)
|
||||
6 => TupleVisitor6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5)
|
||||
7 => TupleVisitor7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6)
|
||||
8 => TupleVisitor8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7)
|
||||
9 => TupleVisitor9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8)
|
||||
10 => TupleVisitor10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9)
|
||||
11 => TupleVisitor11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10)
|
||||
12 => TupleVisitor12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11)
|
||||
13 => TupleVisitor13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12)
|
||||
14 => TupleVisitor14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13)
|
||||
15 => TupleVisitor15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14)
|
||||
16 => TupleVisitor16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15)
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
@@ -802,14 +768,14 @@ map_impl!(
|
||||
S: BuildHasher + Default>,
|
||||
visitor,
|
||||
HashMap::with_hasher(S::default()),
|
||||
HashMap::with_capacity_and_hasher(visitor.size_hint().0, S::default()));
|
||||
HashMap::with_capacity_and_hasher(cmp::min(visitor.size_hint().0, 4096), S::default()));
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Deserialize for net::IpAddr {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
let s = try!(String::deserialize(deserializer));
|
||||
match s.parse() {
|
||||
@@ -822,7 +788,7 @@ impl Deserialize for net::IpAddr {
|
||||
#[cfg(feature = "std")]
|
||||
impl Deserialize for net::Ipv4Addr {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
let s = try!(String::deserialize(deserializer));
|
||||
match s.parse() {
|
||||
@@ -835,7 +801,7 @@ impl Deserialize for net::Ipv4Addr {
|
||||
#[cfg(feature = "std")]
|
||||
impl Deserialize for net::Ipv6Addr {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
let s = try!(String::deserialize(deserializer));
|
||||
match s.parse() {
|
||||
@@ -850,7 +816,7 @@ impl Deserialize for net::Ipv6Addr {
|
||||
#[cfg(feature = "std")]
|
||||
impl Deserialize for net::SocketAddr {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
let s = try!(String::deserialize(deserializer));
|
||||
match s.parse() {
|
||||
@@ -863,7 +829,7 @@ impl Deserialize for net::SocketAddr {
|
||||
#[cfg(feature = "std")]
|
||||
impl Deserialize for net::SocketAddrV4 {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
let s = try!(String::deserialize(deserializer));
|
||||
match s.parse() {
|
||||
@@ -876,7 +842,7 @@ impl Deserialize for net::SocketAddrV4 {
|
||||
#[cfg(feature = "std")]
|
||||
impl Deserialize for net::SocketAddrV6 {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
let s = try!(String::deserialize(deserializer));
|
||||
match s.parse() {
|
||||
@@ -900,13 +866,13 @@ impl Visitor for PathBufVisitor {
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, v: &str) -> Result<path::PathBuf, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Ok(From::from(v))
|
||||
}
|
||||
|
||||
fn visit_string<E>(self, v: String) -> Result<path::PathBuf, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Ok(From::from(v))
|
||||
}
|
||||
@@ -915,7 +881,7 @@ impl Visitor for PathBufVisitor {
|
||||
#[cfg(feature = "std")]
|
||||
impl Deserialize for path::PathBuf {
|
||||
fn deserialize<D>(deserializer: D) -> Result<path::PathBuf, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
deserializer.deserialize_string(PathBufVisitor)
|
||||
}
|
||||
@@ -926,7 +892,7 @@ impl Deserialize for path::PathBuf {
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<T: Deserialize> Deserialize for Box<T> {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Box<T>, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
let val = try!(Deserialize::deserialize(deserializer));
|
||||
Ok(Box::new(val))
|
||||
@@ -936,7 +902,7 @@ impl<T: Deserialize> Deserialize for Box<T> {
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T: Deserialize> Deserialize for Box<[T]> {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Box<[T]>, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
let v: Vec<T> = try!(Deserialize::deserialize(deserializer));
|
||||
Ok(v.into_boxed_slice())
|
||||
@@ -956,7 +922,7 @@ impl Deserialize for Box<str> {
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<T: Deserialize> Deserialize for Arc<T> {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Arc<T>, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
let val = try!(Deserialize::deserialize(deserializer));
|
||||
Ok(Arc::new(val))
|
||||
@@ -966,7 +932,7 @@ impl<T: Deserialize> Deserialize for Arc<T> {
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<T: Deserialize> Deserialize for Rc<T> {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Rc<T>, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
let val = try!(Deserialize::deserialize(deserializer));
|
||||
Ok(Rc::new(val))
|
||||
@@ -974,10 +940,13 @@ impl<T: Deserialize> Deserialize for Rc<T> {
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'a, T: ?Sized> Deserialize for Cow<'a, T> where T: ToOwned, T::Owned: Deserialize, {
|
||||
impl<'a, T: ?Sized> Deserialize for Cow<'a, T>
|
||||
where T: ToOwned,
|
||||
T::Owned: Deserialize
|
||||
{
|
||||
#[inline]
|
||||
fn deserialize<D>(deserializer: D) -> Result<Cow<'a, T>, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
let val = try!(Deserialize::deserialize(deserializer));
|
||||
Ok(Cow::Owned(val))
|
||||
@@ -997,13 +966,16 @@ impl<'a, T: ?Sized> Deserialize for Cow<'a, T> where T: ToOwned, T::Owned: Deser
|
||||
#[cfg(feature = "std")]
|
||||
impl Deserialize for Duration {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
enum Field { Secs, Nanos };
|
||||
enum Field {
|
||||
Secs,
|
||||
Nanos,
|
||||
};
|
||||
|
||||
impl Deserialize for Field {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
struct FieldVisitor;
|
||||
|
||||
@@ -1015,7 +987,7 @@ impl Deserialize for Duration {
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, value: &str) -> Result<Field, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
match value {
|
||||
"secs" => Ok(Field::Secs),
|
||||
@@ -1025,7 +997,7 @@ impl Deserialize for Duration {
|
||||
}
|
||||
|
||||
fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
match value {
|
||||
b"secs" => Ok(Field::Secs),
|
||||
@@ -1052,7 +1024,7 @@ impl Deserialize for Duration {
|
||||
}
|
||||
|
||||
fn visit_seq<V>(self, mut visitor: V) -> Result<Duration, V::Error>
|
||||
where V: SeqVisitor,
|
||||
where V: SeqVisitor
|
||||
{
|
||||
let secs: u64 = match try!(visitor.visit()) {
|
||||
Some(value) => value,
|
||||
@@ -1070,7 +1042,7 @@ impl Deserialize for Duration {
|
||||
}
|
||||
|
||||
fn visit_map<V>(self, mut visitor: V) -> Result<Duration, V::Error>
|
||||
where V: MapVisitor,
|
||||
where V: MapVisitor
|
||||
{
|
||||
let mut secs: Option<u64> = None;
|
||||
let mut nanos: Option<u32> = None;
|
||||
@@ -1111,24 +1083,30 @@ impl Deserialize for Duration {
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[allow(deprecated)] // num::Zero is deprecated but there is no replacement
|
||||
impl<T> Deserialize for NonZero<T> where T: Deserialize + PartialEq + Zeroable + Zero {
|
||||
fn deserialize<D>(deserializer: D) -> Result<NonZero<T>, D::Error> where D: Deserializer {
|
||||
impl<T> Deserialize for NonZero<T>
|
||||
where T: Deserialize + PartialEq + Zeroable + Zero
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<NonZero<T>, D::Error>
|
||||
where D: Deserializer
|
||||
{
|
||||
let value = try!(Deserialize::deserialize(deserializer));
|
||||
if value == Zero::zero() {
|
||||
return Err(Error::custom("expected a non-zero value"))
|
||||
}
|
||||
unsafe {
|
||||
Ok(NonZero::new(value))
|
||||
return Err(Error::custom("expected a non-zero value"));
|
||||
}
|
||||
unsafe { Ok(NonZero::new(value)) }
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
|
||||
impl<T, E> Deserialize for Result<T, E>
|
||||
where T: Deserialize,
|
||||
E: Deserialize
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Result<T, E>, D::Error>
|
||||
where D: Deserializer {
|
||||
where D: Deserializer
|
||||
{
|
||||
enum Field {
|
||||
Ok,
|
||||
Err,
|
||||
@@ -1148,15 +1126,21 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
|
||||
formatter.write_str("`Ok` or `Err`")
|
||||
}
|
||||
|
||||
fn visit_u32<E>(self, value: u32) -> Result<Field, E> where E: Error {
|
||||
fn visit_u32<E>(self, value: u32) -> Result<Field, E>
|
||||
where E: Error
|
||||
{
|
||||
match value {
|
||||
0 => Ok(Field::Ok),
|
||||
1 => Ok(Field::Err),
|
||||
_ => Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self)),
|
||||
_ => {
|
||||
Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, value: &str) -> Result<Field, E> where E: Error {
|
||||
fn visit_str<E>(self, value: &str) -> Result<Field, E>
|
||||
where E: Error
|
||||
{
|
||||
match value {
|
||||
"Ok" => Ok(Field::Ok),
|
||||
"Err" => Ok(Field::Err),
|
||||
@@ -1164,14 +1148,18 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E> where E: Error {
|
||||
fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E>
|
||||
where E: Error
|
||||
{
|
||||
match value {
|
||||
b"Ok" => Ok(Field::Ok),
|
||||
b"Err" => Ok(Field::Err),
|
||||
_ => {
|
||||
match str::from_utf8(value) {
|
||||
Ok(value) => Err(Error::unknown_variant(value, VARIANTS)),
|
||||
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)),
|
||||
Err(_) => {
|
||||
Err(Error::invalid_value(Unexpected::Bytes(value), &self))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1219,7 +1207,7 @@ pub struct IgnoredAny;
|
||||
impl Deserialize for IgnoredAny {
|
||||
#[inline]
|
||||
fn deserialize<D>(deserializer: D) -> Result<IgnoredAny, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
struct IgnoredAnyVisitor;
|
||||
|
||||
@@ -1252,7 +1240,7 @@ impl Deserialize for IgnoredAny {
|
||||
|
||||
#[inline]
|
||||
fn visit_str<E>(self, _: &str) -> Result<IgnoredAny, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Ok(IgnoredAny)
|
||||
}
|
||||
@@ -1264,14 +1252,14 @@ impl Deserialize for IgnoredAny {
|
||||
|
||||
#[inline]
|
||||
fn visit_some<D>(self, _: D) -> Result<IgnoredAny, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
Ok(IgnoredAny)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_newtype_struct<D>(self, _: D) -> Result<IgnoredAny, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
Ok(IgnoredAny)
|
||||
}
|
||||
@@ -1283,7 +1271,7 @@ impl Deserialize for IgnoredAny {
|
||||
|
||||
#[inline]
|
||||
fn visit_seq<V>(self, mut visitor: V) -> Result<IgnoredAny, V::Error>
|
||||
where V: SeqVisitor,
|
||||
where V: SeqVisitor
|
||||
{
|
||||
while let Some(_) = try!(visitor.visit::<IgnoredAny>()) {
|
||||
// Gobble
|
||||
@@ -1293,7 +1281,7 @@ impl Deserialize for IgnoredAny {
|
||||
|
||||
#[inline]
|
||||
fn visit_map<V>(self, mut visitor: V) -> Result<IgnoredAny, V::Error>
|
||||
where V: MapVisitor,
|
||||
where V: MapVisitor
|
||||
{
|
||||
while let Some((_, _)) = try!(visitor.visit::<IgnoredAny, IgnoredAny>()) {
|
||||
// Gobble
|
||||
@@ -1303,7 +1291,7 @@ impl Deserialize for IgnoredAny {
|
||||
|
||||
#[inline]
|
||||
fn visit_bytes<E>(self, _: &[u8]) -> Result<IgnoredAny, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Ok(IgnoredAny)
|
||||
}
|
||||
|
||||
+109
-98
@@ -115,6 +115,8 @@ mod from_primitive;
|
||||
// Helpers used by generated code. Not public API.
|
||||
#[doc(hidden)]
|
||||
pub mod private;
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
mod content;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -179,7 +181,10 @@ pub trait Error: Sized + error::Error {
|
||||
write!(formatter, "invalid type: {}, expected {}", self.unexp, self.exp)
|
||||
}
|
||||
}
|
||||
Error::custom(InvalidType { unexp: unexp, exp: exp })
|
||||
Error::custom(InvalidType {
|
||||
unexp: unexp,
|
||||
exp: exp,
|
||||
})
|
||||
}
|
||||
|
||||
/// Raised when a `Deserialize` receives a value of the right type but that
|
||||
@@ -205,7 +210,10 @@ pub trait Error: Sized + error::Error {
|
||||
write!(formatter, "invalid value: {}, expected {}", self.unexp, self.exp)
|
||||
}
|
||||
}
|
||||
Error::custom(InvalidValue { unexp: unexp, exp: exp })
|
||||
Error::custom(InvalidValue {
|
||||
unexp: unexp,
|
||||
exp: exp,
|
||||
})
|
||||
}
|
||||
|
||||
/// Raised when deserializing a sequence or map and the input data contains
|
||||
@@ -227,7 +235,10 @@ pub trait Error: Sized + error::Error {
|
||||
write!(formatter, "invalid length {}, expected {}", self.len, self.exp)
|
||||
}
|
||||
}
|
||||
Error::custom(InvalidLength { len: len, exp: exp })
|
||||
Error::custom(InvalidLength {
|
||||
len: len,
|
||||
exp: exp,
|
||||
})
|
||||
}
|
||||
|
||||
/// Raised when a `Deserialize` enum type received a variant with an
|
||||
@@ -251,7 +262,10 @@ pub trait Error: Sized + error::Error {
|
||||
}
|
||||
}
|
||||
}
|
||||
Error::custom(UnknownVariant { variant: variant, expected: expected })
|
||||
Error::custom(UnknownVariant {
|
||||
variant: variant,
|
||||
expected: expected,
|
||||
})
|
||||
}
|
||||
|
||||
/// Raised when a `Deserialize` struct type received a field with an
|
||||
@@ -275,7 +289,10 @@ pub trait Error: Sized + error::Error {
|
||||
}
|
||||
}
|
||||
}
|
||||
Error::custom(UnknownField { field: field, expected: expected })
|
||||
Error::custom(UnknownField {
|
||||
field: field,
|
||||
expected: expected,
|
||||
})
|
||||
}
|
||||
|
||||
/// Raised when a `Deserialize` struct type expected to receive a required
|
||||
@@ -468,7 +485,9 @@ pub trait Expected {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result;
|
||||
}
|
||||
|
||||
impl<T> Expected for T where T: Visitor {
|
||||
impl<T> Expected for T
|
||||
where T: Visitor
|
||||
{
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.expecting(formatter)
|
||||
}
|
||||
@@ -488,8 +507,8 @@ impl<'a> Display for Expected + 'a {
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// An implementation of this trait is a **data structure** that can be
|
||||
/// deserialized from any data format supported by Serde.
|
||||
/// A **data structure** that can be deserialized from any data format supported
|
||||
/// by Serde.
|
||||
///
|
||||
/// Serde provides `Deserialize` implementations for many Rust primitive and
|
||||
/// standard library types. The complete list is [here][de]. All of these can
|
||||
@@ -519,8 +538,7 @@ pub trait Deserialize: Sized {
|
||||
/// manual for more information about how to implement this method.
|
||||
///
|
||||
/// [impl-deserialize]: https://serde.rs/impl-deserialize.html
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where D: Deserializer;
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer;
|
||||
}
|
||||
|
||||
/// `DeserializeSeed` is the stateful form of the `Deserialize` trait. If you
|
||||
@@ -668,8 +686,7 @@ pub trait DeserializeSeed: Sized {
|
||||
|
||||
/// Equivalent to the more common `Deserialize::deserialize` method, except
|
||||
/// with some initial piece of data (the seed) passed in.
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer;
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer;
|
||||
}
|
||||
|
||||
impl<T> DeserializeSeed for PhantomData<T>
|
||||
@@ -687,8 +704,8 @@ impl<T> DeserializeSeed for PhantomData<T>
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// An implementation of this trait is a **data format** that can deserialize
|
||||
/// any data structure supported by Serde.
|
||||
/// A **data format** that can deserialize any data structure supported by
|
||||
/// Serde.
|
||||
///
|
||||
/// The role of this trait is to define the deserialization half of the Serde
|
||||
/// data model, which is a way to categorize every Rust data type into one of 28
|
||||
@@ -782,56 +799,43 @@ pub trait Deserializer: Sized {
|
||||
/// `Deserializer::deserialize` means your data type will be able to
|
||||
/// deserialize from self-describing formats only, ruling out Bincode and
|
||||
/// many others.
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a `bool` value.
|
||||
fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a `u8` value.
|
||||
fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a `u16` value.
|
||||
fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a `u32` value.
|
||||
fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a `u64` value.
|
||||
fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting an `i8` value.
|
||||
fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting an `i16` value.
|
||||
fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting an `i32` value.
|
||||
fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting an `i64` value.
|
||||
fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a `f32` value.
|
||||
fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a `f64` value.
|
||||
fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a `char` value.
|
||||
fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a string value and does
|
||||
/// not benefit from taking ownership of buffered data owned by the
|
||||
@@ -840,8 +844,7 @@ pub trait Deserializer: Sized {
|
||||
/// If the `Visitor` would benefit from taking ownership of `String` data,
|
||||
/// indiciate this to the `Deserializer` by using `deserialize_string`
|
||||
/// instead.
|
||||
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a string value and would
|
||||
/// benefit from taking ownership of buffered data owned by the
|
||||
@@ -850,18 +853,16 @@ pub trait Deserializer: Sized {
|
||||
/// If the `Visitor` would not benefit from taking ownership of `String`
|
||||
/// data, indicate that to the `Deserializer` by using `deserialize_str`
|
||||
/// instead.
|
||||
fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a byte array and does not
|
||||
/// benefit from taking ownership of buffered data owned by the
|
||||
/// `Deserializer`.
|
||||
///
|
||||
/// If the `Visitor would benefit from taking ownership of `Vec<u8>` data,
|
||||
/// If the `Visitor` would benefit from taking ownership of `Vec<u8>` data,
|
||||
/// indicate this to the `Deserializer` by using `deserialize_byte_buf`
|
||||
/// instead.
|
||||
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a byte array and would
|
||||
/// benefit from taking ownership of buffered data owned by the
|
||||
@@ -870,44 +871,43 @@ pub trait Deserializer: Sized {
|
||||
/// If the `Visitor` would not benefit from taking ownership of `Vec<u8>`
|
||||
/// data, indicate that to the `Deserializer` by using `deserialize_bytes`
|
||||
/// instead.
|
||||
fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting an optional value.
|
||||
///
|
||||
/// This allows deserializers that encode an optional value as a nullable
|
||||
/// value to convert the null value into `None` and a regular value into
|
||||
/// `Some(value)`.
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a unit value.
|
||||
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a unit struct with a
|
||||
/// particular name.
|
||||
fn deserialize_unit_struct<V>(self,
|
||||
name: &'static str,
|
||||
visitor: V) -> Result<V::Value, Self::Error>
|
||||
visitor: V)
|
||||
-> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a newtype struct with a
|
||||
/// particular name.
|
||||
fn deserialize_newtype_struct<V>(self,
|
||||
name: &'static str,
|
||||
visitor: V) -> Result<V::Value, Self::Error>
|
||||
visitor: V)
|
||||
-> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a sequence of values.
|
||||
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a sequence of values and
|
||||
/// knows how many values there are without looking at the serialized data.
|
||||
fn deserialize_seq_fixed_size<V>(self,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value, Self::Error>
|
||||
visitor: V)
|
||||
-> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a tuple value with a
|
||||
@@ -920,19 +920,20 @@ pub trait Deserializer: Sized {
|
||||
fn deserialize_tuple_struct<V>(self,
|
||||
name: &'static str,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value, Self::Error>
|
||||
visitor: V)
|
||||
-> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a map of key-value pairs.
|
||||
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a struct with a particular
|
||||
/// name and fields.
|
||||
fn deserialize_struct<V>(self,
|
||||
name: &'static str,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value, Self::Error>
|
||||
visitor: V)
|
||||
-> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting the name of a struct
|
||||
@@ -945,7 +946,8 @@ pub trait Deserializer: Sized {
|
||||
fn deserialize_enum<V>(self,
|
||||
name: &'static str,
|
||||
variants: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value, Self::Error>
|
||||
visitor: V)
|
||||
-> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
|
||||
/// Hint that the `Deserialize` type needs to deserialize a value whose type
|
||||
@@ -1014,77 +1016,77 @@ pub trait Visitor: Sized {
|
||||
|
||||
/// Deserialize a `bool` into a `Value`.
|
||||
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Err(Error::invalid_type(Unexpected::Bool(v), &self))
|
||||
}
|
||||
|
||||
/// Deserialize an `i8` into a `Value`.
|
||||
fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
self.visit_i64(v as i64)
|
||||
}
|
||||
|
||||
/// Deserialize an `i16` into a `Value`.
|
||||
fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
self.visit_i64(v as i64)
|
||||
}
|
||||
|
||||
/// Deserialize an `i32` into a `Value`.
|
||||
fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
self.visit_i64(v as i64)
|
||||
}
|
||||
|
||||
/// Deserialize an `i64` into a `Value`.
|
||||
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Err(Error::invalid_type(Unexpected::Signed(v), &self))
|
||||
}
|
||||
|
||||
/// Deserialize a `u8` into a `Value`.
|
||||
fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
self.visit_u64(v as u64)
|
||||
}
|
||||
|
||||
/// Deserialize a `u16` into a `Value`.
|
||||
fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
self.visit_u64(v as u64)
|
||||
}
|
||||
|
||||
/// Deserialize a `u32` into a `Value`.
|
||||
fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
self.visit_u64(v as u64)
|
||||
}
|
||||
|
||||
/// Deserialize a `u64` into a `Value`.
|
||||
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Err(Error::invalid_type(Unexpected::Unsigned(v), &self))
|
||||
}
|
||||
|
||||
/// Deserialize a `f32` into a `Value`.
|
||||
fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
self.visit_f64(v as f64)
|
||||
}
|
||||
|
||||
/// Deserialize a `f64` into a `Value`.
|
||||
fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Err(Error::invalid_type(Unexpected::Float(v), &self))
|
||||
}
|
||||
@@ -1092,7 +1094,7 @@ pub trait Visitor: Sized {
|
||||
/// Deserialize a `char` into a `Value`.
|
||||
#[inline]
|
||||
fn visit_char<E>(self, v: char) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
self.visit_str(::utils::encode_utf8(v).as_str())
|
||||
}
|
||||
@@ -1108,7 +1110,7 @@ pub trait Visitor: Sized {
|
||||
/// It is never correct to implement `visit_string` without implementing
|
||||
/// `visit_str`. Implement neither, both, or just `visit_str`.
|
||||
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Err(Error::invalid_type(Unexpected::Str(v), &self))
|
||||
}
|
||||
@@ -1130,28 +1132,28 @@ pub trait Visitor: Sized {
|
||||
#[inline]
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
self.visit_str(&v)
|
||||
}
|
||||
|
||||
/// Deserialize a `()` into a `Value`.
|
||||
fn visit_unit<E>(self) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Err(Error::invalid_type(Unexpected::Unit, &self))
|
||||
}
|
||||
|
||||
/// Deserialize an absent optional `Value`.
|
||||
fn visit_none<E>(self) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
Err(Error::invalid_type(Unexpected::Option, &self))
|
||||
}
|
||||
|
||||
/// Deserialize a present optional `Value`.
|
||||
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
let _ = deserializer;
|
||||
Err(Error::invalid_type(Unexpected::Option, &self))
|
||||
@@ -1159,7 +1161,7 @@ pub trait Visitor: Sized {
|
||||
|
||||
/// Deserialize `Value` as a newtype struct.
|
||||
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where D: Deserializer,
|
||||
where D: Deserializer
|
||||
{
|
||||
let _ = deserializer;
|
||||
Err(Error::invalid_type(Unexpected::NewtypeStruct, &self))
|
||||
@@ -1167,7 +1169,7 @@ pub trait Visitor: Sized {
|
||||
|
||||
/// Deserialize `Value` as a sequence of elements.
|
||||
fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: SeqVisitor,
|
||||
where V: SeqVisitor
|
||||
{
|
||||
let _ = visitor;
|
||||
Err(Error::invalid_type(Unexpected::Seq, &self))
|
||||
@@ -1175,7 +1177,7 @@ pub trait Visitor: Sized {
|
||||
|
||||
/// Deserialize `Value` as a key-value map.
|
||||
fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: MapVisitor,
|
||||
where V: MapVisitor
|
||||
{
|
||||
let _ = visitor;
|
||||
Err(Error::invalid_type(Unexpected::Map, &self))
|
||||
@@ -1183,7 +1185,7 @@ pub trait Visitor: Sized {
|
||||
|
||||
/// Deserialize `Value` as an enum.
|
||||
fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error>
|
||||
where V: EnumVisitor,
|
||||
where V: EnumVisitor
|
||||
{
|
||||
let _ = visitor;
|
||||
Err(Error::invalid_type(Unexpected::Enum, &self))
|
||||
@@ -1200,7 +1202,7 @@ pub trait Visitor: Sized {
|
||||
/// It is never correct to implement `visit_byte_buf` without implementing
|
||||
/// `visit_bytes`. Implement neither, both, or just `visit_bytes`.
|
||||
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
let _ = v;
|
||||
Err(Error::invalid_type(Unexpected::Bytes(v), &self))
|
||||
@@ -1223,7 +1225,7 @@ pub trait Visitor: Sized {
|
||||
/// `Vec<u8>`.
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
|
||||
where E: Error,
|
||||
where E: Error
|
||||
{
|
||||
self.visit_bytes(&v)
|
||||
}
|
||||
@@ -1267,7 +1269,9 @@ pub trait SeqVisitor {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, V> SeqVisitor for &'a mut V where V: SeqVisitor {
|
||||
impl<'a, V> SeqVisitor for &'a mut V
|
||||
where V: SeqVisitor
|
||||
{
|
||||
type Error = V::Error;
|
||||
|
||||
#[inline]
|
||||
@@ -1324,7 +1328,10 @@ pub trait MapVisitor {
|
||||
/// `Deserialize` implementations should typically use `MapVisitor::visit`
|
||||
/// instead.
|
||||
#[inline]
|
||||
fn visit_seed<K, V>(&mut self, kseed: K, vseed: V) -> Result<Option<(K::Value, V::Value)>, Self::Error>
|
||||
fn visit_seed<K, V>(&mut self,
|
||||
kseed: K,
|
||||
vseed: V)
|
||||
-> Result<Option<(K::Value, V::Value)>, Self::Error>
|
||||
where K: DeserializeSeed,
|
||||
V: DeserializeSeed
|
||||
{
|
||||
@@ -1333,7 +1340,7 @@ pub trait MapVisitor {
|
||||
let value = try!(self.visit_value_seed(vseed));
|
||||
Ok(Some((key, value)))
|
||||
}
|
||||
None => Ok(None)
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1368,7 +1375,7 @@ pub trait MapVisitor {
|
||||
#[inline]
|
||||
fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>
|
||||
where K: Deserialize,
|
||||
V: Deserialize,
|
||||
V: Deserialize
|
||||
{
|
||||
self.visit_seed(PhantomData, PhantomData)
|
||||
}
|
||||
@@ -1380,7 +1387,9 @@ pub trait MapVisitor {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
|
||||
impl<'a, V_> MapVisitor for &'a mut V_
|
||||
where V_: MapVisitor
|
||||
{
|
||||
type Error = V_::Error;
|
||||
|
||||
#[inline]
|
||||
@@ -1398,7 +1407,10 @@ impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_seed<K, V>(&mut self, kseed: K, vseed: V) -> Result<Option<(K::Value, V::Value)>, Self::Error>
|
||||
fn visit_seed<K, V>(&mut self,
|
||||
kseed: K,
|
||||
vseed: V)
|
||||
-> Result<Option<(K::Value, V::Value)>, Self::Error>
|
||||
where K: DeserializeSeed,
|
||||
V: DeserializeSeed
|
||||
{
|
||||
@@ -1408,7 +1420,7 @@ impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
|
||||
#[inline]
|
||||
fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, V_::Error>
|
||||
where K: Deserialize,
|
||||
V: Deserialize,
|
||||
V: Deserialize
|
||||
{
|
||||
(**self).visit()
|
||||
}
|
||||
@@ -1444,7 +1456,7 @@ pub trait EnumVisitor: Sized {
|
||||
type Error: Error;
|
||||
/// The `Visitor` that will be used to deserialize the content of the enum
|
||||
/// variant.
|
||||
type Variant: VariantVisitor<Error=Self::Error>;
|
||||
type Variant: VariantVisitor<Error = Self::Error>;
|
||||
|
||||
/// `visit_variant` is called to identify which variant to deserialize.
|
||||
///
|
||||
@@ -1537,9 +1549,7 @@ pub trait VariantVisitor: Sized {
|
||||
/// Err(Error::invalid_type(unexp, &"tuple variant"))
|
||||
/// }
|
||||
/// ```
|
||||
fn visit_tuple<V>(self,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value, Self::Error>
|
||||
fn visit_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
|
||||
/// Called when deserializing a struct-like variant.
|
||||
@@ -1562,7 +1572,8 @@ pub trait VariantVisitor: Sized {
|
||||
/// ```
|
||||
fn visit_struct<V>(self,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value, Self::Error>
|
||||
visitor: V)
|
||||
-> Result<V::Value, Self::Error>
|
||||
where V: Visitor;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,11 @@ use core::marker::PhantomData;
|
||||
|
||||
use de::{Deserialize, Deserializer, Error, Visitor};
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
pub use de::content::{Content, ContentRefDeserializer, ContentDeserializer, TaggedContentVisitor,
|
||||
TagOrContentField, TagOrContentFieldVisitor, InternallyTaggedUnitVisitor,
|
||||
UntaggedUnitVisitor};
|
||||
|
||||
/// If the missing field is of type `Option<T>` then treat is as `None`,
|
||||
/// otherwise it is an error.
|
||||
pub fn missing_field<V, E>(field: &'static str) -> Result<V, E>
|
||||
|
||||
+181
-139
@@ -1,31 +1,15 @@
|
||||
//! This module supports deserializing from primitives with the `ValueDeserializer` trait.
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use std::collections::{
|
||||
BTreeMap,
|
||||
BTreeSet,
|
||||
HashMap,
|
||||
HashSet,
|
||||
btree_map,
|
||||
btree_set,
|
||||
hash_map,
|
||||
hash_set,
|
||||
};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, btree_map, btree_set, hash_map,
|
||||
hash_set};
|
||||
#[cfg(feature = "std")]
|
||||
use std::borrow::Cow;
|
||||
#[cfg(feature = "std")]
|
||||
use std::vec;
|
||||
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
use collections::{
|
||||
BTreeMap,
|
||||
BTreeSet,
|
||||
Vec,
|
||||
String,
|
||||
btree_map,
|
||||
btree_set,
|
||||
vec,
|
||||
};
|
||||
use collections::{BTreeMap, BTreeSet, Vec, String, btree_map, btree_set, vec};
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
use collections::borrow::Cow;
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
@@ -41,7 +25,7 @@ use std::error;
|
||||
use error;
|
||||
|
||||
use core::fmt::{self, Display};
|
||||
use core::iter::{self, Iterator};
|
||||
use core::iter::{self, Iterator};
|
||||
use core::marker::PhantomData;
|
||||
|
||||
use de::{self, Expected, SeqVisitor};
|
||||
@@ -51,7 +35,9 @@ use bytes;
|
||||
|
||||
/// This represents all the possible errors that can occur using the `ValueDeserializer`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Error(ErrorImpl);
|
||||
pub struct Error {
|
||||
err: ErrorImpl,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
type ErrorImpl = Box<str>;
|
||||
@@ -61,19 +47,19 @@ type ErrorImpl = ();
|
||||
impl de::Error for Error {
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
fn custom<T: Display>(msg: T) -> Self {
|
||||
Error(msg.to_string().into_boxed_str())
|
||||
Error { err: msg.to_string().into_boxed_str() }
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
fn custom<T: Display>(_msg: T) -> Self {
|
||||
Error(())
|
||||
Error { err: () }
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Error {
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||
formatter.write_str(&self.0)
|
||||
formatter.write_str(&self.err)
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
@@ -85,7 +71,7 @@ impl Display for Error {
|
||||
impl error::Error for Error {
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
fn description(&self) -> &str {
|
||||
&self.0
|
||||
&self.err
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
@@ -99,7 +85,7 @@ impl error::Error for Error {
|
||||
/// This trait converts primitive types into a deserializer.
|
||||
pub trait ValueDeserializer<E: de::Error = Error> {
|
||||
/// The actual deserializer type.
|
||||
type Deserializer: de::Deserializer<Error=E>;
|
||||
type Deserializer: de::Deserializer<Error = E>;
|
||||
|
||||
/// Convert this value into a deserializer.
|
||||
fn into_deserializer(self) -> Self::Deserializer;
|
||||
@@ -108,17 +94,19 @@ pub trait ValueDeserializer<E: de::Error = Error> {
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<E> ValueDeserializer<E> for ()
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
type Deserializer = UnitDeserializer<E>;
|
||||
|
||||
fn into_deserializer(self) -> UnitDeserializer<E> {
|
||||
UnitDeserializer(PhantomData)
|
||||
UnitDeserializer { marker: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
/// A helper deserializer that deserializes a `()`.
|
||||
pub struct UnitDeserializer<E>(PhantomData<E>);
|
||||
pub struct UnitDeserializer<E> {
|
||||
marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<E> de::Deserializer for UnitDeserializer<E>
|
||||
where E: de::Error
|
||||
@@ -132,13 +120,13 @@ impl<E> de::Deserializer for UnitDeserializer<E>
|
||||
}
|
||||
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
where V: de::Visitor
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
where V: de::Visitor
|
||||
{
|
||||
visitor.visit_none()
|
||||
}
|
||||
@@ -149,7 +137,10 @@ impl<E> de::Deserializer for UnitDeserializer<E>
|
||||
macro_rules! primitive_deserializer {
|
||||
($ty:ty, $name:ident, $method:ident $($cast:tt)*) => {
|
||||
/// A helper deserializer that deserializes a number.
|
||||
pub struct $name<E>($ty, PhantomData<E>);
|
||||
pub struct $name<E> {
|
||||
value: $ty,
|
||||
marker: PhantomData<E>
|
||||
}
|
||||
|
||||
impl<E> ValueDeserializer<E> for $ty
|
||||
where E: de::Error,
|
||||
@@ -157,7 +148,10 @@ macro_rules! primitive_deserializer {
|
||||
type Deserializer = $name<E>;
|
||||
|
||||
fn into_deserializer(self) -> $name<E> {
|
||||
$name(self, PhantomData)
|
||||
$name {
|
||||
value: self,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,7 +169,7 @@ macro_rules! primitive_deserializer {
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
visitor.$method(self.0 $($cast)*)
|
||||
visitor.$method(self.value $($cast)*)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -199,34 +193,41 @@ primitive_deserializer!(char, CharDeserializer, visit_char);
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// A helper deserializer that deserializes a `&str`.
|
||||
pub struct StrDeserializer<'a, E>(&'a str, PhantomData<E>);
|
||||
pub struct StrDeserializer<'a, E> {
|
||||
value: &'a str,
|
||||
marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<'a, E> ValueDeserializer<E> for &'a str
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
type Deserializer = StrDeserializer<'a, E>;
|
||||
|
||||
fn into_deserializer(self) -> StrDeserializer<'a, E> {
|
||||
StrDeserializer(self, PhantomData)
|
||||
StrDeserializer {
|
||||
value: self,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, E> de::Deserializer for StrDeserializer<'a, E>
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
where V: de::Visitor
|
||||
{
|
||||
visitor.visit_str(self.0)
|
||||
visitor.visit_str(self.value)
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(self,
|
||||
_name: &str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
_name: &str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V)
|
||||
-> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor
|
||||
{
|
||||
visitor.visit_enum(self)
|
||||
}
|
||||
@@ -239,13 +240,13 @@ impl<'a, E> de::Deserializer for StrDeserializer<'a, E>
|
||||
}
|
||||
|
||||
impl<'a, E> de::EnumVisitor for StrDeserializer<'a, E>
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
type Variant = private::UnitOnly<E>;
|
||||
|
||||
fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
|
||||
where T: de::DeserializeSeed,
|
||||
where T: de::DeserializeSeed
|
||||
{
|
||||
seed.deserialize(self).map(private::unit_only)
|
||||
}
|
||||
@@ -255,36 +256,43 @@ impl<'a, E> de::EnumVisitor for StrDeserializer<'a, E>
|
||||
|
||||
/// A helper deserializer that deserializes a `String`.
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
pub struct StringDeserializer<E>(String, PhantomData<E>);
|
||||
pub struct StringDeserializer<E> {
|
||||
value: String,
|
||||
marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<E> ValueDeserializer<E> for String
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
type Deserializer = StringDeserializer<E>;
|
||||
|
||||
fn into_deserializer(self) -> StringDeserializer<E> {
|
||||
StringDeserializer(self, PhantomData)
|
||||
StringDeserializer {
|
||||
value: self,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<E> de::Deserializer for StringDeserializer<E>
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
where V: de::Visitor
|
||||
{
|
||||
visitor.visit_string(self.0)
|
||||
visitor.visit_string(self.value)
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(self,
|
||||
_name: &str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
_name: &str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V)
|
||||
-> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor
|
||||
{
|
||||
visitor.visit_enum(self)
|
||||
}
|
||||
@@ -298,13 +306,13 @@ impl<E> de::Deserializer for StringDeserializer<E>
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'a, E> de::EnumVisitor for StringDeserializer<E>
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
type Variant = private::UnitOnly<E>;
|
||||
|
||||
fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
|
||||
where T: de::DeserializeSeed,
|
||||
where T: de::DeserializeSeed
|
||||
{
|
||||
seed.deserialize(self).map(private::unit_only)
|
||||
}
|
||||
@@ -314,39 +322,46 @@ impl<'a, E> de::EnumVisitor for StringDeserializer<E>
|
||||
|
||||
/// A helper deserializer that deserializes a `String`.
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
pub struct CowStrDeserializer<'a, E>(Cow<'a, str>, PhantomData<E>);
|
||||
pub struct CowStrDeserializer<'a, E> {
|
||||
value: Cow<'a, str>,
|
||||
marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'a, E> ValueDeserializer<E> for Cow<'a, str>
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
type Deserializer = CowStrDeserializer<'a, E>;
|
||||
|
||||
fn into_deserializer(self) -> CowStrDeserializer<'a, E> {
|
||||
CowStrDeserializer(self, PhantomData)
|
||||
CowStrDeserializer {
|
||||
value: self,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E>
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
where V: de::Visitor
|
||||
{
|
||||
match self.0 {
|
||||
match self.value {
|
||||
Cow::Borrowed(string) => visitor.visit_str(string),
|
||||
Cow::Owned(string) => visitor.visit_string(string),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(self,
|
||||
_name: &str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
_name: &str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V)
|
||||
-> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor
|
||||
{
|
||||
visitor.visit_enum(self)
|
||||
}
|
||||
@@ -360,13 +375,13 @@ impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E>
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'a, E> de::EnumVisitor for CowStrDeserializer<'a, E>
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
type Variant = private::UnitOnly<E>;
|
||||
|
||||
fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
|
||||
where T: de::DeserializeSeed,
|
||||
where T: de::DeserializeSeed
|
||||
{
|
||||
seed.deserialize(self).map(private::unit_only)
|
||||
}
|
||||
@@ -383,7 +398,7 @@ pub struct SeqDeserializer<I, E> {
|
||||
|
||||
impl<I, E> SeqDeserializer<I, E>
|
||||
where I: Iterator,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
/// Construct a new `SeqDeserializer<I>`.
|
||||
pub fn new(iter: I) -> Self {
|
||||
@@ -394,7 +409,9 @@ impl<I, E> SeqDeserializer<I, E>
|
||||
}
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), E> {
|
||||
/// Check for remaining elements after passing a `SeqDeserializer` to
|
||||
/// `Visitor::visit_seq`.
|
||||
pub fn end(mut self) -> Result<(), E> {
|
||||
let mut remaining = 0;
|
||||
while self.iter.next().is_some() {
|
||||
remaining += 1;
|
||||
@@ -410,14 +427,14 @@ impl<I, E> SeqDeserializer<I, E>
|
||||
}
|
||||
|
||||
impl<I, T, E> de::Deserializer for SeqDeserializer<I, E>
|
||||
where I: Iterator<Item=T>,
|
||||
where I: Iterator<Item = T>,
|
||||
T: ValueDeserializer<E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
where V: de::Visitor
|
||||
{
|
||||
let v = try!(visitor.visit_seq(&mut self));
|
||||
try!(self.end());
|
||||
@@ -432,9 +449,9 @@ impl<I, T, E> de::Deserializer for SeqDeserializer<I, E>
|
||||
}
|
||||
|
||||
impl<I, T, E> de::SeqVisitor for SeqDeserializer<I, E>
|
||||
where I: Iterator<Item=T>,
|
||||
where I: Iterator<Item = T>,
|
||||
T: ValueDeserializer<E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
@@ -472,7 +489,7 @@ impl Expected for ExpectedInSeq {
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T, E> ValueDeserializer<E> for Vec<T>
|
||||
where T: ValueDeserializer<E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
type Deserializer = SeqDeserializer<vec::IntoIter<T>, E>;
|
||||
|
||||
@@ -484,7 +501,7 @@ impl<T, E> ValueDeserializer<E> for Vec<T>
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T, E> ValueDeserializer<E> for BTreeSet<T>
|
||||
where T: ValueDeserializer<E> + Eq + Ord,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
type Deserializer = SeqDeserializer<btree_set::IntoIter<T>, E>;
|
||||
|
||||
@@ -496,7 +513,7 @@ impl<T, E> ValueDeserializer<E> for BTreeSet<T>
|
||||
#[cfg(feature = "std")]
|
||||
impl<T, E> ValueDeserializer<E> for HashSet<T>
|
||||
where T: ValueDeserializer<E> + Eq + Hash,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
type Deserializer = SeqDeserializer<hash_set::IntoIter<T>, E>;
|
||||
|
||||
@@ -515,20 +532,20 @@ pub struct SeqVisitorDeserializer<V_, E> {
|
||||
|
||||
impl<V_, E> SeqVisitorDeserializer<V_, E>
|
||||
where V_: de::SeqVisitor<Error = E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
/// Construct a new `SeqVisitorDeserializer<V_, E>`.
|
||||
pub fn new(visitor: V_) -> Self {
|
||||
SeqVisitorDeserializer{
|
||||
SeqVisitorDeserializer {
|
||||
visitor: visitor,
|
||||
marker: PhantomData
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V_, E> de::Deserializer for SeqVisitorDeserializer<V_, E>
|
||||
where V_: de::SeqVisitor<Error = E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
@@ -551,7 +568,7 @@ pub struct MapDeserializer<I, E>
|
||||
I::Item: private::Pair,
|
||||
<I::Item as private::Pair>::First: ValueDeserializer<E>,
|
||||
<I::Item as private::Pair>::Second: ValueDeserializer<E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
iter: iter::Fuse<I>,
|
||||
value: Option<<I::Item as private::Pair>::Second>,
|
||||
@@ -564,7 +581,7 @@ impl<I, E> MapDeserializer<I, E>
|
||||
I::Item: private::Pair,
|
||||
<I::Item as private::Pair>::First: ValueDeserializer<E>,
|
||||
<I::Item as private::Pair>::Second: ValueDeserializer<E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
/// Construct a new `MapDeserializer<I, K, V, E>`.
|
||||
pub fn new(iter: I) -> Self {
|
||||
@@ -576,17 +593,9 @@ impl<I, E> MapDeserializer<I, E>
|
||||
}
|
||||
}
|
||||
|
||||
fn next_pair(&mut self) -> Option<(<I::Item as private::Pair>::First, <I::Item as private::Pair>::Second)> {
|
||||
match self.iter.next() {
|
||||
Some(kv) => {
|
||||
self.count += 1;
|
||||
Some(private::Pair::split(kv))
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), E> {
|
||||
/// Check for remaining elements after passing a `MapDeserializer` to
|
||||
/// `Visitor::visit_map`.
|
||||
pub fn end(mut self) -> Result<(), E> {
|
||||
let mut remaining = 0;
|
||||
while self.iter.next().is_some() {
|
||||
remaining += 1;
|
||||
@@ -599,6 +608,18 @@ impl<I, E> MapDeserializer<I, E>
|
||||
Err(de::Error::invalid_length(self.count + remaining, &ExpectedInMap(self.count)))
|
||||
}
|
||||
}
|
||||
|
||||
fn next_pair
|
||||
(&mut self)
|
||||
-> Option<(<I::Item as private::Pair>::First, <I::Item as private::Pair>::Second)> {
|
||||
match self.iter.next() {
|
||||
Some(kv) => {
|
||||
self.count += 1;
|
||||
Some(private::Pair::split(kv))
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<I, E> de::Deserializer for MapDeserializer<I, E>
|
||||
@@ -606,12 +627,12 @@ impl<I, E> de::Deserializer for MapDeserializer<I, E>
|
||||
I::Item: private::Pair,
|
||||
<I::Item as private::Pair>::First: ValueDeserializer<E>,
|
||||
<I::Item as private::Pair>::Second: ValueDeserializer<E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize<V_>(mut self, visitor: V_) -> Result<V_::Value, Self::Error>
|
||||
where V_: de::Visitor,
|
||||
where V_: de::Visitor
|
||||
{
|
||||
let value = try!(visitor.visit_map(&mut self));
|
||||
try!(self.end());
|
||||
@@ -619,15 +640,18 @@ impl<I, E> de::Deserializer for MapDeserializer<I, E>
|
||||
}
|
||||
|
||||
fn deserialize_seq<V_>(mut self, visitor: V_) -> Result<V_::Value, Self::Error>
|
||||
where V_: de::Visitor,
|
||||
where V_: de::Visitor
|
||||
{
|
||||
let value = try!(visitor.visit_seq(&mut self));
|
||||
try!(self.end());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn deserialize_seq_fixed_size<V_>(self, _len: usize, visitor: V_) -> Result<V_::Value, Self::Error>
|
||||
where V_: de::Visitor,
|
||||
fn deserialize_seq_fixed_size<V_>(self,
|
||||
_len: usize,
|
||||
visitor: V_)
|
||||
-> Result<V_::Value, Self::Error>
|
||||
where V_: de::Visitor
|
||||
{
|
||||
self.deserialize_seq(visitor)
|
||||
}
|
||||
@@ -644,12 +668,12 @@ impl<I, E> de::MapVisitor for MapDeserializer<I, E>
|
||||
I::Item: private::Pair,
|
||||
<I::Item as private::Pair>::First: ValueDeserializer<E>,
|
||||
<I::Item as private::Pair>::Second: ValueDeserializer<E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
|
||||
where T: de::DeserializeSeed,
|
||||
where T: de::DeserializeSeed
|
||||
{
|
||||
match self.next_pair() {
|
||||
Some((key, value)) => {
|
||||
@@ -661,7 +685,7 @@ impl<I, E> de::MapVisitor for MapDeserializer<I, E>
|
||||
}
|
||||
|
||||
fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
|
||||
where T: de::DeserializeSeed,
|
||||
where T: de::DeserializeSeed
|
||||
{
|
||||
let value = self.value.take();
|
||||
// Panic because this indicates a bug in the program rather than an
|
||||
@@ -670,7 +694,10 @@ impl<I, E> de::MapVisitor for MapDeserializer<I, E>
|
||||
seed.deserialize(value.into_deserializer())
|
||||
}
|
||||
|
||||
fn visit_seed<TK, TV>(&mut self, kseed: TK, vseed: TV) -> Result<Option<(TK::Value, TV::Value)>, Self::Error>
|
||||
fn visit_seed<TK, TV>(&mut self,
|
||||
kseed: TK,
|
||||
vseed: TV)
|
||||
-> Result<Option<(TK::Value, TV::Value)>, Self::Error>
|
||||
where TK: de::DeserializeSeed,
|
||||
TV: de::DeserializeSeed
|
||||
{
|
||||
@@ -680,7 +707,7 @@ impl<I, E> de::MapVisitor for MapDeserializer<I, E>
|
||||
let value = try!(vseed.deserialize(value.into_deserializer()));
|
||||
Ok(Some((key, value)))
|
||||
}
|
||||
None => Ok(None)
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -694,12 +721,12 @@ impl<I, E> de::SeqVisitor for MapDeserializer<I, E>
|
||||
I::Item: private::Pair,
|
||||
<I::Item as private::Pair>::First: ValueDeserializer<E>,
|
||||
<I::Item as private::Pair>::Second: ValueDeserializer<E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
|
||||
where T: de::DeserializeSeed,
|
||||
where T: de::DeserializeSeed
|
||||
{
|
||||
match self.next_pair() {
|
||||
Some((k, v)) => {
|
||||
@@ -733,13 +760,13 @@ impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E>
|
||||
}
|
||||
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
where V: de::Visitor
|
||||
{
|
||||
self.deserialize_seq(visitor)
|
||||
}
|
||||
|
||||
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
where V: de::Visitor
|
||||
{
|
||||
let mut pair_visitor = PairVisitor(Some(self.0), Some(self.1), PhantomData);
|
||||
let pair = try!(visitor.visit_seq(&mut pair_visitor));
|
||||
@@ -754,7 +781,7 @@ impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E>
|
||||
}
|
||||
|
||||
fn deserialize_seq_fixed_size<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
where V: de::Visitor
|
||||
{
|
||||
if len == 2 {
|
||||
self.deserialize_seq(visitor)
|
||||
@@ -771,12 +798,12 @@ struct PairVisitor<A, B, E>(Option<A>, Option<B>, PhantomData<E>);
|
||||
impl<A, B, E> de::SeqVisitor for PairVisitor<A, B, E>
|
||||
where A: ValueDeserializer<E>,
|
||||
B: ValueDeserializer<E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
|
||||
where T: de::DeserializeSeed,
|
||||
where T: de::DeserializeSeed
|
||||
{
|
||||
if let Some(k) = self.0.take() {
|
||||
seed.deserialize(k.into_deserializer()).map(Some)
|
||||
@@ -817,7 +844,7 @@ impl Expected for ExpectedInMap {
|
||||
impl<K, V, E> ValueDeserializer<E> for BTreeMap<K, V>
|
||||
where K: ValueDeserializer<E> + Eq + Ord,
|
||||
V: ValueDeserializer<E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
type Deserializer = MapDeserializer<btree_map::IntoIter<K, V>, E>;
|
||||
|
||||
@@ -830,7 +857,7 @@ impl<K, V, E> ValueDeserializer<E> for BTreeMap<K, V>
|
||||
impl<K, V, E> ValueDeserializer<E> for HashMap<K, V>
|
||||
where K: ValueDeserializer<E> + Eq + Hash,
|
||||
V: ValueDeserializer<E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
type Deserializer = MapDeserializer<hash_map::IntoIter<K, V>, E>;
|
||||
|
||||
@@ -849,20 +876,20 @@ pub struct MapVisitorDeserializer<V_, E> {
|
||||
|
||||
impl<V_, E> MapVisitorDeserializer<V_, E>
|
||||
where V_: de::MapVisitor<Error = E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
/// Construct a new `MapVisitorDeserializer<V_, E>`.
|
||||
pub fn new(visitor: V_) -> Self {
|
||||
MapVisitorDeserializer{
|
||||
MapVisitorDeserializer {
|
||||
visitor: visitor,
|
||||
marker: PhantomData
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V_, E> de::Deserializer for MapVisitorDeserializer<V_, E>
|
||||
where V_: de::MapVisitor<Error = E>,
|
||||
E: de::Error,
|
||||
E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
@@ -880,17 +907,23 @@ impl<V_, E> de::Deserializer for MapVisitorDeserializer<V_, E>
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<'a, E> ValueDeserializer<E> for bytes::Bytes<'a>
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
type Deserializer = BytesDeserializer<'a, E>;
|
||||
|
||||
fn into_deserializer(self) -> BytesDeserializer<'a, E> {
|
||||
BytesDeserializer(self.into(), PhantomData)
|
||||
BytesDeserializer {
|
||||
value: self.into(),
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A helper deserializer that deserializes a `&[u8]`.
|
||||
pub struct BytesDeserializer<'a, E>(&'a [u8], PhantomData<E>);
|
||||
pub struct BytesDeserializer<'a, E> {
|
||||
value: &'a [u8],
|
||||
marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<'a, E> de::Deserializer for BytesDeserializer<'a, E>
|
||||
where E: de::Error
|
||||
@@ -898,9 +931,9 @@ impl<'a, E> de::Deserializer for BytesDeserializer<'a, E>
|
||||
type Error = E;
|
||||
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
where V: de::Visitor
|
||||
{
|
||||
visitor.visit_bytes(self.0)
|
||||
visitor.visit_bytes(self.value)
|
||||
}
|
||||
|
||||
forward_to_deserialize! {
|
||||
@@ -914,29 +947,35 @@ impl<'a, E> de::Deserializer for BytesDeserializer<'a, E>
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<E> ValueDeserializer<E> for bytes::ByteBuf
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
type Deserializer = ByteBufDeserializer<E>;
|
||||
|
||||
fn into_deserializer(self) -> Self::Deserializer {
|
||||
ByteBufDeserializer(self.into(), PhantomData)
|
||||
ByteBufDeserializer {
|
||||
value: self.into(),
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A helper deserializer that deserializes a `Vec<u8>`.
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
pub struct ByteBufDeserializer<E>(Vec<u8>, PhantomData<E>);
|
||||
pub struct ByteBufDeserializer<E> {
|
||||
value: Vec<u8>,
|
||||
marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<E> de::Deserializer for ByteBufDeserializer<E>
|
||||
where E: de::Error,
|
||||
where E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
where V: de::Visitor
|
||||
{
|
||||
visitor.visit_byte_buf(self.0)
|
||||
visitor.visit_byte_buf(self.value)
|
||||
}
|
||||
|
||||
forward_to_deserialize! {
|
||||
@@ -952,10 +991,12 @@ mod private {
|
||||
use de::{self, Unexpected};
|
||||
use core::marker::PhantomData;
|
||||
|
||||
pub struct UnitOnly<E>(PhantomData<E>);
|
||||
pub struct UnitOnly<E> {
|
||||
marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
pub fn unit_only<T, E>(t: T) -> (T, UnitOnly<E>) {
|
||||
(t, UnitOnly(PhantomData))
|
||||
(t, UnitOnly { marker: PhantomData })
|
||||
}
|
||||
|
||||
impl<E> de::VariantVisitor for UnitOnly<E>
|
||||
@@ -968,14 +1009,12 @@ mod private {
|
||||
}
|
||||
|
||||
fn visit_newtype_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
|
||||
where T: de::DeserializeSeed,
|
||||
where T: de::DeserializeSeed
|
||||
{
|
||||
Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant"))
|
||||
}
|
||||
|
||||
fn visit_tuple<V>(self,
|
||||
_len: usize,
|
||||
_visitor: V) -> Result<V::Value, Self::Error>
|
||||
fn visit_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor
|
||||
{
|
||||
Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"))
|
||||
@@ -983,7 +1022,8 @@ mod private {
|
||||
|
||||
fn visit_struct<V>(self,
|
||||
_fields: &'static [&'static str],
|
||||
_visitor: V) -> Result<V::Value, Self::Error>
|
||||
_visitor: V)
|
||||
-> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor
|
||||
{
|
||||
Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant"))
|
||||
@@ -1001,6 +1041,8 @@ mod private {
|
||||
impl<A, B> Pair for (A, B) {
|
||||
type First = A;
|
||||
type Second = B;
|
||||
fn split(self) -> (A, B) { self }
|
||||
fn split(self) -> (A, B) {
|
||||
self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -11,5 +11,7 @@ pub trait Error: Debug + Display {
|
||||
fn description(&self) -> &str;
|
||||
|
||||
/// The lower-level cause of this error, if any.
|
||||
fn cause(&self) -> Option<&Error> { None }
|
||||
fn cause(&self) -> Option<&Error> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -9,7 +9,8 @@ use collections::borrow::Cow;
|
||||
pub use core::default::Default;
|
||||
pub use core::fmt;
|
||||
pub use core::marker::PhantomData;
|
||||
pub use core::result::Result;
|
||||
pub use core::option::Option::{self, None, Some};
|
||||
pub use core::result::Result::{self, Ok, Err};
|
||||
|
||||
#[cfg(any(feature = "collections", feature = "std"))]
|
||||
pub fn from_utf8_lossy(bytes: &[u8]) -> Cow<str> {
|
||||
|
||||
+24
-12
@@ -4,13 +4,13 @@ use std::io;
|
||||
use std::iter::Peekable;
|
||||
|
||||
/// Iterator over a byte stream that tracks the current position's line and column.
|
||||
pub struct LineColIterator<Iter: Iterator<Item=io::Result<u8>>> {
|
||||
pub struct LineColIterator<Iter: Iterator<Item = io::Result<u8>>> {
|
||||
iter: Iter,
|
||||
line: usize,
|
||||
col: usize,
|
||||
}
|
||||
|
||||
impl<Iter: Iterator<Item=io::Result<u8>>> LineColIterator<Iter> {
|
||||
impl<Iter: Iterator<Item = io::Result<u8>>> LineColIterator<Iter> {
|
||||
/// Construct a new `LineColIterator<Iter>`.
|
||||
pub fn new(iter: Iter) -> LineColIterator<Iter> {
|
||||
LineColIterator {
|
||||
@@ -21,27 +21,39 @@ impl<Iter: Iterator<Item=io::Result<u8>>> LineColIterator<Iter> {
|
||||
}
|
||||
|
||||
/// Report the current line inside the iterator.
|
||||
pub fn line(&self) -> usize { self.line }
|
||||
pub fn line(&self) -> usize {
|
||||
self.line
|
||||
}
|
||||
|
||||
/// Report the current column inside the iterator.
|
||||
pub fn col(&self) -> usize { self.col }
|
||||
pub fn col(&self) -> usize {
|
||||
self.col
|
||||
}
|
||||
|
||||
/// Gets a reference to the underlying iterator.
|
||||
pub fn get_ref(&self) -> &Iter { &self.iter }
|
||||
pub fn get_ref(&self) -> &Iter {
|
||||
&self.iter
|
||||
}
|
||||
|
||||
/// Gets a mutable reference to the underlying iterator.
|
||||
pub fn get_mut(&mut self) -> &mut Iter { &mut self.iter }
|
||||
pub fn get_mut(&mut self) -> &mut Iter {
|
||||
&mut self.iter
|
||||
}
|
||||
|
||||
/// Unwraps this `LineColIterator`, returning the underlying iterator.
|
||||
pub fn into_inner(self) -> Iter { self.iter }
|
||||
pub fn into_inner(self) -> Iter {
|
||||
self.iter
|
||||
}
|
||||
}
|
||||
|
||||
impl<Iter: Iterator<Item=io::Result<u8>>> LineColIterator<Peekable<Iter>> {
|
||||
impl<Iter: Iterator<Item = io::Result<u8>>> LineColIterator<Peekable<Iter>> {
|
||||
/// peeks at the next value
|
||||
pub fn peek(&mut self) -> Option<&io::Result<u8>> { self.iter.peek() }
|
||||
pub fn peek(&mut self) -> Option<&io::Result<u8>> {
|
||||
self.iter.peek()
|
||||
}
|
||||
}
|
||||
|
||||
impl<Iter: Iterator<Item=io::Result<u8>>> Iterator for LineColIterator<Iter> {
|
||||
impl<Iter: Iterator<Item = io::Result<u8>>> Iterator for LineColIterator<Iter> {
|
||||
type Item = io::Result<u8>;
|
||||
fn next(&mut self) -> Option<io::Result<u8>> {
|
||||
match self.iter.next() {
|
||||
@@ -50,11 +62,11 @@ impl<Iter: Iterator<Item=io::Result<u8>>> Iterator for LineColIterator<Iter> {
|
||||
self.line += 1;
|
||||
self.col = 0;
|
||||
Some(Ok(b'\n'))
|
||||
},
|
||||
}
|
||||
Some(Ok(c)) => {
|
||||
self.col += 1;
|
||||
Some(Ok(c))
|
||||
},
|
||||
}
|
||||
Some(Err(e)) => Some(Err(e)),
|
||||
}
|
||||
}
|
||||
|
||||
+6
-6
@@ -61,12 +61,10 @@
|
||||
|
||||
#![doc(html_root_url="https://docs.serde.rs")]
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
#![cfg_attr(feature = "unstable", feature(nonzero, inclusive_range, zero_one))]
|
||||
#![cfg_attr(feature = "unstable", feature(inclusive_range, nonzero, specialization, zero_one))]
|
||||
#![cfg_attr(feature = "alloc", feature(alloc))]
|
||||
#![cfg_attr(feature = "collections", feature(collections, enumset))]
|
||||
#![cfg_attr(feature = "clippy", feature(plugin))]
|
||||
#![cfg_attr(feature = "clippy", plugin(clippy))]
|
||||
#![cfg_attr(feature = "clippy", allow(linkedlist, type_complexity, doc_markdown))]
|
||||
#![cfg_attr(feature = "collections", feature(collections))]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(linkedlist, type_complexity, doc_markdown))]
|
||||
#![deny(missing_docs)]
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
@@ -81,12 +79,14 @@ extern crate core as actual_core;
|
||||
#[cfg(feature = "std")]
|
||||
mod core {
|
||||
pub use std::{ops, hash, fmt, cmp, marker, mem, i8, i16, i32, i64, u8, u16, u32, u64, isize,
|
||||
usize, f32, f64, char, str, num, slice, iter, cell, default, result};
|
||||
usize, f32, f64, char, str, num, slice, iter, cell, default, result, option};
|
||||
#[cfg(feature = "unstable")]
|
||||
pub use actual_core::nonzero;
|
||||
}
|
||||
|
||||
#[doc(inline)]
|
||||
pub use ser::{Serialize, Serializer};
|
||||
#[doc(inline)]
|
||||
pub use de::{Deserialize, Deserializer};
|
||||
|
||||
#[macro_use]
|
||||
|
||||
@@ -188,3 +188,35 @@ macro_rules! forward_to_deserialize {
|
||||
$(forward_to_deserialize_helper!{$func})*
|
||||
};
|
||||
}
|
||||
|
||||
/// Seralize the `$value` that implements Display as a string,
|
||||
/// when that string is statically known to never have more than
|
||||
/// a constant `$MAX_LEN` bytes.
|
||||
///
|
||||
/// Panics if the Display impl tries to write more than `$MAX_LEN` bytes.
|
||||
#[cfg(feature = "std")]
|
||||
// Not exported
|
||||
macro_rules! serialize_display_bounded_length {
|
||||
($value: expr, $MAX_LEN: expr, $serializer: expr) => {
|
||||
{
|
||||
use std::io::Write;
|
||||
let mut buffer: [u8; $MAX_LEN] = unsafe { ::std::mem::uninitialized() };
|
||||
let remaining_len;
|
||||
{
|
||||
let mut remaining = &mut buffer[..];
|
||||
write!(remaining, "{}", $value).unwrap();
|
||||
remaining_len = remaining.len()
|
||||
}
|
||||
let written_len = buffer.len() - remaining_len;
|
||||
let written = &buffer[..written_len];
|
||||
|
||||
// write! only provides std::fmt::Formatter to Display implementations,
|
||||
// which has methods write_str and write_char but no method to write arbitrary bytes.
|
||||
// Therefore, `written` is well-formed in UTF-8.
|
||||
let written_str = unsafe {
|
||||
::std::str::from_utf8_unchecked(written)
|
||||
};
|
||||
$serializer.serialize_str(written_str)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+64
-132
@@ -4,28 +4,10 @@ use std::borrow::Cow;
|
||||
use collections::borrow::Cow;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use std::collections::{
|
||||
BinaryHeap,
|
||||
BTreeMap,
|
||||
BTreeSet,
|
||||
LinkedList,
|
||||
HashMap,
|
||||
HashSet,
|
||||
VecDeque,
|
||||
};
|
||||
use std::collections::{BinaryHeap, BTreeMap, BTreeSet, LinkedList, HashMap, HashSet, VecDeque};
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
use collections::{
|
||||
BinaryHeap,
|
||||
BTreeMap,
|
||||
BTreeSet,
|
||||
LinkedList,
|
||||
VecDeque,
|
||||
String,
|
||||
Vec,
|
||||
};
|
||||
use collections::{BinaryHeap, BTreeMap, BTreeSet, LinkedList, VecDeque, String, Vec};
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
use collections::enum_set::{CLike, EnumSet};
|
||||
#[cfg(feature = "collections")]
|
||||
use collections::borrow::ToOwned;
|
||||
|
||||
@@ -59,18 +41,10 @@ use core::marker::PhantomData;
|
||||
#[cfg(feature = "unstable")]
|
||||
use core::nonzero::{NonZero, Zeroable};
|
||||
|
||||
use super::{
|
||||
Serialize,
|
||||
SerializeSeq,
|
||||
SerializeTuple,
|
||||
Serializer,
|
||||
};
|
||||
#[cfg(any(feature = "std", feature = "unstable"))]
|
||||
use super::{Serialize, SerializeSeq, SerializeTuple, Serializer};
|
||||
#[cfg(feature = "std")]
|
||||
use super::Error;
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
use super::Iterator;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! impl_visit {
|
||||
@@ -106,7 +80,7 @@ impl_visit!(char, serialize_char);
|
||||
impl Serialize for str {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
serializer.serialize_str(self)
|
||||
}
|
||||
@@ -116,7 +90,7 @@ impl Serialize for str {
|
||||
impl Serialize for String {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
(&self[..]).serialize(serializer)
|
||||
}
|
||||
@@ -129,7 +103,7 @@ impl<T> Serialize for Option<T>
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
match *self {
|
||||
Some(ref value) => serializer.serialize_some(value),
|
||||
@@ -143,30 +117,12 @@ impl<T> Serialize for Option<T>
|
||||
impl<T> Serialize for PhantomData<T> {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
serializer.serialize_unit_struct("PhantomData")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<T> Serialize for [T]
|
||||
where T: Serialize,
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
|
||||
for e in self {
|
||||
try!(seq.serialize_element(e));
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! array_impls {
|
||||
@@ -222,48 +178,23 @@ array_impls!(32);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl<'a, I> Serialize for Iterator<I>
|
||||
where I: IntoIterator, <I as IntoIterator>::Item: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
// FIXME: use specialization to prevent invalidating the object in case of clonable iterators?
|
||||
let iter = match self.0.borrow_mut().take() {
|
||||
Some(iter) => iter.into_iter(),
|
||||
None => return Err(Error::custom("Iterator used twice")),
|
||||
};
|
||||
let size = match iter.size_hint() {
|
||||
(lo, Some(hi)) if lo == hi => Some(lo),
|
||||
_ => None,
|
||||
};
|
||||
let mut seq = try!(serializer.serialize_seq(size));
|
||||
for e in iter {
|
||||
try!(seq.serialize_element(&e));
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! serialize_seq {
|
||||
() => {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
|
||||
for e in self {
|
||||
try!(seq.serialize_element(&e));
|
||||
}
|
||||
seq.end()
|
||||
serializer.collect_seq(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Serialize for [T]
|
||||
where T: Serialize
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T> Serialize for BinaryHeap<T>
|
||||
where T: Serialize + Ord
|
||||
@@ -273,14 +204,7 @@ impl<T> Serialize for BinaryHeap<T>
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T> Serialize for BTreeSet<T>
|
||||
where T: Serialize + Ord,
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
impl<T> Serialize for EnumSet<T>
|
||||
where T: Serialize + CLike
|
||||
where T: Serialize + Ord
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
@@ -288,14 +212,14 @@ impl<T> Serialize for EnumSet<T>
|
||||
#[cfg(feature = "std")]
|
||||
impl<T, H> Serialize for HashSet<T, H>
|
||||
where T: Serialize + Eq + Hash,
|
||||
H: BuildHasher,
|
||||
H: BuildHasher
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<T> Serialize for LinkedList<T>
|
||||
where T: Serialize,
|
||||
where T: Serialize
|
||||
{
|
||||
serialize_seq!();
|
||||
}
|
||||
@@ -317,11 +241,11 @@ impl<T> Serialize for VecDeque<T>
|
||||
#[cfg(feature = "unstable")]
|
||||
impl<A> Serialize for ops::Range<A>
|
||||
where ops::Range<A>: ExactSizeIterator + iter::Iterator<Item = A> + Clone,
|
||||
A: Serialize,
|
||||
A: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
|
||||
for e in self.clone() {
|
||||
@@ -334,11 +258,11 @@ impl<A> Serialize for ops::Range<A>
|
||||
#[cfg(feature = "unstable")]
|
||||
impl<A> Serialize for ops::RangeInclusive<A>
|
||||
where ops::RangeInclusive<A>: ExactSizeIterator + iter::Iterator<Item = A> + Clone,
|
||||
A: Serialize,
|
||||
A: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
|
||||
for e in self.clone() {
|
||||
@@ -353,7 +277,7 @@ impl<A> Serialize for ops::RangeInclusive<A>
|
||||
impl Serialize for () {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
serializer.serialize_unit()
|
||||
}
|
||||
@@ -565,12 +489,7 @@ macro_rules! serialize_map {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
use super::SerializeMap;
|
||||
let mut map = try!(serializer.serialize_map(Some(self.len())));
|
||||
for (k, v) in self {
|
||||
try!(map.serialize_entry(k, v));
|
||||
}
|
||||
map.end()
|
||||
serializer.collect_map(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -578,7 +497,7 @@ macro_rules! serialize_map {
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<K, V> Serialize for BTreeMap<K, V>
|
||||
where K: Serialize + Ord,
|
||||
V: Serialize,
|
||||
V: Serialize
|
||||
{
|
||||
serialize_map!();
|
||||
}
|
||||
@@ -587,26 +506,30 @@ impl<K, V> Serialize for BTreeMap<K, V>
|
||||
impl<K, V, H> Serialize for HashMap<K, V, H>
|
||||
where K: Serialize + Eq + Hash,
|
||||
V: Serialize,
|
||||
H: BuildHasher,
|
||||
H: BuildHasher
|
||||
{
|
||||
serialize_map!();
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<'a, T: ?Sized> Serialize for &'a T where T: Serialize {
|
||||
impl<'a, T: ?Sized> Serialize for &'a T
|
||||
where T: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: ?Sized> Serialize for &'a mut T where T: Serialize {
|
||||
impl<'a, T: ?Sized> Serialize for &'a mut T
|
||||
where T: Serialize
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
@@ -618,7 +541,7 @@ impl<T: ?Sized> Serialize for Box<T>
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
@@ -630,7 +553,7 @@ impl<T> Serialize for Rc<T>
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
@@ -642,7 +565,7 @@ impl<T> Serialize for Arc<T>
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
@@ -654,7 +577,7 @@ impl<'a, T: ?Sized> Serialize for Cow<'a, T>
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
(**self).serialize(serializer)
|
||||
}
|
||||
@@ -670,9 +593,7 @@ impl<T, E> Serialize for Result<T, E>
|
||||
where S: Serializer
|
||||
{
|
||||
match *self {
|
||||
Result::Ok(ref value) => {
|
||||
serializer.serialize_newtype_variant("Result", 0, "Ok", value)
|
||||
}
|
||||
Result::Ok(ref value) => serializer.serialize_newtype_variant("Result", 0, "Ok", value),
|
||||
Result::Err(ref value) => {
|
||||
serializer.serialize_newtype_variant("Result", 1, "Err", value)
|
||||
}
|
||||
@@ -685,7 +606,7 @@ impl<T, E> Serialize for Result<T, E>
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for Duration {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
use super::SerializeStruct;
|
||||
let mut state = try!(serializer.serialize_struct("Duration", 2));
|
||||
@@ -700,27 +621,34 @@ impl Serialize for Duration {
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::IpAddr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
self.to_string().serialize(serializer)
|
||||
match *self {
|
||||
net::IpAddr::V4(ref a) => a.serialize(serializer),
|
||||
net::IpAddr::V6(ref a) => a.serialize(serializer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::Ipv4Addr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
self.to_string().serialize(serializer)
|
||||
/// "101.102.103.104".len()
|
||||
const MAX_LEN: usize = 15;
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::Ipv6Addr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
self.to_string().serialize(serializer)
|
||||
/// "1000:1002:1003:1004:1005:1006:1007:1008".len()
|
||||
const MAX_LEN: usize = 39;
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -729,7 +657,7 @@ impl Serialize for net::Ipv6Addr {
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::SocketAddr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
match *self {
|
||||
net::SocketAddr::V4(ref addr) => addr.serialize(serializer),
|
||||
@@ -741,18 +669,22 @@ impl Serialize for net::SocketAddr {
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::SocketAddrV4 {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
self.to_string().serialize(serializer)
|
||||
/// "101.102.103.104:65000".len()
|
||||
const MAX_LEN: usize = 21;
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::SocketAddrV6 {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
self.to_string().serialize(serializer)
|
||||
/// "[1000:1002:1003:1004:1005:1006:1007:1008]:65000".len()
|
||||
const MAX_LEN: usize = 47;
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -761,7 +693,7 @@ impl Serialize for net::SocketAddrV6 {
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for path::Path {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
match self.to_str() {
|
||||
Some(s) => s.serialize(serializer),
|
||||
@@ -773,7 +705,7 @@ impl Serialize for path::Path {
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for path::PathBuf {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
where S: Serializer
|
||||
{
|
||||
self.as_path().serialize(serializer)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
//! This module contains `Impossible` serializer and its implementations.
|
||||
|
||||
use core::marker::PhantomData;
|
||||
|
||||
use ser::{self, Serialize, SerializeSeq, SerializeTuple, SerializeTupleStruct,
|
||||
SerializeTupleVariant, SerializeMap, SerializeStruct, SerializeStructVariant};
|
||||
|
||||
/// Helper type for implementing a `Serializer` that does not support
|
||||
/// serializing one of the compound types.
|
||||
///
|
||||
/// This type cannot be instantiated, but implements every one of the traits
|
||||
/// corresponding to the `Serializer` compound types: `SerializeSeq`,
|
||||
/// `SerializeTuple`, `SerializeTupleStruct`, `SerializeTupleVariant`,
|
||||
/// `SerializeMap`, `SerializeStruct`, and `SerializeStructVariant`.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// impl Serializer for MySerializer {
|
||||
/// type Ok = ();
|
||||
/// type Error = Error;
|
||||
///
|
||||
/// type SerializeSeq = Impossible<(), Error>;
|
||||
/// /* other associated types */
|
||||
///
|
||||
/// /// This data format does not support serializing sequences.
|
||||
/// fn serialize_seq(self,
|
||||
/// len: Option<usize>)
|
||||
/// -> Result<Self::SerializeSeq, Error> {
|
||||
/// // Given Impossible cannot be instantiated, the only
|
||||
/// // thing we can do here is to return an error.
|
||||
/// Err(...)
|
||||
/// }
|
||||
///
|
||||
/// /* other Serializer methods */
|
||||
/// }
|
||||
/// ```
|
||||
pub struct Impossible<Ok, E> {
|
||||
void: Void,
|
||||
_marker: PhantomData<(Ok, E)>,
|
||||
}
|
||||
|
||||
enum Void {}
|
||||
|
||||
impl<Ok, E> SerializeSeq for Impossible<Ok, E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_element<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeTuple for Impossible<Ok, E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_element<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeTupleStruct for Impossible<Ok, E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeTupleVariant for Impossible<Ok, E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeMap for Impossible<Ok, E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_key<T: ?Sized + Serialize>(&mut self, _key: &T) -> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn serialize_value<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeStruct for Impossible<Ok, E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
_key: &'static str,
|
||||
_value: &T)
|
||||
-> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ok, E> SerializeStructVariant for Impossible<Ok, E>
|
||||
where E: ser::Error
|
||||
{
|
||||
type Ok = Ok;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
_key: &'static str,
|
||||
_value: &T)
|
||||
-> Result<(), E> {
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Ok, E> {
|
||||
match self.void {}
|
||||
}
|
||||
}
|
||||
+136
-107
@@ -98,12 +98,17 @@ use std::error;
|
||||
#[cfg(not(feature = "std"))]
|
||||
use error;
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
use core::cell::RefCell;
|
||||
|
||||
use core::fmt::Display;
|
||||
use core::iter::IntoIterator;
|
||||
|
||||
mod impls;
|
||||
mod impossible;
|
||||
|
||||
// Helpers used by generated code. Not public API.
|
||||
#[doc(hidden)]
|
||||
pub mod private;
|
||||
|
||||
pub use self::impossible::Impossible;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -138,8 +143,8 @@ pub trait Error: Sized + error::Error {
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// An implementation of this trait is a **data structure** that can be
|
||||
/// serialized into any data format supported by Serde.
|
||||
/// A **data structure** that can be serialized into any data format supported
|
||||
/// by Serde.
|
||||
///
|
||||
/// Serde provides `Serialize` implementations for many Rust primitive and
|
||||
/// standard library types. The complete list is [here][ser]. All of these can
|
||||
@@ -169,14 +174,12 @@ pub trait Serialize {
|
||||
/// for more information about how to implement this method.
|
||||
///
|
||||
/// [impl-serialize]: https://serde.rs/impl-serialize.html
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer;
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// An implementation of this trait is a **data format** that can serialize any
|
||||
/// data structure supported by Serde.
|
||||
/// A **data format** that can serialize any data structure supported by Serde.
|
||||
///
|
||||
/// The role of this trait is to define the serialization half of the Serde data
|
||||
/// model, which is a way to categorize every Rust data structure into one of 28
|
||||
@@ -236,7 +239,7 @@ pub trait Serialize {
|
||||
/// is the `serde_json::value::Serializer` (distinct from the main `serde_json`
|
||||
/// serializer) that produces a `serde_json::Value` data structure in memory as
|
||||
/// output.
|
||||
pub trait Serializer {
|
||||
pub trait Serializer: Sized {
|
||||
/// The output type produced by this `Serializer` during successful
|
||||
/// serialization. Most serializers that produce text or binary output
|
||||
/// should set `Ok = ()` and serialize into an `io::Write` or buffer
|
||||
@@ -250,31 +253,31 @@ pub trait Serializer {
|
||||
|
||||
/// Type returned from `serialize_seq` and `serialize_seq_fixed_size` for
|
||||
/// serializing the content of the sequence.
|
||||
type SerializeSeq: SerializeSeq<Ok=Self::Ok, Error=Self::Error>;
|
||||
type SerializeSeq: SerializeSeq<Ok = Self::Ok, Error = Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_tuple` for serializing the content of the
|
||||
/// tuple.
|
||||
type SerializeTuple: SerializeTuple<Ok=Self::Ok, Error=Self::Error>;
|
||||
type SerializeTuple: SerializeTuple<Ok = Self::Ok, Error = Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_tuple_struct` for serializing the content
|
||||
/// of the tuple struct.
|
||||
type SerializeTupleStruct: SerializeTupleStruct<Ok=Self::Ok, Error=Self::Error>;
|
||||
type SerializeTupleStruct: SerializeTupleStruct<Ok = Self::Ok, Error = Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_tuple_variant` for serializing the content
|
||||
/// of the tuple variant.
|
||||
type SerializeTupleVariant: SerializeTupleVariant<Ok=Self::Ok, Error=Self::Error>;
|
||||
type SerializeTupleVariant: SerializeTupleVariant<Ok = Self::Ok, Error = Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_map` for serializing the content of the
|
||||
/// map.
|
||||
type SerializeMap: SerializeMap<Ok=Self::Ok, Error=Self::Error>;
|
||||
type SerializeMap: SerializeMap<Ok = Self::Ok, Error = Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_struct` for serializing the content of the
|
||||
/// struct.
|
||||
type SerializeStruct: SerializeStruct<Ok=Self::Ok, Error=Self::Error>;
|
||||
type SerializeStruct: SerializeStruct<Ok = Self::Ok, Error = Self::Error>;
|
||||
|
||||
/// Type returned from `serialize_struct_variant` for serializing the
|
||||
/// content of the struct variant.
|
||||
type SerializeStructVariant: SerializeStructVariant<Ok=Self::Ok, Error=Self::Error>;
|
||||
type SerializeStructVariant: SerializeStructVariant<Ok = Self::Ok, Error = Self::Error>;
|
||||
|
||||
/// Serialize a `bool` value.
|
||||
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>;
|
||||
@@ -367,10 +370,7 @@ pub trait Serializer {
|
||||
fn serialize_none(self) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `Some(T)` value.
|
||||
fn serialize_some<T: ?Sized + Serialize>(
|
||||
self,
|
||||
value: &T,
|
||||
) -> Result<Self::Ok, Self::Error>;
|
||||
fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a `()` value.
|
||||
fn serialize_unit(self) -> Result<Self::Ok, Self::Error>;
|
||||
@@ -378,10 +378,7 @@ pub trait Serializer {
|
||||
/// Serialize a unit struct like `struct Unit` or `PhantomData<T>`.
|
||||
///
|
||||
/// A reasonable implementation would be to forward to `serialize_unit`.
|
||||
fn serialize_unit_struct(
|
||||
self,
|
||||
name: &'static str,
|
||||
) -> Result<Self::Ok, Self::Error>;
|
||||
fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a unit variant like `E::A` in `enum E { A, B }`.
|
||||
///
|
||||
@@ -397,12 +394,11 @@ pub trait Serializer {
|
||||
/// E::B => serializer.serialize_unit_variant("E", 1, "B"),
|
||||
/// }
|
||||
/// ```
|
||||
fn serialize_unit_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
) -> Result<Self::Ok, Self::Error>;
|
||||
fn serialize_unit_variant(self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str)
|
||||
-> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a newtype struct like `struct Millimeters(u8)`.
|
||||
///
|
||||
@@ -413,11 +409,10 @@ pub trait Serializer {
|
||||
/// ```rust,ignore
|
||||
/// serializer.serialize_newtype_struct("Millimeters", &self.0)
|
||||
/// ```
|
||||
fn serialize_newtype_struct<T: ?Sized + Serialize>(
|
||||
self,
|
||||
name: &'static str,
|
||||
value: &T,
|
||||
) -> Result<Self::Ok, Self::Error>;
|
||||
fn serialize_newtype_struct<T: ?Sized + Serialize>(self,
|
||||
name: &'static str,
|
||||
value: &T)
|
||||
-> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`.
|
||||
///
|
||||
@@ -430,13 +425,12 @@ pub trait Serializer {
|
||||
/// E::N(ref n) => serializer.serialize_newtype_variant("E", 0, "N", n),
|
||||
/// }
|
||||
/// ```
|
||||
fn serialize_newtype_variant<T: ?Sized + Serialize>(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
value: &T,
|
||||
) -> Result<Self::Ok, Self::Error>;
|
||||
fn serialize_newtype_variant<T: ?Sized + Serialize>(self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
value: &T)
|
||||
-> Result<Self::Ok, Self::Error>;
|
||||
|
||||
/// Begin to serialize a dynamically sized sequence. This call must be
|
||||
/// followed by zero or more calls to `serialize_element`, then a call to
|
||||
@@ -453,10 +447,7 @@ pub trait Serializer {
|
||||
/// }
|
||||
/// seq.end()
|
||||
/// ```
|
||||
fn serialize_seq(
|
||||
self,
|
||||
len: Option<usize>,
|
||||
) -> Result<Self::SerializeSeq, Self::Error>;
|
||||
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>;
|
||||
|
||||
/// Begin to serialize a statically sized sequence whose length will be
|
||||
/// known at deserialization time without looking at the serialized data.
|
||||
@@ -470,10 +461,7 @@ pub trait Serializer {
|
||||
/// }
|
||||
/// seq.end()
|
||||
/// ```
|
||||
fn serialize_seq_fixed_size(
|
||||
self,
|
||||
size: usize,
|
||||
) -> Result<Self::SerializeSeq, Self::Error>;
|
||||
fn serialize_seq_fixed_size(self, size: usize) -> Result<Self::SerializeSeq, Self::Error>;
|
||||
|
||||
/// Begin to serialize a tuple. This call must be followed by zero or more
|
||||
/// calls to `serialize_field`, then a call to `end`.
|
||||
@@ -485,10 +473,7 @@ pub trait Serializer {
|
||||
/// tup.serialize_field(&self.2)?;
|
||||
/// tup.end()
|
||||
/// ```
|
||||
fn serialize_tuple(
|
||||
self,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTuple, Self::Error>;
|
||||
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error>;
|
||||
|
||||
/// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This
|
||||
/// call must be followed by zero or more calls to `serialize_field`, then a
|
||||
@@ -504,11 +489,10 @@ pub trait Serializer {
|
||||
/// ts.serialize_field(&self.2)?;
|
||||
/// ts.end()
|
||||
/// ```
|
||||
fn serialize_tuple_struct(
|
||||
self,
|
||||
name: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTupleStruct, Self::Error>;
|
||||
fn serialize_tuple_struct(self,
|
||||
name: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeTupleStruct, Self::Error>;
|
||||
|
||||
/// Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8)
|
||||
/// }`. This call must be followed by zero or more calls to
|
||||
@@ -528,13 +512,12 @@ pub trait Serializer {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn serialize_tuple_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTupleVariant, Self::Error>;
|
||||
fn serialize_tuple_variant(self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeTupleVariant, Self::Error>;
|
||||
|
||||
/// Begin to serialize a map. This call must be followed by zero or more
|
||||
/// calls to `serialize_key` and `serialize_value`, then a call to `end`.
|
||||
@@ -550,10 +533,7 @@ pub trait Serializer {
|
||||
/// }
|
||||
/// map.end()
|
||||
/// ```
|
||||
fn serialize_map(
|
||||
self,
|
||||
len: Option<usize>,
|
||||
) -> Result<Self::SerializeMap, Self::Error>;
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>;
|
||||
|
||||
/// Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`.
|
||||
/// This call must be followed by zero or more calls to `serialize_field`,
|
||||
@@ -569,11 +549,10 @@ pub trait Serializer {
|
||||
/// struc.serialize_field("b", &self.b)?;
|
||||
/// struc.end()
|
||||
/// ```
|
||||
fn serialize_struct(
|
||||
self,
|
||||
name: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStruct, Self::Error>;
|
||||
fn serialize_struct(self,
|
||||
name: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeStruct, Self::Error>;
|
||||
|
||||
/// Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8,
|
||||
/// g: u8, b: u8 } }`. This call must be followed by zero or more calls to
|
||||
@@ -594,13 +573,47 @@ pub trait Serializer {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn serialize_struct_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStructVariant, Self::Error>;
|
||||
fn serialize_struct_variant(self,
|
||||
name: &'static str,
|
||||
variant_index: usize,
|
||||
variant: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeStructVariant, Self::Error>;
|
||||
|
||||
/// Collect an iterator as a sequence.
|
||||
///
|
||||
/// The default implementation serializes each item yielded by the iterator
|
||||
/// using `Self::SerializeSeq`. Implementors should not need to override
|
||||
/// this method.
|
||||
fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error>
|
||||
where I: IntoIterator,
|
||||
<I as IntoIterator>::Item: Serialize
|
||||
{
|
||||
let iter = iter.into_iter();
|
||||
let mut serializer = try!(self.serialize_seq(iter.len_hint()));
|
||||
for item in iter {
|
||||
try!(serializer.serialize_element(&item));
|
||||
}
|
||||
serializer.end()
|
||||
}
|
||||
|
||||
/// Collect an iterator as a map.
|
||||
///
|
||||
/// The default implementation serializes each pair yielded by the iterator
|
||||
/// using `Self::SerializeMap`. Implementors should not need to override
|
||||
/// this method.
|
||||
fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>
|
||||
where K: Serialize,
|
||||
V: Serialize,
|
||||
I: IntoIterator<Item = (K, V)>
|
||||
{
|
||||
let iter = iter.into_iter();
|
||||
let mut serializer = try!(self.serialize_map(iter.len_hint()));
|
||||
for (key, value) in iter {
|
||||
try!(serializer.serialize_entry(&key, &value));
|
||||
}
|
||||
serializer.end()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_seq` and
|
||||
@@ -734,11 +747,10 @@ pub trait SerializeMap {
|
||||
/// `serialize_value`. This is appropriate for serializers that do not care
|
||||
/// about performance or are not able to optimize `serialize_entry` any
|
||||
/// better than this.
|
||||
fn serialize_entry<K: ?Sized + Serialize, V: ?Sized + Serialize>(
|
||||
&mut self,
|
||||
key: &K,
|
||||
value: &V,
|
||||
) -> Result<(), Self::Error> {
|
||||
fn serialize_entry<K: ?Sized + Serialize, V: ?Sized + Serialize>(&mut self,
|
||||
key: &K,
|
||||
value: &V)
|
||||
-> Result<(), Self::Error> {
|
||||
try!(self.serialize_key(key));
|
||||
self.serialize_value(value)
|
||||
}
|
||||
@@ -764,7 +776,10 @@ pub trait SerializeStruct {
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a struct field.
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>;
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
key: &'static str,
|
||||
value: &T)
|
||||
-> Result<(), Self::Error>;
|
||||
|
||||
/// Finish serializing a struct.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
@@ -791,27 +806,41 @@ pub trait SerializeStructVariant {
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a struct variant field.
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>;
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||
key: &'static str,
|
||||
value: &T)
|
||||
-> Result<(), Self::Error>;
|
||||
|
||||
/// Finish serializing a struct variant.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
/// A wrapper type for iterators that implements `Serialize` for iterators whose
|
||||
/// items implement `Serialize`. Don't use multiple times. Create new versions
|
||||
/// of this with the `serde::ser::iterator` function every time you want to
|
||||
/// serialize an iterator.
|
||||
#[cfg(feature = "unstable")]
|
||||
pub struct Iterator<I>(RefCell<Option<I>>)
|
||||
where <I as IntoIterator>::Item: Serialize,
|
||||
I: IntoIterator;
|
||||
|
||||
/// Create a wrapper type that can be passed to any function expecting a
|
||||
/// `Serialize` and will serialize the given iterator as a sequence.
|
||||
#[cfg(feature = "unstable")]
|
||||
pub fn iterator<I>(iter: I) -> Iterator<I>
|
||||
where <I as IntoIterator>::Item: Serialize,
|
||||
I: IntoIterator
|
||||
{
|
||||
Iterator(RefCell::new(Some(iter)))
|
||||
trait LenHint: Iterator {
|
||||
fn len_hint(&self) -> Option<usize>;
|
||||
}
|
||||
|
||||
impl<I: Iterator> LenHint for I {
|
||||
#[cfg(not(feature = "unstable"))]
|
||||
fn len_hint(&self) -> Option<usize> {
|
||||
iterator_len_hint(self)
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
default fn len_hint(&self) -> Option<usize> {
|
||||
iterator_len_hint(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl<I: ExactSizeIterator> LenHint for I {
|
||||
fn len_hint(&self) -> Option<usize> {
|
||||
Some(self.len())
|
||||
}
|
||||
}
|
||||
|
||||
fn iterator_len_hint<I: Iterator>(iter: &I) -> Option<usize> {
|
||||
match iter.size_hint() {
|
||||
(lo, Some(hi)) if lo == hi => Some(lo),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
use core::fmt::{self, Display};
|
||||
|
||||
use ser::{self, Serialize, Serializer, SerializeMap, SerializeStruct};
|
||||
|
||||
/// Not public API.
|
||||
pub fn serialize_tagged_newtype<S, T>(serializer: S,
|
||||
type_ident: &'static str,
|
||||
variant_ident: &'static str,
|
||||
tag: &'static str,
|
||||
variant_name: &'static str,
|
||||
value: T)
|
||||
-> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
T: Serialize
|
||||
{
|
||||
value.serialize(TaggedSerializer {
|
||||
type_ident: type_ident,
|
||||
variant_ident: variant_ident,
|
||||
tag: tag,
|
||||
variant_name: variant_name,
|
||||
delegate: serializer,
|
||||
})
|
||||
}
|
||||
|
||||
struct TaggedSerializer<S> {
|
||||
type_ident: &'static str,
|
||||
variant_ident: &'static str,
|
||||
tag: &'static str,
|
||||
variant_name: &'static str,
|
||||
delegate: S,
|
||||
}
|
||||
|
||||
enum Unsupported {
|
||||
Boolean,
|
||||
Integer,
|
||||
Float,
|
||||
Char,
|
||||
String,
|
||||
ByteArray,
|
||||
Optional,
|
||||
Unit,
|
||||
UnitStruct,
|
||||
Sequence,
|
||||
Tuple,
|
||||
TupleStruct,
|
||||
Enum,
|
||||
}
|
||||
|
||||
impl Display for Unsupported {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
Unsupported::Boolean => formatter.write_str("a boolean"),
|
||||
Unsupported::Integer => formatter.write_str("an integer"),
|
||||
Unsupported::Float => formatter.write_str("a float"),
|
||||
Unsupported::Char => formatter.write_str("a char"),
|
||||
Unsupported::String => formatter.write_str("a string"),
|
||||
Unsupported::ByteArray => formatter.write_str("a byte array"),
|
||||
Unsupported::Optional => formatter.write_str("an optional"),
|
||||
Unsupported::Unit => formatter.write_str("unit"),
|
||||
Unsupported::UnitStruct => formatter.write_str("a unit struct"),
|
||||
Unsupported::Sequence => formatter.write_str("a sequence"),
|
||||
Unsupported::Tuple => formatter.write_str("a tuple"),
|
||||
Unsupported::TupleStruct => formatter.write_str("a tuple struct"),
|
||||
Unsupported::Enum => formatter.write_str("an enum"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Error {
|
||||
type_ident: &'static str,
|
||||
variant_ident: &'static str,
|
||||
ty: Unsupported,
|
||||
}
|
||||
|
||||
impl Display for Error {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter,
|
||||
"cannot serialize tagged newtype variant {}::{} containing {}",
|
||||
self.type_ident, self.variant_ident, self.ty)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> TaggedSerializer<S>
|
||||
where S: Serializer
|
||||
{
|
||||
fn bad_type(self, what: Unsupported) -> S::Error {
|
||||
ser::Error::custom(Error {
|
||||
type_ident: self.type_ident,
|
||||
variant_ident: self.variant_ident,
|
||||
ty: what,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Serializer for TaggedSerializer<S>
|
||||
where S: Serializer
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
|
||||
type SerializeSeq = S::SerializeSeq;
|
||||
type SerializeTuple = S::SerializeTuple;
|
||||
type SerializeTupleStruct = S::SerializeTupleStruct;
|
||||
type SerializeTupleVariant = S::SerializeTupleVariant;
|
||||
type SerializeMap = S::SerializeMap;
|
||||
type SerializeStruct = S::SerializeStruct;
|
||||
type SerializeStructVariant = S::SerializeStructVariant;
|
||||
|
||||
fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Boolean))
|
||||
}
|
||||
|
||||
fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Float))
|
||||
}
|
||||
|
||||
fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Float))
|
||||
}
|
||||
|
||||
fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Char))
|
||||
}
|
||||
|
||||
fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::String))
|
||||
}
|
||||
|
||||
fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::ByteArray))
|
||||
}
|
||||
|
||||
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Optional))
|
||||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error>
|
||||
where T: Serialize
|
||||
{
|
||||
Err(self.bad_type(Unsupported::Optional))
|
||||
}
|
||||
|
||||
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Unit))
|
||||
}
|
||||
|
||||
fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::UnitStruct))
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(self,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
_: &'static str)
|
||||
-> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Enum))
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized>(self,
|
||||
_: &'static str,
|
||||
value: &T)
|
||||
-> Result<Self::Ok, Self::Error>
|
||||
where T: Serialize
|
||||
{
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: ?Sized>(self,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
_: &'static str,
|
||||
_: &T)
|
||||
-> Result<Self::Ok, Self::Error>
|
||||
where T: Serialize
|
||||
{
|
||||
Err(self.bad_type(Unsupported::Enum))
|
||||
}
|
||||
|
||||
fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Sequence))
|
||||
}
|
||||
|
||||
fn serialize_seq_fixed_size(self, _: usize) -> Result<Self::SerializeSeq, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Sequence))
|
||||
}
|
||||
|
||||
fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Tuple))
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(self,
|
||||
_: &'static str,
|
||||
_: usize)
|
||||
-> Result<Self::SerializeTupleStruct, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::TupleStruct))
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(self,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
_: &'static str,
|
||||
_: usize)
|
||||
-> Result<Self::SerializeTupleVariant, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Enum))
|
||||
}
|
||||
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
|
||||
let mut map = try!(self.delegate.serialize_map(len.map(|len| len + 1)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
Ok(map)
|
||||
}
|
||||
|
||||
fn serialize_struct(self,
|
||||
name: &'static str,
|
||||
len: usize)
|
||||
-> Result<Self::SerializeStruct, Self::Error> {
|
||||
let mut state = try!(self.delegate.serialize_struct(name, len + 1));
|
||||
try!(state.serialize_field(self.tag, self.variant_name));
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
fn serialize_struct_variant(self,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
_: &'static str,
|
||||
_: usize)
|
||||
-> Result<Self::SerializeStructVariant, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Enum))
|
||||
}
|
||||
}
|
||||
+20
-18
@@ -1,12 +1,12 @@
|
||||
//! Private utility functions
|
||||
|
||||
const TAG_CONT: u8 = 0b1000_0000;
|
||||
const TAG_TWO_B: u8 = 0b1100_0000;
|
||||
const TAG_CONT: u8 = 0b1000_0000;
|
||||
const TAG_TWO_B: u8 = 0b1100_0000;
|
||||
const TAG_THREE_B: u8 = 0b1110_0000;
|
||||
const TAG_FOUR_B: u8 = 0b1111_0000;
|
||||
const MAX_ONE_B: u32 = 0x80;
|
||||
const MAX_TWO_B: u32 = 0x800;
|
||||
const MAX_THREE_B: u32 = 0x10000;
|
||||
const TAG_FOUR_B: u8 = 0b1111_0000;
|
||||
const MAX_ONE_B: u32 = 0x80;
|
||||
const MAX_TWO_B: u32 = 0x800;
|
||||
const MAX_THREE_B: u32 = 0x10000;
|
||||
|
||||
#[inline]
|
||||
pub fn encode_utf8(c: char) -> EncodeUtf8 {
|
||||
@@ -21,17 +21,20 @@ pub fn encode_utf8(c: char) -> EncodeUtf8 {
|
||||
2
|
||||
} else if code < MAX_THREE_B {
|
||||
buf[1] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
1
|
||||
} else {
|
||||
buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
|
||||
buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
0
|
||||
};
|
||||
EncodeUtf8 { buf: buf, pos: pos }
|
||||
EncodeUtf8 {
|
||||
buf: buf,
|
||||
pos: pos,
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EncodeUtf8 {
|
||||
@@ -47,23 +50,22 @@ impl EncodeUtf8 {
|
||||
}
|
||||
|
||||
#[allow(non_upper_case_globals)]
|
||||
const Pattern_White_Space_table: &'static [(char, char)] = &[
|
||||
('\u{9}', '\u{d}'), ('\u{20}', '\u{20}'), ('\u{85}', '\u{85}'), ('\u{200e}', '\u{200f}'),
|
||||
('\u{2028}', '\u{2029}')
|
||||
];
|
||||
const Pattern_White_Space_table: &'static [(char, char)] = &[('\u{9}', '\u{d}'),
|
||||
('\u{20}', '\u{20}'),
|
||||
('\u{85}', '\u{85}'),
|
||||
('\u{200e}', '\u{200f}'),
|
||||
('\u{2028}', '\u{2029}')];
|
||||
|
||||
fn bsearch_range_table(c: char, r: &'static [(char, char)]) -> bool {
|
||||
use core::cmp::Ordering::{Equal, Less, Greater};
|
||||
r.binary_search_by(|&(lo, hi)| {
|
||||
if c < lo {
|
||||
r.binary_search_by(|&(lo, hi)| if c < lo {
|
||||
Greater
|
||||
} else if hi < c {
|
||||
Less
|
||||
} else {
|
||||
Equal
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
})
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde_codegen_internals"
|
||||
version = "0.12.0"
|
||||
version = "0.14.0"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "AST representation used by Serde codegen. Unstable."
|
||||
@@ -8,14 +8,11 @@ homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://docs.serde.rs/serde_codegen_internals/"
|
||||
keywords = ["serde", "serialization"]
|
||||
include = ["Cargo.toml", "src/**/*.rs"]
|
||||
|
||||
[features]
|
||||
unstable-testing = ["clippy"]
|
||||
readme = "../README.md"
|
||||
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
|
||||
[dependencies]
|
||||
clippy = { version = "0.*", optional = true }
|
||||
syn = "0.11"
|
||||
syn = { version = "0.11", default-features = false, features = ["parsing"] }
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "serde-rs/serde" }
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
||||
+1
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
||||
+1
@@ -0,0 +1 @@
|
||||
../README.md
|
||||
@@ -39,9 +39,7 @@ impl<'a> Item<'a> {
|
||||
let attrs = attr::Item::from_ast(cx, item);
|
||||
|
||||
let body = match item.body {
|
||||
syn::Body::Enum(ref variants) => {
|
||||
Body::Enum(enum_from_ast(cx, variants))
|
||||
}
|
||||
syn::Body::Enum(ref variants) => Body::Enum(enum_from_ast(cx, variants)),
|
||||
syn::Body::Struct(ref variant_data) => {
|
||||
let (style, fields) = struct_from_ast(cx, variant_data);
|
||||
Body::Struct(style, fields)
|
||||
@@ -58,15 +56,13 @@ impl<'a> Item<'a> {
|
||||
}
|
||||
|
||||
impl<'a> Body<'a> {
|
||||
pub fn all_fields(&'a self) -> Box<Iterator<Item=&'a Field<'a>> + 'a> {
|
||||
pub fn all_fields(&'a self) -> Box<Iterator<Item = &'a Field<'a>> + 'a> {
|
||||
match *self {
|
||||
Body::Enum(ref variants) => {
|
||||
Box::new(variants.iter()
|
||||
.flat_map(|variant| variant.fields.iter()))
|
||||
}
|
||||
Body::Struct(_, ref fields) => {
|
||||
Box::new(fields.iter())
|
||||
.flat_map(|variant| variant.fields.iter()))
|
||||
}
|
||||
Body::Struct(_, ref fields) => Box::new(fields.iter()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,18 +83,12 @@ fn enum_from_ast<'a>(cx: &Ctxt, variants: &'a [syn::Variant]) -> Vec<Variant<'a>
|
||||
|
||||
fn struct_from_ast<'a>(cx: &Ctxt, data: &'a syn::VariantData) -> (Style, Vec<Field<'a>>) {
|
||||
match *data {
|
||||
syn::VariantData::Struct(ref fields) => {
|
||||
(Style::Struct, fields_from_ast(cx, fields))
|
||||
}
|
||||
syn::VariantData::Struct(ref fields) => (Style::Struct, fields_from_ast(cx, fields)),
|
||||
syn::VariantData::Tuple(ref fields) if fields.len() == 1 => {
|
||||
(Style::Newtype, fields_from_ast(cx, fields))
|
||||
}
|
||||
syn::VariantData::Tuple(ref fields) => {
|
||||
(Style::Tuple, fields_from_ast(cx, fields))
|
||||
}
|
||||
syn::VariantData::Unit => {
|
||||
(Style::Unit, Vec::new())
|
||||
}
|
||||
syn::VariantData::Tuple(ref fields) => (Style::Tuple, fields_from_ast(cx, fields)),
|
||||
syn::VariantData::Unit => (Style::Unit, Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -90,8 +90,42 @@ impl Name {
|
||||
pub struct Item {
|
||||
name: Name,
|
||||
deny_unknown_fields: bool,
|
||||
default: Default,
|
||||
ser_bound: Option<Vec<syn::WherePredicate>>,
|
||||
de_bound: Option<Vec<syn::WherePredicate>>,
|
||||
tag: EnumTag,
|
||||
}
|
||||
|
||||
/// Styles of representing an enum.
|
||||
#[derive(Debug)]
|
||||
pub enum EnumTag {
|
||||
/// The default.
|
||||
///
|
||||
/// ```json
|
||||
/// {"variant1": {"key1": "value1", "key2": "value2"}}
|
||||
/// ```
|
||||
External,
|
||||
|
||||
/// `#[serde(tag = "type")]`
|
||||
///
|
||||
/// ```json
|
||||
/// {"type": "variant1", "key1": "value1", "key2": "value2"}
|
||||
/// ```
|
||||
Internal { tag: String },
|
||||
|
||||
/// `#[serde(tag = "t", content = "c")]`
|
||||
///
|
||||
/// ```json
|
||||
/// {"t": "variant1", "c": {"key1": "value1", "key2": "value2"}}
|
||||
/// ```
|
||||
Adjacent { tag: String, content: String },
|
||||
|
||||
/// `#[serde(untagged)]`
|
||||
///
|
||||
/// ```json
|
||||
/// {"key1": "value1", "key2": "value2"}
|
||||
/// ```
|
||||
None,
|
||||
}
|
||||
|
||||
impl Item {
|
||||
@@ -100,8 +134,12 @@ impl Item {
|
||||
let mut ser_name = Attr::none(cx, "rename");
|
||||
let mut de_name = Attr::none(cx, "rename");
|
||||
let mut deny_unknown_fields = BoolAttr::none(cx, "deny_unknown_fields");
|
||||
let mut default = Attr::none(cx, "default");
|
||||
let mut ser_bound = Attr::none(cx, "bound");
|
||||
let mut de_bound = Attr::none(cx, "bound");
|
||||
let mut untagged = BoolAttr::none(cx, "untagged");
|
||||
let mut internal_tag = Attr::none(cx, "tag");
|
||||
let mut content = Attr::none(cx, "content");
|
||||
|
||||
for meta_items in item.attrs.iter().filter_map(get_serde_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
@@ -127,9 +165,38 @@ impl Item {
|
||||
deny_unknown_fields.set_true();
|
||||
}
|
||||
|
||||
// Parse `#[serde(default)]`
|
||||
MetaItem(Word(ref name)) if name == "default" => {
|
||||
match item.body {
|
||||
syn::Body::Struct(syn::VariantData::Struct(_)) => {
|
||||
default.set(Default::Default);
|
||||
}
|
||||
_ => {
|
||||
cx.error("#[serde(default)] can only be used on structs \
|
||||
with named fields")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(default="...")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "default" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
|
||||
match item.body {
|
||||
syn::Body::Struct(syn::VariantData::Struct(_)) => {
|
||||
default.set(Default::Path(path));
|
||||
}
|
||||
_ => {
|
||||
cx.error("#[serde(default = \"...\")] can only be used \
|
||||
on structs with named fields")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(bound="D: Serialize")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "bound" => {
|
||||
if let Ok(where_predicates) = parse_lit_into_where(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
if let Ok(where_predicates) =
|
||||
parse_lit_into_where(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
ser_bound.set(where_predicates.clone());
|
||||
de_bound.set(where_predicates);
|
||||
}
|
||||
@@ -143,6 +210,46 @@ impl Item {
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(untagged)]`
|
||||
MetaItem(Word(ref name)) if name == "untagged" => {
|
||||
match item.body {
|
||||
syn::Body::Enum(_) => {
|
||||
untagged.set_true();
|
||||
}
|
||||
syn::Body::Struct(_) => {
|
||||
cx.error("#[serde(untagged)] can only be used on enums")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(tag = "type")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "tag" => {
|
||||
if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
match item.body {
|
||||
syn::Body::Enum(_) => {
|
||||
internal_tag.set(s);
|
||||
}
|
||||
syn::Body::Struct(_) => {
|
||||
cx.error("#[serde(tag = \"...\")] can only be used on enums")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(content = "c")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "content" => {
|
||||
if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
match item.body {
|
||||
syn::Body::Enum(_) => {
|
||||
content.set(s);
|
||||
}
|
||||
syn::Body::Struct(_) => {
|
||||
cx.error("#[serde(content = \"...\")] can only be used on enums")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MetaItem(ref meta_item) => {
|
||||
cx.error(format!("unknown serde container attribute `{}`",
|
||||
meta_item.name()));
|
||||
@@ -155,14 +262,59 @@ impl Item {
|
||||
}
|
||||
}
|
||||
|
||||
let tag = match (untagged.get(), internal_tag.get(), content.get()) {
|
||||
(false, None, None) => EnumTag::External,
|
||||
(true, None, None) => EnumTag::None,
|
||||
(false, Some(tag), None) => {
|
||||
// Check that there are no tuple variants.
|
||||
if let syn::Body::Enum(ref variants) = item.body {
|
||||
for variant in variants {
|
||||
match variant.data {
|
||||
syn::VariantData::Struct(_) |
|
||||
syn::VariantData::Unit => {}
|
||||
syn::VariantData::Tuple(ref fields) => {
|
||||
if fields.len() != 1 {
|
||||
cx.error("#[serde(tag = \"...\")] cannot be used with tuple \
|
||||
variants");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
EnumTag::Internal { tag: tag }
|
||||
}
|
||||
(true, Some(_), None) => {
|
||||
cx.error("enum cannot be both untagged and internally tagged");
|
||||
EnumTag::External // doesn't matter, will error
|
||||
}
|
||||
(false, None, Some(_)) => {
|
||||
cx.error("#[serde(tag = \"...\", content = \"...\")] must be used together");
|
||||
EnumTag::External
|
||||
}
|
||||
(true, None, Some(_)) => {
|
||||
cx.error("untagged enum cannot have #[serde(content = \"...\")]");
|
||||
EnumTag::External
|
||||
}
|
||||
(false, Some(tag), Some(content)) => {
|
||||
EnumTag::Adjacent { tag: tag, content: content }
|
||||
}
|
||||
(true, Some(_), Some(_)) => {
|
||||
cx.error("untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]");
|
||||
EnumTag::External
|
||||
}
|
||||
};
|
||||
|
||||
Item {
|
||||
name: Name {
|
||||
serialize: ser_name.get().unwrap_or_else(|| item.ident.to_string()),
|
||||
deserialize: de_name.get().unwrap_or_else(|| item.ident.to_string()),
|
||||
},
|
||||
deny_unknown_fields: deny_unknown_fields.get(),
|
||||
default: default.get().unwrap_or(Default::None),
|
||||
ser_bound: ser_bound.get(),
|
||||
de_bound: de_bound.get(),
|
||||
tag: tag,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,6 +326,10 @@ impl Item {
|
||||
self.deny_unknown_fields
|
||||
}
|
||||
|
||||
pub fn default(&self) -> &Default {
|
||||
&self.default
|
||||
}
|
||||
|
||||
pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> {
|
||||
self.ser_bound.as_ref().map(|vec| &vec[..])
|
||||
}
|
||||
@@ -181,6 +337,10 @@ impl Item {
|
||||
pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
|
||||
self.de_bound.as_ref().map(|vec| &vec[..])
|
||||
}
|
||||
|
||||
pub fn tag(&self) -> &EnumTag {
|
||||
&self.tag
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents variant attribute information
|
||||
@@ -226,8 +386,7 @@ impl Variant {
|
||||
}
|
||||
|
||||
MetaItem(ref meta_item) => {
|
||||
cx.error(format!("unknown serde variant attribute `{}`",
|
||||
meta_item.name()));
|
||||
cx.error(format!("unknown serde variant attribute `{}`", meta_item.name()));
|
||||
}
|
||||
|
||||
Literal(_) => {
|
||||
@@ -267,7 +426,7 @@ pub struct Field {
|
||||
skip_serializing: bool,
|
||||
skip_deserializing: bool,
|
||||
skip_serializing_if: Option<syn::Path>,
|
||||
default: FieldDefault,
|
||||
default: Default,
|
||||
serialize_with: Option<syn::Path>,
|
||||
deserialize_with: Option<syn::Path>,
|
||||
ser_bound: Option<Vec<syn::WherePredicate>>,
|
||||
@@ -276,7 +435,7 @@ pub struct Field {
|
||||
|
||||
/// Represents the default to use for a field when deserializing.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum FieldDefault {
|
||||
pub enum Default {
|
||||
/// Field must always be specified because it does not have a default.
|
||||
None,
|
||||
/// The default is given by `std::default::Default::default()`.
|
||||
@@ -287,9 +446,7 @@ pub enum FieldDefault {
|
||||
|
||||
impl Field {
|
||||
/// Extract out the `#[serde(...)]` attributes from a struct field.
|
||||
pub fn from_ast(cx: &Ctxt,
|
||||
index: usize,
|
||||
field: &syn::Field) -> Self {
|
||||
pub fn from_ast(cx: &Ctxt, index: usize, field: &syn::Field) -> Self {
|
||||
let mut ser_name = Attr::none(cx, "rename");
|
||||
let mut de_name = Attr::none(cx, "rename");
|
||||
let mut skip_serializing = BoolAttr::none(cx, "skip_serializing");
|
||||
@@ -327,13 +484,13 @@ impl Field {
|
||||
|
||||
// Parse `#[serde(default)]`
|
||||
MetaItem(Word(ref name)) if name == "default" => {
|
||||
default.set(FieldDefault::Default);
|
||||
default.set(Default::Default);
|
||||
}
|
||||
|
||||
// Parse `#[serde(default="...")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "default" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
|
||||
default.set(FieldDefault::Path(path));
|
||||
default.set(Default::Path(path));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -368,9 +525,22 @@ impl Field {
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(with="...")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
|
||||
let mut ser_path = path.clone();
|
||||
ser_path.segments.push("serialize".into());
|
||||
serialize_with.set(ser_path);
|
||||
let mut de_path = path;
|
||||
de_path.segments.push("deserialize".into());
|
||||
deserialize_with.set(de_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(bound="D: Serialize")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "bound" => {
|
||||
if let Ok(where_predicates) = parse_lit_into_where(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
if let Ok(where_predicates) =
|
||||
parse_lit_into_where(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
ser_bound.set(where_predicates.clone());
|
||||
de_bound.set(where_predicates);
|
||||
}
|
||||
@@ -385,8 +555,7 @@ impl Field {
|
||||
}
|
||||
|
||||
MetaItem(ref meta_item) => {
|
||||
cx.error(format!("unknown serde field attribute `{}`",
|
||||
meta_item.name()));
|
||||
cx.error(format!("unknown serde field attribute `{}`", meta_item.name()));
|
||||
}
|
||||
|
||||
Literal(_) => {
|
||||
@@ -399,7 +568,7 @@ impl Field {
|
||||
// Is skip_deserializing, initialize the field to Default::default()
|
||||
// unless a different default is specified by `#[serde(default="...")]`
|
||||
if skip_deserializing.0.value.is_some() {
|
||||
default.set_if_none(FieldDefault::Default);
|
||||
default.set_if_none(Default::Default);
|
||||
}
|
||||
|
||||
Field {
|
||||
@@ -410,7 +579,7 @@ impl Field {
|
||||
skip_serializing: skip_serializing.get(),
|
||||
skip_deserializing: skip_deserializing.get(),
|
||||
skip_serializing_if: skip_serializing_if.get(),
|
||||
default: default.get().unwrap_or(FieldDefault::None),
|
||||
default: default.get().unwrap_or(Default::None),
|
||||
serialize_with: serialize_with.get(),
|
||||
deserialize_with: deserialize_with.get(),
|
||||
ser_bound: ser_bound.get(),
|
||||
@@ -434,7 +603,7 @@ impl Field {
|
||||
self.skip_serializing_if.as_ref()
|
||||
}
|
||||
|
||||
pub fn default(&self) -> &FieldDefault {
|
||||
pub fn default(&self) -> &Default {
|
||||
&self.default
|
||||
}
|
||||
|
||||
@@ -457,13 +626,12 @@ impl Field {
|
||||
|
||||
type SerAndDe<T> = (Option<T>, Option<T>);
|
||||
|
||||
fn get_ser_and_de<T, F>(
|
||||
cx: &Ctxt,
|
||||
attr_name: &'static str,
|
||||
items: &[syn::NestedMetaItem],
|
||||
f: F
|
||||
) -> Result<SerAndDe<T>, ()>
|
||||
where F: Fn(&Ctxt, &str, &str, &syn::Lit) -> Result<T, ()>,
|
||||
fn get_ser_and_de<T, F>(cx: &Ctxt,
|
||||
attr_name: &'static str,
|
||||
items: &[syn::NestedMetaItem],
|
||||
f: F)
|
||||
-> Result<SerAndDe<T>, ()>
|
||||
where F: Fn(&Ctxt, &str, &str, &syn::Lit) -> Result<T, ()>
|
||||
{
|
||||
let mut ser_item = Attr::none(cx, attr_name);
|
||||
let mut de_item = Attr::none(cx, attr_name);
|
||||
@@ -483,7 +651,8 @@ fn get_ser_and_de<T, F>(
|
||||
}
|
||||
|
||||
_ => {
|
||||
cx.error(format!("malformed {0} attribute, expected `{0}(serialize = ..., deserialize = ...)`",
|
||||
cx.error(format!("malformed {0} attribute, expected `{0}(serialize = ..., \
|
||||
deserialize = ...)`",
|
||||
attr_name));
|
||||
return Err(());
|
||||
}
|
||||
@@ -493,35 +662,34 @@ fn get_ser_and_de<T, F>(
|
||||
Ok((ser_item.get(), de_item.get()))
|
||||
}
|
||||
|
||||
fn get_renames(
|
||||
cx: &Ctxt,
|
||||
items: &[syn::NestedMetaItem],
|
||||
) -> Result<SerAndDe<String>, ()> {
|
||||
fn get_renames(cx: &Ctxt, items: &[syn::NestedMetaItem]) -> Result<SerAndDe<String>, ()> {
|
||||
get_ser_and_de(cx, "rename", items, get_string_from_lit)
|
||||
}
|
||||
|
||||
fn get_where_predicates(
|
||||
cx: &Ctxt,
|
||||
items: &[syn::NestedMetaItem],
|
||||
) -> Result<SerAndDe<Vec<syn::WherePredicate>>, ()> {
|
||||
fn get_where_predicates(cx: &Ctxt,
|
||||
items: &[syn::NestedMetaItem])
|
||||
-> Result<SerAndDe<Vec<syn::WherePredicate>>, ()> {
|
||||
get_ser_and_de(cx, "bound", items, parse_lit_into_where)
|
||||
}
|
||||
|
||||
pub fn get_serde_meta_items(attr: &syn::Attribute) -> Option<Vec<syn::NestedMetaItem>> {
|
||||
match attr.value {
|
||||
List(ref name, ref items) if name == "serde" => {
|
||||
Some(items.iter().cloned().collect())
|
||||
}
|
||||
_ => None
|
||||
List(ref name, ref items) if name == "serde" => Some(items.iter().cloned().collect()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_string_from_lit(cx: &Ctxt, attr_name: &str, meta_item_name: &str, lit: &syn::Lit) -> Result<String, ()> {
|
||||
fn get_string_from_lit(cx: &Ctxt,
|
||||
attr_name: &str,
|
||||
meta_item_name: &str,
|
||||
lit: &syn::Lit)
|
||||
-> Result<String, ()> {
|
||||
if let syn::Lit::Str(ref s, _) = *lit {
|
||||
Ok(s.clone())
|
||||
} else {
|
||||
cx.error(format!("expected serde {} attribute to be a string: `{} = \"...\"`",
|
||||
attr_name, meta_item_name));
|
||||
attr_name,
|
||||
meta_item_name));
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
@@ -531,7 +699,11 @@ fn parse_lit_into_path(cx: &Ctxt, attr_name: &str, lit: &syn::Lit) -> Result<syn
|
||||
syn::parse_path(&string).map_err(|err| cx.error(err))
|
||||
}
|
||||
|
||||
fn parse_lit_into_where(cx: &Ctxt, attr_name: &str, meta_item_name: &str, lit: &syn::Lit) -> Result<Vec<syn::WherePredicate>, ()> {
|
||||
fn parse_lit_into_where(cx: &Ctxt,
|
||||
attr_name: &str,
|
||||
meta_item_name: &str,
|
||||
lit: &syn::Lit)
|
||||
-> Result<Vec<syn::WherePredicate>, ()> {
|
||||
let string = try!(get_string_from_lit(cx, attr_name, meta_item_name, lit));
|
||||
if string.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
|
||||
@@ -8,9 +8,7 @@ pub struct Ctxt {
|
||||
|
||||
impl Ctxt {
|
||||
pub fn new() -> Self {
|
||||
Ctxt {
|
||||
errors: RefCell::new(Some(Vec::new())),
|
||||
}
|
||||
Ctxt { errors: RefCell::new(Some(Vec::new())) }
|
||||
}
|
||||
|
||||
pub fn error<T: Display>(&self, msg: T) {
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
#![cfg_attr(feature = "clippy", plugin(clippy))]
|
||||
#![cfg_attr(feature = "clippy", feature(plugin))]
|
||||
|
||||
extern crate syn;
|
||||
|
||||
pub mod ast;
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
[package]
|
||||
name = "serde_derive"
|
||||
version = "0.9.2"
|
||||
version = "0.9.8"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]"
|
||||
homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://serde.rs/codegen.html"
|
||||
keywords = ["serde", "serialization"]
|
||||
include = ["Cargo.toml", "src/**/*.rs"]
|
||||
keywords = ["serde", "serialization", "no_std"]
|
||||
readme = "../README.md"
|
||||
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
|
||||
[features]
|
||||
unstable = []
|
||||
unstable-testing = ["clippy", "serde_codegen_internals/unstable-testing"]
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "serde-rs/serde" }
|
||||
@@ -22,7 +22,6 @@ name = "serde_derive"
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
clippy = { version = "0.*", optional = true }
|
||||
quote = "0.3.8"
|
||||
serde_codegen_internals = { version = "=0.12.0", default-features = false, path = "../serde_codegen_internals" }
|
||||
syn = { version = "0.11", features = ["aster", "visit"] }
|
||||
serde_codegen_internals = { version = "=0.14.0", default-features = false, path = "../serde_codegen_internals" }
|
||||
syn = { version = "0.11", features = ["visit"] }
|
||||
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../README.md
|
||||
+154
-47
@@ -1,46 +1,71 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use syn::{self, aster, visit};
|
||||
use syn::{self, visit};
|
||||
|
||||
use internals::ast::Item;
|
||||
use internals::attr;
|
||||
|
||||
macro_rules! path {
|
||||
($first:ident $(:: $rest:ident)*) => {
|
||||
syn::Path {
|
||||
global: false,
|
||||
segments: vec![
|
||||
stringify!($first).into(),
|
||||
$(
|
||||
stringify!($rest).into(),
|
||||
)*
|
||||
],
|
||||
}
|
||||
};
|
||||
|
||||
(::$first:ident $(:: $rest:ident)*) => {
|
||||
syn::Path {
|
||||
global: true,
|
||||
segments: vec![
|
||||
stringify!($first).into(),
|
||||
$(
|
||||
stringify!($rest).into(),
|
||||
)*
|
||||
],
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Remove the default from every type parameter because in the generated impls
|
||||
// they look like associated types: "error: associated type bindings are not
|
||||
// allowed here".
|
||||
pub fn without_defaults(generics: &syn::Generics) -> syn::Generics {
|
||||
syn::Generics {
|
||||
ty_params: generics.ty_params.iter().map(|ty_param| {
|
||||
syn::TyParam {
|
||||
default: None,
|
||||
.. ty_param.clone()
|
||||
}}).collect(),
|
||||
.. generics.clone()
|
||||
ty_params: generics.ty_params
|
||||
.iter()
|
||||
.map(|ty_param| syn::TyParam { default: None, ..ty_param.clone() })
|
||||
.collect(),
|
||||
..generics.clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_where_predicates(
|
||||
generics: &syn::Generics,
|
||||
predicates: &[syn::WherePredicate],
|
||||
) -> syn::Generics {
|
||||
aster::from_generics(generics.clone())
|
||||
.with_predicates(predicates.to_vec())
|
||||
.build()
|
||||
pub fn with_where_predicates(generics: &syn::Generics,
|
||||
predicates: &[syn::WherePredicate])
|
||||
-> syn::Generics {
|
||||
let mut generics = generics.clone();
|
||||
generics.where_clause.predicates.extend_from_slice(predicates);
|
||||
generics
|
||||
}
|
||||
|
||||
pub fn with_where_predicates_from_fields<F>(
|
||||
item: &Item,
|
||||
generics: &syn::Generics,
|
||||
from_field: F,
|
||||
) -> syn::Generics
|
||||
where F: Fn(&attr::Field) -> Option<&[syn::WherePredicate]>,
|
||||
pub fn with_where_predicates_from_fields<F>(item: &Item,
|
||||
generics: &syn::Generics,
|
||||
from_field: F)
|
||||
-> syn::Generics
|
||||
where F: Fn(&attr::Field) -> Option<&[syn::WherePredicate]>
|
||||
{
|
||||
aster::from_generics(generics.clone())
|
||||
.with_predicates(
|
||||
item.body.all_fields()
|
||||
.flat_map(|field| from_field(&field.attrs))
|
||||
.flat_map(|predicates| predicates.to_vec()))
|
||||
.build()
|
||||
let predicates = item.body
|
||||
.all_fields()
|
||||
.flat_map(|field| from_field(&field.attrs))
|
||||
.flat_map(|predicates| predicates.to_vec());
|
||||
|
||||
let mut generics = generics.clone();
|
||||
generics.where_clause.predicates.extend(predicates);
|
||||
generics
|
||||
}
|
||||
|
||||
// Puts the given bound on any generic type parameters that are used in fields
|
||||
@@ -54,13 +79,12 @@ pub fn with_where_predicates_from_fields<F>(
|
||||
// #[serde(skip_serializing)]
|
||||
// c: C,
|
||||
// }
|
||||
pub fn with_bound<F>(
|
||||
item: &Item,
|
||||
generics: &syn::Generics,
|
||||
filter: F,
|
||||
bound: &syn::Path,
|
||||
) -> syn::Generics
|
||||
where F: Fn(&attr::Field) -> bool,
|
||||
pub fn with_bound<F>(item: &Item,
|
||||
generics: &syn::Generics,
|
||||
filter: F,
|
||||
bound: &syn::Path)
|
||||
-> syn::Generics
|
||||
where F: Fn(&attr::Field) -> bool
|
||||
{
|
||||
struct FindTyParams {
|
||||
// Set of all generic type parameters on the current struct (A, B, C in
|
||||
@@ -90,11 +114,13 @@ pub fn with_bound<F>(
|
||||
}
|
||||
}
|
||||
|
||||
let all_ty_params: HashSet<_> = generics.ty_params.iter()
|
||||
let all_ty_params: HashSet<_> = generics.ty_params
|
||||
.iter()
|
||||
.map(|ty_param| ty_param.ident.clone())
|
||||
.collect();
|
||||
|
||||
let relevant_tys = item.body.all_fields()
|
||||
let relevant_tys = item.body
|
||||
.all_fields()
|
||||
.filter(|&field| filter(&field.attrs))
|
||||
.map(|field| &field.ty);
|
||||
|
||||
@@ -106,16 +132,97 @@ pub fn with_bound<F>(
|
||||
visit::walk_ty(&mut visitor, ty);
|
||||
}
|
||||
|
||||
aster::from_generics(generics.clone())
|
||||
.with_predicates(
|
||||
generics.ty_params.iter()
|
||||
.map(|ty_param| ty_param.ident.clone())
|
||||
.filter(|id| visitor.relevant_ty_params.contains(id))
|
||||
.map(|id| aster::where_predicate()
|
||||
// the type parameter that is being bounded e.g. T
|
||||
.bound().build(aster::ty().id(id))
|
||||
// the bound e.g. Serialize
|
||||
.bound().trait_(bound.clone()).build()
|
||||
.build()))
|
||||
.build()
|
||||
let new_predicates = generics.ty_params
|
||||
.iter()
|
||||
.map(|ty_param| ty_param.ident.clone())
|
||||
.filter(|id| visitor.relevant_ty_params.contains(id))
|
||||
.map(|id| {
|
||||
syn::WherePredicate::BoundPredicate(syn::WhereBoundPredicate {
|
||||
bound_lifetimes: Vec::new(),
|
||||
// the type parameter that is being bounded e.g. T
|
||||
bounded_ty: syn::Ty::Path(None, id.into()),
|
||||
// the bound e.g. Serialize
|
||||
bounds: vec![syn::TyParamBound::Trait(
|
||||
syn::PolyTraitRef {
|
||||
bound_lifetimes: Vec::new(),
|
||||
trait_ref: bound.clone(),
|
||||
},
|
||||
syn::TraitBoundModifier::None
|
||||
)],
|
||||
})
|
||||
});
|
||||
|
||||
let mut generics = generics.clone();
|
||||
generics.where_clause.predicates.extend(new_predicates);
|
||||
generics
|
||||
}
|
||||
|
||||
pub fn with_self_bound(item: &Item,
|
||||
generics: &syn::Generics,
|
||||
bound: &syn::Path)
|
||||
-> syn::Generics
|
||||
{
|
||||
let mut generics = generics.clone();
|
||||
generics.where_clause.predicates.push(
|
||||
syn::WherePredicate::BoundPredicate(syn::WhereBoundPredicate {
|
||||
bound_lifetimes: Vec::new(),
|
||||
// the type that is being bounded e.g. MyStruct<'a, T>
|
||||
bounded_ty: type_of_item(item),
|
||||
// the bound e.g. Default
|
||||
bounds: vec![syn::TyParamBound::Trait(
|
||||
syn::PolyTraitRef {
|
||||
bound_lifetimes: Vec::new(),
|
||||
trait_ref: bound.clone(),
|
||||
},
|
||||
syn::TraitBoundModifier::None
|
||||
)],
|
||||
})
|
||||
);
|
||||
generics
|
||||
}
|
||||
|
||||
pub fn with_lifetime_bound(generics: &syn::Generics,
|
||||
lifetime: &str)
|
||||
-> syn::Generics {
|
||||
let mut generics = generics.clone();
|
||||
|
||||
for lifetime_def in &mut generics.lifetimes {
|
||||
lifetime_def.bounds.push(syn::Lifetime::new(lifetime));
|
||||
}
|
||||
|
||||
for ty_param in &mut generics.ty_params {
|
||||
ty_param.bounds.push(syn::TyParamBound::Region(syn::Lifetime::new(lifetime)));
|
||||
}
|
||||
|
||||
generics.lifetimes.push(syn::LifetimeDef {
|
||||
attrs: Vec::new(),
|
||||
lifetime: syn::Lifetime::new(lifetime),
|
||||
bounds: Vec::new(),
|
||||
});
|
||||
|
||||
generics
|
||||
}
|
||||
|
||||
fn type_of_item(item: &Item) -> syn::Ty {
|
||||
syn::Ty::Path(None, syn::Path {
|
||||
global: false,
|
||||
segments: vec![
|
||||
syn::PathSegment {
|
||||
ident: item.ident.clone(),
|
||||
parameters: syn::PathParameters::AngleBracketed(syn::AngleBracketedParameterData {
|
||||
lifetimes: item.generics
|
||||
.lifetimes
|
||||
.iter()
|
||||
.map(|def| def.lifetime.clone())
|
||||
.collect(),
|
||||
types: item.generics
|
||||
.ty_params
|
||||
.iter()
|
||||
.map(|param| syn::Ty::Path(None, param.ident.clone().into()))
|
||||
.collect(),
|
||||
bindings: Vec::new(),
|
||||
}),
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
+815
-461
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,67 @@
|
||||
use quote::{Tokens, ToTokens};
|
||||
|
||||
pub enum Fragment {
|
||||
/// Tokens that can be used as an expression.
|
||||
Expr(Tokens),
|
||||
/// Tokens that can be used inside a block. The surrounding curly braces are
|
||||
/// not part of these tokens.
|
||||
Block(Tokens),
|
||||
}
|
||||
|
||||
macro_rules! quote_expr {
|
||||
($($tt:tt)*) => {
|
||||
$crate::fragment::Fragment::Expr(quote!($($tt)*))
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! quote_block {
|
||||
($($tt:tt)*) => {
|
||||
$crate::fragment::Fragment::Block(quote!($($tt)*))
|
||||
}
|
||||
}
|
||||
|
||||
/// Interpolate a fragment in place of an expression. This involves surrounding
|
||||
/// Block fragments in curly braces.
|
||||
pub struct Expr(pub Fragment);
|
||||
impl ToTokens for Expr {
|
||||
fn to_tokens(&self, out: &mut Tokens) {
|
||||
match self.0 {
|
||||
Fragment::Expr(ref expr) => expr.to_tokens(out),
|
||||
Fragment::Block(ref block) => {
|
||||
out.append("{");
|
||||
block.to_tokens(out);
|
||||
out.append("}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Interpolate a fragment as the statements of a block.
|
||||
pub struct Stmts(pub Fragment);
|
||||
impl ToTokens for Stmts {
|
||||
fn to_tokens(&self, out: &mut Tokens) {
|
||||
match self.0 {
|
||||
Fragment::Expr(ref expr) => expr.to_tokens(out),
|
||||
Fragment::Block(ref block) => block.to_tokens(out),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Interpolate a fragment as the value part of a `match` expression. This
|
||||
/// involves putting a comma after expressions and curly braces around blocks.
|
||||
pub struct Match(pub Fragment);
|
||||
impl ToTokens for Match {
|
||||
fn to_tokens(&self, out: &mut Tokens) {
|
||||
match self.0 {
|
||||
Fragment::Expr(ref expr) => {
|
||||
expr.to_tokens(out);
|
||||
out.append(",");
|
||||
}
|
||||
Fragment::Block(ref block) => {
|
||||
out.append("{");
|
||||
block.to_tokens(out);
|
||||
out.append("}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
#![cfg_attr(feature = "clippy", plugin(clippy))]
|
||||
#![cfg_attr(feature = "clippy", feature(plugin))]
|
||||
#![cfg_attr(feature = "clippy", allow(too_many_arguments))]
|
||||
#![cfg_attr(feature = "clippy", allow(used_underscore_binding))]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(used_underscore_binding))]
|
||||
|
||||
// The `quote!` macro requires deep recursion.
|
||||
#![recursion_limit = "192"]
|
||||
@@ -15,9 +13,13 @@ extern crate serde_codegen_internals as internals;
|
||||
extern crate proc_macro;
|
||||
use proc_macro::TokenStream;
|
||||
|
||||
#[macro_use]
|
||||
mod bound;
|
||||
mod de;
|
||||
#[macro_use]
|
||||
mod fragment;
|
||||
|
||||
mod ser;
|
||||
mod de;
|
||||
|
||||
#[proc_macro_derive(Serialize, attributes(serde))]
|
||||
pub fn derive_serialize(input: TokenStream) -> TokenStream {
|
||||
|
||||
+520
-308
File diff suppressed because it is too large
Load Diff
@@ -1,21 +1,17 @@
|
||||
[package]
|
||||
name = "serde_test"
|
||||
version = "0.9.2"
|
||||
version = "0.9.8"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "Token De/Serializer for testing De/Serialize implementations"
|
||||
homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://docs.serde.rs/serde_test/"
|
||||
readme = "../README.md"
|
||||
keywords = ["serde", "serialization"]
|
||||
include = ["Cargo.toml", "src/**/*.rs"]
|
||||
|
||||
[features]
|
||||
unstable-testing = ["clippy"]
|
||||
readme = "../README.md"
|
||||
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
|
||||
[dependencies]
|
||||
clippy = { version = "0.*", optional = true }
|
||||
serde = { version = "0.9", path = "../serde" }
|
||||
|
||||
[badges]
|
||||
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../README.md
|
||||
@@ -8,14 +8,14 @@ use token::Token;
|
||||
use std::fmt::Debug;
|
||||
|
||||
pub fn assert_tokens<T>(value: &T, tokens: &[Token<'static>])
|
||||
where T: Serialize + Deserialize + PartialEq + Debug,
|
||||
where T: Serialize + Deserialize + PartialEq + Debug
|
||||
{
|
||||
assert_ser_tokens(value, tokens);
|
||||
assert_de_tokens(value, tokens);
|
||||
}
|
||||
|
||||
pub fn assert_ser_tokens<T>(value: &T, tokens: &[Token])
|
||||
where T: Serialize,
|
||||
where T: Serialize
|
||||
{
|
||||
let mut ser = Serializer::new(tokens.iter());
|
||||
assert_eq!(Serialize::serialize(value, &mut ser), Ok(()));
|
||||
@@ -24,7 +24,7 @@ pub fn assert_ser_tokens<T>(value: &T, tokens: &[Token])
|
||||
|
||||
/// Expect an error serializing `T`.
|
||||
pub fn assert_ser_tokens_error<T>(value: &T, tokens: &[Token], error: Error)
|
||||
where T: Serialize + PartialEq + Debug,
|
||||
where T: Serialize + PartialEq + Debug
|
||||
{
|
||||
let mut ser = Serializer::new(tokens.iter());
|
||||
let v: Result<(), Error> = Serialize::serialize(value, &mut ser);
|
||||
@@ -33,7 +33,7 @@ pub fn assert_ser_tokens_error<T>(value: &T, tokens: &[Token], error: Error)
|
||||
}
|
||||
|
||||
pub fn assert_de_tokens<T>(value: &T, tokens: &[Token<'static>])
|
||||
where T: Deserialize + PartialEq + Debug,
|
||||
where T: Deserialize + PartialEq + Debug
|
||||
{
|
||||
let mut de = Deserializer::new(tokens.to_vec().into_iter());
|
||||
let v: Result<T, Error> = Deserialize::deserialize(&mut de);
|
||||
@@ -43,7 +43,7 @@ pub fn assert_de_tokens<T>(value: &T, tokens: &[Token<'static>])
|
||||
|
||||
/// Expect an error deserializing tokens into a `T`.
|
||||
pub fn assert_de_tokens_error<T>(tokens: &[Token<'static>], error: Error)
|
||||
where T: Deserialize + PartialEq + Debug,
|
||||
where T: Deserialize + PartialEq + Debug
|
||||
{
|
||||
let mut de = Deserializer::new(tokens.to_vec().into_iter());
|
||||
let v: Result<T, Error> = Deserialize::deserialize(&mut de);
|
||||
|
||||
+146
-502
@@ -1,33 +1,23 @@
|
||||
use std::iter;
|
||||
|
||||
use serde::de::{
|
||||
self,
|
||||
Deserialize,
|
||||
DeserializeSeed,
|
||||
EnumVisitor,
|
||||
MapVisitor,
|
||||
SeqVisitor,
|
||||
VariantVisitor,
|
||||
Visitor,
|
||||
};
|
||||
use serde::de::{self, Deserialize, DeserializeSeed, EnumVisitor, MapVisitor, SeqVisitor,
|
||||
VariantVisitor, Visitor};
|
||||
use serde::de::value::ValueDeserializer;
|
||||
|
||||
use error::Error;
|
||||
use token::Token;
|
||||
|
||||
pub struct Deserializer<I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
where I: Iterator<Item = Token<'static>>
|
||||
{
|
||||
tokens: iter::Peekable<I>,
|
||||
}
|
||||
|
||||
impl<I> Deserializer<I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
where I: Iterator<Item = Token<'static>>
|
||||
{
|
||||
pub fn new(tokens: I) -> Deserializer<I> {
|
||||
Deserializer {
|
||||
tokens: tokens.peekable(),
|
||||
}
|
||||
Deserializer { tokens: tokens.peekable() }
|
||||
}
|
||||
|
||||
pub fn next_token(&mut self) -> Option<Token<'static>> {
|
||||
@@ -47,187 +37,55 @@ impl<I> Deserializer<I>
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_seq<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
fn visit_seq<V>(&mut self,
|
||||
len: Option<usize>,
|
||||
sep: Token<'static>,
|
||||
end: Token<'static>,
|
||||
visitor: V)
|
||||
-> Result<V::Value, Error>
|
||||
where V: Visitor
|
||||
{
|
||||
let value = try!(visitor.visit_seq(DeserializerSeqVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
sep: sep,
|
||||
end: end.clone(),
|
||||
}));
|
||||
try!(self.expect_token(Token::SeqEnd));
|
||||
try!(self.expect_token(end));
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn visit_array<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
let value = try!(visitor.visit_seq(DeserializerArrayVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
}));
|
||||
try!(self.expect_token(Token::SeqEnd));
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn visit_tuple<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
let value = try!(visitor.visit_seq(DeserializerTupleVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
}));
|
||||
try!(self.expect_token(Token::TupleEnd));
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn visit_tuple_struct<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
let value = try!(visitor.visit_seq(DeserializerTupleStructVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
}));
|
||||
try!(self.expect_token(Token::TupleStructEnd));
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn visit_variant_seq<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
let value = try!(visitor.visit_seq(DeserializerVariantSeqVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
}));
|
||||
try!(self.expect_token(Token::EnumSeqEnd));
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn visit_map<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
fn visit_map<V>(&mut self,
|
||||
len: Option<usize>,
|
||||
sep: Token<'static>,
|
||||
end: Token<'static>,
|
||||
visitor: V)
|
||||
-> Result<V::Value, Error>
|
||||
where V: Visitor
|
||||
{
|
||||
let value = try!(visitor.visit_map(DeserializerMapVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
sep: sep,
|
||||
end: end.clone(),
|
||||
}));
|
||||
try!(self.expect_token(Token::MapEnd));
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn visit_struct<V>(&mut self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
let value = try!(visitor.visit_map(DeserializerStructVisitor {
|
||||
de: self,
|
||||
len: fields.len(),
|
||||
}));
|
||||
try!(self.expect_token(Token::StructEnd));
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn visit_variant_map<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
{
|
||||
let value = try!(visitor.visit_map(DeserializerVariantMapVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
}));
|
||||
try!(self.expect_token(Token::EnumMapEnd));
|
||||
try!(self.expect_token(end));
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
where I: Iterator<Item = Token<'static>>
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn deserialize_seq<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_struct_field<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_map<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_unit<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_bytes<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_byte_buf<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_ignored_any<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_string<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_str<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_char<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_i64<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_i32<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_i16<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_i8<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_u64<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_u32<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_u16<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_u8<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_f32<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_f64<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_bool<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
forward_to_deserialize! {
|
||||
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit
|
||||
seq bytes byte_buf map struct_field ignored_any
|
||||
}
|
||||
|
||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
where V: Visitor
|
||||
{
|
||||
match self.tokens.next() {
|
||||
Some(Token::Bool(v)) => visitor.visit_bool(v),
|
||||
@@ -251,16 +109,25 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
||||
Some(Token::Unit) => visitor.visit_unit(),
|
||||
Some(Token::UnitStruct(_name)) => visitor.visit_unit(),
|
||||
Some(Token::SeqStart(len)) => {
|
||||
self.visit_seq(len, visitor)
|
||||
self.visit_seq(len, Token::SeqSep, Token::SeqEnd, visitor)
|
||||
}
|
||||
Some(Token::SeqArrayStart(len))| Some(Token::TupleStructStart(_, len)) => {
|
||||
self.visit_seq(Some(len), visitor)
|
||||
Some(Token::SeqArrayStart(len)) => {
|
||||
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||
}
|
||||
Some(Token::TupleStart(len)) => {
|
||||
self.visit_seq(Some(len), Token::TupleSep, Token::TupleEnd, visitor)
|
||||
}
|
||||
Some(Token::TupleStructStart(_, len)) => {
|
||||
self.visit_seq(Some(len),
|
||||
Token::TupleStructSep,
|
||||
Token::TupleStructEnd,
|
||||
visitor)
|
||||
}
|
||||
Some(Token::MapStart(len)) => {
|
||||
self.visit_map(len, visitor)
|
||||
self.visit_map(len, Token::MapSep, Token::MapEnd, visitor)
|
||||
}
|
||||
Some(Token::StructStart(_, len)) => {
|
||||
self.visit_map(Some(len), visitor)
|
||||
self.visit_map(Some(len), Token::StructSep, Token::StructEnd, visitor)
|
||||
}
|
||||
Some(token) => Err(Error::UnexpectedToken(token)),
|
||||
None => Err(Error::EndOfTokens),
|
||||
@@ -270,10 +137,11 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
||||
/// Hook into `Option` deserializing so we can treat `Unit` as a
|
||||
/// `None`, or a regular value as `Some(value)`.
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
where V: Visitor
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::Unit) | Some(&Token::Option(false)) => {
|
||||
Some(&Token::Unit) |
|
||||
Some(&Token::Option(false)) => {
|
||||
self.tokens.next();
|
||||
visitor.visit_none()
|
||||
}
|
||||
@@ -287,26 +155,23 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(self,
|
||||
name: &str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
name: &str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V)
|
||||
-> Result<V::Value, Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::EnumStart(n)) if name == n => {
|
||||
self.tokens.next();
|
||||
|
||||
visitor.visit_enum(DeserializerEnumVisitor {
|
||||
de: self,
|
||||
})
|
||||
visitor.visit_enum(DeserializerEnumVisitor { de: self })
|
||||
}
|
||||
Some(&Token::EnumUnit(n, _))
|
||||
| Some(&Token::EnumNewType(n, _))
|
||||
| Some(&Token::EnumSeqStart(n, _, _))
|
||||
| Some(&Token::EnumMapStart(n, _, _)) if name == n => {
|
||||
visitor.visit_enum(DeserializerEnumVisitor {
|
||||
de: self,
|
||||
})
|
||||
Some(&Token::EnumUnit(n, _)) |
|
||||
Some(&Token::EnumNewType(n, _)) |
|
||||
Some(&Token::EnumSeqStart(n, _, _)) |
|
||||
Some(&Token::EnumMapStart(n, _, _)) if name == n => {
|
||||
visitor.visit_enum(DeserializerEnumVisitor { de: self })
|
||||
}
|
||||
Some(_) => {
|
||||
let token = self.tokens.next().unwrap();
|
||||
@@ -317,7 +182,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
||||
}
|
||||
|
||||
fn deserialize_unit_struct<V>(self, name: &str, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
where V: Visitor
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::UnitStruct(n)) => {
|
||||
@@ -333,10 +198,8 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(self,
|
||||
name: &str,
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
fn deserialize_newtype_struct<V>(self, name: &str, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::StructNewType(n)) => {
|
||||
@@ -352,46 +215,46 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_seq_fixed_size<V>(self,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
fn deserialize_seq_fixed_size<V>(self, len: usize, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::SeqArrayStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_array(len, visitor)
|
||||
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||
}
|
||||
Some(_) => self.deserialize(visitor),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_tuple<V>(self,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::Unit) | Some(&Token::UnitStruct(_)) => {
|
||||
Some(&Token::Unit) |
|
||||
Some(&Token::UnitStruct(_)) => {
|
||||
self.tokens.next();
|
||||
visitor.visit_unit()
|
||||
}
|
||||
Some(&Token::SeqStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_seq(Some(len), visitor)
|
||||
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||
}
|
||||
Some(&Token::SeqArrayStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_array(len, visitor)
|
||||
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||
}
|
||||
Some(&Token::TupleStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_tuple(len, visitor)
|
||||
self.visit_seq(Some(len), Token::TupleSep, Token::TupleEnd, visitor)
|
||||
}
|
||||
Some(&Token::TupleStructStart(_, _)) => {
|
||||
self.tokens.next();
|
||||
self.visit_tuple_struct(len, visitor)
|
||||
self.visit_seq(Some(len),
|
||||
Token::TupleStructSep,
|
||||
Token::TupleStructEnd,
|
||||
visitor)
|
||||
}
|
||||
Some(_) => self.deserialize(visitor),
|
||||
None => Err(Error::EndOfTokens),
|
||||
@@ -401,8 +264,9 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
||||
fn deserialize_tuple_struct<V>(self,
|
||||
name: &str,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
visitor: V)
|
||||
-> Result<V::Value, Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::Unit) => {
|
||||
@@ -419,20 +283,23 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
||||
}
|
||||
Some(&Token::SeqStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_seq(Some(len), visitor)
|
||||
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||
}
|
||||
Some(&Token::SeqArrayStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_array(len, visitor)
|
||||
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||
}
|
||||
Some(&Token::TupleStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_tuple(len, visitor)
|
||||
self.visit_seq(Some(len), Token::TupleSep, Token::TupleEnd, visitor)
|
||||
}
|
||||
Some(&Token::TupleStructStart(n, _)) => {
|
||||
self.tokens.next();
|
||||
if name == n {
|
||||
self.visit_tuple_struct(len, visitor)
|
||||
self.visit_seq(Some(len),
|
||||
Token::TupleStructSep,
|
||||
Token::TupleStructEnd,
|
||||
visitor)
|
||||
} else {
|
||||
Err(Error::InvalidName(n))
|
||||
}
|
||||
@@ -445,21 +312,25 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
||||
fn deserialize_struct<V>(self,
|
||||
name: &str,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
visitor: V)
|
||||
-> Result<V::Value, Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match self.tokens.peek() {
|
||||
Some(&Token::StructStart(n, _)) => {
|
||||
self.tokens.next();
|
||||
if name == n {
|
||||
self.visit_struct(fields, visitor)
|
||||
self.visit_map(Some(fields.len()),
|
||||
Token::StructSep,
|
||||
Token::StructEnd,
|
||||
visitor)
|
||||
} else {
|
||||
Err(Error::InvalidName(n))
|
||||
}
|
||||
}
|
||||
Some(&Token::MapStart(_)) => {
|
||||
self.tokens.next();
|
||||
self.visit_map(Some(fields.len()), visitor)
|
||||
self.visit_map(Some(fields.len()), Token::MapSep, Token::MapEnd, visitor)
|
||||
}
|
||||
Some(_) => self.deserialize(visitor),
|
||||
None => Err(Error::EndOfTokens),
|
||||
@@ -469,30 +340,32 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerSeqVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||
struct DeserializerSeqVisitor<'a, I: 'a>
|
||||
where I: Iterator<Item = Token<'static>>
|
||||
{
|
||||
de: &'a mut Deserializer<I>,
|
||||
len: Option<usize>,
|
||||
sep: Token<'static>,
|
||||
end: Token<'static>,
|
||||
}
|
||||
|
||||
impl<'a, I> SeqVisitor for DeserializerSeqVisitor<'a, I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
where I: Iterator<Item = Token<'static>>
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
|
||||
where T: DeserializeSeed,
|
||||
where T: DeserializeSeed
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::SeqSep) => {
|
||||
self.de.tokens.next();
|
||||
self.len = self.len.map(|len| len - 1);
|
||||
if self.de.tokens.peek() == Some(&self.end) {
|
||||
return Ok(None);
|
||||
}
|
||||
match self.de.tokens.next() {
|
||||
Some(ref token) if *token == self.sep => {
|
||||
self.len = self.len.map(|len| len.saturating_sub(1));
|
||||
seed.deserialize(&mut *self.de).map(Some)
|
||||
}
|
||||
Some(&Token::SeqEnd) => Ok(None),
|
||||
Some(_) => {
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
Some(other) => Err(Error::UnexpectedToken(other)),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
@@ -505,177 +378,38 @@ impl<'a, I> SeqVisitor for DeserializerSeqVisitor<'a, I>
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerArrayVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||
de: &'a mut Deserializer<I>,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl<'a, I> SeqVisitor for DeserializerArrayVisitor<'a, I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
struct DeserializerMapVisitor<'a, I: 'a>
|
||||
where I: Iterator<Item = Token<'static>>
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
|
||||
where T: DeserializeSeed,
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::SeqSep) => {
|
||||
self.de.tokens.next();
|
||||
self.len -= 1;
|
||||
seed.deserialize(&mut *self.de).map(Some)
|
||||
}
|
||||
Some(&Token::SeqEnd) => Ok(None),
|
||||
Some(_) => {
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.len, Some(self.len))
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerTupleVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||
de: &'a mut Deserializer<I>,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl<'a, I> SeqVisitor for DeserializerTupleVisitor<'a, I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
|
||||
where T: DeserializeSeed,
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::TupleSep) => {
|
||||
self.de.tokens.next();
|
||||
self.len -= 1;
|
||||
seed.deserialize(&mut *self.de).map(Some)
|
||||
}
|
||||
Some(&Token::TupleEnd) => Ok(None),
|
||||
Some(_) => {
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.len, Some(self.len))
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerTupleStructVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||
de: &'a mut Deserializer<I>,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl<'a, I> SeqVisitor for DeserializerTupleStructVisitor<'a, I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
|
||||
where T: DeserializeSeed,
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::TupleStructSep) => {
|
||||
self.de.tokens.next();
|
||||
self.len -= 1;
|
||||
seed.deserialize(&mut *self.de).map(Some)
|
||||
}
|
||||
Some(&Token::TupleStructEnd) => Ok(None),
|
||||
Some(_) => {
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.len, Some(self.len))
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerVariantSeqVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||
de: &'a mut Deserializer<I>,
|
||||
len: Option<usize>,
|
||||
}
|
||||
|
||||
impl<'a, I> SeqVisitor for DeserializerVariantSeqVisitor<'a, I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
|
||||
where T: DeserializeSeed,
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::EnumSeqSep) => {
|
||||
self.de.tokens.next();
|
||||
self.len = self.len.map(|len| len - 1);
|
||||
seed.deserialize(&mut *self.de).map(Some)
|
||||
}
|
||||
Some(&Token::EnumSeqEnd) => Ok(None),
|
||||
Some(_) => {
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = self.len.unwrap_or(0);
|
||||
(len, self.len)
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerMapVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||
de: &'a mut Deserializer<I>,
|
||||
len: Option<usize>,
|
||||
sep: Token<'static>,
|
||||
end: Token<'static>,
|
||||
}
|
||||
|
||||
impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
where I: Iterator<Item = Token<'static>>
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
|
||||
where K: DeserializeSeed,
|
||||
where K: DeserializeSeed
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::MapSep) => {
|
||||
self.de.tokens.next();
|
||||
self.len = self.len.map(|len| if len > 0 { len - 1} else { 0 });
|
||||
if self.de.tokens.peek() == Some(&self.end) {
|
||||
return Ok(None);
|
||||
}
|
||||
match self.de.tokens.next() {
|
||||
Some(ref token) if *token == self.sep => {
|
||||
self.len = self.len.map(|len| len.saturating_sub(1));
|
||||
seed.deserialize(&mut *self.de).map(Some)
|
||||
}
|
||||
Some(&Token::MapEnd) => Ok(None),
|
||||
Some(_) => {
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
Some(other) => Err(Error::UnexpectedToken(other)),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
|
||||
where V: DeserializeSeed,
|
||||
where V: DeserializeSeed
|
||||
{
|
||||
seed.deserialize(&mut *self.de)
|
||||
}
|
||||
@@ -688,65 +422,26 @@ impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerStructVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||
de: &'a mut Deserializer<I>,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl<'a, I> MapVisitor for DeserializerStructVisitor<'a, I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
struct DeserializerEnumVisitor<'a, I: 'a>
|
||||
where I: Iterator<Item = Token<'static>>
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
|
||||
where K: DeserializeSeed,
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::StructSep) => {
|
||||
self.de.tokens.next();
|
||||
self.len = self.len.saturating_sub(1);
|
||||
seed.deserialize(&mut *self.de).map(Some)
|
||||
}
|
||||
Some(&Token::StructEnd) => Ok(None),
|
||||
Some(_) => {
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
|
||||
where V: DeserializeSeed,
|
||||
{
|
||||
seed.deserialize(&mut *self.de)
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.len, Some(self.len))
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerEnumVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||
de: &'a mut Deserializer<I>,
|
||||
}
|
||||
|
||||
impl<'a, I> EnumVisitor for DeserializerEnumVisitor<'a, I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
where I: Iterator<Item = Token<'static>>
|
||||
{
|
||||
type Error = Error;
|
||||
type Variant = Self;
|
||||
|
||||
fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self), Error>
|
||||
where V: DeserializeSeed,
|
||||
where V: DeserializeSeed
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::EnumUnit(_, v))
|
||||
| Some(&Token::EnumNewType(_, v))
|
||||
| Some(&Token::EnumSeqStart(_, v, _))
|
||||
| Some(&Token::EnumMapStart(_, v, _)) => {
|
||||
Some(&Token::EnumUnit(_, v)) |
|
||||
Some(&Token::EnumNewType(_, v)) |
|
||||
Some(&Token::EnumSeqStart(_, v, _)) |
|
||||
Some(&Token::EnumMapStart(_, v, _)) => {
|
||||
let de = v.into_deserializer();
|
||||
let value = try!(seed.deserialize(de));
|
||||
Ok((value, self))
|
||||
@@ -761,7 +456,7 @@ impl<'a, I> EnumVisitor for DeserializerEnumVisitor<'a, I>
|
||||
}
|
||||
|
||||
impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
|
||||
where I: Iterator<Item=Token<'static>>
|
||||
where I: Iterator<Item = Token<'static>>
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
@@ -771,39 +466,33 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
|
||||
self.de.tokens.next();
|
||||
Ok(())
|
||||
}
|
||||
Some(_) => {
|
||||
Deserialize::deserialize(self.de)
|
||||
}
|
||||
Some(_) => Deserialize::deserialize(self.de),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
|
||||
where T: DeserializeSeed,
|
||||
where T: DeserializeSeed
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::EnumNewType(_, _)) => {
|
||||
self.de.tokens.next();
|
||||
seed.deserialize(self.de)
|
||||
}
|
||||
Some(_) => {
|
||||
seed.deserialize(self.de)
|
||||
}
|
||||
Some(_) => seed.deserialize(self.de),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_tuple<V>(self,
|
||||
len: usize,
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
fn visit_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::EnumSeqStart(_, _, enum_len)) => {
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
|
||||
if len == enum_len {
|
||||
self.de.visit_variant_seq(Some(len), visitor)
|
||||
self.de.visit_seq(Some(len), Token::EnumSeqSep, Token::EnumSeqEnd, visitor)
|
||||
} else {
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
@@ -812,29 +501,28 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
|
||||
if len == enum_len {
|
||||
self.de.visit_seq(Some(len), visitor)
|
||||
self.de.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||
} else {
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
}
|
||||
Some(_) => {
|
||||
de::Deserializer::deserialize(self.de, visitor)
|
||||
}
|
||||
Some(_) => de::Deserializer::deserialize(self.de, visitor),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_struct<V>(self,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor,
|
||||
fn visit_struct<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Error>
|
||||
where V: Visitor
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::EnumMapStart(_, _, enum_len)) => {
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
|
||||
if fields.len() == enum_len {
|
||||
self.de.visit_variant_map(Some(fields.len()), visitor)
|
||||
self.de.visit_map(Some(fields.len()),
|
||||
Token::EnumMapSep,
|
||||
Token::EnumMapEnd,
|
||||
visitor)
|
||||
} else {
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
@@ -843,57 +531,13 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
|
||||
if fields.len() == enum_len {
|
||||
self.de.visit_map(Some(fields.len()), visitor)
|
||||
self.de.visit_map(Some(fields.len()), Token::MapSep, Token::MapEnd, visitor)
|
||||
} else {
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
}
|
||||
Some(_) => {
|
||||
de::Deserializer::deserialize(self.de, visitor)
|
||||
}
|
||||
Some(_) => de::Deserializer::deserialize(self.de, visitor),
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerVariantMapVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||
de: &'a mut Deserializer<I>,
|
||||
len: Option<usize>,
|
||||
}
|
||||
|
||||
impl<'a, I> MapVisitor for DeserializerVariantMapVisitor<'a, I>
|
||||
where I: Iterator<Item=Token<'static>>,
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
|
||||
where K: DeserializeSeed,
|
||||
{
|
||||
match self.de.tokens.peek() {
|
||||
Some(&Token::EnumMapSep) => {
|
||||
self.de.tokens.next();
|
||||
self.len = self.len.map(|len| if len > 0 { len - 1} else { 0 });
|
||||
seed.deserialize(&mut *self.de).map(Some)
|
||||
}
|
||||
Some(&Token::EnumMapEnd) => Ok(None),
|
||||
Some(_) => {
|
||||
let token = self.de.tokens.next().unwrap();
|
||||
Err(Error::UnexpectedToken(token))
|
||||
}
|
||||
None => Err(Error::EndOfTokens),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
|
||||
where V: DeserializeSeed,
|
||||
{
|
||||
seed.deserialize(&mut *self.de)
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = self.len.unwrap_or(0);
|
||||
(len, self.len)
|
||||
}
|
||||
}
|
||||
|
||||
+3
-10
@@ -1,16 +1,9 @@
|
||||
#![cfg_attr(feature = "clippy", feature(plugin))]
|
||||
#![cfg_attr(feature = "clippy", plugin(clippy))]
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde;
|
||||
|
||||
mod assert;
|
||||
pub use assert::{
|
||||
assert_tokens,
|
||||
assert_ser_tokens,
|
||||
assert_ser_tokens_error,
|
||||
assert_de_tokens,
|
||||
assert_de_tokens_error,
|
||||
};
|
||||
pub use assert::{assert_tokens, assert_ser_tokens, assert_ser_tokens_error, assert_de_tokens,
|
||||
assert_de_tokens_error};
|
||||
|
||||
mod ser;
|
||||
pub use ser::Serializer;
|
||||
|
||||
+46
-29
@@ -6,14 +6,14 @@ use error::Error;
|
||||
use token::Token;
|
||||
|
||||
pub struct Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
where I: Iterator<Item = &'a Token<'a>>
|
||||
{
|
||||
tokens: I,
|
||||
phantom: PhantomData<&'a Token<'a>>,
|
||||
}
|
||||
|
||||
impl<'a, I> Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
where I: Iterator<Item = &'a Token<'a>>
|
||||
{
|
||||
pub fn new(tokens: I) -> Serializer<'a, I> {
|
||||
Serializer {
|
||||
@@ -28,7 +28,7 @@ impl<'a, I> Serializer<'a, I>
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
where I: Iterator<Item = &'a Token<'a>>
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
@@ -124,15 +124,14 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
|
||||
fn serialize_unit_variant(self,
|
||||
name: &str,
|
||||
_variant_index: usize,
|
||||
variant: &str) -> Result<(), Error> {
|
||||
variant: &str)
|
||||
-> Result<(), Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::EnumUnit(name, variant)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized>(self,
|
||||
name: &'static str,
|
||||
value: &T) -> Result<(), Error>
|
||||
where T: Serialize,
|
||||
fn serialize_newtype_struct<T: ?Sized>(self, name: &'static str, value: &T) -> Result<(), Error>
|
||||
where T: Serialize
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::StructNewType(name)));
|
||||
value.serialize(self)
|
||||
@@ -142,8 +141,9 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
|
||||
name: &str,
|
||||
_variant_index: usize,
|
||||
variant: &str,
|
||||
value: &T) -> Result<(), Error>
|
||||
where T: Serialize,
|
||||
value: &T)
|
||||
-> Result<(), Error>
|
||||
where T: Serialize
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::EnumNewType(name, variant)));
|
||||
value.serialize(self)
|
||||
@@ -155,7 +155,7 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
|
||||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<(), Error>
|
||||
where T: Serialize,
|
||||
where T: Serialize
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::Option(true)));
|
||||
value.serialize(self)
|
||||
@@ -177,7 +177,8 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(self, name: &'static str, len: usize) -> Result<Self, Error> {
|
||||
assert_eq!(self.tokens.next(), Some(&Token::TupleStructStart(name, len)));
|
||||
assert_eq!(self.tokens.next(),
|
||||
Some(&Token::TupleStructStart(name, len)));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
@@ -185,9 +186,10 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
|
||||
name: &str,
|
||||
_variant_index: usize,
|
||||
variant: &str,
|
||||
len: usize) -> Result<Self, Error>
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::EnumSeqStart(name, variant, len)));
|
||||
len: usize)
|
||||
-> Result<Self, Error> {
|
||||
assert_eq!(self.tokens.next(),
|
||||
Some(&Token::EnumSeqStart(name, variant, len)));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
@@ -205,15 +207,16 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
|
||||
name: &str,
|
||||
_variant_index: usize,
|
||||
variant: &str,
|
||||
len: usize) -> Result<Self, Error>
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::EnumMapStart(name, variant, len)));
|
||||
len: usize)
|
||||
-> Result<Self, Error> {
|
||||
assert_eq!(self.tokens.next(),
|
||||
Some(&Token::EnumMapStart(name, variant, len)));
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::SerializeSeq for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
where I: Iterator<Item = &'a Token<'a>>
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
@@ -232,7 +235,7 @@ impl<'s, 'a, I> ser::SerializeSeq for &'s mut Serializer<'a, I>
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::SerializeTuple for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
where I: Iterator<Item = &'a Token<'a>>
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
@@ -251,7 +254,7 @@ impl<'s, 'a, I> ser::SerializeTuple for &'s mut Serializer<'a, I>
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::SerializeTupleStruct for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
where I: Iterator<Item = &'a Token<'a>>
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
@@ -270,7 +273,7 @@ impl<'s, 'a, I> ser::SerializeTupleStruct for &'s mut Serializer<'a, I>
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::SerializeTupleVariant for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
where I: Iterator<Item = &'a Token<'a>>
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
@@ -289,17 +292,21 @@ impl<'s, 'a, I> ser::SerializeTupleVariant for &'s mut Serializer<'a, I>
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::SerializeMap for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
where I: Iterator<Item = &'a Token<'a>>
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error> where T: Serialize {
|
||||
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
|
||||
where T: Serialize
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::MapSep));
|
||||
key.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize {
|
||||
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
where T: Serialize
|
||||
{
|
||||
value.serialize(&mut **self)
|
||||
}
|
||||
|
||||
@@ -310,12 +317,17 @@ impl<'s, 'a, I> ser::SerializeMap for &'s mut Serializer<'a, I>
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::SerializeStruct for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
where I: Iterator<Item = &'a Token<'a>>
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> where T: Serialize {
|
||||
fn serialize_field<T: ?Sized>(&mut self,
|
||||
key: &'static str,
|
||||
value: &T)
|
||||
-> Result<(), Self::Error>
|
||||
where T: Serialize
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::StructSep));
|
||||
try!(key.serialize(&mut **self));
|
||||
value.serialize(&mut **self)
|
||||
@@ -328,12 +340,17 @@ impl<'s, 'a, I> ser::SerializeStruct for &'s mut Serializer<'a, I>
|
||||
}
|
||||
|
||||
impl<'s, 'a, I> ser::SerializeStructVariant for &'s mut Serializer<'a, I>
|
||||
where I: Iterator<Item=&'a Token<'a>>,
|
||||
where I: Iterator<Item = &'a Token<'a>>
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> where T: Serialize {
|
||||
fn serialize_field<T: ?Sized>(&mut self,
|
||||
key: &'static str,
|
||||
value: &T)
|
||||
-> Result<(), Self::Error>
|
||||
where T: Serialize
|
||||
{
|
||||
assert_eq!(self.tokens.next(), Some(&Token::EnumMapSep));
|
||||
try!(key.serialize(&mut **self));
|
||||
value.serialize(&mut **self)
|
||||
|
||||
@@ -2,22 +2,12 @@
|
||||
name = "serde_test_suite"
|
||||
version = "0.0.0"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "A generic serialization/deserialization framework"
|
||||
homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://docs.serde.rs/serde/"
|
||||
readme = "README.md"
|
||||
keywords = ["serialization"]
|
||||
publish = false
|
||||
|
||||
[features]
|
||||
unstable-testing = [
|
||||
"clippy",
|
||||
"compiletest_rs",
|
||||
"serde/unstable-testing",
|
||||
"serde_derive/unstable-testing",
|
||||
"serde_test/unstable-testing",
|
||||
]
|
||||
|
||||
[dev-dependencies]
|
||||
@@ -28,7 +18,6 @@ serde_derive = { path = "../serde_derive" }
|
||||
serde_test = { path = "../serde_test" }
|
||||
|
||||
[dependencies]
|
||||
clippy = { version = "0.*", optional = true }
|
||||
compiletest_rs = { version = "0.2", optional = true }
|
||||
|
||||
[[test]]
|
||||
|
||||
@@ -4,6 +4,8 @@ version = "0.0.0"
|
||||
authors = ["David Tolnay <dtolnay@gmail.com>"]
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
serde = { path = "../../serde" }
|
||||
serde_derive = { path = "../../serde_derive" }
|
||||
|
||||
@@ -21,7 +21,9 @@ pub extern fn rust_eh_unwind_resume() {}
|
||||
pub extern fn rust_begin_panic(_msg: core::fmt::Arguments,
|
||||
_file: &'static str,
|
||||
_line: u32) -> ! {
|
||||
loop {}
|
||||
unsafe {
|
||||
libc::abort()
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
|
||||
#[serde(default)] //~^ HELP: #[serde(default)] can only be used on structs
|
||||
enum E {
|
||||
S { f: u8 },
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
|
||||
#[serde(default)] //~^ HELP: #[serde(default)] can only be used on structs
|
||||
struct T(u8, u8);
|
||||
|
||||
fn main() { }
|
||||
@@ -1,7 +1,7 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct S {
|
||||
#[serde(rename="x", serialize="y")] //~^^ HELP: unknown serde field attribute `serialize`
|
||||
x: (),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct S {
|
||||
#[serde(rename="x")]
|
||||
#[serde(rename(deserialize="y"))] //~^^^ HELP: duplicate serde attribute `rename`
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct S {
|
||||
#[serde(rename(serialize="x"), rename(serialize="y"))] //~^^ HELP: duplicate serde attribute `rename`
|
||||
x: (),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct S {
|
||||
#[serde(rename(serialize="x"))]
|
||||
#[serde(rename="y")] //~^^^ HELP: duplicate serde attribute `rename`
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct S {
|
||||
#[serde(rename(serialize="x", serialize="y"))] //~^^ HELP: duplicate serde attribute `rename`
|
||||
x: (),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct S {
|
||||
#[serde(rename(serialize="x"))]
|
||||
#[serde(rename(serialize="y"))] //~^^^ HELP: duplicate serde attribute `rename`
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct S {
|
||||
#[serde(with = "w", serialize_with = "s")] //~^^ HELP: duplicate serde attribute `serialize_with`
|
||||
x: (),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
#[serde(tag = "type")] //~^ HELP: #[serde(tag = "...")] cannot be used with tuple variants
|
||||
enum E {
|
||||
Tuple(u8, u8),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,8 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
#[serde(tag = "type")] //~^ HELP: #[serde(tag = "...")] can only be used on enums
|
||||
struct S;
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,12 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
#[serde(untagged)]
|
||||
#[serde(tag = "type")] //~^^ HELP: enum cannot be both untagged and internally tagged
|
||||
enum E {
|
||||
A(u8),
|
||||
B(String),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,8 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
#[serde(untagged)] //~^ HELP: #[serde(untagged)] can only be used on enums
|
||||
struct S;
|
||||
|
||||
fn main() {}
|
||||
@@ -1,7 +1,7 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize, Deserialize)] //~ ERROR: custom derive attribute panicked
|
||||
#[derive(Serialize, Deserialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct Test<'a> {
|
||||
s: &'a str, //~^^ HELP: Serde does not support deserializing fields of type &str
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
#[serde(abc="xyz")] //~^ HELP: unknown serde container attribute `abc`
|
||||
struct A {
|
||||
x: u32,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
struct C {
|
||||
#[serde(abc="xyz")] //~^^ HELP: unknown serde field attribute `abc`
|
||||
x: u32,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
enum E {
|
||||
#[serde(abc="xyz")] //~^^ HELP: unknown serde variant attribute `abc`
|
||||
V,
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
#![cfg_attr(feature = "clippy", feature(plugin))]
|
||||
#![cfg_attr(feature = "clippy", plugin(clippy))]
|
||||
|
||||
#![cfg_attr(feature = "unstable-testing", feature(test, non_ascii_idents))]
|
||||
|
||||
#[cfg(feature = "unstable-testing")]
|
||||
|
||||
@@ -2,6 +2,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::net;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use std::default::Default;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
@@ -40,6 +41,22 @@ struct StructDenyUnknown {
|
||||
b: i32,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
#[serde(default)]
|
||||
struct StructDefault<T> {
|
||||
a: i32,
|
||||
b: T,
|
||||
}
|
||||
|
||||
impl Default for StructDefault<String> {
|
||||
fn default() -> Self {
|
||||
StructDefault {
|
||||
a: 100,
|
||||
b: "default".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
struct StructSkipAll {
|
||||
#[serde(skip_deserializing)]
|
||||
@@ -97,7 +114,7 @@ macro_rules! declare_tests {
|
||||
}
|
||||
|
||||
macro_rules! declare_error_tests {
|
||||
($($name:ident<$target:ident> { $tokens:expr, $expected:expr, })+) => {
|
||||
($($name:ident<$target:ty> { $tokens:expr, $expected:expr, })+) => {
|
||||
$(
|
||||
#[test]
|
||||
fn $name() {
|
||||
@@ -225,7 +242,7 @@ declare_tests! {
|
||||
],
|
||||
() => &[
|
||||
Token::TupleStructStart("Anything", 0),
|
||||
Token::SeqEnd,
|
||||
Token::TupleStructEnd,
|
||||
],
|
||||
}
|
||||
test_unit_struct {
|
||||
@@ -330,7 +347,7 @@ declare_tests! {
|
||||
],
|
||||
BTreeSet::<isize>::new() => &[
|
||||
Token::TupleStructStart("Anything", 0),
|
||||
Token::SeqEnd,
|
||||
Token::TupleStructEnd,
|
||||
],
|
||||
}
|
||||
test_hashset {
|
||||
@@ -358,7 +375,7 @@ declare_tests! {
|
||||
],
|
||||
HashSet::<isize>::new() => &[
|
||||
Token::TupleStructStart("Anything", 0),
|
||||
Token::SeqEnd,
|
||||
Token::TupleStructEnd,
|
||||
],
|
||||
hashset![FnvHasher @ 1, 2, 3] => &[
|
||||
Token::SeqStart(Some(3)),
|
||||
@@ -408,7 +425,7 @@ declare_tests! {
|
||||
],
|
||||
Vec::<isize>::new() => &[
|
||||
Token::TupleStructStart("Anything", 0),
|
||||
Token::SeqEnd,
|
||||
Token::TupleStructEnd,
|
||||
],
|
||||
}
|
||||
test_array {
|
||||
@@ -472,7 +489,7 @@ declare_tests! {
|
||||
],
|
||||
[0; 0] => &[
|
||||
Token::TupleStructStart("Anything", 0),
|
||||
Token::SeqEnd,
|
||||
Token::TupleStructEnd,
|
||||
],
|
||||
}
|
||||
test_tuple {
|
||||
@@ -564,7 +581,7 @@ declare_tests! {
|
||||
],
|
||||
BTreeMap::<isize, isize>::new() => &[
|
||||
Token::StructStart("Anything", 0),
|
||||
Token::MapEnd,
|
||||
Token::StructEnd,
|
||||
],
|
||||
}
|
||||
test_hashmap {
|
||||
@@ -618,7 +635,7 @@ declare_tests! {
|
||||
],
|
||||
HashMap::<isize, isize>::new() => &[
|
||||
Token::StructStart("Anything", 0),
|
||||
Token::MapEnd,
|
||||
Token::StructEnd,
|
||||
],
|
||||
hashmap![FnvHasher @ 1 => 2, 3 => 4] => &[
|
||||
Token::MapStart(Some(2)),
|
||||
@@ -728,6 +745,23 @@ declare_tests! {
|
||||
Token::StructEnd,
|
||||
],
|
||||
}
|
||||
test_struct_default {
|
||||
StructDefault { a: 50, b: "overwritten".to_string() } => &[
|
||||
Token::StructStart("StructDefault", 1),
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::I32(50),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::String("overwritten".to_string()),
|
||||
Token::StructEnd,
|
||||
],
|
||||
StructDefault { a: 100, b: "default".to_string() } => &[
|
||||
Token::StructStart("StructDefault", 0),
|
||||
Token::StructEnd,
|
||||
],
|
||||
}
|
||||
test_enum_unit {
|
||||
Enum::Unit => &[
|
||||
Token::EnumUnit("Enum", "Unit"),
|
||||
@@ -936,4 +970,22 @@ declare_error_tests! {
|
||||
],
|
||||
Error::Message("invalid value: integer `4`, expected variant index 0 <= i < 4".into()),
|
||||
}
|
||||
test_short_tuple<(u8, u8, u8)> {
|
||||
&[
|
||||
Token::TupleStart(1),
|
||||
Token::TupleSep,
|
||||
Token::U8(1),
|
||||
Token::TupleEnd,
|
||||
],
|
||||
Error::Message("invalid length 1, expected a tuple of size 3".into()),
|
||||
}
|
||||
test_short_array<[u8; 3]> {
|
||||
&[
|
||||
Token::SeqStart(Some(1)),
|
||||
Token::SeqSep,
|
||||
Token::U8(1),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
Error::Message("invalid length 1, expected an array of length 3".into()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,11 +8,15 @@ use self::serde::de::{Deserialize, Deserializer};
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::marker::PhantomData;
|
||||
use std::result::Result as StdResult;
|
||||
|
||||
// Try to trip up the generated code if it fails to use fully qualified paths.
|
||||
#[allow(dead_code)]
|
||||
struct Result;
|
||||
use std::result::Result as StdResult;
|
||||
#[allow(dead_code)]
|
||||
struct Ok;
|
||||
#[allow(dead_code)]
|
||||
struct Err;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -26,6 +30,14 @@ fn test_gen() {
|
||||
}
|
||||
assert::<With<i32>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct WithTogether<T> {
|
||||
t: T,
|
||||
#[serde(with="both_x")]
|
||||
x: X,
|
||||
}
|
||||
assert::<WithTogether<i32>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct WithRef<'a, T: 'a> {
|
||||
#[serde(skip_deserializing)]
|
||||
@@ -303,16 +315,20 @@ trait DeserializeWith: Sized {
|
||||
}
|
||||
|
||||
// Implements neither Serialize nor Deserialize
|
||||
struct X;
|
||||
pub struct X;
|
||||
|
||||
fn ser_x<S: Serializer>(_: &X, _: S) -> StdResult<S::Ok, S::Error> {
|
||||
pub fn ser_x<S: Serializer>(_: &X, _: S) -> StdResult<S::Ok, S::Error> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn de_x<D: Deserializer>(_: D) -> StdResult<X, D::Error> {
|
||||
pub fn de_x<D: Deserializer>(_: D) -> StdResult<X, D::Error> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
mod both_x {
|
||||
pub use super::{ser_x as serialize, de_x as deserialize};
|
||||
}
|
||||
|
||||
impl SerializeWith for X {
|
||||
fn serialize_with<S: Serializer>(_: &Self, _: S) -> StdResult<S::Ok, S::Error> {
|
||||
unimplemented!()
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
extern crate serde_test;
|
||||
use self::serde_test::{
|
||||
Error,
|
||||
Token,
|
||||
assert_tokens,
|
||||
assert_ser_tokens,
|
||||
assert_de_tokens,
|
||||
assert_de_tokens_error,
|
||||
};
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
// That tests that the derived Serialize implementation doesn't trigger
|
||||
@@ -625,3 +628,444 @@ fn test_enum_state_field() {
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_untagged_enum() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Untagged {
|
||||
A {
|
||||
a: u8,
|
||||
},
|
||||
B {
|
||||
b: u8,
|
||||
},
|
||||
C,
|
||||
D(u8),
|
||||
E(String),
|
||||
F(u8, u8),
|
||||
}
|
||||
|
||||
assert_tokens(
|
||||
&Untagged::A { a: 1 },
|
||||
&[
|
||||
Token::StructStart("Untagged", 1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::U8(1),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&Untagged::B { b: 2 },
|
||||
&[
|
||||
Token::StructStart("Untagged", 1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::U8(2),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&Untagged::C,
|
||||
&[
|
||||
Token::Unit,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&Untagged::D(4),
|
||||
&[
|
||||
Token::U8(4),
|
||||
]
|
||||
);
|
||||
assert_tokens(
|
||||
&Untagged::E("e".to_owned()),
|
||||
&[
|
||||
Token::Str("e"),
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&Untagged::F(1, 2),
|
||||
&[
|
||||
Token::TupleStart(2),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::U8(1),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::U8(2),
|
||||
|
||||
Token::TupleEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<Untagged>(
|
||||
&[
|
||||
Token::Option(false),
|
||||
],
|
||||
Error::Message("data did not match any variant of untagged enum Untagged".to_owned()),
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<Untagged>(
|
||||
&[
|
||||
Token::TupleStart(1),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::U8(1),
|
||||
|
||||
Token::TupleEnd,
|
||||
],
|
||||
Error::Message("data did not match any variant of untagged enum Untagged".to_owned()),
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<Untagged>(
|
||||
&[
|
||||
Token::TupleStart(3),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::U8(1),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::U8(2),
|
||||
|
||||
Token::TupleSep,
|
||||
Token::U8(3),
|
||||
|
||||
Token::TupleEnd,
|
||||
],
|
||||
Error::Message("data did not match any variant of untagged enum Untagged".to_owned()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_internally_tagged_enum() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Newtype(BTreeMap<String, String>);
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Struct {
|
||||
f: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type")]
|
||||
enum InternallyTagged {
|
||||
A {
|
||||
a: u8,
|
||||
},
|
||||
B {
|
||||
b: u8,
|
||||
},
|
||||
C,
|
||||
D(BTreeMap<String, String>),
|
||||
E(Newtype),
|
||||
F(Struct),
|
||||
}
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::A { a: 1 },
|
||||
&[
|
||||
Token::StructStart("InternallyTagged", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("type"),
|
||||
Token::Str("A"),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("a"),
|
||||
Token::U8(1),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::B { b: 2 },
|
||||
&[
|
||||
Token::StructStart("InternallyTagged", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("type"),
|
||||
Token::Str("B"),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("b"),
|
||||
Token::U8(2),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::C,
|
||||
&[
|
||||
Token::StructStart("InternallyTagged", 1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("type"),
|
||||
Token::Str("C"),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::D(BTreeMap::new()),
|
||||
&[
|
||||
Token::MapStart(Some(1)),
|
||||
|
||||
Token::MapSep,
|
||||
Token::Str("type"),
|
||||
Token::Str("D"),
|
||||
|
||||
Token::MapEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::E(Newtype(BTreeMap::new())),
|
||||
&[
|
||||
Token::MapStart(Some(1)),
|
||||
|
||||
Token::MapSep,
|
||||
Token::Str("type"),
|
||||
Token::Str("E"),
|
||||
|
||||
Token::MapEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::F(Struct { f: 6 }),
|
||||
&[
|
||||
Token::StructStart("Struct", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("type"),
|
||||
Token::Str("F"),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("f"),
|
||||
Token::U8(6),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<InternallyTagged>(
|
||||
&[
|
||||
Token::MapStart(Some(0)),
|
||||
Token::MapEnd,
|
||||
],
|
||||
Error::Message("missing field `type`".to_owned()),
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<InternallyTagged>(
|
||||
&[
|
||||
Token::MapStart(Some(1)),
|
||||
|
||||
Token::MapSep,
|
||||
Token::Str("type"),
|
||||
Token::Str("Z"),
|
||||
|
||||
Token::MapEnd,
|
||||
],
|
||||
Error::Message("unknown variant `Z`, expected one of `A`, `B`, `C`, `D`, `E`, `F`".to_owned()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_adjacently_tagged_enum() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "t", content = "c")]
|
||||
enum AdjacentlyTagged<T> {
|
||||
Unit,
|
||||
Newtype(T),
|
||||
Tuple(u8, u8),
|
||||
Struct { f: u8 },
|
||||
}
|
||||
|
||||
// unit with no content
|
||||
assert_tokens(
|
||||
&AdjacentlyTagged::Unit::<u8>,
|
||||
&[
|
||||
Token::StructStart("AdjacentlyTagged", 1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
// unit with tag first
|
||||
assert_de_tokens(
|
||||
&AdjacentlyTagged::Unit::<u8>,
|
||||
&[
|
||||
Token::StructStart("AdjacentlyTagged", 1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("c"),
|
||||
Token::Unit,
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
// unit with content first
|
||||
assert_de_tokens(
|
||||
&AdjacentlyTagged::Unit::<u8>,
|
||||
&[
|
||||
Token::StructStart("AdjacentlyTagged", 1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("c"),
|
||||
Token::Unit,
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
// newtype with tag first
|
||||
assert_tokens(
|
||||
&AdjacentlyTagged::Newtype::<u8>(1),
|
||||
&[
|
||||
Token::StructStart("AdjacentlyTagged", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("t"),
|
||||
Token::Str("Newtype"),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("c"),
|
||||
Token::U8(1),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
// newtype with content first
|
||||
assert_de_tokens(
|
||||
&AdjacentlyTagged::Newtype::<u8>(1),
|
||||
&[
|
||||
Token::StructStart("AdjacentlyTagged", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("c"),
|
||||
Token::U8(1),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("t"),
|
||||
Token::Str("Newtype"),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
// tuple with tag first
|
||||
assert_tokens(
|
||||
&AdjacentlyTagged::Tuple::<u8>(1, 1),
|
||||
&[
|
||||
Token::StructStart("AdjacentlyTagged", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("t"),
|
||||
Token::Str("Tuple"),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("c"),
|
||||
Token::TupleStart(2),
|
||||
Token::TupleSep,
|
||||
Token::U8(1),
|
||||
Token::TupleSep,
|
||||
Token::U8(1),
|
||||
Token::TupleEnd,
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
// tuple with content first
|
||||
assert_de_tokens(
|
||||
&AdjacentlyTagged::Tuple::<u8>(1, 1),
|
||||
&[
|
||||
Token::StructStart("AdjacentlyTagged", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("c"),
|
||||
Token::TupleStart(2),
|
||||
Token::TupleSep,
|
||||
Token::U8(1),
|
||||
Token::TupleSep,
|
||||
Token::U8(1),
|
||||
Token::TupleEnd,
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("t"),
|
||||
Token::Str("Tuple"),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
// struct with tag first
|
||||
assert_tokens(
|
||||
&AdjacentlyTagged::Struct::<u8> { f: 1 },
|
||||
&[
|
||||
Token::StructStart("AdjacentlyTagged", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("t"),
|
||||
Token::Str("Struct"),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("c"),
|
||||
Token::StructStart("Struct", 1),
|
||||
Token::StructSep,
|
||||
Token::Str("f"),
|
||||
Token::U8(1),
|
||||
Token::StructEnd,
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
|
||||
// struct with content first
|
||||
assert_de_tokens(
|
||||
&AdjacentlyTagged::Struct::<u8> { f: 1 },
|
||||
&[
|
||||
Token::StructStart("AdjacentlyTagged", 2),
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("c"),
|
||||
Token::StructStart("Struct", 1),
|
||||
Token::StructSep,
|
||||
Token::Str("f"),
|
||||
Token::U8(1),
|
||||
Token::StructEnd,
|
||||
|
||||
Token::StructSep,
|
||||
Token::Str("t"),
|
||||
Token::Str("Struct"),
|
||||
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
channel() {
|
||||
if [ -n "${TRAVIS}" ]; then
|
||||
if [ "${TRAVIS_RUST_VERSION}" = "${CHANNEL}" ]; then
|
||||
pwd
|
||||
(set -x; cargo "$@")
|
||||
fi
|
||||
else
|
||||
pwd
|
||||
(set -x; cargo "+${CHANNEL}" "$@")
|
||||
fi
|
||||
}
|
||||
|
||||
if [ -n "${CLIPPY}" ]; then
|
||||
# cached installation will not work on a later nightly
|
||||
if [ -n "${TRAVIS}" ] && ! cargo install clippy --debug --force; then
|
||||
echo "COULD NOT COMPILE CLIPPY, IGNORING CLIPPY TESTS"
|
||||
exit
|
||||
fi
|
||||
|
||||
cd "$DIR/serde"
|
||||
cargo clippy --features unstable-testing -- -Dclippy
|
||||
|
||||
cd "$DIR/serde_derive"
|
||||
cargo clippy --features unstable-testing -- -Dclippy
|
||||
|
||||
cd "$DIR/test_suite"
|
||||
cargo clippy --features unstable-testing -- -Dclippy
|
||||
|
||||
cd "$DIR/test_suite/no_std"
|
||||
cargo clippy -- -Dclippy
|
||||
else
|
||||
CHANNEL=nightly
|
||||
cargo clean
|
||||
cd "$DIR/serde"
|
||||
channel build
|
||||
channel build --no-default-features
|
||||
channel build --no-default-features --features alloc
|
||||
channel build --no-default-features --features collections
|
||||
channel test --features unstable-testing
|
||||
cd "$DIR/test_suite/deps"
|
||||
channel build
|
||||
cd "$DIR/test_suite"
|
||||
channel test --features unstable-testing
|
||||
cd "$DIR/test_suite/no_std"
|
||||
channel build
|
||||
|
||||
CHANNEL=beta
|
||||
cargo clean
|
||||
cd "$DIR/serde"
|
||||
channel build
|
||||
cd "$DIR/test_suite"
|
||||
channel test
|
||||
|
||||
CHANNEL=stable
|
||||
cargo clean
|
||||
cd "$DIR/serde"
|
||||
channel build
|
||||
channel build --no-default-features
|
||||
|
||||
CHANNEL=1.13.0
|
||||
cargo clean
|
||||
cd "$DIR/serde"
|
||||
channel build
|
||||
channel build --no-default-features
|
||||
fi
|
||||
Reference in New Issue
Block a user