mirror of
https://github.com/pezkuwichain/serde.git
synced 2026-04-23 08:18:03 +00:00
Compare commits
159 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1f65ce75ec | |||
| 9536e52aa6 | |||
| 9e45bd8c87 | |||
| e461a23798 | |||
| 894a21bc1f | |||
| 1ecf3730ee | |||
| b6e8b58cb2 | |||
| a3f556959f | |||
| 9338c4f1b9 | |||
| 28d67f4172 | |||
| 2401ae61a8 | |||
| 57d3fce0c6 | |||
| a020cceed8 | |||
| 49e985eb90 | |||
| 63def96c66 | |||
| 2fea8c9c28 | |||
| b7ea213926 | |||
| 871fb5adee | |||
| 2c984980a0 | |||
| 36f07912b8 | |||
| 7222cf7514 | |||
| 08c59a2e0e | |||
| 4a0bf4de65 | |||
| 95ffca9bbe | |||
| 5e47c87ba0 | |||
| c6d5d9be14 | |||
| d63d09f4db | |||
| de6d00c306 | |||
| 5bda95ba81 | |||
| 36641e7b81 | |||
| 6eca34c45c | |||
| 7efa0153b0 | |||
| 8dba87661b | |||
| 17fb4cb503 | |||
| 5bd0386b8e | |||
| 8b484c9703 | |||
| a16f07858b | |||
| 133d117bf4 | |||
| e7f3a80867 | |||
| f8c3d225a3 | |||
| 6d40d9e8ec | |||
| c91fca19e1 | |||
| f13a805530 | |||
| 54802983b8 | |||
| f430d9d1c8 | |||
| c9612a2f57 | |||
| 7ffea5a716 | |||
| c8c9f7d96c | |||
| f75d286b90 | |||
| 9acb17ab54 | |||
| f15ff1868e | |||
| 86f0d0382f | |||
| 8595b25763 | |||
| 49aca521f1 | |||
| 4c38bd0180 | |||
| 02c4ff7b7e | |||
| a8d1c0253a | |||
| bb5370b746 | |||
| 536e78a146 | |||
| 21c9446890 | |||
| 1b42f3f594 | |||
| cafa02d9b4 | |||
| a9b6cbb8b3 | |||
| 1d719b542c | |||
| 532b950971 | |||
| f93b4e91e6 | |||
| 94e2ccc94e | |||
| cbe6b4c97c | |||
| a46a4e27dd | |||
| 4919a3184d | |||
| 0b19608d85 | |||
| 99bddddd8e | |||
| 85c95040b3 | |||
| 339c0f5493 | |||
| b4d5c26f4e | |||
| f4e1ffa2cb | |||
| ef5d09e144 | |||
| e547a06639 | |||
| c61b20cceb | |||
| 42987a5b24 | |||
| 3f28a93240 | |||
| 9970084550 | |||
| 3920993370 | |||
| 22690cedc2 | |||
| b27039d34d | |||
| 1b6fd5a362 | |||
| 8b7b886036 | |||
| 2a2c098eeb | |||
| f68f32d3ee | |||
| 6ccb6c9130 | |||
| 49d24a1377 | |||
| b0eee50947 | |||
| 554b81d636 | |||
| 9fe16767c5 | |||
| 3a3777a2fb | |||
| effa298871 | |||
| 9a86e6818f | |||
| 7d09b1475c | |||
| 7e441e5110 | |||
| 40b874214a | |||
| 0c18c151e2 | |||
| 4ad6c4fd56 | |||
| 8ee8c07090 | |||
| 8e77960e3a | |||
| 819d47fea2 | |||
| 8e865f62c4 | |||
| 6cbf0d32da | |||
| 20afa85087 | |||
| da6d967776 | |||
| f47a50e996 | |||
| 1eca7766ba | |||
| 51f95575ec | |||
| 429de89276 | |||
| a69b82c7c5 | |||
| 55e5f19437 | |||
| c34baa1e5f | |||
| 7cc36a9cd3 | |||
| d343017f47 | |||
| 2212bfbf2c | |||
| e85ca8411e | |||
| 1ff2053262 | |||
| bf779ea343 | |||
| 8fe66c7f2a | |||
| e03dedabe4 | |||
| 08bc2d2e76 | |||
| 35be61d85f | |||
| 3692edfd08 | |||
| 5a258ade27 | |||
| f3052c392e | |||
| d1ce4d62c9 | |||
| 869ebd9e4e | |||
| 14446af537 | |||
| 248d937f9a | |||
| ffa2f80186 | |||
| ac1128a647 | |||
| 88d845c4d1 | |||
| 87a402a751 | |||
| cdb0e6c899 | |||
| 54cee86fd3 | |||
| 178edd1abc | |||
| 4bb9279074 | |||
| 3c45e5c7a5 | |||
| d36f28971c | |||
| d914fdf67b | |||
| 7014c105b4 | |||
| f3d566af09 | |||
| 278e8eb720 | |||
| e9b04de9a5 | |||
| 2a2891d54b | |||
| 123e040189 | |||
| 6f0f273d9c | |||
| fb7ba225d1 | |||
| d690ffda8d | |||
| 18a775277f | |||
| fbb250766d | |||
| 71116b860a | |||
| ce3f134145 | |||
| 80507d650c | |||
| 0ae61a3dd1 |
+4
-12
@@ -1,17 +1,11 @@
|
||||
sudo: false
|
||||
language: rust
|
||||
rust:
|
||||
- 1.12.0
|
||||
- 1.13.0
|
||||
- stable
|
||||
- nightly
|
||||
- 1.8.0
|
||||
- 1.9.0
|
||||
- beta
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- libcurl4-openssl-dev
|
||||
- libelf-dev
|
||||
- libdw-dev
|
||||
- nightly
|
||||
before_script:
|
||||
- pip install 'travis-cargo<0.2' --user
|
||||
- export PATH=$HOME/.local/bin:$PATH
|
||||
@@ -24,12 +18,10 @@ script:
|
||||
- (cd serde && travis-cargo --only nightly build -- --no-default-features --features collections)
|
||||
- (cd testing && travis-cargo --skip nightly test)
|
||||
- (cd testing && travis-cargo --only nightly test -- --features unstable-testing)
|
||||
- (cd serde_macros && travis-cargo --only nightly test -- --features unstable-testing)
|
||||
- (cd serde_derive && travis-cargo --only nightly test)
|
||||
- (cd examples/serde-syntex-example && travis-cargo --skip nightly run)
|
||||
- (cd examples/serde-syntex-example && travis-cargo --only nightly run -- --no-default-features --features unstable)
|
||||
- (cd serde && travis-cargo --only stable doc)
|
||||
after_success:
|
||||
- (cd testing && travis-cargo --only stable coveralls --no-sudo)
|
||||
env:
|
||||
global:
|
||||
- TRAVIS_CARGO_NIGHTLY_FEATURE=""
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Serde   [](https://travis-ci.org/serde-rs/serde) [](https://coveralls.io/github/serde-rs/serde?branch=master) [](https://crates.io/crates/serde) [](https://clippy.bashy.io/github/serde-rs/serde/master/log)
|
||||
# Serde   [](https://travis-ci.org/serde-rs/serde) [](https://crates.io/crates/serde)
|
||||
|
||||
**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.**
|
||||
|
||||
@@ -11,12 +11,13 @@ You may be looking for:
|
||||
- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html)
|
||||
- [Examples](https://serde.rs/examples.html)
|
||||
- [API documentation](https://docs.serde.rs/serde/)
|
||||
- [Release notes](https://github.com/serde-rs/serde/releases)
|
||||
|
||||
## Serde in action
|
||||
|
||||
```rust
|
||||
#![feature(plugin, custom_derive)]
|
||||
#![plugin(serde_macros)]
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
extern crate serde_json;
|
||||
|
||||
|
||||
@@ -3,15 +3,16 @@ name = "serde-syntex-example"
|
||||
version = "0.1.0"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
build = "build.rs"
|
||||
publish = false
|
||||
|
||||
[features]
|
||||
default = ["serde_codegen"]
|
||||
unstable = ["serde_macros"]
|
||||
unstable = ["serde_derive"]
|
||||
|
||||
[build-dependencies]
|
||||
serde_codegen = { version = "^0.8", optional = true, path = "../../serde_codegen" }
|
||||
|
||||
[dependencies]
|
||||
serde = "^0.8"
|
||||
serde_derive = { version = "^0.8", optional = true, path = "../../serde_derive" }
|
||||
serde_json = "^0.8"
|
||||
serde_macros = { version = "^0.8", optional = true, path = "../../serde_macros" }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#[cfg(not(feature = "serde_macros"))]
|
||||
#[cfg(not(feature = "serde_derive"))]
|
||||
mod inner {
|
||||
extern crate serde_codegen;
|
||||
|
||||
@@ -15,7 +15,7 @@ mod inner {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde_macros")]
|
||||
#[cfg(feature = "serde_derive")]
|
||||
mod inner {
|
||||
pub fn main() {}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#![cfg_attr(feature = "serde_macros", feature(custom_derive, plugin))]
|
||||
#![cfg_attr(feature = "serde_macros", plugin(serde_macros))]
|
||||
#![cfg_attr(feature = "serde_derive", feature(proc_macro))]
|
||||
|
||||
#[cfg(feature = "serde_derive")]
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
extern crate serde;
|
||||
extern crate serde_json;
|
||||
|
||||
#[cfg(feature = "serde_macros")]
|
||||
#[cfg(feature = "serde_derive")]
|
||||
include!("main.rs.in");
|
||||
|
||||
#[cfg(not(feature = "serde_macros"))]
|
||||
#[cfg(not(feature = "serde_derive"))]
|
||||
include!(concat!(env!("OUT_DIR"), "/main.rs"));
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde"
|
||||
version = "0.8.3"
|
||||
version = "0.8.23"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "A generic serialization/deserialization framework"
|
||||
@@ -9,6 +9,7 @@ repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://docs.serde.rs/serde/"
|
||||
readme = "../README.md"
|
||||
keywords = ["serde", "serialization"]
|
||||
categories = ["encoding"]
|
||||
include = ["Cargo.toml", "src/**/*.rs"]
|
||||
|
||||
[features]
|
||||
|
||||
+36
-24
@@ -19,6 +19,15 @@ pub struct Bytes<'a> {
|
||||
bytes: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> Bytes<'a> {
|
||||
/// Wrap an existing `&[u8]`.
|
||||
pub fn new(bytes: &'a [u8]) -> Self {
|
||||
Bytes {
|
||||
bytes: bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> fmt::Debug for Bytes<'a> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
try!(f.write_str("b\""));
|
||||
@@ -31,18 +40,14 @@ impl<'a> fmt::Debug for Bytes<'a> {
|
||||
|
||||
impl<'a> From<&'a [u8]> for Bytes<'a> {
|
||||
fn from(bytes: &'a [u8]) -> Self {
|
||||
Bytes {
|
||||
bytes: bytes,
|
||||
}
|
||||
Bytes::new(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'a> From<&'a Vec<u8>> for Bytes<'a> {
|
||||
fn from(bytes: &'a Vec<u8>) -> Self {
|
||||
Bytes {
|
||||
bytes: bytes,
|
||||
}
|
||||
Bytes::new(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +84,7 @@ mod bytebuf {
|
||||
use de;
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
use collections::Vec;
|
||||
use collections::{String, Vec};
|
||||
|
||||
/// `ByteBuf` wraps a `Vec<u8>` and serializes as a byte array.
|
||||
#[derive(Clone, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
|
||||
@@ -90,15 +95,18 @@ mod bytebuf {
|
||||
impl ByteBuf {
|
||||
/// Construct a new, empty `ByteBuf`.
|
||||
pub fn new() -> Self {
|
||||
ByteBuf {
|
||||
bytes: Vec::new(),
|
||||
}
|
||||
ByteBuf::from(Vec::new())
|
||||
}
|
||||
|
||||
/// Construct a new, empty `ByteBuf` with the specified capacity.
|
||||
pub fn with_capacity(cap: usize) -> Self {
|
||||
ByteBuf::from(Vec::with_capacity(cap))
|
||||
}
|
||||
|
||||
/// Wrap existing bytes in a `ByteBuf`.
|
||||
pub fn from<T: Into<Vec<u8>>>(bytes: T) -> Self {
|
||||
ByteBuf {
|
||||
bytes: Vec::with_capacity(cap)
|
||||
bytes: bytes.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -121,9 +129,7 @@ mod bytebuf {
|
||||
|
||||
impl From<Vec<u8>> for ByteBuf {
|
||||
fn from(bytes: Vec<u8>) -> Self {
|
||||
ByteBuf {
|
||||
bytes: bytes,
|
||||
}
|
||||
ByteBuf::from(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,9 +185,7 @@ mod bytebuf {
|
||||
fn visit_unit<E>(&mut self) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
{
|
||||
Ok(ByteBuf {
|
||||
bytes: Vec::new(),
|
||||
})
|
||||
Ok(ByteBuf::new())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -197,25 +201,33 @@ mod bytebuf {
|
||||
|
||||
try!(visitor.end());
|
||||
|
||||
Ok(ByteBuf {
|
||||
bytes: values,
|
||||
})
|
||||
Ok(ByteBuf::from(values))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_bytes<E>(&mut self, v: &[u8]) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
{
|
||||
self.visit_byte_buf(v.to_vec())
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn visit_byte_buf<E>(&mut self, v: Vec<u8>) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
{
|
||||
Ok(ByteBuf {
|
||||
bytes: v,
|
||||
})
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
|
||||
fn visit_str<E>(&mut self, v: &str) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
{
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
|
||||
fn visit_string<E>(&mut self, v: String) -> Result<ByteBuf, E>
|
||||
where E: de::Error,
|
||||
{
|
||||
Ok(ByteBuf::from(v))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+76
-99
@@ -283,6 +283,12 @@ impl Visitor for StringVisitor {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn visit_unit<E>(&mut self) -> Result<String, E>
|
||||
where E: Error,
|
||||
{
|
||||
Ok(String::new())
|
||||
}
|
||||
|
||||
fn visit_bytes<E>(&mut self, v: &[u8]) -> Result<String, E>
|
||||
where E: Error,
|
||||
{
|
||||
@@ -512,27 +518,26 @@ seq_impl!(
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct ArrayVisitor0<T> {
|
||||
marker: PhantomData<T>,
|
||||
struct ArrayVisitor<A> {
|
||||
marker: PhantomData<A>,
|
||||
}
|
||||
|
||||
impl<T> ArrayVisitor0<T> {
|
||||
/// Construct a `ArrayVisitor0<T>`.
|
||||
impl<A> ArrayVisitor<A> {
|
||||
pub fn new() -> Self {
|
||||
ArrayVisitor0 {
|
||||
ArrayVisitor {
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Visitor for ArrayVisitor0<T> where T: Deserialize + Default {
|
||||
impl<T> Visitor for ArrayVisitor<[T; 0]> where T: Deserialize {
|
||||
type Value = [T; 0];
|
||||
|
||||
#[inline]
|
||||
fn visit_unit<E>(&mut self) -> Result<[T; 0], E>
|
||||
where E: Error,
|
||||
{
|
||||
Ok([T::default(); 0])
|
||||
Ok([])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -540,37 +545,24 @@ impl<T> Visitor for ArrayVisitor0<T> where T: Deserialize + Default {
|
||||
where V: SeqVisitor,
|
||||
{
|
||||
try!(visitor.end());
|
||||
Ok([T::default(); 0])
|
||||
Ok([])
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deserialize for [T; 0]
|
||||
where T: Deserialize + Default
|
||||
where T: Deserialize
|
||||
{
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<[T; 0], D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.deserialize_seq(ArrayVisitor0::new())
|
||||
deserializer.deserialize_seq_fixed_size(0, ArrayVisitor::<[T; 0]>::new())
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! array_impls {
|
||||
($($visitor:ident, $len:expr => ($($name:ident),+),)+) => {
|
||||
($($len:expr => ($($name:ident)+))+) => {
|
||||
$(
|
||||
struct $visitor<T> {
|
||||
marker: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> $visitor<T> {
|
||||
/// Construct a `ArrayVisitor*<T>`.
|
||||
pub fn new() -> Self {
|
||||
$visitor {
|
||||
marker: PhantomData
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Visitor for $visitor<T> where T: Deserialize {
|
||||
impl<T> Visitor for ArrayVisitor<[T; $len]> where T: Deserialize {
|
||||
type Value = [T; $len];
|
||||
|
||||
#[inline]
|
||||
@@ -580,13 +572,13 @@ macro_rules! array_impls {
|
||||
$(
|
||||
let $name = match try!(visitor.visit()) {
|
||||
Some(val) => val,
|
||||
None => { return Err(Error::end_of_stream()); }
|
||||
None => return Err(Error::end_of_stream()),
|
||||
};
|
||||
)+;
|
||||
)+
|
||||
|
||||
try!(visitor.end());
|
||||
|
||||
Ok([$($name,)+])
|
||||
Ok([$($name),+])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -596,7 +588,7 @@ macro_rules! array_impls {
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<[T; $len], D::Error>
|
||||
where D: Deserializer,
|
||||
{
|
||||
deserializer.deserialize_seq_fixed_size($len, $visitor::new())
|
||||
deserializer.deserialize_seq_fixed_size($len, ArrayVisitor::<[T; $len]>::new())
|
||||
}
|
||||
}
|
||||
)+
|
||||
@@ -604,71 +596,58 @@ macro_rules! array_impls {
|
||||
}
|
||||
|
||||
array_impls! {
|
||||
ArrayVisitor1, 1 => (a),
|
||||
ArrayVisitor2, 2 => (a, b),
|
||||
ArrayVisitor3, 3 => (a, b, c),
|
||||
ArrayVisitor4, 4 => (a, b, c, d),
|
||||
ArrayVisitor5, 5 => (a, b, c, d, e),
|
||||
ArrayVisitor6, 6 => (a, b, c, d, e, f),
|
||||
ArrayVisitor7, 7 => (a, b, c, d, e, f, g),
|
||||
ArrayVisitor8, 8 => (a, b, c, d, e, f, g, h),
|
||||
ArrayVisitor9, 9 => (a, b, c, d, e, f, g, h, i),
|
||||
ArrayVisitor10, 10 => (a, b, c, d, e, f, g, h, i, j),
|
||||
ArrayVisitor11, 11 => (a, b, c, d, e, f, g, h, i, j, k),
|
||||
ArrayVisitor12, 12 => (a, b, c, d, e, f, g, h, i, j, k, l),
|
||||
ArrayVisitor13, 13 => (a, b, c, d, e, f, g, h, i, j, k, l, m),
|
||||
ArrayVisitor14, 14 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n),
|
||||
ArrayVisitor15, 15 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o),
|
||||
ArrayVisitor16, 16 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p),
|
||||
ArrayVisitor17, 17 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q),
|
||||
ArrayVisitor18, 18 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r),
|
||||
ArrayVisitor19, 19 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s),
|
||||
ArrayVisitor20, 20 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s ,t),
|
||||
ArrayVisitor21, 21 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u),
|
||||
ArrayVisitor22, 22 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v),
|
||||
ArrayVisitor23, 23 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w),
|
||||
ArrayVisitor24, 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),
|
||||
ArrayVisitor25, 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),
|
||||
ArrayVisitor26, 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),
|
||||
ArrayVisitor27, 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),
|
||||
ArrayVisitor28, 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),
|
||||
ArrayVisitor29, 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),
|
||||
ArrayVisitor30, 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),
|
||||
ArrayVisitor31, 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),
|
||||
ArrayVisitor32, 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 => (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)
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! tuple_impls {
|
||||
($($len:expr => $visitor:ident => ($($name:ident),+),)+) => {
|
||||
($($len:expr => $visitor:ident => ($($name:ident)+))+) => {
|
||||
$(
|
||||
/// Construct a tuple visitor.
|
||||
pub struct $visitor<$($name,)+> {
|
||||
marker: PhantomData<($($name,)+)>,
|
||||
}
|
||||
|
||||
impl<
|
||||
$($name: Deserialize,)+
|
||||
> $visitor<$($name,)+> {
|
||||
impl<$($name: Deserialize,)+> $visitor<$($name,)+> {
|
||||
/// Construct a `TupleVisitor*<T>`.
|
||||
pub fn new() -> Self {
|
||||
$visitor { marker: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl<
|
||||
$($name: Deserialize,)+
|
||||
> Visitor for $visitor<$($name,)+> {
|
||||
impl<$($name: Deserialize),+> Visitor for $visitor<$($name,)+> {
|
||||
type Value = ($($name,)+);
|
||||
|
||||
#[inline]
|
||||
@@ -679,9 +658,9 @@ macro_rules! tuple_impls {
|
||||
$(
|
||||
let $name = match try!(visitor.visit()) {
|
||||
Some(value) => value,
|
||||
None => { return Err(Error::end_of_stream()); }
|
||||
None => return Err(Error::end_of_stream()),
|
||||
};
|
||||
)+;
|
||||
)+
|
||||
|
||||
try!(visitor.end());
|
||||
|
||||
@@ -689,9 +668,7 @@ macro_rules! tuple_impls {
|
||||
}
|
||||
}
|
||||
|
||||
impl<
|
||||
$($name: Deserialize),+
|
||||
> Deserialize for ($($name,)+) {
|
||||
impl<$($name: Deserialize),+> Deserialize for ($($name,)+) {
|
||||
#[inline]
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<($($name,)+), D::Error>
|
||||
where D: Deserializer,
|
||||
@@ -704,22 +681,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 => (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)
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
@@ -809,7 +786,7 @@ map_impl!(
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(all(feature = "unstable", feature = "std"))]
|
||||
#[cfg(feature = "std")]
|
||||
impl Deserialize for net::IpAddr {
|
||||
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
|
||||
where D: Deserializer,
|
||||
|
||||
@@ -11,71 +11,6 @@ use collections::{String, Vec};
|
||||
use core::fmt;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
/// Macro helper to not have to re-implement all the defaulted methods.
|
||||
/// Every given method ignores all arguments and forwards to `deserialize`.
|
||||
/// Note that `deserialize_enum` simply returns an `Error::invalid_type`.
|
||||
macro_rules! de_forward_to_deserialize {
|
||||
($($func:ident),*) => {
|
||||
$(de_forward_to_deserialize!{func: $func})*
|
||||
};
|
||||
(func: deserialize_unit_struct) => {
|
||||
de_forward_to_deserialize!{named: deserialize_unit_struct}
|
||||
};
|
||||
(func: deserialize_newtype_struct) => {
|
||||
de_forward_to_deserialize!{named: deserialize_newtype_struct}
|
||||
};
|
||||
(func: deserialize_tuple) => {
|
||||
de_forward_to_deserialize!{tup_fn: deserialize_tuple}
|
||||
};
|
||||
(func: deserialize_seq_fixed_size) => {
|
||||
de_forward_to_deserialize!{tup_fn: deserialize_seq_fixed_size}
|
||||
};
|
||||
(func: deserialize_tuple_struct) => {
|
||||
#[inline]
|
||||
fn deserialize_tuple_struct<__V>(&mut self, _: &str, _: usize, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: $crate::de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
};
|
||||
(func: deserialize_struct) => {
|
||||
#[inline]
|
||||
fn deserialize_struct<__V>(&mut self, _: &str, _: &[&str], visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: $crate::de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
};
|
||||
(func: deserialize_enum) => {
|
||||
#[inline]
|
||||
fn deserialize_enum<__V>(&mut self, _: &str, _: &[&str], _: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: $crate::de::EnumVisitor {
|
||||
Err($crate::de::Error::invalid_type($crate::de::Type::Enum))
|
||||
}
|
||||
};
|
||||
(named: $func:ident) => {
|
||||
#[inline]
|
||||
fn $func<__V>(&mut self, _: &str, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: $crate::de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
};
|
||||
(tup_fn: $func: ident) => {
|
||||
#[inline]
|
||||
fn $func<__V>(&mut self, _: usize, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: $crate::de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
};
|
||||
(func: $func:ident) => {
|
||||
#[inline]
|
||||
fn $func<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: $crate::de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// modules come after macros
|
||||
|
||||
pub mod impls;
|
||||
pub mod value;
|
||||
|
||||
+298
-159
@@ -12,6 +12,8 @@ use std::collections::{
|
||||
hash_set,
|
||||
};
|
||||
#[cfg(feature = "std")]
|
||||
use std::borrow::Cow;
|
||||
#[cfg(feature = "std")]
|
||||
use std::vec;
|
||||
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
@@ -24,6 +26,8 @@ use collections::{
|
||||
btree_set,
|
||||
vec,
|
||||
};
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
use collections::borrow::Cow;
|
||||
|
||||
#[cfg(all(feature = "unstable", feature = "collections"))]
|
||||
use collections::borrow::ToOwned;
|
||||
@@ -174,20 +178,10 @@ impl<E> de::Deserializer for UnitDeserializer<E>
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
de_forward_to_deserialize!{
|
||||
deserialize_bool,
|
||||
deserialize_f64, deserialize_f32,
|
||||
deserialize_u8, deserialize_u16, deserialize_u32, deserialize_u64, deserialize_usize,
|
||||
deserialize_i8, deserialize_i16, deserialize_i32, deserialize_i64, deserialize_isize,
|
||||
deserialize_char, deserialize_str, deserialize_string,
|
||||
deserialize_ignored_any,
|
||||
deserialize_bytes,
|
||||
deserialize_unit_struct, deserialize_unit,
|
||||
deserialize_seq, deserialize_seq_fixed_size,
|
||||
deserialize_map, deserialize_newtype_struct, deserialize_struct_field,
|
||||
deserialize_tuple,
|
||||
deserialize_enum,
|
||||
deserialize_struct, deserialize_tuple_struct
|
||||
forward_to_deserialize! {
|
||||
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
|
||||
unit seq seq_fixed_size bytes map unit_struct newtype_struct
|
||||
tuple_struct struct struct_field tuple enum ignored_any
|
||||
}
|
||||
|
||||
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
|
||||
@@ -225,21 +219,11 @@ macro_rules! primitive_deserializer {
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
de_forward_to_deserialize!{
|
||||
deserialize_bool,
|
||||
deserialize_f64, deserialize_f32,
|
||||
deserialize_u8, deserialize_u16, deserialize_u32, deserialize_u64, deserialize_usize,
|
||||
deserialize_i8, deserialize_i16, deserialize_i32, deserialize_i64, deserialize_isize,
|
||||
deserialize_char, deserialize_str, deserialize_string,
|
||||
deserialize_ignored_any,
|
||||
deserialize_bytes,
|
||||
deserialize_unit_struct, deserialize_unit,
|
||||
deserialize_seq, deserialize_seq_fixed_size,
|
||||
deserialize_map, deserialize_newtype_struct, deserialize_struct_field,
|
||||
deserialize_tuple,
|
||||
deserialize_enum,
|
||||
deserialize_struct, deserialize_tuple_struct,
|
||||
deserialize_option
|
||||
forward_to_deserialize! {
|
||||
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str
|
||||
string unit option seq seq_fixed_size bytes map unit_struct
|
||||
newtype_struct tuple_struct struct struct_field tuple enum
|
||||
ignored_any
|
||||
}
|
||||
|
||||
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
|
||||
@@ -307,20 +291,10 @@ impl<'a, E> de::Deserializer for StrDeserializer<'a, E>
|
||||
visitor.visit(self)
|
||||
}
|
||||
|
||||
de_forward_to_deserialize!{
|
||||
deserialize_bool,
|
||||
deserialize_f64, deserialize_f32,
|
||||
deserialize_u8, deserialize_u16, deserialize_u32, deserialize_u64, deserialize_usize,
|
||||
deserialize_i8, deserialize_i16, deserialize_i32, deserialize_i64, deserialize_isize,
|
||||
deserialize_char, deserialize_str, deserialize_string,
|
||||
deserialize_ignored_any,
|
||||
deserialize_bytes,
|
||||
deserialize_unit_struct, deserialize_unit,
|
||||
deserialize_seq, deserialize_seq_fixed_size,
|
||||
deserialize_map, deserialize_newtype_struct, deserialize_struct_field,
|
||||
deserialize_tuple,
|
||||
deserialize_struct, deserialize_tuple_struct,
|
||||
deserialize_option
|
||||
forward_to_deserialize! {
|
||||
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
|
||||
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
|
||||
tuple_struct struct struct_field tuple ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
@@ -404,20 +378,10 @@ impl<E> de::Deserializer for StringDeserializer<E>
|
||||
visitor.visit(self)
|
||||
}
|
||||
|
||||
de_forward_to_deserialize!{
|
||||
deserialize_bool,
|
||||
deserialize_f64, deserialize_f32,
|
||||
deserialize_u8, deserialize_u16, deserialize_u32, deserialize_u64, deserialize_usize,
|
||||
deserialize_i8, deserialize_i16, deserialize_i32, deserialize_i64, deserialize_isize,
|
||||
deserialize_char, deserialize_str, deserialize_string,
|
||||
deserialize_ignored_any,
|
||||
deserialize_bytes,
|
||||
deserialize_unit_struct, deserialize_unit,
|
||||
deserialize_seq, deserialize_seq_fixed_size,
|
||||
deserialize_map, deserialize_newtype_struct, deserialize_struct_field,
|
||||
deserialize_tuple,
|
||||
deserialize_struct, deserialize_tuple_struct,
|
||||
deserialize_option
|
||||
forward_to_deserialize! {
|
||||
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
|
||||
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
|
||||
tuple_struct struct struct_field tuple ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,6 +427,95 @@ impl<'a, E> de::VariantVisitor for StringDeserializer<E>
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// A helper deserializer that deserializes a `String`.
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
pub struct CowStrDeserializer<'a, E>(Option<Cow<'a, str>>, PhantomData<E>);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'a, E> ValueDeserializer<E> for Cow<'a, str>
|
||||
where E: de::Error,
|
||||
{
|
||||
type Deserializer = CowStrDeserializer<'a, E>;
|
||||
|
||||
fn into_deserializer(self) -> CowStrDeserializer<'a, E> {
|
||||
CowStrDeserializer(Some(self), PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E>
|
||||
where E: de::Error,
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
match self.0.take() {
|
||||
Some(Cow::Borrowed(string)) => visitor.visit_str(string),
|
||||
Some(Cow::Owned(string)) => visitor.visit_string(string),
|
||||
None => Err(de::Error::end_of_stream()),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(&mut self,
|
||||
_name: &str,
|
||||
_variants: &'static [&'static str],
|
||||
mut visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::EnumVisitor,
|
||||
{
|
||||
visitor.visit(self)
|
||||
}
|
||||
|
||||
forward_to_deserialize! {
|
||||
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
|
||||
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
|
||||
tuple_struct struct struct_field tuple ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'a, E> de::VariantVisitor for CowStrDeserializer<'a, E>
|
||||
where E: de::Error,
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn visit_variant<T>(&mut self) -> Result<T, Self::Error>
|
||||
where T: de::Deserialize,
|
||||
{
|
||||
de::Deserialize::deserialize(self)
|
||||
}
|
||||
|
||||
fn visit_unit(&mut self) -> Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_newtype<T>(&mut self) -> Result<T, Self::Error>
|
||||
where T: super::Deserialize,
|
||||
{
|
||||
let (value,) = try!(self.visit_tuple(1, super::impls::TupleVisitor1::new()));
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn visit_tuple<V>(&mut self,
|
||||
_len: usize,
|
||||
_visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: super::Visitor
|
||||
{
|
||||
Err(super::Error::invalid_type(super::Type::TupleVariant))
|
||||
}
|
||||
|
||||
fn visit_struct<V>(&mut self,
|
||||
_fields: &'static [&'static str],
|
||||
_visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: super::Visitor
|
||||
{
|
||||
Err(super::Error::invalid_type(super::Type::StructVariant))
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// A helper deserializer that deserializes a sequence.
|
||||
pub struct SeqDeserializer<I, E> {
|
||||
iter: I,
|
||||
@@ -496,21 +549,10 @@ impl<I, T, E> de::Deserializer for SeqDeserializer<I, E>
|
||||
visitor.visit_seq(self)
|
||||
}
|
||||
|
||||
de_forward_to_deserialize!{
|
||||
deserialize_bool,
|
||||
deserialize_f64, deserialize_f32,
|
||||
deserialize_u8, deserialize_u16, deserialize_u32, deserialize_u64, deserialize_usize,
|
||||
deserialize_i8, deserialize_i16, deserialize_i32, deserialize_i64, deserialize_isize,
|
||||
deserialize_char, deserialize_str, deserialize_string,
|
||||
deserialize_ignored_any,
|
||||
deserialize_bytes,
|
||||
deserialize_unit_struct, deserialize_unit,
|
||||
deserialize_seq, deserialize_seq_fixed_size,
|
||||
deserialize_map, deserialize_newtype_struct, deserialize_struct_field,
|
||||
deserialize_tuple,
|
||||
deserialize_enum,
|
||||
deserialize_struct, deserialize_tuple_struct,
|
||||
deserialize_option
|
||||
forward_to_deserialize! {
|
||||
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
|
||||
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
|
||||
tuple_struct struct struct_field tuple enum ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
@@ -619,21 +661,10 @@ impl<V_, E> de::Deserializer for SeqVisitorDeserializer<V_, E>
|
||||
visitor.visit_seq(&mut self.visitor)
|
||||
}
|
||||
|
||||
de_forward_to_deserialize!{
|
||||
deserialize_bool,
|
||||
deserialize_f64, deserialize_f32,
|
||||
deserialize_u8, deserialize_u16, deserialize_u32, deserialize_u64, deserialize_usize,
|
||||
deserialize_i8, deserialize_i16, deserialize_i32, deserialize_i64, deserialize_isize,
|
||||
deserialize_char, deserialize_str, deserialize_string,
|
||||
deserialize_ignored_any,
|
||||
deserialize_bytes,
|
||||
deserialize_unit_struct, deserialize_unit,
|
||||
deserialize_seq, deserialize_seq_fixed_size,
|
||||
deserialize_map, deserialize_newtype_struct, deserialize_struct_field,
|
||||
deserialize_tuple,
|
||||
deserialize_enum,
|
||||
deserialize_struct, deserialize_tuple_struct,
|
||||
deserialize_option
|
||||
forward_to_deserialize! {
|
||||
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
|
||||
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
|
||||
tuple_struct struct struct_field tuple enum ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
@@ -648,7 +679,7 @@ pub struct MapDeserializer<I, K, V, E>
|
||||
{
|
||||
iter: I,
|
||||
value: Option<V>,
|
||||
len: usize,
|
||||
len: Option<usize>,
|
||||
marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
@@ -658,15 +689,35 @@ impl<I, K, V, E> MapDeserializer<I, K, V, E>
|
||||
V: ValueDeserializer<E>,
|
||||
E: de::Error,
|
||||
{
|
||||
/// Construct a new `MapDeserializer<I, K, V>`.
|
||||
/// Construct a new `MapDeserializer<I, K, V, E>` with a specific length.
|
||||
pub fn new(iter: I, len: usize) -> Self {
|
||||
MapDeserializer {
|
||||
iter: iter,
|
||||
value: None,
|
||||
len: len,
|
||||
len: Some(len),
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct a new `MapDeserializer<I, K, V, E>` that is not bounded
|
||||
/// by a specific length and that delegates to `iter` for its size hint.
|
||||
pub fn unbounded(iter: I) -> Self {
|
||||
MapDeserializer {
|
||||
iter: iter,
|
||||
value: None,
|
||||
len: None,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Option<(K, V)> {
|
||||
self.iter.next().map(|(k, v)| {
|
||||
if let Some(len) = self.len.as_mut() {
|
||||
*len -= 1;
|
||||
}
|
||||
(k, v)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<I, K, V, E> de::Deserializer for MapDeserializer<I, K, V, E>
|
||||
@@ -683,21 +734,26 @@ impl<I, K, V, E> de::Deserializer for MapDeserializer<I, K, V, E>
|
||||
visitor.visit_map(self)
|
||||
}
|
||||
|
||||
de_forward_to_deserialize!{
|
||||
deserialize_bool,
|
||||
deserialize_f64, deserialize_f32,
|
||||
deserialize_u8, deserialize_u16, deserialize_u32, deserialize_u64, deserialize_usize,
|
||||
deserialize_i8, deserialize_i16, deserialize_i32, deserialize_i64, deserialize_isize,
|
||||
deserialize_char, deserialize_str, deserialize_string,
|
||||
deserialize_ignored_any,
|
||||
deserialize_bytes,
|
||||
deserialize_unit_struct, deserialize_unit,
|
||||
deserialize_seq, deserialize_seq_fixed_size,
|
||||
deserialize_map, deserialize_newtype_struct, deserialize_struct_field,
|
||||
deserialize_tuple,
|
||||
deserialize_enum,
|
||||
deserialize_struct, deserialize_tuple_struct,
|
||||
deserialize_option
|
||||
fn deserialize_seq<V_>(&mut self, mut visitor: V_) -> Result<V_::Value, Self::Error>
|
||||
where V_: de::Visitor,
|
||||
{
|
||||
visitor.visit_seq(self)
|
||||
}
|
||||
|
||||
fn deserialize_seq_fixed_size<V_>(&mut self, len: usize, mut visitor: V_) -> Result<V_::Value, Self::Error>
|
||||
where V_: de::Visitor,
|
||||
{
|
||||
match self.len {
|
||||
Some(map_len) if map_len == len => visitor.visit_seq(self),
|
||||
Some(_) => Err(de::Error::invalid_length(len)),
|
||||
None => visitor.visit_seq(self),
|
||||
}
|
||||
}
|
||||
|
||||
forward_to_deserialize! {
|
||||
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
|
||||
unit option bytes map unit_struct newtype_struct tuple_struct struct
|
||||
struct_field tuple enum ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
@@ -712,12 +768,11 @@ impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
|
||||
fn visit_key<T>(&mut self) -> Result<Option<T>, Self::Error>
|
||||
where T: de::Deserialize,
|
||||
{
|
||||
match self.iter.next() {
|
||||
match self.next() {
|
||||
Some((key, value)) => {
|
||||
self.len -= 1;
|
||||
self.value = Some(value);
|
||||
let mut de = key.into_deserializer();
|
||||
Ok(Some(try!(de::Deserialize::deserialize(&mut de))))
|
||||
de::Deserialize::deserialize(&mut de).map(Some)
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
@@ -738,15 +793,133 @@ impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Self::Error> {
|
||||
if self.len == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(de::Error::invalid_length(self.len))
|
||||
match self.len {
|
||||
Some(len) if len > 0 => Err(de::Error::invalid_length(len)),
|
||||
_ => Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.len, Some(self.len))
|
||||
self.len.map_or_else(
|
||||
|| self.iter.size_hint(),
|
||||
|len| (len, Some(len)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<I, K, V, E> de::SeqVisitor for MapDeserializer<I, K, V, E>
|
||||
where I: Iterator<Item=(K, V)>,
|
||||
K: ValueDeserializer<E>,
|
||||
V: ValueDeserializer<E>,
|
||||
E: de::Error,
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, Self::Error>
|
||||
where T: de::Deserialize,
|
||||
{
|
||||
match self.next() {
|
||||
Some(kv) => {
|
||||
let mut de = PairDeserializer(Some(kv), PhantomData);
|
||||
de::Deserialize::deserialize(&mut de).map(Some)
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Self::Error> {
|
||||
de::MapVisitor::end(self)
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
de::MapVisitor::size_hint(self)
|
||||
}
|
||||
}
|
||||
|
||||
// Used in the `impl SeqVisitor for MapDeserializer` to visit the map as a
|
||||
// sequence of pairs.
|
||||
struct PairDeserializer<A, B, E>(Option<(A, B)>, PhantomData<E>);
|
||||
|
||||
impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E>
|
||||
where A: ValueDeserializer<E>,
|
||||
B: ValueDeserializer<E>,
|
||||
E: de::Error
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
forward_to_deserialize! {
|
||||
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
|
||||
unit option bytes map unit_struct newtype_struct tuple_struct struct
|
||||
struct_field tuple enum ignored_any
|
||||
}
|
||||
|
||||
fn deserialize<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
self.deserialize_seq(visitor)
|
||||
}
|
||||
|
||||
fn deserialize_seq<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
match self.0.take() {
|
||||
Some((k, v)) => {
|
||||
visitor.visit_seq(PairVisitor(Some(k), Some(v), PhantomData))
|
||||
}
|
||||
None => Err(de::Error::end_of_stream()),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_seq_fixed_size<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
if len == 2 {
|
||||
self.deserialize_seq(visitor)
|
||||
} else {
|
||||
Err(de::Error::invalid_length(len))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, Self::Error>
|
||||
where T: de::Deserialize,
|
||||
{
|
||||
if let Some(k) = self.0.take() {
|
||||
let mut de = k.into_deserializer();
|
||||
de::Deserialize::deserialize(&mut de).map(Some)
|
||||
} else if let Some(v) = self.1.take() {
|
||||
let mut de = v.into_deserializer();
|
||||
de::Deserialize::deserialize(&mut de).map(Some)
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Self::Error> {
|
||||
if self.1.is_none() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(de::Error::invalid_length(self.size_hint().0))
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = if self.0.is_some() {
|
||||
2
|
||||
} else if self.1.is_some() {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
(len, Some(len))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -811,21 +984,10 @@ impl<V_, E> de::Deserializer for MapVisitorDeserializer<V_, E>
|
||||
visitor.visit_map(&mut self.visitor)
|
||||
}
|
||||
|
||||
de_forward_to_deserialize!{
|
||||
deserialize_bool,
|
||||
deserialize_f64, deserialize_f32,
|
||||
deserialize_u8, deserialize_u16, deserialize_u32, deserialize_u64, deserialize_usize,
|
||||
deserialize_i8, deserialize_i16, deserialize_i32, deserialize_i64, deserialize_isize,
|
||||
deserialize_char, deserialize_str, deserialize_string,
|
||||
deserialize_ignored_any,
|
||||
deserialize_bytes,
|
||||
deserialize_unit_struct, deserialize_unit,
|
||||
deserialize_seq, deserialize_seq_fixed_size,
|
||||
deserialize_map, deserialize_newtype_struct, deserialize_struct_field,
|
||||
deserialize_tuple,
|
||||
deserialize_enum,
|
||||
deserialize_struct, deserialize_tuple_struct,
|
||||
deserialize_option
|
||||
forward_to_deserialize! {
|
||||
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
|
||||
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
|
||||
tuple_struct struct struct_field tuple enum ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
@@ -858,25 +1020,13 @@ impl<'a, E> de::Deserializer for BytesDeserializer<'a, E>
|
||||
}
|
||||
}
|
||||
|
||||
de_forward_to_deserialize!{
|
||||
deserialize_bool,
|
||||
deserialize_f64, deserialize_f32,
|
||||
deserialize_u8, deserialize_u16, deserialize_u32, deserialize_u64, deserialize_usize,
|
||||
deserialize_i8, deserialize_i16, deserialize_i32, deserialize_i64, deserialize_isize,
|
||||
deserialize_char, deserialize_str, deserialize_string,
|
||||
deserialize_ignored_any,
|
||||
deserialize_bytes,
|
||||
deserialize_unit_struct, deserialize_unit,
|
||||
deserialize_seq, deserialize_seq_fixed_size,
|
||||
deserialize_map, deserialize_newtype_struct, deserialize_struct_field,
|
||||
deserialize_tuple,
|
||||
deserialize_enum,
|
||||
deserialize_struct, deserialize_tuple_struct,
|
||||
deserialize_option
|
||||
forward_to_deserialize! {
|
||||
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
|
||||
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
|
||||
tuple_struct struct struct_field tuple enum ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
@@ -909,20 +1059,9 @@ impl<E> de::Deserializer for ByteBufDeserializer<E>
|
||||
}
|
||||
}
|
||||
|
||||
de_forward_to_deserialize!{
|
||||
deserialize_bool,
|
||||
deserialize_f64, deserialize_f32,
|
||||
deserialize_u8, deserialize_u16, deserialize_u32, deserialize_u64, deserialize_usize,
|
||||
deserialize_i8, deserialize_i16, deserialize_i32, deserialize_i64, deserialize_isize,
|
||||
deserialize_char, deserialize_str, deserialize_string,
|
||||
deserialize_ignored_any,
|
||||
deserialize_bytes,
|
||||
deserialize_unit_struct, deserialize_unit,
|
||||
deserialize_seq, deserialize_seq_fixed_size,
|
||||
deserialize_map, deserialize_newtype_struct, deserialize_struct_field,
|
||||
deserialize_tuple,
|
||||
deserialize_enum,
|
||||
deserialize_struct, deserialize_tuple_struct,
|
||||
deserialize_option
|
||||
forward_to_deserialize! {
|
||||
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
|
||||
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
|
||||
tuple_struct struct struct_field tuple enum ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,9 @@ macro_rules! format {
|
||||
($s:expr, $($rest:tt)*) => ($s)
|
||||
}
|
||||
|
||||
#[macro_use]
|
||||
mod macros;
|
||||
|
||||
pub mod bytes;
|
||||
pub mod de;
|
||||
#[cfg(feature = "std")]
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
#[cfg(feature = "std")]
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! forward_to_deserialize_method {
|
||||
($func:ident($($arg:ty),*)) => {
|
||||
#[inline]
|
||||
fn $func<__V>(&mut self, $(_: $arg,)* visitor: __V) -> ::std::result::Result<__V::Value, Self::Error>
|
||||
where __V: $crate::de::Visitor
|
||||
{
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "std"))]
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! forward_to_deserialize_method {
|
||||
($func:ident($($arg:ty),*)) => {
|
||||
#[inline]
|
||||
fn $func<__V>(&mut self, $(_: $arg,)* visitor: __V) -> ::core::result::Result<__V::Value, Self::Error>
|
||||
where __V: $crate::de::Visitor
|
||||
{
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! forward_to_deserialize_enum {
|
||||
() => {
|
||||
#[inline]
|
||||
fn deserialize_enum<__V>(&mut self, _: &str, _: &[&str], _: __V) -> ::std::result::Result<__V::Value, Self::Error>
|
||||
where __V: $crate::de::EnumVisitor
|
||||
{
|
||||
Err($crate::de::Error::invalid_type($crate::de::Type::Enum))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "std"))]
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! forward_to_deserialize_enum {
|
||||
() => {
|
||||
#[inline]
|
||||
fn deserialize_enum<__V>(&mut self, _: &str, _: &[&str], _: __V) -> ::core::result::Result<__V::Value, Self::Error>
|
||||
where __V: $crate::de::EnumVisitor
|
||||
{
|
||||
Err($crate::de::Error::invalid_type($crate::de::Type::Enum))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! forward_to_deserialize_helper {
|
||||
(bool) => {
|
||||
forward_to_deserialize_method!{deserialize_bool()}
|
||||
};
|
||||
(usize) => {
|
||||
forward_to_deserialize_method!{deserialize_usize()}
|
||||
};
|
||||
(u8) => {
|
||||
forward_to_deserialize_method!{deserialize_u8()}
|
||||
};
|
||||
(u16) => {
|
||||
forward_to_deserialize_method!{deserialize_u16()}
|
||||
};
|
||||
(u32) => {
|
||||
forward_to_deserialize_method!{deserialize_u32()}
|
||||
};
|
||||
(u64) => {
|
||||
forward_to_deserialize_method!{deserialize_u64()}
|
||||
};
|
||||
(isize) => {
|
||||
forward_to_deserialize_method!{deserialize_isize()}
|
||||
};
|
||||
(i8) => {
|
||||
forward_to_deserialize_method!{deserialize_i8()}
|
||||
};
|
||||
(i16) => {
|
||||
forward_to_deserialize_method!{deserialize_i16()}
|
||||
};
|
||||
(i32) => {
|
||||
forward_to_deserialize_method!{deserialize_i32()}
|
||||
};
|
||||
(i64) => {
|
||||
forward_to_deserialize_method!{deserialize_i64()}
|
||||
};
|
||||
(f32) => {
|
||||
forward_to_deserialize_method!{deserialize_f32()}
|
||||
};
|
||||
(f64) => {
|
||||
forward_to_deserialize_method!{deserialize_f64()}
|
||||
};
|
||||
(char) => {
|
||||
forward_to_deserialize_method!{deserialize_char()}
|
||||
};
|
||||
(str) => {
|
||||
forward_to_deserialize_method!{deserialize_str()}
|
||||
};
|
||||
(string) => {
|
||||
forward_to_deserialize_method!{deserialize_string()}
|
||||
};
|
||||
(unit) => {
|
||||
forward_to_deserialize_method!{deserialize_unit()}
|
||||
};
|
||||
(option) => {
|
||||
forward_to_deserialize_method!{deserialize_option()}
|
||||
};
|
||||
(seq) => {
|
||||
forward_to_deserialize_method!{deserialize_seq()}
|
||||
};
|
||||
(seq_fixed_size) => {
|
||||
forward_to_deserialize_method!{deserialize_seq_fixed_size(usize)}
|
||||
};
|
||||
(bytes) => {
|
||||
forward_to_deserialize_method!{deserialize_bytes()}
|
||||
};
|
||||
(map) => {
|
||||
forward_to_deserialize_method!{deserialize_map()}
|
||||
};
|
||||
(unit_struct) => {
|
||||
forward_to_deserialize_method!{deserialize_unit_struct(&'static str)}
|
||||
};
|
||||
(newtype_struct) => {
|
||||
forward_to_deserialize_method!{deserialize_newtype_struct(&'static str)}
|
||||
};
|
||||
(tuple_struct) => {
|
||||
forward_to_deserialize_method!{deserialize_tuple_struct(&'static str, usize)}
|
||||
};
|
||||
(struct) => {
|
||||
forward_to_deserialize_method!{deserialize_struct(&'static str, &'static [&'static str])}
|
||||
};
|
||||
(struct_field) => {
|
||||
forward_to_deserialize_method!{deserialize_struct_field()}
|
||||
};
|
||||
(tuple) => {
|
||||
forward_to_deserialize_method!{deserialize_tuple(usize)}
|
||||
};
|
||||
(ignored_any) => {
|
||||
forward_to_deserialize_method!{deserialize_ignored_any()}
|
||||
};
|
||||
(enum) => {
|
||||
forward_to_deserialize_enum!();
|
||||
};
|
||||
}
|
||||
|
||||
/// Helper to forward `Deserializer` methods to `Deserializer::deserialize`.
|
||||
/// Every given method ignores all arguments and forwards to `deserialize`.
|
||||
/// Note that `deserialize_enum` simply returns an `Error::invalid_type`; a
|
||||
/// better approach is tracked in [serde-rs/serde#521][1].
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// impl Deserializer for MyDeserializer {
|
||||
/// fn deserialize<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
/// where V: Visitor
|
||||
/// {
|
||||
/// /* ... */
|
||||
/// }
|
||||
///
|
||||
/// forward_to_deserialize! {
|
||||
/// bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
|
||||
/// unit option seq seq_fixed_size bytes map unit_struct newtype_struct
|
||||
/// tuple_struct struct struct_field tuple enum ignored_any
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// [1]: https://github.com/serde-rs/serde/issues/521
|
||||
#[macro_export]
|
||||
macro_rules! forward_to_deserialize {
|
||||
($($func:ident)*) => {
|
||||
$(forward_to_deserialize_helper!{$func})*
|
||||
};
|
||||
}
|
||||
+3
-11
@@ -313,11 +313,6 @@ impl Serialize for () {
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// FIXME(rust #19630) Remove this work-around
|
||||
macro_rules! e {
|
||||
($e:expr) => { $e }
|
||||
}
|
||||
|
||||
macro_rules! tuple_impls {
|
||||
($(
|
||||
$TupleVisitor:ident ($len:expr, $($T:ident),+) {
|
||||
@@ -334,7 +329,7 @@ macro_rules! tuple_impls {
|
||||
{
|
||||
let mut state = try!(serializer.serialize_tuple($len));
|
||||
$(
|
||||
try!(serializer.serialize_tuple_elt(&mut state, &e!(self.$idx)));
|
||||
try!(serializer.serialize_tuple_elt(&mut state, &self.$idx));
|
||||
)+
|
||||
serializer.serialize_tuple_end(state)
|
||||
}
|
||||
@@ -640,15 +635,12 @@ impl Serialize for Duration {
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(all(feature = "std", feature = "unstable"))]
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for net::IpAddr {
|
||||
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
match *self {
|
||||
net::IpAddr::V4(ref addr) => addr.serialize(serializer),
|
||||
net::IpAddr::V6(ref addr) => addr.serialize(serializer),
|
||||
}
|
||||
self.to_string().serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde_codegen"
|
||||
version = "0.8.3"
|
||||
version = "0.8.23"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "Macros to auto-generate implementations for the serde framework"
|
||||
@@ -8,31 +8,22 @@ homepage = "https://serde.rs"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
documentation = "https://serde.rs/codegen.html"
|
||||
keywords = ["serde", "serialization"]
|
||||
build = "build.rs"
|
||||
include = ["Cargo.toml", "build.rs", "src/**/*.rs", "src/lib.rs.in"]
|
||||
include = ["Cargo.toml", "src/**/*.rs"]
|
||||
|
||||
[features]
|
||||
default = ["with-syntex"]
|
||||
unstable = ["quasi_macros"]
|
||||
unstable = []
|
||||
unstable-testing = ["clippy"]
|
||||
with-syntex = [
|
||||
"quasi/with-syntex",
|
||||
"quasi_codegen",
|
||||
"quasi_codegen/with-syntex",
|
||||
"serde_codegen_internals/with-syntex",
|
||||
"syntex",
|
||||
"syntex_syntax",
|
||||
]
|
||||
|
||||
[build-dependencies]
|
||||
quasi_codegen = { version = "^0.17.0", optional = true }
|
||||
syntex = { version = "^0.41.0", optional = true }
|
||||
with-syn = []
|
||||
|
||||
[dependencies]
|
||||
aster = { version = "^0.24.0", default-features = false }
|
||||
clippy = { version = "^0.*", optional = true }
|
||||
quasi = { version = "^0.17.0", default-features = false }
|
||||
quasi_macros = { version = "^0.17.0", optional = true }
|
||||
serde_codegen_internals = { version = "=0.6.1", default-features = false, path = "../serde_codegen_internals" }
|
||||
syntex = { version = "^0.41.0", optional = true }
|
||||
syntex_syntax = { version = "^0.41.0", optional = true }
|
||||
quote = "0.3.8"
|
||||
serde_codegen_internals = { version = "=0.11.3", default-features = false, path = "../serde_codegen_internals" }
|
||||
syn = { version = "0.10", features = ["aster", "visit"] }
|
||||
syntex = { version = "^0.54.0", optional = true }
|
||||
syntex_syntax = { version = "^0.54.0", optional = true }
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
#[cfg(feature = "with-syntex")]
|
||||
mod inner {
|
||||
extern crate quasi_codegen;
|
||||
|
||||
use std::env;
|
||||
use std::path::Path;
|
||||
use std::thread::spawn;
|
||||
|
||||
pub fn main() {
|
||||
// put everything into a thread, so users can use `RUST_MIN_STACK` to increase the amount of stack
|
||||
spawn(|| {
|
||||
let out_dir = env::var_os("OUT_DIR").unwrap();
|
||||
|
||||
let src = Path::new("src/lib.rs.in");
|
||||
let dst = Path::new(&out_dir).join("lib.rs");
|
||||
quasi_codegen::expand(&src, &dst).unwrap();
|
||||
}).join().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "with-syntex"))]
|
||||
mod inner {
|
||||
pub fn main() {}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
inner::main();
|
||||
}
|
||||
+25
-31
@@ -1,9 +1,6 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use aster::AstBuilder;
|
||||
|
||||
use syntax::ast;
|
||||
use syntax::visit;
|
||||
use syn::{self, aster, visit};
|
||||
|
||||
use internals::ast::Item;
|
||||
use internals::attr;
|
||||
@@ -11,10 +8,10 @@ use internals::attr;
|
||||
// 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: &ast::Generics) -> ast::Generics {
|
||||
ast::Generics {
|
||||
pub fn without_defaults(generics: &syn::Generics) -> syn::Generics {
|
||||
syn::Generics {
|
||||
ty_params: generics.ty_params.iter().map(|ty_param| {
|
||||
ast::TyParam {
|
||||
syn::TyParam {
|
||||
default: None,
|
||||
.. ty_param.clone()
|
||||
}}).collect(),
|
||||
@@ -23,24 +20,22 @@ pub fn without_defaults(generics: &ast::Generics) -> ast::Generics {
|
||||
}
|
||||
|
||||
pub fn with_where_predicates(
|
||||
builder: &AstBuilder,
|
||||
generics: &ast::Generics,
|
||||
predicates: &[ast::WherePredicate],
|
||||
) -> ast::Generics {
|
||||
builder.from_generics(generics.clone())
|
||||
generics: &syn::Generics,
|
||||
predicates: &[syn::WherePredicate],
|
||||
) -> syn::Generics {
|
||||
aster::from_generics(generics.clone())
|
||||
.with_predicates(predicates.to_vec())
|
||||
.build()
|
||||
}
|
||||
|
||||
pub fn with_where_predicates_from_fields<F>(
|
||||
builder: &AstBuilder,
|
||||
item: &Item,
|
||||
generics: &ast::Generics,
|
||||
generics: &syn::Generics,
|
||||
from_field: F,
|
||||
) -> ast::Generics
|
||||
where F: Fn(&attr::Field) -> Option<&[ast::WherePredicate]>,
|
||||
) -> syn::Generics
|
||||
where F: Fn(&attr::Field) -> Option<&[syn::WherePredicate]>,
|
||||
{
|
||||
builder.from_generics(generics.clone())
|
||||
aster::from_generics(generics.clone())
|
||||
.with_predicates(
|
||||
item.body.all_fields()
|
||||
.flat_map(|field| from_field(&field.attrs))
|
||||
@@ -60,34 +55,33 @@ pub fn with_where_predicates_from_fields<F>(
|
||||
// c: C,
|
||||
// }
|
||||
pub fn with_bound<F>(
|
||||
builder: &AstBuilder,
|
||||
item: &Item,
|
||||
generics: &ast::Generics,
|
||||
generics: &syn::Generics,
|
||||
filter: F,
|
||||
bound: &ast::Path,
|
||||
) -> ast::Generics
|
||||
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
|
||||
// the example). Initialized up front.
|
||||
all_ty_params: HashSet<ast::Name>,
|
||||
all_ty_params: HashSet<syn::Ident>,
|
||||
// Set of generic type parameters used in fields for which filter
|
||||
// returns true (A and B in the example). Filled in as the visitor sees
|
||||
// them.
|
||||
relevant_ty_params: HashSet<ast::Name>,
|
||||
relevant_ty_params: HashSet<syn::Ident>,
|
||||
}
|
||||
impl visit::Visitor for FindTyParams {
|
||||
fn visit_path(&mut self, path: &ast::Path, _id: ast::NodeId) {
|
||||
fn visit_path(&mut self, path: &syn::Path) {
|
||||
if let Some(seg) = path.segments.last() {
|
||||
if seg.identifier.name.as_str() == "PhantomData" {
|
||||
if seg.ident == "PhantomData" {
|
||||
// Hardcoded exception, because PhantomData<T> implements
|
||||
// Serialize and Deserialize whether or not T implements it.
|
||||
return;
|
||||
}
|
||||
}
|
||||
if !path.global && path.segments.len() == 1 {
|
||||
let id = path.segments[0].identifier.name;
|
||||
let id = path.segments[0].ident.clone();
|
||||
if self.all_ty_params.contains(&id) {
|
||||
self.relevant_ty_params.insert(id);
|
||||
}
|
||||
@@ -97,7 +91,7 @@ pub fn with_bound<F>(
|
||||
}
|
||||
|
||||
let all_ty_params: HashSet<_> = generics.ty_params.iter()
|
||||
.map(|ty_param| ty_param.ident.name)
|
||||
.map(|ty_param| ty_param.ident.clone())
|
||||
.collect();
|
||||
|
||||
let relevant_tys = item.body.all_fields()
|
||||
@@ -112,14 +106,14 @@ pub fn with_bound<F>(
|
||||
visit::walk_ty(&mut visitor, ty);
|
||||
}
|
||||
|
||||
builder.from_generics(generics.clone())
|
||||
aster::from_generics(generics.clone())
|
||||
.with_predicates(
|
||||
generics.ty_params.iter()
|
||||
.map(|ty_param| ty_param.ident.name)
|
||||
.map(|ty_param| ty_param.ident.clone())
|
||||
.filter(|id| visitor.relevant_ty_params.contains(id))
|
||||
.map(|id| builder.where_predicate()
|
||||
.map(|id| aster::where_predicate()
|
||||
// the type parameter that is being bounded e.g. T
|
||||
.bound().build(builder.ty().id(id))
|
||||
.bound().build(aster::ty().id(id))
|
||||
// the bound e.g. Serialize
|
||||
.bound().trait_(bound.clone()).build()
|
||||
.build()))
|
||||
|
||||
+432
-561
File diff suppressed because it is too large
Load Diff
@@ -1,36 +0,0 @@
|
||||
use std::env;
|
||||
use std::ffi::OsStr;
|
||||
use std::ops::Drop;
|
||||
|
||||
pub fn set_if_unset<K, V>(k: K, v: V) -> TmpEnv<K>
|
||||
where K: AsRef<OsStr>,
|
||||
V: AsRef<OsStr>,
|
||||
{
|
||||
match env::var(&k) {
|
||||
Ok(_) => TmpEnv::WasAlreadySet,
|
||||
Err(_) => {
|
||||
env::set_var(&k, v);
|
||||
TmpEnv::WasNotSet { k: k }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub enum TmpEnv<K>
|
||||
where K: AsRef<OsStr>,
|
||||
{
|
||||
WasAlreadySet,
|
||||
WasNotSet {
|
||||
k: K,
|
||||
}
|
||||
}
|
||||
|
||||
impl<K> Drop for TmpEnv<K>
|
||||
where K: AsRef<OsStr>,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
if let TmpEnv::WasNotSet { ref k } = *self {
|
||||
env::remove_var(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
+131
-68
@@ -2,11 +2,10 @@
|
||||
#![cfg_attr(feature = "clippy", feature(plugin))]
|
||||
#![cfg_attr(feature = "clippy", allow(too_many_arguments))]
|
||||
#![cfg_attr(feature = "clippy", allow(used_underscore_binding))]
|
||||
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))]
|
||||
#![cfg_attr(not(feature = "with-syntex"), plugin(quasi_macros))]
|
||||
|
||||
extern crate aster;
|
||||
extern crate quasi;
|
||||
// The `quote!` macro requires deep recursion.
|
||||
#![recursion_limit = "192"]
|
||||
|
||||
extern crate serde_codegen_internals as internals;
|
||||
|
||||
#[cfg(feature = "with-syntex")]
|
||||
@@ -16,27 +15,68 @@ extern crate syntex;
|
||||
#[macro_use]
|
||||
extern crate syntex_syntax as syntax;
|
||||
|
||||
#[cfg(not(feature = "with-syntex"))]
|
||||
extern crate syn;
|
||||
#[macro_use]
|
||||
extern crate syntax;
|
||||
|
||||
#[cfg(not(feature = "with-syntex"))]
|
||||
extern crate rustc_plugin;
|
||||
extern crate quote;
|
||||
|
||||
#[cfg(feature = "with-syntex")]
|
||||
use std::path::Path;
|
||||
|
||||
#[cfg(not(feature = "with-syntex"))]
|
||||
use syntax::feature_gate::AttributeType;
|
||||
mod bound;
|
||||
mod de;
|
||||
mod ser;
|
||||
|
||||
#[cfg(feature = "with-syntex")]
|
||||
include!(concat!(env!("OUT_DIR"), "/lib.rs"));
|
||||
fn syntex_registry() -> syntex::Registry {
|
||||
use syntax::{ast, fold};
|
||||
|
||||
#[cfg(not(feature = "with-syntex"))]
|
||||
include!("lib.rs.in");
|
||||
/// Strip the serde attributes from the crate.
|
||||
#[cfg(feature = "with-syntex")]
|
||||
fn strip_attributes(krate: ast::Crate) -> ast::Crate {
|
||||
/// Helper folder that strips the serde attributes after the extensions have been expanded.
|
||||
struct StripAttributeFolder;
|
||||
|
||||
impl fold::Folder for StripAttributeFolder {
|
||||
fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
|
||||
if attr.value.name == "serde" {
|
||||
if let ast::MetaItemKind::List(..) = attr.value.node {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(attr)
|
||||
}
|
||||
|
||||
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
|
||||
fold::noop_fold_mac(mac, self)
|
||||
}
|
||||
}
|
||||
|
||||
fold::Folder::fold_crate(&mut StripAttributeFolder, krate)
|
||||
}
|
||||
|
||||
let mut reg = syntex::Registry::new();
|
||||
|
||||
reg.add_attr("feature(custom_derive)");
|
||||
reg.add_attr("feature(custom_attribute)");
|
||||
|
||||
reg.add_decorator("derive_Serialize", shim::expand_derive_serialize);
|
||||
reg.add_decorator("derive_Deserialize", shim::expand_derive_deserialize);
|
||||
|
||||
reg.add_post_expansion_pass(strip_attributes);
|
||||
|
||||
reg
|
||||
}
|
||||
|
||||
#[cfg(feature = "with-syntex")]
|
||||
mod env;
|
||||
pub fn expand_str(src: &str) -> Result<String, syntex::Error> {
|
||||
let src = src.to_owned();
|
||||
|
||||
let expand_thread = move || {
|
||||
syntex_registry().expand_str("", "", &src)
|
||||
};
|
||||
|
||||
syntex::with_extra_stack(expand_thread)
|
||||
}
|
||||
|
||||
#[cfg(feature = "with-syntex")]
|
||||
pub fn expand<S, D>(src: S, dst: D) -> Result<(), syntex::Error>
|
||||
@@ -47,63 +87,86 @@ pub fn expand<S, D>(src: S, dst: D) -> Result<(), syntex::Error>
|
||||
let dst = dst.as_ref().to_owned();
|
||||
|
||||
let expand_thread = move || {
|
||||
use syntax::{ast, fold};
|
||||
|
||||
/// Strip the serde attributes from the crate.
|
||||
#[cfg(feature = "with-syntex")]
|
||||
fn strip_attributes(krate: ast::Crate) -> ast::Crate {
|
||||
/// Helper folder that strips the serde attributes after the extensions have been expanded.
|
||||
struct StripAttributeFolder;
|
||||
|
||||
impl fold::Folder for StripAttributeFolder {
|
||||
fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
|
||||
match attr.node.value.node {
|
||||
ast::MetaItemKind::List(ref n, _) if n == &"serde" => { return None; }
|
||||
_ => {}
|
||||
}
|
||||
|
||||
Some(attr)
|
||||
}
|
||||
|
||||
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
|
||||
fold::noop_fold_mac(mac, self)
|
||||
}
|
||||
}
|
||||
|
||||
fold::Folder::fold_crate(&mut StripAttributeFolder, krate)
|
||||
}
|
||||
|
||||
let mut reg = syntex::Registry::new();
|
||||
|
||||
reg.add_attr("feature(custom_derive)");
|
||||
reg.add_attr("feature(custom_attribute)");
|
||||
|
||||
reg.add_decorator("derive_Serialize", ser::expand_derive_serialize);
|
||||
reg.add_decorator("derive_Deserialize", de::expand_derive_deserialize);
|
||||
|
||||
reg.add_post_expansion_pass(strip_attributes);
|
||||
|
||||
reg.expand("", src, dst)
|
||||
syntex_registry().expand("", src, dst)
|
||||
};
|
||||
|
||||
// 16 MB stack unless otherwise specified
|
||||
let _tmp_env = env::set_if_unset("RUST_MIN_STACK", "16777216");
|
||||
|
||||
use std::thread;
|
||||
thread::spawn(expand_thread).join().unwrap()
|
||||
syntex::with_extra_stack(expand_thread)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "with-syntex"))]
|
||||
pub fn register(reg: &mut rustc_plugin::Registry) {
|
||||
reg.register_syntax_extension(
|
||||
syntax::parse::token::intern("derive_Serialize"),
|
||||
syntax::ext::base::MultiDecorator(
|
||||
Box::new(ser::expand_derive_serialize)));
|
||||
macro_rules! shim {
|
||||
($name:ident $pkg:ident :: $func:ident) => {
|
||||
pub fn $func(
|
||||
cx: &mut ::syntax::ext::base::ExtCtxt,
|
||||
span: ::syntax::codemap::Span,
|
||||
meta_item: &::syntax::ast::MetaItem,
|
||||
annotatable: &::syntax::ext::base::Annotatable,
|
||||
push: &mut FnMut(::syntax::ext::base::Annotatable)
|
||||
) {
|
||||
let item = match *annotatable {
|
||||
::syntax::ext::base::Annotatable::Item(ref item) => item,
|
||||
_ => {
|
||||
cx.span_err(
|
||||
meta_item.span,
|
||||
concat!("`#[derive(",
|
||||
stringify!($name),
|
||||
")]` may only be applied to structs and enums"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
reg.register_syntax_extension(
|
||||
syntax::parse::token::intern("derive_Deserialize"),
|
||||
syntax::ext::base::MultiDecorator(
|
||||
Box::new(de::expand_derive_deserialize)));
|
||||
use syntax::{attr, ast, visit};
|
||||
struct MarkSerdeAttributesUsed;
|
||||
impl<'a> visit::Visitor<'a> for MarkSerdeAttributesUsed {
|
||||
fn visit_attribute(&mut self, attr: &ast::Attribute) {
|
||||
if attr.value.name == "serde" {
|
||||
if let ast::MetaItemKind::List(..) = attr.value.node {
|
||||
attr::mark_used(attr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
visit::walk_item(&mut MarkSerdeAttributesUsed, item);
|
||||
|
||||
reg.register_attribute("serde".to_owned(), AttributeType::Normal);
|
||||
use syntax::print::pprust;
|
||||
let s = pprust::item_to_string(item);
|
||||
|
||||
use {syn, $pkg};
|
||||
let syn_item = syn::parse_macro_input(&s).unwrap();
|
||||
let expanded = match $pkg::$func(&syn_item) {
|
||||
Ok(expanded) => expanded.to_string(),
|
||||
Err(msg) => {
|
||||
cx.span_err(span, &msg);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
use syntax::parse;
|
||||
let name = stringify!($name).to_string();
|
||||
let sess = cx.parse_sess;
|
||||
let impl_item = parse::parse_item_from_source_str(name, expanded, sess);
|
||||
push(::syntax::ext::base::Annotatable::Item(impl_item.unwrap().unwrap()));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(feature = "with-syntex")]
|
||||
mod shim {
|
||||
shim!(Serialize ser::expand_derive_serialize);
|
||||
shim!(Deserialize de::expand_derive_deserialize);
|
||||
}
|
||||
|
||||
#[cfg(feature = "with-syn")]
|
||||
#[doc(hidden)]
|
||||
/// Not public API. Use the serde_derive crate.
|
||||
pub fn expand_derive_serialize(item: &str) -> Result<quote::Tokens, String> {
|
||||
let syn_item = syn::parse_macro_input(item).unwrap();
|
||||
ser::expand_derive_serialize(&syn_item)
|
||||
}
|
||||
|
||||
#[cfg(feature = "with-syn")]
|
||||
#[doc(hidden)]
|
||||
/// Not public API. Use the serde_derive crate.
|
||||
pub fn expand_derive_deserialize(item: &str) -> Result<quote::Tokens, String> {
|
||||
let syn_item = syn::parse_macro_input(item).unwrap();
|
||||
de::expand_derive_deserialize(&syn_item)
|
||||
}
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
mod bound;
|
||||
mod de;
|
||||
mod ser;
|
||||
mod span;
|
||||
+287
-356
@@ -1,102 +1,62 @@
|
||||
use aster;
|
||||
|
||||
use syntax::ast::{self, Ident, MetaItem};
|
||||
use syntax::codemap::Span;
|
||||
use syntax::ext::base::{Annotatable, ExtCtxt};
|
||||
use syntax::ptr::P;
|
||||
use syn::{self, aster};
|
||||
use quote::Tokens;
|
||||
|
||||
use bound;
|
||||
use span;
|
||||
use internals::ast::{Body, Field, Item, Style, Variant};
|
||||
use internals::{attr, Error};
|
||||
use internals::{self, attr};
|
||||
|
||||
pub fn expand_derive_serialize(
|
||||
cx: &mut ExtCtxt,
|
||||
span: Span,
|
||||
meta_item: &MetaItem,
|
||||
annotatable: &Annotatable,
|
||||
push: &mut FnMut(Annotatable)
|
||||
) {
|
||||
let item = match *annotatable {
|
||||
Annotatable::Item(ref item) => item,
|
||||
_ => {
|
||||
cx.span_err(
|
||||
meta_item.span,
|
||||
"`#[derive(Serialize)]` may only be applied to structs and enums");
|
||||
return;
|
||||
}
|
||||
};
|
||||
pub fn expand_derive_serialize(item: &syn::MacroInput) -> Result<Tokens, String> {
|
||||
let ctxt = internals::Ctxt::new();
|
||||
let item = Item::from_ast(&ctxt, item);
|
||||
try!(ctxt.check());
|
||||
|
||||
let item = match Item::from_ast(cx, item) {
|
||||
Ok(item) => item,
|
||||
Err(Error::UnexpectedItemKind) => {
|
||||
cx.span_err(item.span,
|
||||
"`#[derive(Serialize)]` may only be applied to structs and enums");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let impl_generics = build_impl_generics(&item);
|
||||
|
||||
let builder = aster::AstBuilder::new().span(span);
|
||||
|
||||
let impl_item = serialize_item(cx, &builder, &item);
|
||||
push(span::record_expansion(cx, impl_item, "Serialize"))
|
||||
}
|
||||
|
||||
fn serialize_item(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
item: &Item,
|
||||
) -> P<ast::Item> {
|
||||
let impl_generics = build_impl_generics(builder, &item);
|
||||
|
||||
let ty = builder.ty().path()
|
||||
.segment(item.ident).with_generics(impl_generics.clone()).build()
|
||||
let ty = aster::ty().path()
|
||||
.segment(item.ident.clone()).with_generics(impl_generics.clone()).build()
|
||||
.build();
|
||||
|
||||
let body = serialize_body(cx,
|
||||
builder,
|
||||
&item,
|
||||
let body = serialize_body(&item,
|
||||
&impl_generics,
|
||||
ty.clone());
|
||||
|
||||
let where_clause = &impl_generics.where_clause;
|
||||
|
||||
let dummy_const = builder.id(format!("_IMPL_SERIALIZE_FOR_{}", item.ident));
|
||||
let dummy_const = aster::id(format!("_IMPL_SERIALIZE_FOR_{}", item.ident));
|
||||
|
||||
quote_item!(cx,
|
||||
Ok(quote! {
|
||||
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
|
||||
const $dummy_const: () = {
|
||||
const #dummy_const: () = {
|
||||
extern crate serde as _serde;
|
||||
#[automatically_derived]
|
||||
impl $impl_generics _serde::ser::Serialize for $ty $where_clause {
|
||||
impl #impl_generics _serde::ser::Serialize for #ty #where_clause {
|
||||
fn serialize<__S>(&self, _serializer: &mut __S) -> ::std::result::Result<(), __S::Error>
|
||||
where __S: _serde::ser::Serializer
|
||||
$body
|
||||
{
|
||||
#body
|
||||
}
|
||||
}
|
||||
};
|
||||
).unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
// All the generics in the input, plus a bound `T: Serialize` for each generic
|
||||
// field type that will be serialized by us.
|
||||
fn build_impl_generics(
|
||||
builder: &aster::AstBuilder,
|
||||
item: &Item,
|
||||
) -> ast::Generics {
|
||||
fn build_impl_generics(item: &Item) -> syn::Generics {
|
||||
let generics = bound::without_defaults(item.generics);
|
||||
|
||||
let generics = bound::with_where_predicates_from_fields(
|
||||
builder, item, &generics,
|
||||
item, &generics,
|
||||
|attrs| attrs.ser_bound());
|
||||
|
||||
match item.attrs.ser_bound() {
|
||||
Some(predicates) => {
|
||||
bound::with_where_predicates(builder, &generics, predicates)
|
||||
bound::with_where_predicates(&generics, predicates)
|
||||
}
|
||||
None => {
|
||||
bound::with_bound(builder, item, &generics,
|
||||
bound::with_bound(item, &generics,
|
||||
needs_serialize_bound,
|
||||
&builder.path().ids(&["_serde", "ser", "Serialize"]).build())
|
||||
&aster::path().ids(&["_serde", "ser", "Serialize"]).build())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -112,18 +72,14 @@ fn needs_serialize_bound(attrs: &attr::Field) -> bool {
|
||||
}
|
||||
|
||||
fn serialize_body(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
item: &Item,
|
||||
impl_generics: &ast::Generics,
|
||||
ty: P<ast::Ty>,
|
||||
) -> P<ast::Block> {
|
||||
impl_generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
) -> Tokens {
|
||||
match item.body {
|
||||
Body::Enum(ref variants) => {
|
||||
serialize_item_enum(
|
||||
cx,
|
||||
builder,
|
||||
item.ident,
|
||||
&item.ident,
|
||||
impl_generics,
|
||||
ty,
|
||||
variants,
|
||||
@@ -131,12 +87,10 @@ fn serialize_body(
|
||||
}
|
||||
Body::Struct(Style::Struct, ref fields) => {
|
||||
if fields.iter().any(|field| field.ident.is_none()) {
|
||||
cx.span_bug(item.span, "struct has unnamed fields")
|
||||
panic!("struct has unnamed fields");
|
||||
}
|
||||
|
||||
serialize_struct(
|
||||
cx,
|
||||
builder,
|
||||
impl_generics,
|
||||
ty,
|
||||
fields,
|
||||
@@ -144,12 +98,10 @@ fn serialize_body(
|
||||
}
|
||||
Body::Struct(Style::Tuple, ref fields) => {
|
||||
if fields.iter().any(|field| field.ident.is_some()) {
|
||||
cx.span_bug(item.span, "tuple struct has named fields")
|
||||
panic!("tuple struct has named fields");
|
||||
}
|
||||
|
||||
serialize_tuple_struct(
|
||||
cx,
|
||||
builder,
|
||||
impl_generics,
|
||||
ty,
|
||||
fields,
|
||||
@@ -157,8 +109,6 @@ fn serialize_body(
|
||||
}
|
||||
Body::Struct(Style::Newtype, ref fields) => {
|
||||
serialize_newtype_struct(
|
||||
cx,
|
||||
builder,
|
||||
impl_generics,
|
||||
ty,
|
||||
&fields[0],
|
||||
@@ -166,129 +116,116 @@ fn serialize_body(
|
||||
}
|
||||
Body::Struct(Style::Unit, _) => {
|
||||
serialize_unit_struct(
|
||||
cx,
|
||||
builder,
|
||||
&item.attrs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_unit_struct(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
item_attrs: &attr::Item,
|
||||
) -> P<ast::Block> {
|
||||
let type_name = name_expr(builder, item_attrs.name());
|
||||
fn serialize_unit_struct(item_attrs: &attr::Item) -> Tokens {
|
||||
let type_name = item_attrs.name().serialize_name();
|
||||
|
||||
quote_block!(cx, {
|
||||
_serializer.serialize_unit_struct($type_name)
|
||||
}).unwrap()
|
||||
quote! {
|
||||
_serializer.serialize_unit_struct(#type_name)
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
impl_generics: &ast::Generics,
|
||||
item_ty: P<ast::Ty>,
|
||||
impl_generics: &syn::Generics,
|
||||
item_ty: syn::Ty,
|
||||
field: &Field,
|
||||
item_attrs: &attr::Item,
|
||||
) -> P<ast::Block> {
|
||||
let type_name = name_expr(builder, item_attrs.name());
|
||||
) -> Tokens {
|
||||
let type_name = item_attrs.name().serialize_name();
|
||||
|
||||
let mut field_expr = quote_expr!(cx, &self.0);
|
||||
let mut field_expr = quote!(&self.0);
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(cx, builder,
|
||||
&item_ty, impl_generics, &field.ty, path, field_expr);
|
||||
field_expr = wrap_serialize_with(
|
||||
&item_ty, impl_generics, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
quote_block!(cx, {
|
||||
_serializer.serialize_newtype_struct($type_name, $field_expr)
|
||||
}).unwrap()
|
||||
quote! {
|
||||
_serializer.serialize_newtype_struct(#type_name, #field_expr)
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
impl_generics: &ast::Generics,
|
||||
ty: P<ast::Ty>,
|
||||
impl_generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
fields: &[Field],
|
||||
item_attrs: &attr::Item,
|
||||
) -> P<ast::Block> {
|
||||
) -> Tokens {
|
||||
let serialize_stmts = serialize_tuple_struct_visitor(
|
||||
cx,
|
||||
builder,
|
||||
ty.clone(),
|
||||
fields,
|
||||
impl_generics,
|
||||
false,
|
||||
cx.ident_of("serialize_tuple_struct_elt"),
|
||||
aster::id("serialize_tuple_struct_elt"),
|
||||
);
|
||||
|
||||
let type_name = name_expr(builder, item_attrs.name());
|
||||
let type_name = item_attrs.name().serialize_name();
|
||||
let len = serialize_stmts.len();
|
||||
let let_mut = mut_if(len > 0);
|
||||
|
||||
quote_block!(cx, {
|
||||
let mut state = try!(_serializer.serialize_tuple_struct($type_name, $len));
|
||||
$serialize_stmts
|
||||
_serializer.serialize_tuple_struct_end(state)
|
||||
}).unwrap()
|
||||
quote! {
|
||||
let #let_mut __serde_state = try!(_serializer.serialize_tuple_struct(#type_name, #len));
|
||||
#(#serialize_stmts)*
|
||||
_serializer.serialize_tuple_struct_end(__serde_state)
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_struct(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
impl_generics: &ast::Generics,
|
||||
ty: P<ast::Ty>,
|
||||
impl_generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
fields: &[Field],
|
||||
item_attrs: &attr::Item,
|
||||
) -> P<ast::Block> {
|
||||
) -> Tokens {
|
||||
let serialize_fields = serialize_struct_visitor(
|
||||
cx,
|
||||
builder,
|
||||
ty.clone(),
|
||||
fields,
|
||||
impl_generics,
|
||||
false,
|
||||
cx.ident_of("serialize_struct_elt"),
|
||||
aster::id("serialize_struct_elt"),
|
||||
);
|
||||
|
||||
let type_name = name_expr(builder, item_attrs.name());
|
||||
let len = fields.iter()
|
||||
let type_name = item_attrs.name().serialize_name();
|
||||
|
||||
let mut serialized_fields = fields.iter()
|
||||
.filter(|&field| !field.attrs.skip_serializing())
|
||||
.peekable();
|
||||
|
||||
let let_mut = mut_if(serialized_fields.peek().is_some());
|
||||
|
||||
let len = serialized_fields
|
||||
.map(|field| {
|
||||
let ident = field.ident.expect("struct has unnamed fields");
|
||||
let field_expr = quote_expr!(cx, &self.$ident);
|
||||
let ident = field.ident.clone().expect("struct has unnamed fields");
|
||||
let field_expr = quote!(&self.#ident);
|
||||
|
||||
match field.attrs.skip_serializing_if() {
|
||||
Some(path) => quote_expr!(cx, if $path($field_expr) { 0 } else { 1 }),
|
||||
None => quote_expr!(cx, 1),
|
||||
Some(path) => quote!(if #path(#field_expr) { 0 } else { 1 }),
|
||||
None => quote!(1),
|
||||
}
|
||||
})
|
||||
.fold(quote_expr!(cx, 0), |sum, expr| quote_expr!(cx, $sum + $expr));
|
||||
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
|
||||
|
||||
quote_block!(cx, {
|
||||
let mut state = try!(_serializer.serialize_struct($type_name, $len));
|
||||
$serialize_fields
|
||||
_serializer.serialize_struct_end(state)
|
||||
}).unwrap()
|
||||
quote! {
|
||||
let #let_mut __serde_state = try!(_serializer.serialize_struct(#type_name, #len));
|
||||
#(#serialize_fields)*
|
||||
_serializer.serialize_struct_end(__serde_state)
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_item_enum(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
type_ident: Ident,
|
||||
impl_generics: &ast::Generics,
|
||||
ty: P<ast::Ty>,
|
||||
type_ident: &syn::Ident,
|
||||
impl_generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
variants: &[Variant],
|
||||
item_attrs: &attr::Item,
|
||||
) -> P<ast::Block> {
|
||||
) -> Tokens {
|
||||
let arms: Vec<_> =
|
||||
variants.iter()
|
||||
.enumerate()
|
||||
.map(|(variant_index, variant)| {
|
||||
serialize_variant(
|
||||
cx,
|
||||
builder,
|
||||
type_ident,
|
||||
impl_generics,
|
||||
ty.clone(),
|
||||
@@ -299,341 +236,335 @@ fn serialize_item_enum(
|
||||
})
|
||||
.collect();
|
||||
|
||||
quote_block!(cx, {
|
||||
quote! {
|
||||
match *self {
|
||||
$arms
|
||||
#(#arms)*
|
||||
}
|
||||
}).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_variant(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
type_ident: Ident,
|
||||
generics: &ast::Generics,
|
||||
ty: P<ast::Ty>,
|
||||
type_ident: &syn::Ident,
|
||||
generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
variant: &Variant,
|
||||
variant_index: usize,
|
||||
item_attrs: &attr::Item,
|
||||
) -> ast::Arm {
|
||||
let type_name = name_expr(builder, item_attrs.name());
|
||||
) -> Tokens {
|
||||
let type_name = item_attrs.name().serialize_name();
|
||||
|
||||
let variant_ident = variant.ident;
|
||||
let variant_name = name_expr(builder, variant.attrs.name());
|
||||
let variant_ident = variant.ident.clone();
|
||||
let variant_name = variant.attrs.name().serialize_name();
|
||||
|
||||
match variant.style {
|
||||
Style::Unit => {
|
||||
quote_arm!(cx,
|
||||
$type_ident::$variant_ident =>
|
||||
_serde::ser::Serializer::serialize_unit_variant(
|
||||
_serializer,
|
||||
$type_name,
|
||||
$variant_index,
|
||||
$variant_name,
|
||||
),
|
||||
)
|
||||
},
|
||||
Style::Newtype => {
|
||||
let block = serialize_newtype_variant(
|
||||
cx,
|
||||
builder,
|
||||
type_name,
|
||||
variant_index,
|
||||
variant_name,
|
||||
ty,
|
||||
generics,
|
||||
&variant.fields[0],
|
||||
);
|
||||
|
||||
quote_arm!(cx,
|
||||
$type_ident::$variant_ident(ref __simple_value) => $block
|
||||
)
|
||||
},
|
||||
Style::Tuple => {
|
||||
let field_names: Vec<ast::Ident> = (0 .. variant.fields.len())
|
||||
.map(|i| builder.id(format!("__field{}", i)))
|
||||
.collect();
|
||||
|
||||
let pat = builder.pat().enum_()
|
||||
.id(type_ident).id(variant_ident).build()
|
||||
.with_pats(
|
||||
field_names.iter()
|
||||
.map(|field| builder.pat().ref_id(field))
|
||||
)
|
||||
.build();
|
||||
|
||||
let block = serialize_tuple_variant(
|
||||
cx,
|
||||
builder,
|
||||
type_name,
|
||||
variant_index,
|
||||
variant_name,
|
||||
generics,
|
||||
ty,
|
||||
&variant.fields,
|
||||
);
|
||||
|
||||
quote_arm!(cx,
|
||||
$pat => $block
|
||||
)
|
||||
if variant.attrs.skip_serializing() {
|
||||
let skipped_msg = format!("The enum variant {}::{} cannot be serialized",
|
||||
type_ident, variant_ident);
|
||||
let skipped_err = quote! {
|
||||
Err(_serde::ser::Error::invalid_value(#skipped_msg))
|
||||
};
|
||||
let fields_pat = match variant.style {
|
||||
Style::Unit => quote!(),
|
||||
Style::Newtype | Style::Tuple => quote!( (..) ),
|
||||
Style::Struct => quote!( {..} ),
|
||||
};
|
||||
quote! {
|
||||
#type_ident::#variant_ident #fields_pat => #skipped_err,
|
||||
}
|
||||
Style::Struct => {
|
||||
let mut pat = builder.pat().struct_().id(type_ident).id(variant_ident).build();
|
||||
for field in &variant.fields {
|
||||
let name = match field.ident {
|
||||
Some(name) => name,
|
||||
None => cx.span_bug(field.span, "struct variant has unnamed fields"),
|
||||
};
|
||||
pat = pat.with_field_pat(ast::FieldPat {
|
||||
ident: name,
|
||||
pat: builder.pat().ref_id(name),
|
||||
is_shorthand: true,
|
||||
});
|
||||
} else { // variant wasn't skipped
|
||||
match variant.style {
|
||||
Style::Unit => {
|
||||
quote! {
|
||||
#type_ident::#variant_ident =>
|
||||
_serde::ser::Serializer::serialize_unit_variant(
|
||||
_serializer,
|
||||
#type_name,
|
||||
#variant_index,
|
||||
#variant_name,
|
||||
),
|
||||
}
|
||||
},
|
||||
Style::Newtype => {
|
||||
let block = serialize_newtype_variant(
|
||||
type_name,
|
||||
variant_index,
|
||||
variant_name,
|
||||
ty,
|
||||
generics,
|
||||
&variant.fields[0],
|
||||
);
|
||||
|
||||
quote! {
|
||||
#type_ident::#variant_ident(ref __simple_value) => #block,
|
||||
}
|
||||
},
|
||||
Style::Tuple => {
|
||||
let field_names = (0 .. variant.fields.len())
|
||||
.map(|i| aster::id(format!("__field{}", i)));
|
||||
|
||||
let block = serialize_tuple_variant(
|
||||
type_name,
|
||||
variant_index,
|
||||
variant_name,
|
||||
generics,
|
||||
ty,
|
||||
&variant.fields,
|
||||
);
|
||||
|
||||
quote! {
|
||||
#type_ident::#variant_ident(#(ref #field_names),*) => { #block }
|
||||
}
|
||||
}
|
||||
let pat = pat.build();
|
||||
Style::Struct => {
|
||||
let fields = variant.fields.iter()
|
||||
.map(|f| f.ident.clone().expect("struct variant has unnamed fields"));
|
||||
|
||||
let block = serialize_struct_variant(
|
||||
cx,
|
||||
builder,
|
||||
variant_index,
|
||||
variant_name,
|
||||
generics,
|
||||
ty,
|
||||
&variant.fields,
|
||||
item_attrs,
|
||||
);
|
||||
let block = serialize_struct_variant(
|
||||
variant_index,
|
||||
variant_name,
|
||||
generics,
|
||||
ty,
|
||||
&variant.fields,
|
||||
item_attrs,
|
||||
);
|
||||
|
||||
quote_arm!(cx,
|
||||
$pat => $block
|
||||
)
|
||||
quote! {
|
||||
#type_ident::#variant_ident { #(ref #fields),* } => { #block }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
type_name: P<ast::Expr>,
|
||||
type_name: String,
|
||||
variant_index: usize,
|
||||
variant_name: P<ast::Expr>,
|
||||
item_ty: P<ast::Ty>,
|
||||
generics: &ast::Generics,
|
||||
variant_name: String,
|
||||
item_ty: syn::Ty,
|
||||
generics: &syn::Generics,
|
||||
field: &Field,
|
||||
) -> P<ast::Block> {
|
||||
let mut field_expr = quote_expr!(cx, __simple_value);
|
||||
) -> Tokens {
|
||||
let mut field_expr = quote!(__simple_value);
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(cx, builder,
|
||||
&item_ty, generics, &field.ty, path, field_expr);
|
||||
field_expr = wrap_serialize_with(
|
||||
&item_ty, generics, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
quote_block!(cx, {
|
||||
quote! {
|
||||
_serde::ser::Serializer::serialize_newtype_variant(
|
||||
_serializer,
|
||||
$type_name,
|
||||
$variant_index,
|
||||
$variant_name,
|
||||
$field_expr,
|
||||
#type_name,
|
||||
#variant_index,
|
||||
#variant_name,
|
||||
#field_expr,
|
||||
)
|
||||
}).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
type_name: P<ast::Expr>,
|
||||
type_name: String,
|
||||
variant_index: usize,
|
||||
variant_name: P<ast::Expr>,
|
||||
generics: &ast::Generics,
|
||||
structure_ty: P<ast::Ty>,
|
||||
variant_name: String,
|
||||
generics: &syn::Generics,
|
||||
structure_ty: syn::Ty,
|
||||
fields: &[Field],
|
||||
) -> P<ast::Block> {
|
||||
) -> Tokens {
|
||||
let serialize_stmts = serialize_tuple_struct_visitor(
|
||||
cx,
|
||||
builder,
|
||||
structure_ty,
|
||||
fields,
|
||||
generics,
|
||||
true,
|
||||
cx.ident_of("serialize_tuple_variant_elt"),
|
||||
aster::id("serialize_tuple_variant_elt"),
|
||||
);
|
||||
|
||||
let len = serialize_stmts.len();
|
||||
let let_mut = mut_if(len > 0);
|
||||
|
||||
quote_block!(cx, {
|
||||
let mut state = try!(_serializer.serialize_tuple_variant($type_name, $variant_index, $variant_name, $len));
|
||||
$serialize_stmts
|
||||
_serializer.serialize_tuple_variant_end(state)
|
||||
}).unwrap()
|
||||
quote! {
|
||||
let #let_mut __serde_state = try!(_serializer.serialize_tuple_variant(
|
||||
#type_name,
|
||||
#variant_index,
|
||||
#variant_name,
|
||||
#len));
|
||||
#(#serialize_stmts)*
|
||||
_serializer.serialize_tuple_variant_end(__serde_state)
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_struct_variant(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
variant_index: usize,
|
||||
variant_name: P<ast::Expr>,
|
||||
generics: &ast::Generics,
|
||||
ty: P<ast::Ty>,
|
||||
variant_name: String,
|
||||
generics: &syn::Generics,
|
||||
ty: syn::Ty,
|
||||
fields: &[Field],
|
||||
item_attrs: &attr::Item,
|
||||
) -> P<ast::Block> {
|
||||
|
||||
) -> Tokens {
|
||||
let serialize_fields = serialize_struct_visitor(
|
||||
cx,
|
||||
builder,
|
||||
ty.clone(),
|
||||
fields,
|
||||
&generics,
|
||||
generics,
|
||||
true,
|
||||
cx.ident_of("serialize_struct_variant_elt"),
|
||||
aster::id("serialize_struct_variant_elt"),
|
||||
);
|
||||
|
||||
let item_name = name_expr(builder, item_attrs.name());
|
||||
let len = fields.iter()
|
||||
let item_name = item_attrs.name().serialize_name();
|
||||
|
||||
let mut serialized_fields = fields.iter()
|
||||
.filter(|&field| !field.attrs.skip_serializing())
|
||||
.peekable();
|
||||
|
||||
let let_mut = mut_if(serialized_fields.peek().is_some());
|
||||
|
||||
let len = serialized_fields
|
||||
.map(|field| {
|
||||
let ident = field.ident.expect("struct has unnamed fields");
|
||||
let field_expr = quote_expr!(cx, $ident);
|
||||
let ident = field.ident.clone().expect("struct has unnamed fields");
|
||||
|
||||
match field.attrs.skip_serializing_if() {
|
||||
Some(path) => quote_expr!(cx, if $path($field_expr) { 0 } else { 1 }),
|
||||
None => quote_expr!(cx, 1),
|
||||
Some(path) => quote!(if #path(#ident) { 0 } else { 1 }),
|
||||
None => quote!(1),
|
||||
}
|
||||
})
|
||||
.fold(quote_expr!(cx, 0), |sum, expr| quote_expr!(cx, $sum + $expr));
|
||||
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
|
||||
|
||||
quote_block!(cx, {
|
||||
let mut state = try!(_serializer.serialize_struct_variant(
|
||||
$item_name,
|
||||
$variant_index,
|
||||
$variant_name,
|
||||
$len,
|
||||
quote! {
|
||||
let #let_mut __serde_state = try!(_serializer.serialize_struct_variant(
|
||||
#item_name,
|
||||
#variant_index,
|
||||
#variant_name,
|
||||
#len,
|
||||
));
|
||||
$serialize_fields
|
||||
_serializer.serialize_struct_variant_end(state)
|
||||
}).unwrap()
|
||||
#(#serialize_fields)*
|
||||
_serializer.serialize_struct_variant_end(__serde_state)
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct_visitor(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
structure_ty: P<ast::Ty>,
|
||||
structure_ty: syn::Ty,
|
||||
fields: &[Field],
|
||||
generics: &ast::Generics,
|
||||
generics: &syn::Generics,
|
||||
is_enum: bool,
|
||||
func: ast::Ident,
|
||||
) -> Vec<ast::Stmt> {
|
||||
func: syn::Ident,
|
||||
) -> Vec<Tokens> {
|
||||
fields.iter()
|
||||
.enumerate()
|
||||
.map(|(i, field)| {
|
||||
let mut field_expr = if is_enum {
|
||||
builder.expr().path().id(format!("__field{}", i)).build()
|
||||
let id = aster::id(format!("__field{}", i));
|
||||
quote!(#id)
|
||||
} else {
|
||||
builder.expr().ref_().tup_field(i).self_()
|
||||
let i = aster::id(i);
|
||||
quote!(&self.#i)
|
||||
};
|
||||
|
||||
let skip = field.attrs.skip_serializing_if()
|
||||
.map(|path| quote_expr!(cx, $path($field_expr)))
|
||||
.unwrap_or(quote_expr!(cx, false));
|
||||
.map(|path| quote!(#path(#field_expr)));
|
||||
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(cx, builder,
|
||||
&structure_ty, generics, &field.ty, path, field_expr);
|
||||
field_expr = wrap_serialize_with(
|
||||
&structure_ty, generics, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
quote_stmt!(cx,
|
||||
if !$skip {
|
||||
try!(_serializer.$func(&mut state, $field_expr));
|
||||
}
|
||||
).unwrap()
|
||||
let ser = quote! {
|
||||
try!(_serializer.#func(&mut __serde_state, #field_expr));
|
||||
};
|
||||
|
||||
match skip {
|
||||
None => ser,
|
||||
Some(skip) => quote!(if !#skip { #ser }),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn serialize_struct_visitor(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
structure_ty: P<ast::Ty>,
|
||||
structure_ty: syn::Ty,
|
||||
fields: &[Field],
|
||||
generics: &ast::Generics,
|
||||
generics: &syn::Generics,
|
||||
is_enum: bool,
|
||||
func: ast::Ident,
|
||||
) -> Vec<ast::Stmt> {
|
||||
func: syn::Ident,
|
||||
) -> Vec<Tokens> {
|
||||
fields.iter()
|
||||
.filter(|&field| !field.attrs.skip_serializing())
|
||||
.map(|field| {
|
||||
let ident = field.ident.expect("struct has unnamed field");
|
||||
let ident = field.ident.clone().expect("struct has unnamed field");
|
||||
let mut field_expr = if is_enum {
|
||||
quote_expr!(cx, $ident)
|
||||
quote!(#ident)
|
||||
} else {
|
||||
quote_expr!(cx, &self.$ident)
|
||||
quote!(&self.#ident)
|
||||
};
|
||||
|
||||
let key_expr = name_expr(builder, field.attrs.name());
|
||||
let key_expr = field.attrs.name().serialize_name();
|
||||
|
||||
let skip = field.attrs.skip_serializing_if()
|
||||
.map(|path| quote_expr!(cx, $path($field_expr)))
|
||||
.unwrap_or(quote_expr!(cx, false));
|
||||
.map(|path| quote!(#path(#field_expr)));
|
||||
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(cx, builder,
|
||||
&structure_ty, generics, &field.ty, path, field_expr)
|
||||
field_expr = wrap_serialize_with(
|
||||
&structure_ty, generics, field.ty, path, field_expr)
|
||||
}
|
||||
|
||||
quote_stmt!(cx,
|
||||
if !$skip {
|
||||
try!(_serializer.$func(&mut state, $key_expr, $field_expr));
|
||||
}
|
||||
).unwrap()
|
||||
let ser = quote! {
|
||||
try!(_serializer.#func(&mut __serde_state, #key_expr, #field_expr));
|
||||
};
|
||||
|
||||
match skip {
|
||||
None => ser,
|
||||
Some(skip) => quote!(if !#skip { #ser }),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn wrap_serialize_with(
|
||||
cx: &ExtCtxt,
|
||||
builder: &aster::AstBuilder,
|
||||
item_ty: &P<ast::Ty>,
|
||||
generics: &ast::Generics,
|
||||
field_ty: &P<ast::Ty>,
|
||||
path: &ast::Path,
|
||||
value: P<ast::Expr>,
|
||||
) -> P<ast::Expr> {
|
||||
item_ty: &syn::Ty,
|
||||
generics: &syn::Generics,
|
||||
field_ty: &syn::Ty,
|
||||
path: &syn::Path,
|
||||
value: Tokens,
|
||||
) -> Tokens {
|
||||
let where_clause = &generics.where_clause;
|
||||
|
||||
let wrapper_generics = builder.from_generics(generics.clone())
|
||||
let wrapper_generics = aster::from_generics(generics.clone())
|
||||
.add_lifetime_bound("'__a")
|
||||
.lifetime_name("'__a")
|
||||
.build();
|
||||
|
||||
let wrapper_ty = builder.path()
|
||||
let wrapper_ty = aster::path()
|
||||
.segment("__SerializeWith")
|
||||
.with_generics(wrapper_generics.clone())
|
||||
.build()
|
||||
.build();
|
||||
|
||||
quote_expr!(cx, {
|
||||
struct __SerializeWith $wrapper_generics $where_clause {
|
||||
value: &'__a $field_ty,
|
||||
phantom: ::std::marker::PhantomData<$item_ty>,
|
||||
quote!({
|
||||
struct __SerializeWith #wrapper_generics #where_clause {
|
||||
value: &'__a #field_ty,
|
||||
phantom: ::std::marker::PhantomData<#item_ty>,
|
||||
}
|
||||
|
||||
impl $wrapper_generics _serde::ser::Serialize for $wrapper_ty $where_clause {
|
||||
fn serialize<__S>(&self, __s: &mut __S) -> Result<(), __S::Error>
|
||||
impl #wrapper_generics _serde::ser::Serialize for #wrapper_ty #where_clause {
|
||||
fn serialize<__S>(&self, __s: &mut __S) -> ::std::result::Result<(), __S::Error>
|
||||
where __S: _serde::ser::Serializer
|
||||
{
|
||||
$path(self.value, __s)
|
||||
#path(self.value, __s)
|
||||
}
|
||||
}
|
||||
|
||||
__SerializeWith {
|
||||
value: $value,
|
||||
phantom: ::std::marker::PhantomData::<$item_ty>,
|
||||
value: #value,
|
||||
phantom: ::std::marker::PhantomData::<#item_ty>,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn name_expr(
|
||||
builder: &aster::AstBuilder,
|
||||
name: &attr::Name,
|
||||
) -> P<ast::Expr> {
|
||||
builder.expr().str(name.serialize_name())
|
||||
// Serialization of an empty struct results in code like:
|
||||
//
|
||||
// let mut __serde_state = try!(serializer.serialize_struct("S", 0));
|
||||
// serializer.serialize_struct_end(__serde_state)
|
||||
//
|
||||
// where we want to omit the `mut` to avoid a warning.
|
||||
fn mut_if(is_mut: bool) -> Option<Tokens> {
|
||||
if is_mut {
|
||||
Some(quote!(mut))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
use syntax::ast;
|
||||
use syntax::codemap::{self, ExpnId, Span};
|
||||
use syntax::ext::base::{Annotatable, ExtCtxt};
|
||||
use syntax::fold::{self, Folder};
|
||||
use syntax::parse::token::intern;
|
||||
use syntax::ptr::P;
|
||||
|
||||
pub fn record_expansion(
|
||||
cx: &ExtCtxt,
|
||||
item: P<ast::Item>,
|
||||
derive: &str,
|
||||
) -> Annotatable {
|
||||
let info = codemap::ExpnInfo {
|
||||
call_site: codemap::DUMMY_SP,
|
||||
callee: codemap::NameAndSpan {
|
||||
format: codemap::MacroAttribute(intern(&format!("derive({})", derive))),
|
||||
span: None,
|
||||
allow_internal_unstable: false,
|
||||
},
|
||||
};
|
||||
let expn_id = cx.codemap().record_expansion(info);
|
||||
|
||||
let mut respanner = Respanner { expn_id: expn_id };
|
||||
let item = item.map(|item| respanner.fold_item_simple(item));
|
||||
Annotatable::Item(item)
|
||||
}
|
||||
|
||||
struct Respanner {
|
||||
expn_id: ExpnId,
|
||||
}
|
||||
|
||||
impl Folder for Respanner {
|
||||
fn new_span(&mut self, span: Span) -> Span {
|
||||
Span {
|
||||
expn_id: self.expn_id,
|
||||
.. span
|
||||
}
|
||||
}
|
||||
|
||||
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
|
||||
fold::noop_fold_mac(mac, self)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde_codegen_internals"
|
||||
version = "0.6.1"
|
||||
version = "0.11.3"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "AST representation used by Serde codegen. Unstable."
|
||||
@@ -11,11 +11,8 @@ keywords = ["serde", "serialization"]
|
||||
include = ["Cargo.toml", "src/**/*.rs"]
|
||||
|
||||
[features]
|
||||
default = ["with-syntex"]
|
||||
unstable-testing = ["clippy"]
|
||||
with-syntex = ["syntex_syntax", "syntex_errors"]
|
||||
|
||||
[dependencies]
|
||||
clippy = { version = "^0.*", optional = true }
|
||||
syntex_syntax = { version = "^0.41.0", optional = true }
|
||||
syntex_errors = { version = "^0.41.0", optional = true }
|
||||
syn = "0.10"
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
use syntax::ast;
|
||||
use syntax::codemap;
|
||||
use syntax::ext::base::ExtCtxt;
|
||||
use syntax::ptr::P;
|
||||
|
||||
use syn;
|
||||
use attr;
|
||||
use Error;
|
||||
use Ctxt;
|
||||
|
||||
pub struct Item<'a> {
|
||||
pub ident: ast::Ident,
|
||||
pub span: codemap::Span,
|
||||
pub ident: syn::Ident,
|
||||
pub attrs: attr::Item,
|
||||
pub body: Body<'a>,
|
||||
pub generics: &'a ast::Generics,
|
||||
pub generics: &'a syn::Generics,
|
||||
}
|
||||
|
||||
pub enum Body<'a> {
|
||||
@@ -20,18 +15,16 @@ pub enum Body<'a> {
|
||||
}
|
||||
|
||||
pub struct Variant<'a> {
|
||||
pub ident: ast::Ident,
|
||||
pub span: codemap::Span,
|
||||
pub ident: syn::Ident,
|
||||
pub attrs: attr::Variant,
|
||||
pub style: Style,
|
||||
pub fields: Vec<Field<'a>>,
|
||||
}
|
||||
|
||||
pub struct Field<'a> {
|
||||
pub ident: Option<ast::Ident>,
|
||||
pub span: codemap::Span,
|
||||
pub ident: Option<syn::Ident>,
|
||||
pub attrs: attr::Field,
|
||||
pub ty: &'a P<ast::Ty>,
|
||||
pub ty: &'a syn::Ty,
|
||||
}
|
||||
|
||||
pub enum Style {
|
||||
@@ -42,33 +35,25 @@ pub enum Style {
|
||||
}
|
||||
|
||||
impl<'a> Item<'a> {
|
||||
pub fn from_ast(
|
||||
cx: &ExtCtxt,
|
||||
item: &'a ast::Item,
|
||||
) -> Result<Item<'a>, Error> {
|
||||
pub fn from_ast(cx: &Ctxt, item: &'a syn::MacroInput) -> Item<'a> {
|
||||
let attrs = attr::Item::from_ast(cx, item);
|
||||
|
||||
let (body, generics) = match item.node {
|
||||
ast::ItemKind::Enum(ref enum_def, ref generics) => {
|
||||
let variants = enum_from_ast(cx, enum_def);
|
||||
(Body::Enum(variants), generics)
|
||||
let body = match item.body {
|
||||
syn::Body::Enum(ref variants) => {
|
||||
Body::Enum(enum_from_ast(cx, variants))
|
||||
}
|
||||
ast::ItemKind::Struct(ref variant_data, ref generics) => {
|
||||
syn::Body::Struct(ref variant_data) => {
|
||||
let (style, fields) = struct_from_ast(cx, variant_data);
|
||||
(Body::Struct(style, fields), generics)
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::UnexpectedItemKind);
|
||||
Body::Struct(style, fields)
|
||||
}
|
||||
};
|
||||
|
||||
Ok(Item {
|
||||
ident: item.ident,
|
||||
span: item.span,
|
||||
Item {
|
||||
ident: item.ident.clone(),
|
||||
attrs: attrs,
|
||||
body: body,
|
||||
generics: generics,
|
||||
})
|
||||
generics: &item.generics,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,16 +71,12 @@ impl<'a> Body<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn enum_from_ast<'a>(
|
||||
cx: &ExtCtxt,
|
||||
enum_def: &'a ast::EnumDef,
|
||||
) -> Vec<Variant<'a>> {
|
||||
enum_def.variants.iter()
|
||||
fn enum_from_ast<'a>(cx: &Ctxt, variants: &'a [syn::Variant]) -> Vec<Variant<'a>> {
|
||||
variants.iter()
|
||||
.map(|variant| {
|
||||
let (style, fields) = struct_from_ast(cx, &variant.node.data);
|
||||
let (style, fields) = struct_from_ast(cx, &variant.data);
|
||||
Variant {
|
||||
ident: variant.node.name,
|
||||
span: variant.span,
|
||||
ident: variant.ident.clone(),
|
||||
attrs: attr::Variant::from_ast(cx, variant),
|
||||
style: style,
|
||||
fields: fields,
|
||||
@@ -104,36 +85,29 @@ fn enum_from_ast<'a>(
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn struct_from_ast<'a>(
|
||||
cx: &ExtCtxt,
|
||||
variant_data: &'a ast::VariantData,
|
||||
) -> (Style, Vec<Field<'a>>) {
|
||||
match *variant_data {
|
||||
ast::VariantData::Struct(ref fields, _) => {
|
||||
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))
|
||||
}
|
||||
ast::VariantData::Tuple(ref fields, _) if fields.len() == 1 => {
|
||||
syn::VariantData::Tuple(ref fields) if fields.len() == 1 => {
|
||||
(Style::Newtype, fields_from_ast(cx, fields))
|
||||
}
|
||||
ast::VariantData::Tuple(ref fields, _) => {
|
||||
syn::VariantData::Tuple(ref fields) => {
|
||||
(Style::Tuple, fields_from_ast(cx, fields))
|
||||
}
|
||||
ast::VariantData::Unit(_) => {
|
||||
syn::VariantData::Unit => {
|
||||
(Style::Unit, Vec::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fields_from_ast<'a>(
|
||||
cx: &ExtCtxt,
|
||||
fields: &'a [ast::StructField],
|
||||
) -> Vec<Field<'a>> {
|
||||
fn fields_from_ast<'a>(cx: &Ctxt, fields: &'a [syn::Field]) -> Vec<Field<'a>> {
|
||||
fields.iter()
|
||||
.enumerate()
|
||||
.map(|(i, field)| {
|
||||
Field {
|
||||
ident: field.ident,
|
||||
span: field.span,
|
||||
ident: field.ident.clone(),
|
||||
attrs: attr::Field::from_ast(cx, i, field),
|
||||
ty: &field.ty,
|
||||
}
|
||||
|
||||
+190
-287
@@ -1,16 +1,7 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use syntax::ast;
|
||||
use syntax::attr::{self, HasAttrs};
|
||||
use syntax::codemap::{Span, Spanned, respan};
|
||||
use syntax::ext::base::ExtCtxt;
|
||||
use syntax::fold::Folder;
|
||||
use syntax::parse::parser::{Parser, PathStyle};
|
||||
use syntax::parse::token::{self, InternedString};
|
||||
use syntax::parse;
|
||||
use syntax::print::pprust::{lit_to_string, meta_item_to_string};
|
||||
use syntax::ptr::P;
|
||||
use syntax::tokenstream::{self, TokenTree};
|
||||
use Ctxt;
|
||||
use syn;
|
||||
use syn::MetaItem::{List, NameValue, Word};
|
||||
use syn::NestedMetaItem::{Literal, MetaItem};
|
||||
|
||||
// This module handles parsing of `#[serde(...)]` attributes. The entrypoints
|
||||
// are `attr::Item::from_ast`, `attr::Variant::from_ast`, and
|
||||
@@ -20,13 +11,14 @@ use syntax::tokenstream::{self, TokenTree};
|
||||
// user will see errors simultaneously for all bad attributes in the crate
|
||||
// rather than just the first.
|
||||
|
||||
struct Attr<'a, 'b: 'a, T> {
|
||||
cx: &'a ExtCtxt<'b>,
|
||||
struct Attr<'c, T> {
|
||||
cx: &'c Ctxt,
|
||||
name: &'static str,
|
||||
value: Option<Spanned<T>>,
|
||||
value: Option<T>,
|
||||
}
|
||||
impl<'a, 'b, T> Attr<'a, 'b, T> {
|
||||
fn none(cx: &'a ExtCtxt<'b>, name: &'static str) -> Self {
|
||||
|
||||
impl<'c, T> Attr<'c, T> {
|
||||
fn none(cx: &'c Ctxt, name: &'static str) -> Self {
|
||||
Attr {
|
||||
cx: cx,
|
||||
name: name,
|
||||
@@ -34,47 +26,40 @@ impl<'a, 'b, T> Attr<'a, 'b, T> {
|
||||
}
|
||||
}
|
||||
|
||||
fn set(&mut self, span: Span, t: T) {
|
||||
if let Some(Spanned { span: prev_span, .. }) = self.value {
|
||||
let mut err = self.cx.struct_span_err(
|
||||
span,
|
||||
&format!("duplicate serde attribute `{}`", self.name));
|
||||
err.span_help(prev_span, "previously set here");
|
||||
err.emit();
|
||||
fn set(&mut self, value: T) {
|
||||
if self.value.is_some() {
|
||||
self.cx.error(format!("duplicate serde attribute `{}`", self.name));
|
||||
} else {
|
||||
self.value = Some(respan(span, t));
|
||||
self.value = Some(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_opt(&mut self, v: Option<Spanned<T>>) {
|
||||
if let Some(v) = v {
|
||||
self.set(v.span, v.node);
|
||||
fn set_opt(&mut self, value: Option<T>) {
|
||||
if let Some(value) = value {
|
||||
self.set(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_if_none(&mut self, span: Span, t: T) {
|
||||
fn set_if_none(&mut self, value: T) {
|
||||
if self.value.is_none() {
|
||||
self.value = Some(respan(span, t));
|
||||
self.value = Some(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn get(self) -> Option<T> {
|
||||
self.value.map(|spanned| spanned.node)
|
||||
}
|
||||
|
||||
fn get_spanned(self) -> Option<Spanned<T>> {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
|
||||
struct BoolAttr<'a, 'b: 'a>(Attr<'a, 'b, ()>);
|
||||
impl<'a, 'b> BoolAttr<'a, 'b> {
|
||||
fn none(cx: &'a ExtCtxt<'b>, name: &'static str) -> Self {
|
||||
struct BoolAttr<'c>(Attr<'c, ()>);
|
||||
|
||||
impl<'c> BoolAttr<'c> {
|
||||
fn none(cx: &'c Ctxt, name: &'static str) -> Self {
|
||||
BoolAttr(Attr::none(cx, name))
|
||||
}
|
||||
|
||||
fn set_true(&mut self, span: Span) {
|
||||
self.0.set(span, ());
|
||||
fn set_true(&mut self) {
|
||||
self.0.set(());
|
||||
}
|
||||
|
||||
fn get(&self) -> bool {
|
||||
@@ -84,18 +69,18 @@ impl<'a, 'b> BoolAttr<'a, 'b> {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Name {
|
||||
serialize: InternedString,
|
||||
deserialize: InternedString,
|
||||
serialize: String,
|
||||
deserialize: String,
|
||||
}
|
||||
|
||||
impl Name {
|
||||
/// Return the container name for the container when serializing.
|
||||
pub fn serialize_name(&self) -> InternedString {
|
||||
pub fn serialize_name(&self) -> String {
|
||||
self.serialize.clone()
|
||||
}
|
||||
|
||||
/// Return the container name for the container when deserializing.
|
||||
pub fn deserialize_name(&self) -> InternedString {
|
||||
pub fn deserialize_name(&self) -> String {
|
||||
self.deserialize.clone()
|
||||
}
|
||||
}
|
||||
@@ -105,35 +90,32 @@ impl Name {
|
||||
pub struct Item {
|
||||
name: Name,
|
||||
deny_unknown_fields: bool,
|
||||
ser_bound: Option<Vec<ast::WherePredicate>>,
|
||||
de_bound: Option<Vec<ast::WherePredicate>>,
|
||||
ser_bound: Option<Vec<syn::WherePredicate>>,
|
||||
de_bound: Option<Vec<syn::WherePredicate>>,
|
||||
}
|
||||
|
||||
impl Item {
|
||||
/// Extract out the `#[serde(...)]` attributes from an item.
|
||||
pub fn from_ast(cx: &ExtCtxt, item: &ast::Item) -> Self {
|
||||
pub fn from_ast(cx: &Ctxt, item: &syn::MacroInput) -> Self {
|
||||
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 ser_bound = Attr::none(cx, "bound");
|
||||
let mut de_bound = Attr::none(cx, "bound");
|
||||
|
||||
let ident = item.ident.name.as_str();
|
||||
|
||||
for meta_items in item.attrs().iter().filter_map(get_serde_meta_items) {
|
||||
for meta_items in item.attrs.iter().filter_map(get_serde_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
let span = meta_item.span;
|
||||
match meta_item.node {
|
||||
match meta_item {
|
||||
// Parse `#[serde(rename="foo")]`
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
|
||||
if let Ok(s) = get_str_from_lit(cx, name, lit) {
|
||||
ser_name.set(span, s.clone());
|
||||
de_name.set(span, s);
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "rename" => {
|
||||
if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
ser_name.set(s.clone());
|
||||
de_name.set(s);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
|
||||
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
|
||||
MetaItem(List(ref name, ref meta_items)) if name == "rename" => {
|
||||
if let Ok((ser, de)) = get_renames(cx, meta_items) {
|
||||
ser_name.set_opt(ser);
|
||||
de_name.set_opt(de);
|
||||
@@ -141,31 +123,33 @@ impl Item {
|
||||
}
|
||||
|
||||
// Parse `#[serde(deny_unknown_fields)]`
|
||||
ast::MetaItemKind::Word(ref name) if name == &"deny_unknown_fields" => {
|
||||
deny_unknown_fields.set_true(span);
|
||||
MetaItem(Word(ref name)) if name == "deny_unknown_fields" => {
|
||||
deny_unknown_fields.set_true();
|
||||
}
|
||||
|
||||
// Parse `#[serde(bound="D: Serialize")]`
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"bound" => {
|
||||
if let Ok(where_predicates) = parse_lit_into_where(cx, name, lit) {
|
||||
ser_bound.set(span, where_predicates.clone());
|
||||
de_bound.set(span, where_predicates);
|
||||
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) {
|
||||
ser_bound.set(where_predicates.clone());
|
||||
de_bound.set(where_predicates);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(bound(serialize="D: Serialize", deserialize="D: Deserialize"))]`
|
||||
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"bound" => {
|
||||
MetaItem(List(ref name, ref meta_items)) if name == "bound" => {
|
||||
if let Ok((ser, de)) = get_where_predicates(cx, meta_items) {
|
||||
ser_bound.set_opt(ser);
|
||||
de_bound.set_opt(de);
|
||||
}
|
||||
}
|
||||
|
||||
_ => {
|
||||
cx.span_err(
|
||||
meta_item.span,
|
||||
&format!("unknown serde container attribute `{}`",
|
||||
meta_item_to_string(meta_item)));
|
||||
MetaItem(ref meta_item) => {
|
||||
cx.error(format!("unknown serde container attribute `{}`",
|
||||
meta_item.name()));
|
||||
}
|
||||
|
||||
Literal(_) => {
|
||||
cx.error(format!("unexpected literal in serde container attribute"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -173,8 +157,8 @@ impl Item {
|
||||
|
||||
Item {
|
||||
name: Name {
|
||||
serialize: ser_name.get().unwrap_or(ident.clone()),
|
||||
deserialize: de_name.get().unwrap_or(ident),
|
||||
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(),
|
||||
ser_bound: ser_bound.get(),
|
||||
@@ -190,11 +174,11 @@ impl Item {
|
||||
self.deny_unknown_fields
|
||||
}
|
||||
|
||||
pub fn ser_bound(&self) -> Option<&[ast::WherePredicate]> {
|
||||
pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> {
|
||||
self.ser_bound.as_ref().map(|vec| &vec[..])
|
||||
}
|
||||
|
||||
pub fn de_bound(&self) -> Option<&[ast::WherePredicate]> {
|
||||
pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
|
||||
self.de_bound.as_ref().map(|vec| &vec[..])
|
||||
}
|
||||
}
|
||||
@@ -203,40 +187,51 @@ impl Item {
|
||||
#[derive(Debug)]
|
||||
pub struct Variant {
|
||||
name: Name,
|
||||
skip_deserializing: bool,
|
||||
skip_serializing: bool,
|
||||
}
|
||||
|
||||
impl Variant {
|
||||
pub fn from_ast(cx: &ExtCtxt, variant: &ast::Variant) -> Self {
|
||||
pub fn from_ast(cx: &Ctxt, variant: &syn::Variant) -> Self {
|
||||
let mut ser_name = Attr::none(cx, "rename");
|
||||
let mut de_name = Attr::none(cx, "rename");
|
||||
let mut skip_deserializing = BoolAttr::none(cx, "skip_deserializing");
|
||||
let mut skip_serializing = BoolAttr::none(cx, "skip_serializing");
|
||||
|
||||
let ident = variant.node.name.name.as_str();
|
||||
|
||||
for meta_items in variant.node.attrs.iter().filter_map(get_serde_meta_items) {
|
||||
for meta_items in variant.attrs.iter().filter_map(get_serde_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
let span = meta_item.span;
|
||||
match meta_item.node {
|
||||
match meta_item {
|
||||
// Parse `#[serde(rename="foo")]`
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
|
||||
if let Ok(s) = get_str_from_lit(cx, name, lit) {
|
||||
ser_name.set(span, s.clone());
|
||||
de_name.set(span, s);
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "rename" => {
|
||||
if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
ser_name.set(s.clone());
|
||||
de_name.set(s);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
|
||||
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
|
||||
MetaItem(List(ref name, ref meta_items)) if name == "rename" => {
|
||||
if let Ok((ser, de)) = get_renames(cx, meta_items) {
|
||||
ser_name.set_opt(ser);
|
||||
de_name.set_opt(de);
|
||||
}
|
||||
}
|
||||
// Parse `#[serde(skip_deserializing)]`
|
||||
MetaItem(Word(ref name)) if name == "skip_deserializing" => {
|
||||
skip_deserializing.set_true();
|
||||
}
|
||||
// Parse `#[serde(skip_serializing)]`
|
||||
MetaItem(Word(ref name)) if name == "skip_serializing" => {
|
||||
skip_serializing.set_true();
|
||||
}
|
||||
|
||||
_ => {
|
||||
cx.span_err(
|
||||
meta_item.span,
|
||||
&format!("unknown serde variant attribute `{}`",
|
||||
meta_item_to_string(meta_item)));
|
||||
MetaItem(ref meta_item) => {
|
||||
cx.error(format!("unknown serde variant attribute `{}`",
|
||||
meta_item.name()));
|
||||
}
|
||||
|
||||
Literal(_) => {
|
||||
cx.error(format!("unexpected literal in serde variant attribute"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -244,15 +239,25 @@ impl Variant {
|
||||
|
||||
Variant {
|
||||
name: Name {
|
||||
serialize: ser_name.get().unwrap_or(ident.clone()),
|
||||
deserialize: de_name.get().unwrap_or(ident),
|
||||
serialize: ser_name.get().unwrap_or_else(|| variant.ident.to_string()),
|
||||
deserialize: de_name.get().unwrap_or_else(|| variant.ident.to_string()),
|
||||
},
|
||||
skip_deserializing: skip_deserializing.get(),
|
||||
skip_serializing: skip_serializing.get(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &Name {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub fn skip_deserializing(&self) -> bool {
|
||||
self.skip_deserializing
|
||||
}
|
||||
|
||||
pub fn skip_serializing(&self) -> bool {
|
||||
self.skip_serializing
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents field attribute information
|
||||
@@ -261,12 +266,12 @@ pub struct Field {
|
||||
name: Name,
|
||||
skip_serializing: bool,
|
||||
skip_deserializing: bool,
|
||||
skip_serializing_if: Option<ast::Path>,
|
||||
skip_serializing_if: Option<syn::Path>,
|
||||
default: FieldDefault,
|
||||
serialize_with: Option<ast::Path>,
|
||||
deserialize_with: Option<ast::Path>,
|
||||
ser_bound: Option<Vec<ast::WherePredicate>>,
|
||||
de_bound: Option<Vec<ast::WherePredicate>>,
|
||||
serialize_with: Option<syn::Path>,
|
||||
deserialize_with: Option<syn::Path>,
|
||||
ser_bound: Option<Vec<syn::WherePredicate>>,
|
||||
de_bound: Option<Vec<syn::WherePredicate>>,
|
||||
}
|
||||
|
||||
/// Represents the default to use for a field when deserializing.
|
||||
@@ -277,14 +282,14 @@ pub enum FieldDefault {
|
||||
/// The default is given by `std::default::Default::default()`.
|
||||
Default,
|
||||
/// The default is given by this function.
|
||||
Path(ast::Path),
|
||||
Path(syn::Path),
|
||||
}
|
||||
|
||||
impl Field {
|
||||
/// Extract out the `#[serde(...)]` attributes from a struct field.
|
||||
pub fn from_ast(cx: &ExtCtxt,
|
||||
pub fn from_ast(cx: &Ctxt,
|
||||
index: usize,
|
||||
field: &ast::StructField) -> Self {
|
||||
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");
|
||||
@@ -297,24 +302,23 @@ impl Field {
|
||||
let mut de_bound = Attr::none(cx, "bound");
|
||||
|
||||
let ident = match field.ident {
|
||||
Some(ident) => ident.name.as_str(),
|
||||
None => token::intern_and_get_ident(&index.to_string()),
|
||||
Some(ref ident) => ident.to_string(),
|
||||
None => index.to_string(),
|
||||
};
|
||||
|
||||
for meta_items in field.attrs.iter().filter_map(get_serde_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
let span = meta_item.span;
|
||||
match meta_item.node {
|
||||
match meta_item {
|
||||
// Parse `#[serde(rename="foo")]`
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
|
||||
if let Ok(s) = get_str_from_lit(cx, name, lit) {
|
||||
ser_name.set(span, s.clone());
|
||||
de_name.set(span, s);
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "rename" => {
|
||||
if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) {
|
||||
ser_name.set(s.clone());
|
||||
de_name.set(s);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
|
||||
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
|
||||
MetaItem(List(ref name, ref meta_items)) if name == "rename" => {
|
||||
if let Ok((ser, de)) = get_renames(cx, meta_items) {
|
||||
ser_name.set_opt(ser);
|
||||
de_name.set_opt(de);
|
||||
@@ -322,69 +326,71 @@ impl Field {
|
||||
}
|
||||
|
||||
// Parse `#[serde(default)]`
|
||||
ast::MetaItemKind::Word(ref name) if name == &"default" => {
|
||||
default.set(span, FieldDefault::Default);
|
||||
MetaItem(Word(ref name)) if name == "default" => {
|
||||
default.set(FieldDefault::Default);
|
||||
}
|
||||
|
||||
// Parse `#[serde(default="...")]`
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"default" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name, lit) {
|
||||
default.set(span, FieldDefault::Path(path));
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(skip_serializing)]`
|
||||
ast::MetaItemKind::Word(ref name) if name == &"skip_serializing" => {
|
||||
skip_serializing.set_true(span);
|
||||
MetaItem(Word(ref name)) if name == "skip_serializing" => {
|
||||
skip_serializing.set_true();
|
||||
}
|
||||
|
||||
// Parse `#[serde(skip_deserializing)]`
|
||||
ast::MetaItemKind::Word(ref name) if name == &"skip_deserializing" => {
|
||||
skip_deserializing.set_true(span);
|
||||
MetaItem(Word(ref name)) if name == "skip_deserializing" => {
|
||||
skip_deserializing.set_true();
|
||||
}
|
||||
|
||||
// Parse `#[serde(skip_serializing_if="...")]`
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"skip_serializing_if" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name, lit) {
|
||||
skip_serializing_if.set(span, path);
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "skip_serializing_if" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
|
||||
skip_serializing_if.set(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(serialize_with="...")]`
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"serialize_with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name, lit) {
|
||||
serialize_with.set(span, path);
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "serialize_with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
|
||||
serialize_with.set(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(deserialize_with="...")]`
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"deserialize_with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name, lit) {
|
||||
deserialize_with.set(span, path);
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "deserialize_with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
|
||||
deserialize_with.set(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(bound="D: Serialize")]`
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"bound" => {
|
||||
if let Ok(where_predicates) = parse_lit_into_where(cx, name, lit) {
|
||||
ser_bound.set(span, where_predicates.clone());
|
||||
de_bound.set(span, where_predicates);
|
||||
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) {
|
||||
ser_bound.set(where_predicates.clone());
|
||||
de_bound.set(where_predicates);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(bound(serialize="D: Serialize", deserialize="D: Deserialize"))]`
|
||||
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"bound" => {
|
||||
MetaItem(List(ref name, ref meta_items)) if name == "bound" => {
|
||||
if let Ok((ser, de)) = get_where_predicates(cx, meta_items) {
|
||||
ser_bound.set_opt(ser);
|
||||
de_bound.set_opt(de);
|
||||
}
|
||||
}
|
||||
|
||||
_ => {
|
||||
cx.span_err(
|
||||
meta_item.span,
|
||||
&format!("unknown serde field attribute `{}`",
|
||||
meta_item_to_string(meta_item)));
|
||||
MetaItem(ref meta_item) => {
|
||||
cx.error(format!("unknown serde field attribute `{}`",
|
||||
meta_item.name()));
|
||||
}
|
||||
|
||||
Literal(_) => {
|
||||
cx.error(format!("unexpected literal in serde field attribute"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -392,8 +398,8 @@ impl Field {
|
||||
|
||||
// Is skip_deserializing, initialize the field to Default::default()
|
||||
// unless a different default is specified by `#[serde(default="...")]`
|
||||
if let Some(Spanned { span, .. }) = skip_deserializing.0.value {
|
||||
default.set_if_none(span, FieldDefault::Default);
|
||||
if skip_deserializing.0.value.is_some() {
|
||||
default.set_if_none(FieldDefault::Default);
|
||||
}
|
||||
|
||||
Field {
|
||||
@@ -424,7 +430,7 @@ impl Field {
|
||||
self.skip_deserializing
|
||||
}
|
||||
|
||||
pub fn skip_serializing_if(&self) -> Option<&ast::Path> {
|
||||
pub fn skip_serializing_if(&self) -> Option<&syn::Path> {
|
||||
self.skip_serializing_if.as_ref()
|
||||
}
|
||||
|
||||
@@ -432,209 +438,106 @@ impl Field {
|
||||
&self.default
|
||||
}
|
||||
|
||||
pub fn serialize_with(&self) -> Option<&ast::Path> {
|
||||
pub fn serialize_with(&self) -> Option<&syn::Path> {
|
||||
self.serialize_with.as_ref()
|
||||
}
|
||||
|
||||
pub fn deserialize_with(&self) -> Option<&ast::Path> {
|
||||
pub fn deserialize_with(&self) -> Option<&syn::Path> {
|
||||
self.deserialize_with.as_ref()
|
||||
}
|
||||
|
||||
pub fn ser_bound(&self) -> Option<&[ast::WherePredicate]> {
|
||||
pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> {
|
||||
self.ser_bound.as_ref().map(|vec| &vec[..])
|
||||
}
|
||||
|
||||
pub fn de_bound(&self) -> Option<&[ast::WherePredicate]> {
|
||||
pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
|
||||
self.de_bound.as_ref().map(|vec| &vec[..])
|
||||
}
|
||||
}
|
||||
|
||||
type SerAndDe<T> = (Option<Spanned<T>>, Option<Spanned<T>>);
|
||||
type SerAndDe<T> = (Option<T>, Option<T>);
|
||||
|
||||
fn get_ser_and_de<T, F>(
|
||||
cx: &ExtCtxt,
|
||||
attribute: &'static str,
|
||||
items: &[P<ast::MetaItem>],
|
||||
cx: &Ctxt,
|
||||
attr_name: &'static str,
|
||||
items: &[syn::NestedMetaItem],
|
||||
f: F
|
||||
) -> Result<SerAndDe<T>, ()>
|
||||
where F: Fn(&ExtCtxt, &str, &ast::Lit) -> Result<T, ()>,
|
||||
where F: Fn(&Ctxt, &str, &str, &syn::Lit) -> Result<T, ()>,
|
||||
{
|
||||
let mut ser_item = Attr::none(cx, attribute);
|
||||
let mut de_item = Attr::none(cx, attribute);
|
||||
let mut ser_item = Attr::none(cx, attr_name);
|
||||
let mut de_item = Attr::none(cx, attr_name);
|
||||
|
||||
for item in items {
|
||||
match item.node {
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"serialize" => {
|
||||
if let Ok(v) = f(cx, name, lit) {
|
||||
ser_item.set(item.span, v);
|
||||
match *item {
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "serialize" => {
|
||||
if let Ok(v) = f(cx, attr_name, name.as_ref(), lit) {
|
||||
ser_item.set(v);
|
||||
}
|
||||
}
|
||||
|
||||
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"deserialize" => {
|
||||
if let Ok(v) = f(cx, name, lit) {
|
||||
de_item.set(item.span, v);
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "deserialize" => {
|
||||
if let Ok(v) = f(cx, attr_name, name.as_ref(), lit) {
|
||||
de_item.set(v);
|
||||
}
|
||||
}
|
||||
|
||||
_ => {
|
||||
cx.span_err(
|
||||
item.span,
|
||||
&format!("unknown {} attribute `{}`",
|
||||
attribute,
|
||||
meta_item_to_string(item)));
|
||||
|
||||
cx.error(format!("malformed {0} attribute, expected `{0}(serialize = ..., deserialize = ...)`",
|
||||
attr_name));
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok((ser_item.get_spanned(), de_item.get_spanned()))
|
||||
Ok((ser_item.get(), de_item.get()))
|
||||
}
|
||||
|
||||
fn get_renames(
|
||||
cx: &ExtCtxt,
|
||||
items: &[P<ast::MetaItem>],
|
||||
) -> Result<SerAndDe<InternedString>, ()> {
|
||||
get_ser_and_de(cx, "rename", items, get_str_from_lit)
|
||||
cx: &Ctxt,
|
||||
items: &[syn::NestedMetaItem],
|
||||
) -> Result<SerAndDe<String>, ()> {
|
||||
get_ser_and_de(cx, "rename", items, get_string_from_lit)
|
||||
}
|
||||
|
||||
fn get_where_predicates(
|
||||
cx: &ExtCtxt,
|
||||
items: &[P<ast::MetaItem>],
|
||||
) -> Result<SerAndDe<Vec<ast::WherePredicate>>, ()> {
|
||||
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: &ast::Attribute) -> Option<&[P<ast::MetaItem>]> {
|
||||
match attr.node.value.node {
|
||||
ast::MetaItemKind::List(ref name, ref items) if name == &"serde" => {
|
||||
attr::mark_used(attr);
|
||||
Some(items)
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// This syntax folder rewrites tokens to say their spans are coming from a macro context.
|
||||
struct Respanner<'a, 'b: 'a> {
|
||||
cx: &'a ExtCtxt<'b>,
|
||||
}
|
||||
|
||||
impl<'a, 'b> Folder for Respanner<'a, 'b> {
|
||||
fn fold_tt(&mut self, tt: &TokenTree) -> TokenTree {
|
||||
match *tt {
|
||||
TokenTree::Token(span, ref tok) => {
|
||||
TokenTree::Token(
|
||||
self.new_span(span),
|
||||
self.fold_token(tok.clone())
|
||||
)
|
||||
}
|
||||
TokenTree::Delimited(span, ref delimed) => {
|
||||
TokenTree::Delimited(
|
||||
self.new_span(span),
|
||||
Rc::new(tokenstream::Delimited {
|
||||
delim: delimed.delim,
|
||||
open_span: delimed.open_span,
|
||||
tts: self.fold_tts(&delimed.tts),
|
||||
close_span: delimed.close_span,
|
||||
})
|
||||
)
|
||||
}
|
||||
TokenTree::Sequence(span, ref seq) => {
|
||||
TokenTree::Sequence(
|
||||
self.new_span(span),
|
||||
Rc::new(tokenstream::SequenceRepetition {
|
||||
tts: self.fold_tts(&seq.tts),
|
||||
separator: seq.separator.clone().map(|tok| self.fold_token(tok)),
|
||||
..**seq
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn new_span(&mut self, span: Span) -> Span {
|
||||
Span {
|
||||
lo: span.lo,
|
||||
hi: span.hi,
|
||||
expn_id: self.cx.backtrace(),
|
||||
}
|
||||
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));
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
|
||||
fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<InternedString, ()> {
|
||||
match lit.node {
|
||||
ast::LitKind::Str(ref s, _) => Ok(s.clone()),
|
||||
_ => {
|
||||
cx.span_err(
|
||||
lit.span,
|
||||
&format!("serde annotation `{}` must be a string, not `{}`",
|
||||
name,
|
||||
lit_to_string(lit)));
|
||||
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
fn parse_lit_into_path(cx: &Ctxt, attr_name: &str, lit: &syn::Lit) -> Result<syn::Path, ()> {
|
||||
let string = try!(get_string_from_lit(cx, attr_name, attr_name, lit));
|
||||
syn::parse_path(&string).map_err(|err| cx.error(err))
|
||||
}
|
||||
|
||||
// If we just parse a string literal from an attibute, any syntax errors in the
|
||||
// source will only have spans that point inside the string and not back to the
|
||||
// attribute. So to have better error reporting, we'll first parse the string
|
||||
// into a token tree. Then we'll update those spans to say they're coming from a
|
||||
// macro context that originally came from the attribnute, and then finally
|
||||
// parse them into an expression or where-clause.
|
||||
fn parse_string_via_tts<T, F>(cx: &ExtCtxt, name: &str, string: String, action: F) -> Result<T, ()>
|
||||
where F: for<'a> Fn(&'a mut Parser) -> parse::PResult<'a, T>,
|
||||
{
|
||||
let tts = panictry!(parse::parse_tts_from_source_str(
|
||||
format!("<serde {} expansion>", name),
|
||||
string,
|
||||
cx.cfg(),
|
||||
cx.parse_sess()));
|
||||
|
||||
// Respan the spans to say they are all coming from this macro.
|
||||
let tts = Respanner { cx: cx }.fold_tts(&tts);
|
||||
|
||||
let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts);
|
||||
|
||||
let path = match action(&mut parser) {
|
||||
Ok(path) => path,
|
||||
Err(mut e) => {
|
||||
e.emit();
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
|
||||
// Make sure to error out if there are trailing characters in the stream.
|
||||
match parser.expect(&token::Eof) {
|
||||
Ok(()) => { }
|
||||
Err(mut e) => {
|
||||
e.emit();
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn parse_lit_into_path(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<ast::Path, ()> {
|
||||
let string = try!(get_str_from_lit(cx, name, lit)).to_string();
|
||||
|
||||
parse_string_via_tts(cx, name, string, |parser| {
|
||||
parser.parse_path(PathStyle::Type)
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_lit_into_where(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<Vec<ast::WherePredicate>, ()> {
|
||||
let string = try!(get_str_from_lit(cx, name, lit));
|
||||
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());
|
||||
}
|
||||
|
||||
let where_string = format!("where {}", string);
|
||||
|
||||
parse_string_via_tts(cx, name, where_string, |parser| {
|
||||
let where_clause = try!(parser.parse_where_clause());
|
||||
Ok(where_clause.predicates)
|
||||
})
|
||||
syn::parse_where_clause(&where_string).map(|wh| wh.predicates).map_err(|err| cx.error(err))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
use std::fmt::Display;
|
||||
use std::cell::RefCell;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Ctxt {
|
||||
errors: RefCell<Option<Vec<String>>>,
|
||||
}
|
||||
|
||||
impl Ctxt {
|
||||
pub fn new() -> Self {
|
||||
Ctxt {
|
||||
errors: RefCell::new(Some(Vec::new())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn error<T: Display>(&self, msg: T) {
|
||||
self.errors.borrow_mut().as_mut().unwrap().push(msg.to_string());
|
||||
}
|
||||
|
||||
pub fn check(self) -> Result<(), String> {
|
||||
let mut errors = self.errors.borrow_mut().take().unwrap();
|
||||
match errors.len() {
|
||||
0 => Ok(()),
|
||||
1 => Err(errors.pop().unwrap()),
|
||||
n => {
|
||||
let mut msg = format!("{} errors:", n);
|
||||
for err in errors {
|
||||
msg.push_str("\n\t# ");
|
||||
msg.push_str(&err);
|
||||
}
|
||||
Err(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Ctxt {
|
||||
fn drop(&mut self) {
|
||||
if self.errors.borrow().is_some() {
|
||||
panic!("forgot to check for errors");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
use std::error;
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
UnexpectedItemKind,
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "expected a struct or enum")
|
||||
}
|
||||
}
|
||||
|
||||
impl error::Error for Error {
|
||||
fn description(&self) -> &str {
|
||||
"expected a struct or enum"
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,10 @@
|
||||
#![cfg_attr(feature = "clippy", plugin(clippy))]
|
||||
#![cfg_attr(feature = "clippy", feature(plugin))]
|
||||
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))]
|
||||
|
||||
#[cfg(feature = "with-syntex")]
|
||||
#[macro_use]
|
||||
extern crate syntex_syntax as syntax;
|
||||
#[cfg(feature = "with-syntex")]
|
||||
extern crate syntex_errors as errors;
|
||||
|
||||
#[cfg(not(feature = "with-syntex"))]
|
||||
#[macro_use]
|
||||
extern crate syntax;
|
||||
#[cfg(not(feature = "with-syntex"))]
|
||||
extern crate rustc_errors as errors;
|
||||
extern crate syn;
|
||||
|
||||
pub mod ast;
|
||||
pub mod attr;
|
||||
|
||||
mod error;
|
||||
pub use error::Error;
|
||||
mod ctxt;
|
||||
pub use ctxt::Ctxt;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "serde_derive"
|
||||
version = "0.8.23"
|
||||
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"]
|
||||
|
||||
[lib]
|
||||
name = "serde_derive"
|
||||
proc-macro = true
|
||||
|
||||
[dependencies.serde_codegen]
|
||||
version = "=0.8.23"
|
||||
path = "../serde_codegen"
|
||||
default-features = false
|
||||
features = ["with-syn"]
|
||||
|
||||
[dev-dependencies]
|
||||
compiletest_rs = "^0.2.0"
|
||||
fnv = "1.0"
|
||||
serde = { version = "0.8.23", path = "../serde" }
|
||||
serde_test = { version = "0.8.23", path = "../serde_test" }
|
||||
@@ -0,0 +1,20 @@
|
||||
extern crate proc_macro;
|
||||
extern crate serde_codegen;
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
|
||||
#[proc_macro_derive(Serialize, attributes(serde))]
|
||||
pub fn derive_serialize(input: TokenStream) -> TokenStream {
|
||||
match serde_codegen::expand_derive_serialize(&input.to_string()) {
|
||||
Ok(expanded) => expanded.parse().unwrap(),
|
||||
Err(msg) => panic!(msg),
|
||||
}
|
||||
}
|
||||
|
||||
#[proc_macro_derive(Deserialize, attributes(serde))]
|
||||
pub fn derive_deserialize(input: TokenStream) -> TokenStream {
|
||||
match serde_codegen::expand_derive_deserialize(&input.to_string()) {
|
||||
Ok(expanded) => expanded.parse().unwrap(),
|
||||
Err(msg) => panic!(msg),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
struct S {
|
||||
#[serde(rename="x", serialize="y")] //~^^ HELP: unknown serde field attribute `serialize`
|
||||
x: (),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,11 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
struct S {
|
||||
#[serde(rename="x")]
|
||||
#[serde(rename(deserialize="y"))] //~^^^ HELP: duplicate serde attribute `rename`
|
||||
x: (),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
struct S {
|
||||
#[serde(rename(serialize="x"), rename(serialize="y"))] //~^^ HELP: duplicate serde attribute `rename`
|
||||
x: (),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,11 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
struct S {
|
||||
#[serde(rename(serialize="x"))]
|
||||
#[serde(rename="y")] //~^^^ HELP: duplicate serde attribute `rename`
|
||||
x: (),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
struct S {
|
||||
#[serde(rename(serialize="x", serialize="y"))] //~^^ HELP: duplicate serde attribute `rename`
|
||||
x: (),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,11 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
struct S {
|
||||
#[serde(rename(serialize="x"))]
|
||||
#[serde(rename(serialize="y"))] //~^^^ HELP: duplicate serde attribute `rename`
|
||||
x: (),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,9 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize, Deserialize)] //~ ERROR: custom derive attribute panicked
|
||||
struct Test<'a> {
|
||||
s: &'a str, //~^^ HELP: Serde does not support deserializing fields of type &str
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
#[serde(abc="xyz")] //~^ HELP: unknown serde container attribute `abc`
|
||||
struct A {
|
||||
x: u32,
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
struct C {
|
||||
#[serde(abc="xyz")] //~^^ HELP: unknown serde field attribute `abc`
|
||||
x: u32,
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,10 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||
enum E {
|
||||
#[serde(abc="xyz")] //~^^ HELP: unknown serde variant attribute `abc`
|
||||
V,
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
+3
-3
@@ -1,8 +1,8 @@
|
||||
#![feature(custom_derive, plugin)]
|
||||
#![plugin(serde_macros, clippy)]
|
||||
|
||||
#![deny(identity_op)]
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
// The derived implementation uses 0+1 to add up the number of fields
|
||||
// serialized, which Clippy warns about. If the expansion info is registered
|
||||
// correctly, the Clippy lint is not triggered.
|
||||
@@ -0,0 +1,10 @@
|
||||
#![feature(test)]
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
extern crate test;
|
||||
|
||||
include!("../../testing/tests/test.rs.in");
|
||||
|
||||
mod compile_tests;
|
||||
@@ -1,2 +0,0 @@
|
||||
# To prevent compiletest from seeing two versions of serde
|
||||
paths = ["../serde"]
|
||||
@@ -1,2 +0,0 @@
|
||||
/target
|
||||
/Cargo.lock
|
||||
@@ -1,53 +0,0 @@
|
||||
[package]
|
||||
name = "serde_macros"
|
||||
version = "0.8.3"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "Macros to auto-generate implementations for the serde framework"
|
||||
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", "build.rs"]
|
||||
build = "build.rs"
|
||||
|
||||
[lib]
|
||||
name = "serde_macros"
|
||||
plugin = true
|
||||
|
||||
[features]
|
||||
unstable-testing = [
|
||||
"clippy",
|
||||
"skeptic",
|
||||
"serde_json",
|
||||
"serde/unstable-testing",
|
||||
"serde_codegen/unstable-testing"
|
||||
]
|
||||
|
||||
[build-dependencies]
|
||||
skeptic = { version = "^0.6.0", optional = true }
|
||||
|
||||
[dependencies]
|
||||
clippy = { version = "^0.*", optional = true }
|
||||
serde_codegen = { version = "=0.8.3", default-features = false, features = ["unstable"], path = "../serde_codegen" }
|
||||
skeptic = { version = "^0.6.0", optional = true }
|
||||
serde_json = { version = "0.8.0", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
compiletest_rs = "^0.2.0"
|
||||
fnv = "1.0"
|
||||
rustc-serialize = "^0.3.16"
|
||||
serde = { version = "0.8.3", path = "../serde" }
|
||||
serde_test = { version = "0.8.3", path = "../serde_test" }
|
||||
|
||||
[[test]]
|
||||
name = "test"
|
||||
path = "tests/test.rs"
|
||||
|
||||
[[test]]
|
||||
name = "skeptic"
|
||||
path = "tests/skeptic.rs"
|
||||
|
||||
[[bench]]
|
||||
name = "bench"
|
||||
path = "benches/bench.rs"
|
||||
@@ -1,9 +0,0 @@
|
||||
#![feature(custom_attribute, custom_derive, plugin, test)]
|
||||
#![cfg_attr(feature = "clippy", plugin(clippy))]
|
||||
#![plugin(serde_macros)]
|
||||
|
||||
extern crate rustc_serialize;
|
||||
extern crate serde;
|
||||
extern crate test;
|
||||
|
||||
include!("../../testing/benches/bench.rs.in");
|
||||
@@ -1,18 +0,0 @@
|
||||
#[cfg(feature = "unstable-testing")]
|
||||
mod inner {
|
||||
extern crate skeptic;
|
||||
|
||||
pub fn main() {
|
||||
println!("cargo:rerun-if-changed=../README.md");
|
||||
skeptic::generate_doc_tests(&["../README.md"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "unstable-testing"))]
|
||||
mod inner {
|
||||
pub fn main() {}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
inner::main()
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
#![feature(plugin_registrar, rustc_private)]
|
||||
#![cfg_attr(feature = "clippy", feature(plugin))]
|
||||
#![cfg_attr(feature = "clippy", plugin(clippy))]
|
||||
|
||||
extern crate serde_codegen;
|
||||
extern crate rustc_plugin;
|
||||
|
||||
#[plugin_registrar]
|
||||
#[doc(hidden)]
|
||||
pub fn plugin_registrar(reg: &mut rustc_plugin::Registry) {
|
||||
serde_codegen::register(reg);
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
#![feature(custom_attribute, custom_derive, plugin)]
|
||||
#![plugin(serde_macros)]
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct S {
|
||||
#[serde(rename(serialize="x"))]
|
||||
#[serde(rename(serialize="y"))] //~ ERROR: duplicate serde attribute `rename`
|
||||
a: (),
|
||||
|
||||
#[serde(rename(serialize="x"))]
|
||||
#[serde(rename="y")] //~ ERROR: duplicate serde attribute `rename`
|
||||
b: (),
|
||||
|
||||
#[serde(rename(serialize="x"))]
|
||||
#[serde(rename(deserialize="y"))] // ok
|
||||
c: (),
|
||||
|
||||
#[serde(rename="x")]
|
||||
#[serde(rename(deserialize="y"))] //~ ERROR: duplicate serde attribute `rename`
|
||||
d: (),
|
||||
|
||||
#[serde(rename(serialize="x", serialize="y"))] //~ ERROR: duplicate serde attribute `rename`
|
||||
e: (),
|
||||
|
||||
#[serde(rename="x", serialize="y")] //~ ERROR: unknown serde field attribute `serialize = "y"`
|
||||
f: (),
|
||||
|
||||
#[serde(rename(serialize="x"), rename(serialize="y"))] //~ ERROR: duplicate serde attribute `rename`
|
||||
g: (),
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -1,30 +0,0 @@
|
||||
#![feature(custom_attribute, custom_derive, plugin)]
|
||||
#![plugin(serde_macros)]
|
||||
|
||||
extern crate serde;
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(abc="xyz")] //~ unknown serde container attribute `abc = "xyz"`
|
||||
struct Foo {
|
||||
x: u32,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(abc="xyz")] //~ unknown serde container attribute `abc = "xyz"`
|
||||
struct Foo {
|
||||
x: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Foo {
|
||||
#[serde(abc="xyz")] //~ unknown serde field attribute `abc = "xyz"`
|
||||
x: u32,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Foo {
|
||||
#[serde(abc="xyz")] //~ unknown serde field attribute `abc = "xyz"`
|
||||
x: u32,
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -1,9 +0,0 @@
|
||||
#![feature(custom_attribute, custom_derive, plugin)]
|
||||
#![plugin(serde_macros)]
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Test<'a> {
|
||||
s: &'a str, //~ ERROR: Serde does not support deserializing fields of type &str
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -1,3 +0,0 @@
|
||||
#![cfg(feature = "unstable-testing")]
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/skeptic-tests.rs"));
|
||||
@@ -1,9 +0,0 @@
|
||||
#![feature(test, custom_attribute, custom_derive, plugin)]
|
||||
#![plugin(serde_macros)]
|
||||
|
||||
extern crate test;
|
||||
|
||||
include!("../../testing/tests/test.rs.in");
|
||||
|
||||
mod compile_tests;
|
||||
mod skeptic;
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde_test"
|
||||
version = "0.8.3"
|
||||
version = "0.8.23"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "Token De/Serializer for testing De/Serialize implementations"
|
||||
@@ -12,4 +12,4 @@ keywords = ["serde", "serialization"]
|
||||
include = ["Cargo.toml", "src/**/*.rs"]
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "0.8.3", path = "../serde" }
|
||||
serde = { version = "0.8.23", path = "../serde" }
|
||||
|
||||
+2
-5
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde_testing"
|
||||
version = "0.8.3"
|
||||
version = "0.8.23"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "A generic serialization/deserialization framework"
|
||||
@@ -10,6 +10,7 @@ documentation = "https://docs.serde.rs/serde/"
|
||||
readme = "README.md"
|
||||
keywords = ["serialization"]
|
||||
build = "build.rs"
|
||||
publish = false
|
||||
|
||||
[features]
|
||||
unstable-testing = ["clippy", "serde/unstable-testing", "serde_codegen/unstable-testing"]
|
||||
@@ -29,7 +30,3 @@ clippy = { version = "^0.*", optional = true }
|
||||
[[test]]
|
||||
name = "test"
|
||||
path = "tests/test.rs"
|
||||
|
||||
[[bench]]
|
||||
name = "bench"
|
||||
path = "benches/bench.rs"
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
#![feature(test)]
|
||||
#![cfg_attr(feature = "clippy", feature(plugin))]
|
||||
#![cfg_attr(feature = "clippy", plugin(clippy))]
|
||||
|
||||
extern crate rustc_serialize;
|
||||
extern crate serde;
|
||||
extern crate test;
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/bench.rs"));
|
||||
@@ -1,4 +0,0 @@
|
||||
mod bench_enum;
|
||||
mod bench_map;
|
||||
mod bench_struct;
|
||||
mod bench_vec;
|
||||
@@ -1,466 +0,0 @@
|
||||
use test::Bencher;
|
||||
use std::error;
|
||||
use std::fmt;
|
||||
use rustc_serialize::Decodable;
|
||||
use serde;
|
||||
use serde::de::Deserialize;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Clone, PartialEq, Debug, RustcDecodable, Deserialize)]
|
||||
pub enum Animal {
|
||||
Dog,
|
||||
Frog(String, isize)
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
EndOfStream,
|
||||
Syntax,
|
||||
}
|
||||
|
||||
impl serde::de::Error for Error {
|
||||
fn custom<T: Into<String>>(_: T) -> Error { Error::Syntax }
|
||||
|
||||
fn end_of_stream() -> Error { Error::EndOfStream }
|
||||
|
||||
fn unknown_field(_: &str) -> Error { Error::Syntax }
|
||||
|
||||
fn missing_field(_: &'static str) -> Error { Error::Syntax }
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||
formatter.write_str(format!("{:?}", self).as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl error::Error for Error {
|
||||
fn description(&self) -> &str {
|
||||
"Serde Deserialization Error"
|
||||
}
|
||||
|
||||
fn cause(&self) -> Option<&error::Error> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod decoder {
|
||||
use rustc_serialize::Decoder;
|
||||
|
||||
use super::{Animal, Error};
|
||||
use super::Animal::{Dog, Frog};
|
||||
|
||||
enum State {
|
||||
Animal(Animal),
|
||||
Isize(isize),
|
||||
String(String),
|
||||
}
|
||||
|
||||
pub struct AnimalDecoder {
|
||||
stack: Vec<State>,
|
||||
|
||||
}
|
||||
|
||||
impl AnimalDecoder {
|
||||
#[inline]
|
||||
pub fn new(animal: Animal) -> AnimalDecoder {
|
||||
AnimalDecoder {
|
||||
stack: vec!(State::Animal(animal)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Decoder for AnimalDecoder {
|
||||
type Error = Error;
|
||||
|
||||
fn error(&mut self, _: &str) -> Error { Error::Syntax }
|
||||
|
||||
// Primitive types:
|
||||
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
|
||||
fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::Syntax) }
|
||||
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
|
||||
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
|
||||
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
|
||||
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
|
||||
#[inline]
|
||||
fn read_isize(&mut self) -> Result<isize, Error> {
|
||||
match self.stack.pop() {
|
||||
Some(State::Isize(x)) => Ok(x),
|
||||
_ => Err(Error::Syntax),
|
||||
}
|
||||
}
|
||||
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
|
||||
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
|
||||
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
|
||||
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
|
||||
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
|
||||
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
|
||||
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
|
||||
fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
|
||||
#[inline]
|
||||
fn read_str(&mut self) -> Result<String, Error> {
|
||||
match self.stack.pop() {
|
||||
Some(State::String(x)) => Ok(x),
|
||||
_ => Err(Error::Syntax),
|
||||
}
|
||||
}
|
||||
|
||||
// Compound types:
|
||||
#[inline]
|
||||
fn read_enum<T, F>(&mut self, name: &str, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(State::Animal(animal)) => {
|
||||
self.stack.push(State::Animal(animal));
|
||||
if name == "Animal" {
|
||||
f(self)
|
||||
} else {
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
_ => Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_enum_variant<T, F>(&mut self, names: &[&str], f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
let name = match self.stack.pop() {
|
||||
Some(State::Animal(Dog)) => "Dog",
|
||||
Some(State::Animal(Frog(x0, x1))) => {
|
||||
self.stack.push(State::Isize(x1));
|
||||
self.stack.push(State::String(x0));
|
||||
"Frog"
|
||||
}
|
||||
_ => { return Err(Error::Syntax); }
|
||||
};
|
||||
|
||||
let idx = match names.iter().position(|n| *n == name) {
|
||||
Some(idx) => idx,
|
||||
None => { return Err(Error::Syntax); }
|
||||
};
|
||||
|
||||
f(self, idx)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
// Specialized types:
|
||||
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder, bool) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
f(self, 3)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
|
||||
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod deserializer {
|
||||
use super::{Animal, Error};
|
||||
|
||||
use serde::de;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum State {
|
||||
Animal(Animal),
|
||||
Isize(isize),
|
||||
Str(&'static str),
|
||||
String(String),
|
||||
UnitState,
|
||||
}
|
||||
|
||||
pub struct AnimalDeserializer {
|
||||
stack: Vec<State>,
|
||||
}
|
||||
|
||||
impl AnimalDeserializer {
|
||||
#[inline]
|
||||
pub fn new(animal: Animal) -> AnimalDeserializer {
|
||||
AnimalDeserializer {
|
||||
stack: vec!(State::Animal(animal)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserializer for AnimalDeserializer {
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(State::Isize(value)) => {
|
||||
visitor.visit_isize(value)
|
||||
}
|
||||
Some(State::String(value)) => {
|
||||
visitor.visit_string(value)
|
||||
}
|
||||
Some(State::Str(value)) => {
|
||||
visitor.visit_str(value)
|
||||
}
|
||||
Some(State::UnitState) => {
|
||||
visitor.visit_unit()
|
||||
}
|
||||
Some(_) => {
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
None => {
|
||||
Err(Error::EndOfStream)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn deserialize_enum<V>(&mut self,
|
||||
_name: &str,
|
||||
_variants: &[&str],
|
||||
mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::EnumVisitor,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(State::Animal(Animal::Dog)) => {
|
||||
self.stack.push(State::UnitState);
|
||||
self.stack.push(State::Str("Dog"));
|
||||
visitor.visit(DogVisitor {
|
||||
de: self,
|
||||
})
|
||||
}
|
||||
Some(State::Animal(Animal::Frog(x0, x1))) => {
|
||||
self.stack.push(State::Isize(x1));
|
||||
self.stack.push(State::String(x0));
|
||||
self.stack.push(State::Str("Frog"));
|
||||
visitor.visit(FrogVisitor {
|
||||
de: self,
|
||||
state: 0,
|
||||
})
|
||||
}
|
||||
Some(_) => {
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
None => {
|
||||
Err(Error::EndOfStream)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct DogVisitor<'a> {
|
||||
de: &'a mut AnimalDeserializer,
|
||||
}
|
||||
|
||||
impl<'a> de::VariantVisitor for DogVisitor<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_variant<V>(&mut self) -> Result<V, Error>
|
||||
where V: de::Deserialize
|
||||
{
|
||||
de::Deserialize::deserialize(self.de)
|
||||
}
|
||||
|
||||
fn visit_unit(&mut self) -> Result<(), Error> {
|
||||
de::Deserialize::deserialize(self.de)
|
||||
}
|
||||
}
|
||||
|
||||
struct FrogVisitor<'a> {
|
||||
de: &'a mut AnimalDeserializer,
|
||||
state: usize,
|
||||
}
|
||||
|
||||
impl<'a> de::VariantVisitor for FrogVisitor<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_variant<V>(&mut self) -> Result<V, Error>
|
||||
where V: de::Deserialize
|
||||
{
|
||||
de::Deserialize::deserialize(self.de)
|
||||
}
|
||||
|
||||
fn visit_tuple<V>(&mut self,
|
||||
_len: usize,
|
||||
mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
visitor.visit_seq(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> de::SeqVisitor for FrogVisitor<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
||||
where T: de::Deserialize,
|
||||
{
|
||||
match self.state {
|
||||
0 => {
|
||||
self.state += 1;
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
1 => {
|
||||
self.state += 1;
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
_ => {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
if self.state == 2 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = 2 - self.state;
|
||||
(len, Some(len))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_dog(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let animal = Animal::Dog;
|
||||
|
||||
let mut d = decoder::AnimalDecoder::new(animal.clone());
|
||||
let value: Animal = Decodable::decode(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, animal);
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_frog(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let animal = Animal::Frog("Henry".to_owned(), 349);
|
||||
|
||||
let mut d = decoder::AnimalDecoder::new(animal.clone());
|
||||
let value: Animal = Decodable::decode(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, animal);
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_dog(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let animal = Animal::Dog;
|
||||
|
||||
let mut d = deserializer::AnimalDeserializer::new(animal.clone());
|
||||
let value: Animal = Deserialize::deserialize(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, animal);
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_frog(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let animal = Animal::Frog("Henry".to_owned(), 349);
|
||||
|
||||
let mut d = deserializer::AnimalDeserializer::new(animal.clone());
|
||||
let value: Animal = Deserialize::deserialize(&mut d).unwrap();
|
||||
|
||||
assert_eq!(value, animal);
|
||||
})
|
||||
}
|
||||
@@ -1,474 +0,0 @@
|
||||
use std::fmt::Debug;
|
||||
use std::fmt;
|
||||
use std::error;
|
||||
use std::collections::HashMap;
|
||||
use test::Bencher;
|
||||
|
||||
use rustc_serialize::{Decoder, Decodable};
|
||||
|
||||
use serde;
|
||||
use serde::de::{Deserializer, Deserialize};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
pub enum Error {
|
||||
EndOfStream,
|
||||
Syntax,
|
||||
MissingField,
|
||||
}
|
||||
|
||||
impl serde::de::Error for Error {
|
||||
fn custom<T: Into<String>>(_: T) -> Error { Error::Syntax }
|
||||
|
||||
fn end_of_stream() -> Error { Error::EndOfStream }
|
||||
|
||||
fn unknown_field(_: &str) -> Error { Error::Syntax }
|
||||
|
||||
fn missing_field(_: &'static str) -> Error {
|
||||
Error::MissingField
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||
formatter.write_str(format!("{:?}", self).as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl error::Error for Error {
|
||||
fn description(&self) -> &str {
|
||||
"Serde Deserialization Error"
|
||||
}
|
||||
|
||||
fn cause(&self) -> Option<&error::Error> {
|
||||
None
|
||||
}
|
||||
}
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod decoder {
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::IntoIter;
|
||||
use rustc_serialize;
|
||||
|
||||
use super::Error;
|
||||
|
||||
enum Value {
|
||||
String(String),
|
||||
Isize(isize),
|
||||
}
|
||||
|
||||
pub struct IsizeDecoder {
|
||||
len: usize,
|
||||
iter: IntoIter<String, isize>,
|
||||
stack: Vec<Value>,
|
||||
}
|
||||
|
||||
impl IsizeDecoder {
|
||||
#[inline]
|
||||
pub fn new(values: HashMap<String, isize>) -> IsizeDecoder {
|
||||
IsizeDecoder {
|
||||
len: values.len(),
|
||||
iter: values.into_iter(),
|
||||
stack: vec!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl rustc_serialize::Decoder for IsizeDecoder {
|
||||
type Error = Error;
|
||||
|
||||
fn error(&mut self, _msg: &str) -> Error {
|
||||
Error::Syntax
|
||||
}
|
||||
|
||||
// Primitive types:
|
||||
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
|
||||
fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::Syntax) }
|
||||
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
|
||||
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
|
||||
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
|
||||
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
|
||||
#[inline]
|
||||
fn read_isize(&mut self) -> Result<isize, Error> {
|
||||
match self.stack.pop() {
|
||||
Some(Value::Isize(x)) => Ok(x),
|
||||
Some(_) => Err(Error::Syntax),
|
||||
None => Err(Error::EndOfStream),
|
||||
}
|
||||
}
|
||||
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
|
||||
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
|
||||
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
|
||||
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
|
||||
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
|
||||
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
|
||||
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
|
||||
fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
|
||||
#[inline]
|
||||
fn read_str(&mut self) -> Result<String, Error> {
|
||||
match self.stack.pop() {
|
||||
Some(Value::String(x)) => Ok(x),
|
||||
Some(_) => Err(Error::Syntax),
|
||||
None => Err(Error::EndOfStream),
|
||||
}
|
||||
}
|
||||
|
||||
// Compound types:
|
||||
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
// Specialized types:
|
||||
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder, bool) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_seq<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_seq_elt<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_map<T, F>(&mut self, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
let len = self.len;
|
||||
f(self, len)
|
||||
}
|
||||
#[inline]
|
||||
fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some((key, value)) => {
|
||||
self.stack.push(Value::Isize(value));
|
||||
self.stack.push(Value::String(key));
|
||||
f(self)
|
||||
}
|
||||
None => {
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod deserializer {
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map;
|
||||
|
||||
use super::Error;
|
||||
|
||||
use serde::de;
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
enum State {
|
||||
StartState,
|
||||
Key(String),
|
||||
Value(isize),
|
||||
}
|
||||
|
||||
pub struct IsizeDeserializer {
|
||||
stack: Vec<State>,
|
||||
iter: hash_map::IntoIter<String, isize>,
|
||||
}
|
||||
|
||||
impl IsizeDeserializer {
|
||||
#[inline]
|
||||
pub fn new(values: HashMap<String, isize>) -> IsizeDeserializer {
|
||||
IsizeDeserializer {
|
||||
stack: vec!(State::StartState),
|
||||
iter: values.into_iter(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserializer for IsizeDeserializer {
|
||||
type Error = Error;
|
||||
|
||||
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(State::StartState) => {
|
||||
visitor.visit_map(self)
|
||||
}
|
||||
Some(State::Key(key)) => {
|
||||
visitor.visit_string(key)
|
||||
}
|
||||
Some(State::Value(value)) => {
|
||||
visitor.visit_isize(value)
|
||||
}
|
||||
None => {
|
||||
Err(Error::EndOfStream)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::MapVisitor for IsizeDeserializer {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
|
||||
where K: de::Deserialize,
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some((key, value)) => {
|
||||
self.stack.push(State::Value(value));
|
||||
self.stack.push(State::Key(key));
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self))))
|
||||
}
|
||||
None => {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_value<V>(&mut self) -> Result<V, Error>
|
||||
where V: de::Deserialize,
|
||||
{
|
||||
de::Deserialize::deserialize(self)
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
match self.iter.next() {
|
||||
Some(_) => Err(Error::Syntax),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.iter.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
impl Iterator for IsizeDeserializer {
|
||||
type Item = Result<de::Token, Error>;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Result<de::Token, Error>> {
|
||||
match self.stack.pop() {
|
||||
Some(State::StartState) => {
|
||||
self.stack.push(KeyOrEndState);
|
||||
Some(Ok(de::Token::MapStart(self.len)))
|
||||
}
|
||||
Some(State::KeyOrEndState) => {
|
||||
match self.iter.next() {
|
||||
Some((key, value)) => {
|
||||
self.stack.push(Value(value));
|
||||
Some(Ok(de::Token::String(key)))
|
||||
}
|
||||
None => {
|
||||
self.stack.push(EndState);
|
||||
Some(Ok(de::Token::End))
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(State::Value(x)) => {
|
||||
self.stack.push(KeyOrEndState);
|
||||
Some(Ok(de::Token::Isize(x)))
|
||||
}
|
||||
Some(EndState) => {
|
||||
None
|
||||
}
|
||||
None => {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserializer<Error> for IsizeDeserializer {
|
||||
#[inline]
|
||||
fn end_of_stream(&mut self) -> Error {
|
||||
EndOfStream
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn syntax(&mut self, _token: de::Token, _expected: &[de::TokenKind]) -> Error {
|
||||
Syntax
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn unexpected_name(&mut self, _token: de::Token) -> Error {
|
||||
Syntax
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn conversion_error(&mut self, _token: de::Token) -> Error {
|
||||
Syntax
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn missing_field<
|
||||
T: de::Deserialize<IsizeDeserializer, Error>
|
||||
>(&mut self, _field: &'static str) -> Result<T, Error> {
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
fn run_decoder<
|
||||
D: Decoder<Error=Error>,
|
||||
T: Clone + PartialEq + Debug + Decodable
|
||||
>(mut d: D, value: T) {
|
||||
let v = Decodable::decode(&mut d);
|
||||
|
||||
assert_eq!(Ok(value), v);
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_000(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let m: HashMap<String, isize> = HashMap::new();
|
||||
run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_003(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut m: HashMap<String, isize> = HashMap::new();
|
||||
for i in 0 .. 3 {
|
||||
m.insert(i.to_string(), i);
|
||||
}
|
||||
run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_100(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut m: HashMap<String, isize> = HashMap::new();
|
||||
for i in 0 .. 100 {
|
||||
m.insert(i.to_string(), i);
|
||||
}
|
||||
run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
|
||||
})
|
||||
}
|
||||
|
||||
fn run_deserializer<D, T>(mut d: D, value: T)
|
||||
where D: Deserializer,
|
||||
D::Error: Debug + PartialEq,
|
||||
T: Clone + PartialEq + Debug + Deserialize
|
||||
{
|
||||
let v = T::deserialize(&mut d);
|
||||
|
||||
assert_eq!(Ok(value), v);
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_000(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let m: HashMap<String, isize> = HashMap::new();
|
||||
run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_003(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut m: HashMap<String, isize> = HashMap::new();
|
||||
for i in 0 .. 3 {
|
||||
m.insert(i.to_string(), i);
|
||||
}
|
||||
run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_100(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut m: HashMap<String, isize> = HashMap::new();
|
||||
for i in 0 .. 100 {
|
||||
m.insert(i.to_string(), i);
|
||||
}
|
||||
run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
|
||||
})
|
||||
}
|
||||
@@ -1,745 +0,0 @@
|
||||
use std::collections::HashMap;
|
||||
use test::Bencher;
|
||||
use std::fmt;
|
||||
use std::error;
|
||||
|
||||
use rustc_serialize::Decodable;
|
||||
|
||||
use serde;
|
||||
use serde::de::Deserialize;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Clone, PartialEq, Debug, RustcDecodable, Deserialize)]
|
||||
pub struct Inner {
|
||||
a: (),
|
||||
b: usize,
|
||||
c: HashMap<String, Option<char>>,
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Clone, PartialEq, Debug, RustcDecodable, Deserialize)]
|
||||
pub struct Outer {
|
||||
inner: Vec<Inner>,
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Error {
|
||||
EndOfStream,
|
||||
Syntax,
|
||||
MissingField,
|
||||
OtherError,
|
||||
}
|
||||
|
||||
impl serde::de::Error for Error {
|
||||
fn custom<T: Into<String>>(_: T) -> Error { Error::Syntax }
|
||||
|
||||
fn end_of_stream() -> Error { Error::EndOfStream }
|
||||
|
||||
fn unknown_field(_: &str) -> Error { Error::Syntax }
|
||||
|
||||
fn missing_field(_: &'static str) -> Error {
|
||||
Error::MissingField
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||
formatter.write_str(format!("{:?}", self).as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl error::Error for Error {
|
||||
fn description(&self) -> &str {
|
||||
"Serde Deserialization Error"
|
||||
}
|
||||
|
||||
fn cause(&self) -> Option<&error::Error> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
mod decoder {
|
||||
use std::collections::HashMap;
|
||||
use rustc_serialize::Decoder;
|
||||
|
||||
use super::{Outer, Inner, Error};
|
||||
|
||||
#[derive(Debug)]
|
||||
enum State {
|
||||
Outer(Outer),
|
||||
Inner(Inner),
|
||||
Null,
|
||||
Usize(usize),
|
||||
Char(char),
|
||||
String(String),
|
||||
Field(&'static str),
|
||||
Vec(Vec<Inner>),
|
||||
Map(HashMap<String, Option<char>>),
|
||||
Option(bool),
|
||||
}
|
||||
|
||||
pub struct OuterDecoder {
|
||||
stack: Vec<State>,
|
||||
|
||||
}
|
||||
|
||||
impl OuterDecoder {
|
||||
#[inline]
|
||||
pub fn new(animal: Outer) -> OuterDecoder {
|
||||
OuterDecoder {
|
||||
stack: vec!(State::Outer(animal)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Decoder for OuterDecoder {
|
||||
type Error = Error;
|
||||
|
||||
fn error(&mut self, _msg: &str) -> Error {
|
||||
Error::OtherError
|
||||
}
|
||||
|
||||
// Primitive types:
|
||||
#[inline]
|
||||
fn read_nil(&mut self) -> Result<(), Error> {
|
||||
match self.stack.pop() {
|
||||
Some(State::Null) => Ok(()),
|
||||
_ => Err(Error::Syntax),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn read_usize(&mut self) -> Result<usize, Error> {
|
||||
match self.stack.pop() {
|
||||
Some(State::Usize(value)) => Ok(value),
|
||||
_ => Err(Error::Syntax),
|
||||
}
|
||||
}
|
||||
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
|
||||
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
|
||||
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
|
||||
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
|
||||
fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::Syntax) }
|
||||
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
|
||||
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
|
||||
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
|
||||
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
|
||||
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
|
||||
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
|
||||
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
|
||||
#[inline]
|
||||
fn read_char(&mut self) -> Result<char, Error> {
|
||||
match self.stack.pop() {
|
||||
Some(State::Char(c)) => Ok(c),
|
||||
_ => Err(Error::Syntax),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn read_str(&mut self) -> Result<String, Error> {
|
||||
match self.stack.pop() {
|
||||
Some(State::String(value)) => Ok(value),
|
||||
_ => Err(Error::Syntax),
|
||||
}
|
||||
}
|
||||
|
||||
// Compound types:
|
||||
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_struct<T, F>(&mut self, s_name: &str, _len: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(State::Outer(Outer { inner })) => {
|
||||
if s_name == "Outer" {
|
||||
self.stack.push(State::Vec(inner));
|
||||
self.stack.push(State::Field("inner"));
|
||||
f(self)
|
||||
} else {
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
Some(State::Inner(Inner { a: (), b, c })) => {
|
||||
if s_name == "Inner" {
|
||||
self.stack.push(State::Map(c));
|
||||
self.stack.push(State::Field("c"));
|
||||
|
||||
self.stack.push(State::Usize(b));
|
||||
self.stack.push(State::Field("b"));
|
||||
|
||||
self.stack.push(State::Null);
|
||||
self.stack.push(State::Field("a"));
|
||||
f(self)
|
||||
} else {
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
_ => Err(Error::Syntax),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn read_struct_field<T, F>(&mut self, f_name: &str, _f_idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(State::Field(name)) => {
|
||||
if f_name == name {
|
||||
f(self)
|
||||
} else {
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
_ => Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
|
||||
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
// Specialized types:
|
||||
#[inline]
|
||||
fn read_option<T, F>(&mut self, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder, bool) -> Result<T, Error>,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(State::Option(b)) => f(self, b),
|
||||
_ => Err(Error::Syntax),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(State::Vec(value)) => {
|
||||
let len = value.len();
|
||||
for inner in value.into_iter().rev() {
|
||||
self.stack.push(State::Inner(inner));
|
||||
}
|
||||
f(self, len)
|
||||
}
|
||||
_ => Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_map<T, F>(&mut self, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(State::Map(map)) => {
|
||||
let len = map.len();
|
||||
for (key, value) in map {
|
||||
match value {
|
||||
Some(c) => {
|
||||
self.stack.push(State::Char(c));
|
||||
self.stack.push(State::Option(true));
|
||||
}
|
||||
None => {
|
||||
self.stack.push(State::Option(false));
|
||||
}
|
||||
}
|
||||
self.stack.push(State::String(key));
|
||||
}
|
||||
f(self, len)
|
||||
}
|
||||
_ => Err(Error::Syntax),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod deserializer {
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map;
|
||||
use std::vec;
|
||||
use super::{Outer, Inner};
|
||||
use super::Error;
|
||||
use serde::de;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum State {
|
||||
Outer(Outer),
|
||||
Inner(Inner),
|
||||
Str(&'static str),
|
||||
Null,
|
||||
Usize(usize),
|
||||
Char(char),
|
||||
String(String),
|
||||
Option(bool),
|
||||
Vec(Vec<Inner>),
|
||||
Map(HashMap<String, Option<char>>),
|
||||
}
|
||||
|
||||
pub struct OuterDeserializer {
|
||||
stack: Vec<State>,
|
||||
}
|
||||
|
||||
impl OuterDeserializer {
|
||||
#[inline]
|
||||
pub fn new(outer: Outer) -> OuterDeserializer {
|
||||
OuterDeserializer {
|
||||
stack: vec!(State::Outer(outer)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserializer for OuterDeserializer {
|
||||
type Error = Error;
|
||||
|
||||
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(State::Vec(value)) => {
|
||||
visitor.visit_seq(OuterSeqVisitor {
|
||||
de: self,
|
||||
iter: value.into_iter(),
|
||||
})
|
||||
}
|
||||
Some(State::Map(value)) => {
|
||||
visitor.visit_map(MapVisitor {
|
||||
de: self,
|
||||
iter: value.into_iter(),
|
||||
})
|
||||
}
|
||||
Some(State::Null) => {
|
||||
visitor.visit_unit()
|
||||
}
|
||||
Some(State::Usize(x)) => {
|
||||
visitor.visit_usize(x)
|
||||
}
|
||||
Some(State::Char(x)) => {
|
||||
visitor.visit_char(x)
|
||||
}
|
||||
Some(State::Str(x)) => {
|
||||
visitor.visit_str(x)
|
||||
}
|
||||
Some(State::String(x)) => {
|
||||
visitor.visit_string(x)
|
||||
}
|
||||
Some(State::Option(false)) => {
|
||||
visitor.visit_none()
|
||||
}
|
||||
Some(State::Option(true)) => {
|
||||
visitor.visit_some(self)
|
||||
}
|
||||
Some(_) => Err(Error::Syntax),
|
||||
None => Err(Error::EndOfStream),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_struct<V>(&mut self,
|
||||
name: &str,
|
||||
_fields: &'static [&'static str],
|
||||
mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
match self.stack.pop() {
|
||||
Some(State::Outer(Outer { inner })) => {
|
||||
if name != "Outer" {
|
||||
return Err(Error::Syntax);
|
||||
}
|
||||
|
||||
self.stack.push(State::Vec(inner));
|
||||
self.stack.push(State::Str("inner"));
|
||||
|
||||
visitor.visit_map(OuterMapVisitor {
|
||||
de: self,
|
||||
state: 0,
|
||||
})
|
||||
}
|
||||
Some(State::Inner(Inner { a: (), b, c })) => {
|
||||
if name != "Inner" {
|
||||
return Err(Error::Syntax);
|
||||
}
|
||||
|
||||
self.stack.push(State::Map(c));
|
||||
self.stack.push(State::Str("c"));
|
||||
|
||||
self.stack.push(State::Usize(b));
|
||||
self.stack.push(State::Str("b"));
|
||||
|
||||
self.stack.push(State::Null);
|
||||
self.stack.push(State::Str("a"));
|
||||
|
||||
visitor.visit_map(InnerMapVisitor {
|
||||
de: self,
|
||||
state: 0,
|
||||
})
|
||||
}
|
||||
_ => {
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct OuterMapVisitor<'a> {
|
||||
de: &'a mut OuterDeserializer,
|
||||
state: usize,
|
||||
}
|
||||
|
||||
impl<'a> de::MapVisitor for OuterMapVisitor<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
|
||||
where K: de::Deserialize,
|
||||
{
|
||||
match self.state {
|
||||
0 => {
|
||||
self.state += 1;
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
_ => {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_value<V>(&mut self) -> Result<V, Error>
|
||||
where V: de::Deserialize,
|
||||
{
|
||||
de::Deserialize::deserialize(self.de)
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
if self.state == 1 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = 1 - self.state;
|
||||
(len, Some(len))
|
||||
}
|
||||
}
|
||||
|
||||
struct OuterSeqVisitor<'a> {
|
||||
de: &'a mut OuterDeserializer,
|
||||
iter: vec::IntoIter<Inner>,
|
||||
}
|
||||
|
||||
impl<'a> de::SeqVisitor for OuterSeqVisitor<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
||||
where T: de::Deserialize,
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some(value) => {
|
||||
self.de.stack.push(State::Inner(value));
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
None => {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
match self.iter.next() {
|
||||
Some(_) => Err(Error::Syntax),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.iter.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
struct InnerMapVisitor<'a> {
|
||||
de: &'a mut OuterDeserializer,
|
||||
state: usize,
|
||||
}
|
||||
|
||||
impl<'a> de::MapVisitor for InnerMapVisitor<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
|
||||
where K: de::Deserialize,
|
||||
{
|
||||
match self.state {
|
||||
0 ... 2 => {
|
||||
self.state += 1;
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
_ => {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_value<V>(&mut self) -> Result<V, Error>
|
||||
where V: de::Deserialize,
|
||||
{
|
||||
de::Deserialize::deserialize(self.de)
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
if self.state == 3 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = 1 - self.state;
|
||||
(len, Some(len))
|
||||
}
|
||||
}
|
||||
|
||||
struct MapVisitor<'a> {
|
||||
de: &'a mut OuterDeserializer,
|
||||
iter: hash_map::IntoIter<String, Option<char>>,
|
||||
}
|
||||
|
||||
impl<'a> de::MapVisitor for MapVisitor<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
|
||||
where K: de::Deserialize,
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some((key, Some(value))) => {
|
||||
self.de.stack.push(State::Char(value));
|
||||
self.de.stack.push(State::Option(true));
|
||||
self.de.stack.push(State::String(key));
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
Some((key, None)) => {
|
||||
self.de.stack.push(State::Option(false));
|
||||
self.de.stack.push(State::String(key));
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
|
||||
}
|
||||
None => {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_value<V>(&mut self) -> Result<V, Error>
|
||||
where V: de::Deserialize,
|
||||
{
|
||||
de::Deserialize::deserialize(self.de)
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
match self.iter.next() {
|
||||
Some(_) => Err(Error::Syntax),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.iter.size_hint()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_0_0(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut map = HashMap::new();
|
||||
map.insert("abc".to_owned(), Some('c'));
|
||||
|
||||
let outer = Outer {
|
||||
inner: vec!(),
|
||||
};
|
||||
|
||||
let mut d = decoder::OuterDecoder::new(outer.clone());
|
||||
let value: Result<Outer, Error> = Decodable::decode(&mut d);
|
||||
|
||||
assert_eq!(value, Ok(outer));
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_1_0(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let map = HashMap::new();
|
||||
|
||||
let outer = Outer {
|
||||
inner: vec!(
|
||||
Inner {
|
||||
a: (),
|
||||
b: 5,
|
||||
c: map,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let mut d = decoder::OuterDecoder::new(outer.clone());
|
||||
let value: Result<Outer, Error> = Decodable::decode(&mut d);
|
||||
|
||||
assert_eq!(value, Ok(outer));
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_1_5(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut map = HashMap::new();
|
||||
map.insert("1".to_owned(), Some('a'));
|
||||
map.insert("2".to_owned(), None);
|
||||
map.insert("3".to_owned(), Some('b'));
|
||||
map.insert("4".to_owned(), None);
|
||||
map.insert("5".to_owned(), Some('c'));
|
||||
|
||||
let outer = Outer {
|
||||
inner: vec!(
|
||||
Inner {
|
||||
a: (),
|
||||
b: 5,
|
||||
c: map,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let mut d = decoder::OuterDecoder::new(outer.clone());
|
||||
let value: Result<Outer, Error> = Decodable::decode(&mut d);
|
||||
|
||||
assert_eq!(value, Ok(outer));
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_0_0(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let outer = Outer {
|
||||
inner: vec!(),
|
||||
};
|
||||
|
||||
let mut d = deserializer::OuterDeserializer::new(outer.clone());
|
||||
let value: Result<Outer, Error> = Deserialize::deserialize(&mut d);
|
||||
|
||||
assert_eq!(value, Ok(outer));
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_1_0(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let map = HashMap::new();
|
||||
|
||||
let outer = Outer {
|
||||
inner: vec!(
|
||||
Inner {
|
||||
a: (),
|
||||
b: 5,
|
||||
c: map,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let mut d = deserializer::OuterDeserializer::new(outer.clone());
|
||||
let value: Result<Outer, Error> = Deserialize::deserialize(&mut d);
|
||||
|
||||
assert_eq!(value, Ok(outer));
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_1_5(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut map = HashMap::new();
|
||||
map.insert("1".to_owned(), Some('a'));
|
||||
map.insert("2".to_owned(), None);
|
||||
map.insert("3".to_owned(), Some('b'));
|
||||
map.insert("4".to_owned(), None);
|
||||
map.insert("5".to_owned(), Some('c'));
|
||||
|
||||
let outer = Outer {
|
||||
inner: vec!(
|
||||
Inner {
|
||||
a: (),
|
||||
b: 5,
|
||||
c: map,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let mut d = deserializer::OuterDeserializer::new(outer.clone());
|
||||
let value: Result<Outer, Error> = Deserialize::deserialize(&mut d);
|
||||
|
||||
assert_eq!(value, Ok(outer));
|
||||
})
|
||||
}
|
||||
@@ -1,628 +0,0 @@
|
||||
use std::fmt::Debug;
|
||||
use std::fmt;
|
||||
use std::error;
|
||||
use test::Bencher;
|
||||
|
||||
use rustc_serialize::{Decoder, Decodable};
|
||||
|
||||
use serde;
|
||||
use serde::de::{Deserializer, Deserialize};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
pub enum Error {
|
||||
EndOfStream,
|
||||
Syntax,
|
||||
}
|
||||
|
||||
impl serde::de::Error for Error {
|
||||
fn custom<T: Into<String>>(_: T) -> Error { Error::Syntax }
|
||||
|
||||
fn end_of_stream() -> Error { Error::EndOfStream }
|
||||
|
||||
fn unknown_field(_: &str) -> Error { Error::Syntax }
|
||||
|
||||
fn missing_field(_: &'static str) -> Error { Error::Syntax }
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||
formatter.write_str(format!("{:?}", self).as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl error::Error for Error {
|
||||
fn description(&self) -> &str {
|
||||
"Serde Deserialization Error"
|
||||
}
|
||||
|
||||
fn cause(&self) -> Option<&error::Error> {
|
||||
None
|
||||
}
|
||||
}
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod decoder {
|
||||
use std::vec;
|
||||
use rustc_serialize;
|
||||
|
||||
use super::Error;
|
||||
|
||||
pub struct UsizeDecoder {
|
||||
len: usize,
|
||||
iter: vec::IntoIter<usize>,
|
||||
}
|
||||
|
||||
impl UsizeDecoder {
|
||||
#[inline]
|
||||
pub fn new(values: Vec<usize>) -> UsizeDecoder {
|
||||
UsizeDecoder {
|
||||
len: values.len(),
|
||||
iter: values.into_iter(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl rustc_serialize::Decoder for UsizeDecoder {
|
||||
type Error = Error;
|
||||
|
||||
fn error(&mut self, _: &str) -> Error { Error::Syntax }
|
||||
|
||||
// Primitive types:
|
||||
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
|
||||
#[inline]
|
||||
fn read_usize(&mut self) -> Result<usize, Error> {
|
||||
match self.iter.next() {
|
||||
Some(value) => Ok(value),
|
||||
None => Err(Error::EndOfStream),
|
||||
}
|
||||
}
|
||||
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
|
||||
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
|
||||
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
|
||||
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
|
||||
fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::Syntax) }
|
||||
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
|
||||
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
|
||||
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
|
||||
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
|
||||
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
|
||||
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
|
||||
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
|
||||
fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
|
||||
fn read_str(&mut self) -> Result<String, Error> { Err(Error::Syntax) }
|
||||
|
||||
// Compound types:
|
||||
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
// Specialized types:
|
||||
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder, bool) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
let len = self.len;
|
||||
f(self, len)
|
||||
}
|
||||
#[inline]
|
||||
fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
|
||||
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub struct U8Decoder {
|
||||
len: usize,
|
||||
iter: vec::IntoIter<u8>,
|
||||
}
|
||||
|
||||
impl U8Decoder {
|
||||
#[inline]
|
||||
pub fn new(values: Vec<u8>) -> U8Decoder {
|
||||
U8Decoder {
|
||||
len: values.len(),
|
||||
iter: values.into_iter(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl rustc_serialize::Decoder for U8Decoder {
|
||||
type Error = Error;
|
||||
|
||||
fn error(&mut self, _: &str) -> Error { Error::Syntax }
|
||||
|
||||
// Primitive types:
|
||||
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
|
||||
fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::Syntax) }
|
||||
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
|
||||
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
|
||||
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
|
||||
#[inline]
|
||||
fn read_u8(&mut self) -> Result<u8, Error> {
|
||||
match self.iter.next() {
|
||||
Some(value) => Ok(value),
|
||||
None => Err(Error::EndOfStream),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::Syntax) }
|
||||
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
|
||||
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
|
||||
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
|
||||
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
|
||||
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
|
||||
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
|
||||
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
|
||||
fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
|
||||
fn read_str(&mut self) -> Result<String, Error> { Err(Error::Syntax) }
|
||||
|
||||
// Compound types:
|
||||
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
// Specialized types:
|
||||
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder, bool) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
let len = self.len;
|
||||
f(self, len)
|
||||
}
|
||||
#[inline]
|
||||
fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
f(self)
|
||||
}
|
||||
|
||||
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
|
||||
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
|
||||
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
|
||||
{
|
||||
Err(Error::Syntax)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod deserializer {
|
||||
//use std::num;
|
||||
use std::vec;
|
||||
|
||||
use super::Error;
|
||||
|
||||
use serde::de;
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
enum State {
|
||||
Start,
|
||||
SepOrEnd,
|
||||
End,
|
||||
}
|
||||
|
||||
pub struct Deserializer<A> {
|
||||
state: State,
|
||||
iter: vec::IntoIter<A>,
|
||||
len: usize,
|
||||
value: Option<A>,
|
||||
}
|
||||
|
||||
impl<A> Deserializer<A> {
|
||||
#[inline]
|
||||
pub fn new(values: Vec<A>) -> Deserializer<A> {
|
||||
let len = values.len();
|
||||
Deserializer {
|
||||
state: State::Start,
|
||||
iter: values.into_iter(),
|
||||
len: len,
|
||||
value: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserializer for Deserializer<usize> {
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
match self.state {
|
||||
State::Start => {
|
||||
self.state = State::SepOrEnd;
|
||||
visitor.visit_seq(self)
|
||||
}
|
||||
State::SepOrEnd => {
|
||||
visitor.visit_usize(self.value.take().unwrap())
|
||||
}
|
||||
State::End => {
|
||||
Err(Error::EndOfStream)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::SeqVisitor for Deserializer<usize> {
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
||||
where T: de::Deserialize,
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some(value) => {
|
||||
self.len -= 1;
|
||||
self.value = Some(value);
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self))))
|
||||
}
|
||||
None => {
|
||||
self.state = State::End;
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
match self.iter.next() {
|
||||
Some(_) => Err(Error::Syntax),
|
||||
None => {
|
||||
self.state = State::End;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.len, Some(self.len))
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Deserializer for Deserializer<u8> {
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
match self.state {
|
||||
State::Start => {
|
||||
self.state = State::SepOrEnd;
|
||||
visitor.visit_seq(self)
|
||||
}
|
||||
State::SepOrEnd => {
|
||||
visitor.visit_u8(self.value.take().unwrap())
|
||||
}
|
||||
State::End => {
|
||||
Err(Error::EndOfStream)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::SeqVisitor for Deserializer<u8> {
|
||||
type Error = Error;
|
||||
|
||||
#[inline]
|
||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
||||
where T: de::Deserialize,
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some(value) => {
|
||||
self.len -= 1;
|
||||
self.value = Some(value);
|
||||
Ok(Some(try!(de::Deserialize::deserialize(self))))
|
||||
}
|
||||
None => {
|
||||
self.state = State::End;
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn end(&mut self) -> Result<(), Error> {
|
||||
match self.iter.next() {
|
||||
Some(_) => Err(Error::Syntax),
|
||||
None => {
|
||||
self.state = State::End;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.len, Some(self.len))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
fn run_decoder<
|
||||
D: Decoder<Error=Error>,
|
||||
T: Clone + PartialEq + Debug + Decodable
|
||||
>(mut d: D, value: T) {
|
||||
let v = Decodable::decode(&mut d);
|
||||
|
||||
assert_eq!(Ok(value), v);
|
||||
}
|
||||
|
||||
fn run_deserializer<D, T>(mut d: D, value: T)
|
||||
where D: Deserializer,
|
||||
D::Error: Debug + PartialEq,
|
||||
T: Clone + PartialEq + Debug + Deserialize
|
||||
{
|
||||
let v = T::deserialize(&mut d);
|
||||
|
||||
assert_eq!(Ok(value), v);
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_usize_000(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<usize> = vec!();
|
||||
run_decoder(decoder::UsizeDecoder::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_usize_003(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<usize> = vec!(1, 2, 3);
|
||||
run_decoder(decoder::UsizeDecoder::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_usize_100(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<usize> = (0 .. 100).collect();
|
||||
run_decoder(decoder::UsizeDecoder::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_u8_000(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<u8> = vec!();
|
||||
run_decoder(decoder::U8Decoder::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_u8_003(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<u8> = vec!(1, 2, 3);
|
||||
run_decoder(decoder::U8Decoder::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_decoder_u8_100(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<u8> = (0 .. 100).collect();
|
||||
run_decoder(decoder::U8Decoder::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_usize_000(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<usize> = vec!();
|
||||
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_usize_003(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<usize> = vec!(1, 2, 3);
|
||||
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_usize_100(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<usize> = (0 .. 100).collect();
|
||||
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_u8_000(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<u8> = vec!();
|
||||
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_u8_003(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<u8> = vec!(1, 2, 3);
|
||||
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_deserializer_u8_100(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let v: Vec<u8> = (0 .. 100).collect();
|
||||
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
|
||||
})
|
||||
}
|
||||
+3
-9
@@ -5,13 +5,7 @@ use std::path::Path;
|
||||
|
||||
fn main() {
|
||||
let out_dir = env::var_os("OUT_DIR").unwrap();
|
||||
|
||||
for &(src, dst) in &[
|
||||
("tests/test.rs.in", "test.rs"),
|
||||
("benches/bench.rs.in", "bench.rs"),
|
||||
] {
|
||||
let src = Path::new(src);
|
||||
let dst = Path::new(&out_dir).join(dst);
|
||||
serde_codegen::expand(&src, &dst).unwrap();
|
||||
}
|
||||
let src = Path::new("tests/test.rs.in");
|
||||
let dst = Path::new(&out_dir).join("test.rs");
|
||||
serde_codegen::expand(&src, &dst).unwrap();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
extern crate serde;
|
||||
extern crate serde_test;
|
||||
|
||||
#[macro_use]
|
||||
mod macros;
|
||||
|
||||
+40
-155
@@ -1,11 +1,13 @@
|
||||
use std::fmt;
|
||||
use std::error;
|
||||
|
||||
use serde::{Serialize, Serializer, Deserialize, Deserializer};
|
||||
use serde::{Serialize, Serializer};
|
||||
use serde::bytes::{ByteBuf, Bytes};
|
||||
use serde::ser;
|
||||
use serde::de;
|
||||
|
||||
use serde_test::{assert_de_tokens, Token};
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
@@ -286,153 +288,6 @@ impl Serializer for BytesSerializer {
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct BytesDeserializer {
|
||||
bytes: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl BytesDeserializer {
|
||||
fn new(bytes: Vec<u8>) -> Self {
|
||||
BytesDeserializer {
|
||||
bytes: Some(bytes),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deserializer for BytesDeserializer {
|
||||
type Error = Error;
|
||||
|
||||
fn deserialize<V>(&mut self, _visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
Err(Error)
|
||||
}
|
||||
|
||||
fn deserialize_bytes<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
|
||||
where V: de::Visitor,
|
||||
{
|
||||
visitor.visit_byte_buf(self.bytes.take().unwrap())
|
||||
}
|
||||
|
||||
fn deserialize_seq<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_struct_field<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_map<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_unit<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_ignored_any<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_string<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_str<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_char<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_i64<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_i32<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_i16<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_i8<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_u64<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_u32<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_u16<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_u8<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_f32<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_f64<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_bool<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_usize<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_isize<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
|
||||
where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_option<__V>(&mut self, visitor: __V)
|
||||
-> Result<__V::Value, Self::Error> where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_seq_fixed_size<__V>(&mut self, _: usize, visitor: __V)
|
||||
-> Result<__V::Value, Self::Error> where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_unit_struct<__V>(&mut self, _: &str, visitor: __V)
|
||||
-> Result<__V::Value, Self::Error> where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_newtype_struct<__V>(&mut self, _: &str, visitor: __V)
|
||||
-> Result<__V::Value, Self::Error> where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_tuple_struct<__V>(&mut self, _: &str, _: usize, visitor: __V)
|
||||
-> Result<__V::Value, Self::Error> where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_struct<__V>(&mut self, _: &str, _: &[&str], visitor: __V)
|
||||
-> Result<__V::Value, Self::Error> where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_tuple<__V>(&mut self, _: usize, visitor: __V)
|
||||
-> Result<__V::Value, Self::Error> where __V: de::Visitor {
|
||||
self.deserialize(visitor)
|
||||
}
|
||||
fn deserialize_enum<__V>(&mut self, _: &str, _: &[&str], _visitor: __V)
|
||||
-> Result<__V::Value, Self::Error> where __V: de::EnumVisitor {
|
||||
Err(Error)
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[test]
|
||||
fn test_bytes_ser_bytes() {
|
||||
let buf = vec![];
|
||||
@@ -449,12 +304,42 @@ fn test_bytes_ser_bytes() {
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[test]
|
||||
fn test_byte_buf_de_bytes() {
|
||||
let mut de = BytesDeserializer::new(vec![]);
|
||||
let bytes = Deserialize::deserialize(&mut de);
|
||||
assert_eq!(bytes, Ok(ByteBuf::new()));
|
||||
fn test_byte_buf_de() {
|
||||
let empty = ByteBuf::new();
|
||||
assert_de_tokens(&empty, &[Token::Bytes(b""),]);
|
||||
assert_de_tokens(&empty, &[Token::Str("")]);
|
||||
assert_de_tokens(&empty, &[Token::String(String::new())]);
|
||||
assert_de_tokens(&empty, &[
|
||||
Token::SeqStart(None),
|
||||
Token::SeqEnd,
|
||||
]);
|
||||
assert_de_tokens(&empty, &[
|
||||
Token::SeqStart(Some(0)),
|
||||
Token::SeqEnd,
|
||||
]);
|
||||
|
||||
let mut de = BytesDeserializer::new(vec![1, 2, 3]);
|
||||
let bytes = Deserialize::deserialize(&mut de);
|
||||
assert_eq!(bytes, Ok(ByteBuf::from(vec![1, 2, 3])));
|
||||
let buf = ByteBuf::from(vec![65, 66, 67]);
|
||||
assert_de_tokens(&buf, &[Token::Bytes(b"ABC")]);
|
||||
assert_de_tokens(&buf, &[Token::Str("ABC")]);
|
||||
assert_de_tokens(&buf, &[Token::String("ABC".to_owned())]);
|
||||
assert_de_tokens(&buf, &[
|
||||
Token::SeqStart(None),
|
||||
Token::SeqSep,
|
||||
Token::U8(65),
|
||||
Token::SeqSep,
|
||||
Token::U8(66),
|
||||
Token::SeqSep,
|
||||
Token::U8(67),
|
||||
Token::SeqEnd,
|
||||
]);
|
||||
assert_de_tokens(&buf, &[
|
||||
Token::SeqStart(Some(3)),
|
||||
Token::SeqSep,
|
||||
Token::U8(65),
|
||||
Token::SeqSep,
|
||||
Token::U8(66),
|
||||
Token::SeqSep,
|
||||
Token::U8(67),
|
||||
Token::SeqEnd,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -37,7 +37,10 @@ enum Enum {
|
||||
Unit,
|
||||
Simple(i32),
|
||||
Seq(i32, i32, i32),
|
||||
Map { a: i32, b: i32, c: i32 }
|
||||
Map { a: i32, b: i32, c: i32 },
|
||||
#[allow(dead_code)]
|
||||
#[serde(skip_deserializing)]
|
||||
Skipped,
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
@@ -215,6 +218,9 @@ declare_tests! {
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_unit_string {
|
||||
String::new() => &[Token::Unit],
|
||||
}
|
||||
test_tuple_struct {
|
||||
TupleStruct(1, 2, 3) => &[
|
||||
Token::SeqStart(Some(3)),
|
||||
@@ -802,6 +808,12 @@ declare_error_tests! {
|
||||
],
|
||||
Error::UnknownVariant("Foo".to_owned()),
|
||||
}
|
||||
test_enum_skipped_variant<Enum> {
|
||||
&[
|
||||
Token::EnumUnit("Enum", "Skipped"),
|
||||
],
|
||||
Error::UnknownVariant("Skipped".to_owned()),
|
||||
}
|
||||
test_struct_seq_too_long<Struct> {
|
||||
&[
|
||||
Token::SeqStart(Some(4)),
|
||||
|
||||
@@ -9,6 +9,11 @@ use self::serde::de::{Deserialize, Deserializer};
|
||||
use std::borrow::Cow;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
// 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;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[test]
|
||||
@@ -187,6 +192,16 @@ fn test_gen() {
|
||||
#[serde(bound(deserialize = "T::Owned: Deserialize"))]
|
||||
struct CowT<'a, T: ?Sized + 'a + ToOwned>(Cow<'a, T>);
|
||||
assert::<CowT<str>>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct EmptyStruct {}
|
||||
assert::<EmptyStruct>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum EmptyEnumVariant {
|
||||
EmptyStruct {},
|
||||
}
|
||||
assert::<EmptyEnumVariant>();
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
@@ -195,32 +210,32 @@ fn assert<T: Serialize + Deserialize>() {}
|
||||
fn assert_ser<T: Serialize>() {}
|
||||
|
||||
trait SerializeWith {
|
||||
fn serialize_with<S: Serializer>(_: &Self, _: &mut S) -> Result<(), S::Error>;
|
||||
fn serialize_with<S: Serializer>(_: &Self, _: &mut S) -> StdResult<(), S::Error>;
|
||||
}
|
||||
|
||||
trait DeserializeWith: Sized {
|
||||
fn deserialize_with<D: Deserializer>(_: &mut D) -> Result<Self, D::Error>;
|
||||
fn deserialize_with<D: Deserializer>(_: &mut D) -> StdResult<Self, D::Error>;
|
||||
}
|
||||
|
||||
// Implements neither Serialize nor Deserialize
|
||||
struct X;
|
||||
|
||||
fn ser_x<S: Serializer>(_: &X, _: &mut S) -> Result<(), S::Error> {
|
||||
fn ser_x<S: Serializer>(_: &X, _: &mut S) -> StdResult<(), S::Error> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn de_x<D: Deserializer>(_: &mut D) -> Result<X, D::Error> {
|
||||
fn de_x<D: Deserializer>(_: &mut D) -> StdResult<X, D::Error> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
impl SerializeWith for X {
|
||||
fn serialize_with<S: Serializer>(_: &Self, _: &mut S) -> Result<(), S::Error> {
|
||||
fn serialize_with<S: Serializer>(_: &Self, _: &mut S) -> StdResult<(), S::Error> {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
impl DeserializeWith for X {
|
||||
fn deserialize_with<D: Deserializer>(_: &mut D) -> Result<Self, D::Error> {
|
||||
fn deserialize_with<D: Deserializer>(_: &mut D) -> StdResult<Self, D::Error> {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -600,3 +600,28 @@ fn test_default_ty_param() {
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_enum_state_field() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
enum SomeEnum {
|
||||
Key { key: char, state: bool },
|
||||
}
|
||||
|
||||
assert_tokens(
|
||||
&SomeEnum::Key { key: 'a', state: true },
|
||||
&[
|
||||
Token::EnumMapStart("SomeEnum", "Key", 2),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("key"),
|
||||
Token::Char('a'),
|
||||
|
||||
Token::EnumMapSep,
|
||||
Token::Str("state"),
|
||||
Token::Bool(true),
|
||||
|
||||
Token::EnumMapEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -30,12 +30,20 @@ struct Struct {
|
||||
c: i32,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[derive(Serialize, PartialEq, Debug)]
|
||||
enum Enum {
|
||||
Unit,
|
||||
One(i32),
|
||||
Seq(i32, i32),
|
||||
Map { a: i32, b: i32 },
|
||||
#[serde(skip_serializing)]
|
||||
SkippedUnit,
|
||||
#[serde(skip_serializing)]
|
||||
SkippedOne(i32),
|
||||
#[serde(skip_serializing)]
|
||||
SkippedSeq(i32, i32),
|
||||
#[serde(skip_serializing)]
|
||||
SkippedMap { _a: i32, _b: i32 },
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
@@ -388,3 +396,23 @@ fn test_cannot_serialize_paths() {
|
||||
&[],
|
||||
Error::InvalidValue("Path contains invalid UTF-8 characters".to_owned()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_enum_skipped() {
|
||||
assert_ser_tokens_error(
|
||||
&Enum::SkippedUnit,
|
||||
&[],
|
||||
Error::InvalidValue("The enum variant Enum::SkippedUnit cannot be serialized".to_owned()));
|
||||
assert_ser_tokens_error(
|
||||
&Enum::SkippedOne(42),
|
||||
&[],
|
||||
Error::InvalidValue("The enum variant Enum::SkippedOne cannot be serialized".to_owned()));
|
||||
assert_ser_tokens_error(
|
||||
&Enum::SkippedSeq(1, 2),
|
||||
&[],
|
||||
Error::InvalidValue("The enum variant Enum::SkippedSeq cannot be serialized".to_owned()));
|
||||
assert_ser_tokens_error(
|
||||
&Enum::SkippedMap { _a: 1, _b: 2 },
|
||||
&[],
|
||||
Error::InvalidValue("The enum variant Enum::SkippedMap cannot be serialized".to_owned()));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user