mirror of
https://github.com/pezkuwichain/serde.git
synced 2026-04-29 12:57:55 +00:00
Compare commits
108 Commits
v0.9.0-rc1
...
v0.9.6
| Author | SHA1 | Date | |
|---|---|---|---|
| d1306a78ec | |||
| ce230adf12 | |||
| 066c9a15cf | |||
| d60fd84b7e | |||
| 02e6c04e9f | |||
| 9f04b9d6e7 | |||
| d298da0b4f | |||
| ff21d557c7 | |||
| faaa494579 | |||
| 661cdf4e00 | |||
| a55d812441 | |||
| b7ca574bb3 | |||
| d960571439 | |||
| 1ccc58e2aa | |||
| 34b39083bc | |||
| 48f4deac55 | |||
| 9a0f05d00d | |||
| b47e1a6dc3 | |||
| 39c7797633 | |||
| 368784949e | |||
| 74cf80989d | |||
| f0b4735781 | |||
| 297f373548 | |||
| 81f28da8e1 | |||
| d4bb687032 | |||
| f9bc5037f5 | |||
| 8624ca6f1d | |||
| a9b5cc4830 | |||
| c31f76321c | |||
| f2402dcf52 | |||
| 361402ac4d | |||
| c52e131a03 | |||
| c0a06bdc96 | |||
| dd13fd3a34 | |||
| 91f628727b | |||
| 571a2e4e2d | |||
| 7edcf6ec3b | |||
| e4f7d8513c | |||
| 09c69da909 | |||
| 7ee175f448 | |||
| 70ab3cdd61 | |||
| 8fb554e593 | |||
| 7a2bfdc1dd | |||
| 9046e9d7a1 | |||
| 87040b4bc4 | |||
| 68aab2424f | |||
| 9b9b697eb1 | |||
| db449c4bf2 | |||
| 948aa47687 | |||
| 3e1e42ef9b | |||
| dbdfe4f306 | |||
| e0d6b9d010 | |||
| a5b8e806f8 | |||
| d7dadd83b6 | |||
| 7612fd8e82 | |||
| 4c77af53e5 | |||
| 5d9c1aeb06 | |||
| 59e48997dd | |||
| ffcd97834f | |||
| e0c049dbf2 | |||
| 8cb6607e82 | |||
| 1ffb0570b6 | |||
| 2c1dd60575 | |||
| 24f849da2d | |||
| a5024a4238 | |||
| b105423e5e | |||
| 42c1bc2907 | |||
| c334c1c7b5 | |||
| 92668d7061 | |||
| b9d865d8e7 | |||
| fc4e370ba9 | |||
| a982d27536 | |||
| dc87826298 | |||
| a09a8a039a | |||
| ea702755a2 | |||
| d161911c63 | |||
| e27553d3df | |||
| 48eaf988bc | |||
| 73a364d4fd | |||
| 6dfdcb6ba1 | |||
| 089c7eb1d7 | |||
| 1e05fc2145 | |||
| 977612d8dd | |||
| 5855078703 | |||
| 3c88a93fb2 | |||
| 530c29466e | |||
| ea99e8b686 | |||
| 2a148112d4 | |||
| a4126e4c5a | |||
| d1325862f7 | |||
| 1f65ce75ec | |||
| 9536e52aa6 | |||
| be0c755731 | |||
| 42bc63bed8 | |||
| e41b940a3d | |||
| 88149fc0c3 | |||
| 5ecfb3b388 | |||
| 13a9f929de | |||
| e40fbe0767 | |||
| 0a10116bf5 | |||
| b1fbbfd3ce | |||
| 984ebcead0 | |||
| aa88f01cdc | |||
| 13794c1b48 | |||
| b5e64abba1 | |||
| 503ce310f5 | |||
| b26f291d93 | |||
| bc6bc9e3f0 |
+14
-24
@@ -1,27 +1,17 @@
|
|||||||
sudo: false
|
sudo: false
|
||||||
language: rust
|
language: rust
|
||||||
|
cache: cargo
|
||||||
|
|
||||||
|
# run builds for all the trains (and more)
|
||||||
rust:
|
rust:
|
||||||
- 1.12.0
|
- 1.13.0
|
||||||
- 1.13.0
|
- stable
|
||||||
- stable
|
- beta
|
||||||
- beta
|
- nightly
|
||||||
- nightly
|
|
||||||
before_script:
|
matrix:
|
||||||
- pip install 'travis-cargo<0.2' --user
|
include:
|
||||||
- export PATH=$HOME/.local/bin:$PATH
|
- rust: nightly
|
||||||
script:
|
env: CLIPPY=true
|
||||||
- (cd serde && travis-cargo build)
|
|
||||||
- (cd serde && travis-cargo --skip nightly test)
|
script: ./travis.sh
|
||||||
- (cd serde && travis-cargo --only nightly test -- --features unstable-testing)
|
|
||||||
- (cd serde && travis-cargo build -- --no-default-features)
|
|
||||||
- (cd serde && travis-cargo --only nightly build -- --no-default-features --features alloc)
|
|
||||||
- (cd serde && travis-cargo --only nightly build -- --no-default-features --features collections)
|
|
||||||
- (cd testing && travis-cargo --skip nightly test)
|
|
||||||
- (cd testing && 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)
|
|
||||||
env:
|
|
||||||
global:
|
|
||||||
- TRAVIS_CARGO_NIGHTLY_FEATURE=""
|
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[workspace]
|
||||||
|
members = [
|
||||||
|
"serde",
|
||||||
|
"serde_codegen_internals",
|
||||||
|
"serde_derive",
|
||||||
|
"serde_test",
|
||||||
|
"test_suite",
|
||||||
|
"test_suite/no_std",
|
||||||
|
]
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
See LICENSE-APACHE and LICENSE-MIT.
|
|
||||||
|
|
||||||
----
|
|
||||||
|
|
||||||
bench_log is derived from https://github.com/cloudflare/goser, which has the
|
|
||||||
following license:
|
|
||||||
|
|
||||||
Copyright (c) 2013, CloudFlare, Inc.
|
|
||||||
All rights reserved.
|
|
||||||
|
|
||||||
Redistribution and use in source and binary forms, with or without
|
|
||||||
modification, are permitted provided that the following conditions are met:
|
|
||||||
|
|
||||||
* Redistributions of source code must retain the above copyright
|
|
||||||
notice, this list of conditions and the following disclaimer.
|
|
||||||
* Redistributions in binary form must reproduce the above copyright
|
|
||||||
notice, this list of conditions and the following disclaimer in the
|
|
||||||
documentation and/or other materials provided with the distribution.
|
|
||||||
* Neither the name of the author nor the
|
|
||||||
names of its contributors may be used to endorse or promote products
|
|
||||||
derived from this software without specific prior written permission.
|
|
||||||
|
|
||||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
||||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
||||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
||||||
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
|
|
||||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
|
||||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
|
||||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
|
||||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
|
||||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
target
|
|
||||||
Cargo.lock
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
[package]
|
|
||||||
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_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"
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
This example demonstrates how to use Serde with Syntex. On stable or nightly
|
|
||||||
with Syntex, it can be built with:
|
|
||||||
|
|
||||||
```
|
|
||||||
% rustup run stable cargo run
|
|
||||||
Running `target/debug/serde-syntex-example`
|
|
||||||
{"x":1,"y":2}
|
|
||||||
Point { x: 1, y: 2 }
|
|
||||||
|
|
||||||
% rustup run nightly cargo run
|
|
||||||
Running `target/debug/serde-syntex-example`
|
|
||||||
{"x":1,"y":2}
|
|
||||||
Point { x: 1, y: 2 }
|
|
||||||
```
|
|
||||||
|
|
||||||
On nightly, it can use a plugin with:
|
|
||||||
|
|
||||||
```
|
|
||||||
% rustup run nightly cargo run --features unstable --no-default-features
|
|
||||||
```
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
#[cfg(not(feature = "serde_derive"))]
|
|
||||||
mod inner {
|
|
||||||
extern crate serde_codegen;
|
|
||||||
|
|
||||||
use std::env;
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
pub fn main() {
|
|
||||||
let out_dir = env::var_os("OUT_DIR").unwrap();
|
|
||||||
|
|
||||||
let src = Path::new("src/main.rs.in");
|
|
||||||
let dst = Path::new(&out_dir).join("main.rs");
|
|
||||||
|
|
||||||
serde_codegen::expand(&src, &dst).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "serde_derive")]
|
|
||||||
mod inner {
|
|
||||||
pub fn main() {}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
inner::main();
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
#[cfg(feature = "serde_derive")]
|
|
||||||
#[macro_use]
|
|
||||||
extern crate serde_derive;
|
|
||||||
|
|
||||||
extern crate serde;
|
|
||||||
extern crate serde_json;
|
|
||||||
|
|
||||||
#[cfg(feature = "serde_derive")]
|
|
||||||
include!("main.rs.in");
|
|
||||||
|
|
||||||
#[cfg(not(feature = "serde_derive"))]
|
|
||||||
include!(concat!(env!("OUT_DIR"), "/main.rs"));
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
#[derive(Serialize, Deserialize, Debug)]
|
|
||||||
struct Point {
|
|
||||||
x: i32,
|
|
||||||
y: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let point = Point { x: 1, y: 2 };
|
|
||||||
let serialized = serde_json::to_string(&point).unwrap();
|
|
||||||
|
|
||||||
println!("{}", serialized);
|
|
||||||
|
|
||||||
let deserialized: Point = serde_json::from_str(&serialized).unwrap();
|
|
||||||
|
|
||||||
println!("{:?}", deserialized);
|
|
||||||
}
|
|
||||||
+8
-4
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "serde"
|
name = "serde"
|
||||||
version = "0.9.0-rc1"
|
version = "0.9.6"
|
||||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
description = "A generic serialization/deserialization framework"
|
description = "A generic serialization/deserialization framework"
|
||||||
@@ -9,8 +9,12 @@ repository = "https://github.com/serde-rs/serde"
|
|||||||
documentation = "https://docs.serde.rs/serde/"
|
documentation = "https://docs.serde.rs/serde/"
|
||||||
readme = "../README.md"
|
readme = "../README.md"
|
||||||
keywords = ["serde", "serialization"]
|
keywords = ["serde", "serialization"]
|
||||||
|
categories = ["encoding"]
|
||||||
include = ["Cargo.toml", "src/**/*.rs"]
|
include = ["Cargo.toml", "src/**/*.rs"]
|
||||||
|
|
||||||
|
[badges]
|
||||||
|
travis-ci = { repository = "serde-rs/serde" }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["std"]
|
default = ["std"]
|
||||||
|
|
||||||
@@ -18,7 +22,7 @@ std = []
|
|||||||
unstable = []
|
unstable = []
|
||||||
alloc = ["unstable"]
|
alloc = ["unstable"]
|
||||||
collections = ["alloc"]
|
collections = ["alloc"]
|
||||||
unstable-testing = ["clippy", "unstable", "std"]
|
unstable-testing = ["unstable", "std"]
|
||||||
|
|
||||||
[dependencies]
|
[dev-dependencies]
|
||||||
clippy = { version = "^0.*", optional = true }
|
serde_derive = "0.9"
|
||||||
|
|||||||
+65
-5
@@ -1,4 +1,20 @@
|
|||||||
//! Helper module to enable serializing bytes more efficiently
|
//! Wrapper types to enable optimized handling of `&[u8]` and `Vec<u8>`.
|
||||||
|
//!
|
||||||
|
//! Without specialization, Rust forces us to treat `&[u8]` just like any other
|
||||||
|
//! slice and `Vec<u8>` just like any other vector. In reality this particular
|
||||||
|
//! slice and vector can often be serialized and deserialized in a more
|
||||||
|
//! efficient, compact representation in many formats.
|
||||||
|
//!
|
||||||
|
//! When working with such a format, you can opt into specialized handling of
|
||||||
|
//! `&[u8]` by wrapping it in `bytes::Bytes` and `Vec<u8>` by wrapping it in
|
||||||
|
//! `bytes::ByteBuf`.
|
||||||
|
//!
|
||||||
|
//! Rust support for specialization is being tracked in
|
||||||
|
//! [rust-lang/rust#31844][specialization]. Once it lands in the stable compiler
|
||||||
|
//! we will be deprecating these wrapper types in favor of optimizing `&[u8]`
|
||||||
|
//! and `Vec<u8>` out of the box.
|
||||||
|
//!
|
||||||
|
//! [specialization]: https://github.com/rust-lang/rust/issues/31844
|
||||||
|
|
||||||
use core::{ops, fmt, char, iter, slice};
|
use core::{ops, fmt, char, iter, slice};
|
||||||
use core::fmt::Write;
|
use core::fmt::Write;
|
||||||
@@ -6,14 +22,36 @@ use core::fmt::Write;
|
|||||||
use ser;
|
use ser;
|
||||||
|
|
||||||
#[cfg(any(feature = "std", feature = "collections"))]
|
#[cfg(any(feature = "std", feature = "collections"))]
|
||||||
pub use self::bytebuf::{ByteBuf, ByteBufVisitor};
|
pub use self::bytebuf::ByteBuf;
|
||||||
|
|
||||||
|
#[cfg(any(feature = "std", feature = "collections"))]
|
||||||
|
#[doc(hidden)] // does anybody need this?
|
||||||
|
pub use self::bytebuf::ByteBufVisitor;
|
||||||
|
|
||||||
#[cfg(feature = "collections")]
|
#[cfg(feature = "collections")]
|
||||||
use collections::Vec;
|
use collections::Vec;
|
||||||
|
|
||||||
///////////////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
/// `Bytes` wraps a `&[u8]` in order to serialize into a byte array.
|
/// Wraps a `&[u8]` in order to serialize in an efficient way. Does not support
|
||||||
|
/// deserialization.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// # #[macro_use] extern crate serde_derive;
|
||||||
|
/// # extern crate serde;
|
||||||
|
/// # use std::net::IpAddr;
|
||||||
|
/// #
|
||||||
|
/// use serde::bytes::Bytes;
|
||||||
|
///
|
||||||
|
/// # #[allow(dead_code)]
|
||||||
|
/// #[derive(Serialize)]
|
||||||
|
/// struct Packet<'a> {
|
||||||
|
/// destination: IpAddr,
|
||||||
|
/// payload: Bytes<'a>,
|
||||||
|
/// }
|
||||||
|
/// #
|
||||||
|
/// # fn main() {}
|
||||||
|
/// ```
|
||||||
#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
|
#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
|
||||||
pub struct Bytes<'a> {
|
pub struct Bytes<'a> {
|
||||||
bytes: &'a [u8],
|
bytes: &'a [u8],
|
||||||
@@ -86,7 +124,25 @@ mod bytebuf {
|
|||||||
#[cfg(feature = "collections")]
|
#[cfg(feature = "collections")]
|
||||||
use collections::{String, Vec};
|
use collections::{String, Vec};
|
||||||
|
|
||||||
/// `ByteBuf` wraps a `Vec<u8>` and serializes as a byte array.
|
/// Wraps a `Vec<u8>` in order to serialize and deserialize in an efficient
|
||||||
|
/// way.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// # #[macro_use] extern crate serde_derive;
|
||||||
|
/// # extern crate serde;
|
||||||
|
/// # use std::net::IpAddr;
|
||||||
|
/// #
|
||||||
|
/// use serde::bytes::ByteBuf;
|
||||||
|
///
|
||||||
|
/// # #[allow(dead_code)]
|
||||||
|
/// #[derive(Serialize, Deserialize)]
|
||||||
|
/// struct Packet {
|
||||||
|
/// destination: IpAddr,
|
||||||
|
/// payload: ByteBuf,
|
||||||
|
/// }
|
||||||
|
/// #
|
||||||
|
/// # fn main() {}
|
||||||
|
/// ```
|
||||||
#[derive(Clone, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
|
#[derive(Clone, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
|
||||||
pub struct ByteBuf {
|
pub struct ByteBuf {
|
||||||
bytes: Vec<u8>,
|
bytes: Vec<u8>,
|
||||||
@@ -181,6 +237,10 @@ mod bytebuf {
|
|||||||
impl de::Visitor for ByteBufVisitor {
|
impl de::Visitor for ByteBufVisitor {
|
||||||
type Value = ByteBuf;
|
type Value = ByteBuf;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str("byte array")
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn visit_unit<E>(self) -> Result<ByteBuf, E>
|
fn visit_unit<E>(self) -> Result<ByteBuf, E>
|
||||||
where E: de::Error,
|
where E: de::Error,
|
||||||
@@ -234,7 +294,7 @@ mod bytebuf {
|
|||||||
fn deserialize<D>(deserializer: D) -> Result<ByteBuf, D::Error>
|
fn deserialize<D>(deserializer: D) -> Result<ByteBuf, D::Error>
|
||||||
where D: de::Deserializer
|
where D: de::Deserializer
|
||||||
{
|
{
|
||||||
deserializer.deserialize_bytes(ByteBufVisitor)
|
deserializer.deserialize_byte_buf(ByteBufVisitor)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,743 @@
|
|||||||
|
// This module is doc(hidden) and nothing here should be used outside of
|
||||||
|
// generated code.
|
||||||
|
//
|
||||||
|
// We will iterate on the implementation for a few releases and only have to
|
||||||
|
// worry about backward compatibility for the `untagged` and `tag` attributes
|
||||||
|
// rather than for this entire mechanism.
|
||||||
|
//
|
||||||
|
// This issue is tracking making some of this stuff public:
|
||||||
|
// https://github.com/serde-rs/serde/issues/741
|
||||||
|
|
||||||
|
#![doc(hidden)]
|
||||||
|
|
||||||
|
use core::fmt;
|
||||||
|
use core::marker::PhantomData;
|
||||||
|
|
||||||
|
#[cfg(all(not(feature = "std"), feature = "collections"))]
|
||||||
|
use collections::{String, Vec};
|
||||||
|
|
||||||
|
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||||
|
use alloc::boxed::Box;
|
||||||
|
|
||||||
|
use de::{
|
||||||
|
self,
|
||||||
|
Deserialize,
|
||||||
|
DeserializeSeed,
|
||||||
|
Deserializer,
|
||||||
|
Visitor,
|
||||||
|
SeqVisitor,
|
||||||
|
MapVisitor,
|
||||||
|
EnumVisitor,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Used from generated code to buffer the contents of the Deserializer when
|
||||||
|
/// deserializing untagged enums and internally tagged enums.
|
||||||
|
///
|
||||||
|
/// Not public API. Use serde-value instead.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum Content<E> {
|
||||||
|
// Don't mind the PhantomData, just need to use E somewhere.
|
||||||
|
Bool(bool, PhantomData<E>),
|
||||||
|
|
||||||
|
U8(u8),
|
||||||
|
U16(u16),
|
||||||
|
U32(u32),
|
||||||
|
U64(u64),
|
||||||
|
|
||||||
|
I8(i8),
|
||||||
|
I16(i16),
|
||||||
|
I32(i32),
|
||||||
|
I64(i64),
|
||||||
|
|
||||||
|
F32(f32),
|
||||||
|
F64(f64),
|
||||||
|
|
||||||
|
Char(char),
|
||||||
|
String(String),
|
||||||
|
Bytes(Vec<u8>),
|
||||||
|
|
||||||
|
None,
|
||||||
|
Some(Box<Content<E>>),
|
||||||
|
|
||||||
|
Unit,
|
||||||
|
Newtype(Box<Content<E>>),
|
||||||
|
Seq(Vec<Content<E>>),
|
||||||
|
Map(Vec<(Content<E>, Content<E>)>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<E> Deserialize for Content<E> {
|
||||||
|
fn deserialize<D: Deserializer>(deserializer: D) -> Result<Self, D::Error> {
|
||||||
|
// Untagged and internally tagged enums are only supported in
|
||||||
|
// self-describing formats.
|
||||||
|
deserializer.deserialize(ContentVisitor::new())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ContentVisitor<E> {
|
||||||
|
err: PhantomData<E>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<E> ContentVisitor<E> {
|
||||||
|
fn new() -> Self {
|
||||||
|
ContentVisitor {
|
||||||
|
err: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<E> Visitor for ContentVisitor<E> {
|
||||||
|
type Value = Content<E>;
|
||||||
|
|
||||||
|
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
fmt.write_str("any value")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::Bool(value, PhantomData))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::I8(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::I16(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::I32(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::I64(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::U8(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::U16(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::U32(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::U64(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::F32(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::F64(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::Char(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::String(value.into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::String(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::Bytes(value.into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::Bytes(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_unit<F>(self) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::Unit)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_none<F>(self) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
Ok(Content::None)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||||
|
where D: Deserializer
|
||||||
|
{
|
||||||
|
Deserialize::deserialize(deserializer).map(|v| Content::Some(Box::new(v)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||||
|
where D: Deserializer
|
||||||
|
{
|
||||||
|
Deserialize::deserialize(deserializer).map(|v| Content::Newtype(Box::new(v)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
|
||||||
|
where V: SeqVisitor
|
||||||
|
{
|
||||||
|
let mut vec = Vec::with_capacity(visitor.size_hint().0);
|
||||||
|
while let Some(e) = try!(visitor.visit()) {
|
||||||
|
vec.push(e);
|
||||||
|
}
|
||||||
|
Ok(Content::Seq(vec))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
|
||||||
|
where V: MapVisitor
|
||||||
|
{
|
||||||
|
let mut vec = Vec::with_capacity(visitor.size_hint().0);
|
||||||
|
while let Some(kv) = try!(visitor.visit()) {
|
||||||
|
vec.push(kv);
|
||||||
|
}
|
||||||
|
Ok(Content::Map(vec))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_enum<V>(self, _visitor: V) -> Result<Self::Value, V::Error>
|
||||||
|
where V: EnumVisitor
|
||||||
|
{
|
||||||
|
Err(de::Error::custom("untagged and internally tagged enums do not support enum input"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This is the type of the map keys in an internally tagged enum.
|
||||||
|
///
|
||||||
|
/// Not public API.
|
||||||
|
pub enum TagOrContent<E> {
|
||||||
|
Tag,
|
||||||
|
Content(Content<E>),
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TagOrContentVisitor<E> {
|
||||||
|
name: &'static str,
|
||||||
|
err: PhantomData<E>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<E> TagOrContentVisitor<E> {
|
||||||
|
fn new(name: &'static str) -> Self {
|
||||||
|
TagOrContentVisitor {
|
||||||
|
name: name,
|
||||||
|
err: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<E> DeserializeSeed for TagOrContentVisitor<E> {
|
||||||
|
type Value = TagOrContent<E>;
|
||||||
|
|
||||||
|
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||||
|
where D: Deserializer
|
||||||
|
{
|
||||||
|
// Internally tagged enums are only supported in self-describing
|
||||||
|
// formats.
|
||||||
|
deserializer.deserialize(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<E> Visitor for TagOrContentVisitor<E> {
|
||||||
|
type Value = TagOrContent<E>;
|
||||||
|
|
||||||
|
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
write!(fmt, "a type tag `{}` or any other value", self.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_bool(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_i8(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_i16(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_i32(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_i64(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_u8(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_u16(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_u32(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_u64(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_f32(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_f64(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_char(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
if value == self.name {
|
||||||
|
Ok(TagOrContent::Tag)
|
||||||
|
} else {
|
||||||
|
ContentVisitor::new().visit_str(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
if value == self.name {
|
||||||
|
Ok(TagOrContent::Tag)
|
||||||
|
} else {
|
||||||
|
ContentVisitor::new().visit_string(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
if value == self.name.as_bytes() {
|
||||||
|
Ok(TagOrContent::Tag)
|
||||||
|
} else {
|
||||||
|
ContentVisitor::new().visit_bytes(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
if value == self.name.as_bytes() {
|
||||||
|
Ok(TagOrContent::Tag)
|
||||||
|
} else {
|
||||||
|
ContentVisitor::new().visit_byte_buf(value).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_unit<F>(self) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_unit().map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_none<F>(self) -> Result<Self::Value, F>
|
||||||
|
where F: de::Error
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_none().map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||||
|
where D: Deserializer
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_some(deserializer).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||||
|
where D: Deserializer
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_newtype_struct(deserializer).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error>
|
||||||
|
where V: SeqVisitor
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_seq(visitor).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error>
|
||||||
|
where V: MapVisitor
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_map(visitor).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error>
|
||||||
|
where V: EnumVisitor
|
||||||
|
{
|
||||||
|
ContentVisitor::new().visit_enum(visitor).map(TagOrContent::Content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Used by generated code to deserialize an internally tagged enum.
|
||||||
|
///
|
||||||
|
/// Not public API.
|
||||||
|
pub struct TaggedContent<T, E> {
|
||||||
|
pub tag: T,
|
||||||
|
pub content: Content<E>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Not public API.
|
||||||
|
pub struct TaggedContentVisitor<T, E> {
|
||||||
|
tag_name: &'static str,
|
||||||
|
tag: PhantomData<T>,
|
||||||
|
err: PhantomData<E>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, E> TaggedContentVisitor<T, E> {
|
||||||
|
/// Visitor for the content of an internally tagged enum with the given tag
|
||||||
|
/// name.
|
||||||
|
pub fn new(name: &'static str) -> Self {
|
||||||
|
TaggedContentVisitor {
|
||||||
|
tag_name: name,
|
||||||
|
tag: PhantomData,
|
||||||
|
err: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, E> DeserializeSeed for TaggedContentVisitor<T, E>
|
||||||
|
where T: Deserialize
|
||||||
|
{
|
||||||
|
type Value = TaggedContent<T, E>;
|
||||||
|
|
||||||
|
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||||
|
where D: Deserializer
|
||||||
|
{
|
||||||
|
// Internally tagged enums are only supported in self-describing
|
||||||
|
// formats.
|
||||||
|
deserializer.deserialize(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, E> Visitor for TaggedContentVisitor<T, E>
|
||||||
|
where T: Deserialize
|
||||||
|
{
|
||||||
|
type Value = TaggedContent<T, E>;
|
||||||
|
|
||||||
|
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
fmt.write_str("any value")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
|
||||||
|
where V: MapVisitor
|
||||||
|
{
|
||||||
|
let mut tag = None;
|
||||||
|
let mut vec = Vec::with_capacity(visitor.size_hint().0);
|
||||||
|
while let Some(k) = try!(visitor.visit_key_seed(TagOrContentVisitor::new(self.tag_name))) {
|
||||||
|
match k {
|
||||||
|
TagOrContent::Tag => {
|
||||||
|
if tag.is_some() {
|
||||||
|
return Err(de::Error::duplicate_field(self.tag_name));
|
||||||
|
}
|
||||||
|
tag = Some(try!(visitor.visit_value()));
|
||||||
|
}
|
||||||
|
TagOrContent::Content(k) => {
|
||||||
|
let v = try!(visitor.visit_value());
|
||||||
|
vec.push((k, v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match tag {
|
||||||
|
None => {
|
||||||
|
Err(de::Error::missing_field(self.tag_name))
|
||||||
|
}
|
||||||
|
Some(tag) => {
|
||||||
|
Ok(TaggedContent {
|
||||||
|
tag: tag,
|
||||||
|
content: Content::Map(vec),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Used when deserializing an internally tagged enum because the content will
|
||||||
|
/// be used exactly once.
|
||||||
|
impl<E> Deserializer for Content<E>
|
||||||
|
where E: de::Error
|
||||||
|
{
|
||||||
|
type Error = E;
|
||||||
|
|
||||||
|
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||||
|
where V: Visitor
|
||||||
|
{
|
||||||
|
match self {
|
||||||
|
Content::Bool(v, _) => visitor.visit_bool(v),
|
||||||
|
Content::U8(v) => visitor.visit_u8(v),
|
||||||
|
Content::U16(v) => visitor.visit_u16(v),
|
||||||
|
Content::U32(v) => visitor.visit_u32(v),
|
||||||
|
Content::U64(v) => visitor.visit_u64(v),
|
||||||
|
Content::I8(v) => visitor.visit_i8(v),
|
||||||
|
Content::I16(v) => visitor.visit_i16(v),
|
||||||
|
Content::I32(v) => visitor.visit_i32(v),
|
||||||
|
Content::I64(v) => visitor.visit_i64(v),
|
||||||
|
Content::F32(v) => visitor.visit_f32(v),
|
||||||
|
Content::F64(v) => visitor.visit_f64(v),
|
||||||
|
Content::Char(v) => visitor.visit_char(v),
|
||||||
|
Content::String(v) => visitor.visit_string(v),
|
||||||
|
Content::Unit => visitor.visit_unit(),
|
||||||
|
Content::None => visitor.visit_none(),
|
||||||
|
Content::Some(v) => visitor.visit_some(*v),
|
||||||
|
Content::Newtype(v) => visitor.visit_newtype_struct(*v),
|
||||||
|
Content::Seq(v) => {
|
||||||
|
let seq = v.into_iter();
|
||||||
|
let mut seq_visitor = de::value::SeqDeserializer::new(seq);
|
||||||
|
let value = try!(visitor.visit_seq(&mut seq_visitor));
|
||||||
|
try!(seq_visitor.end());
|
||||||
|
Ok(value)
|
||||||
|
},
|
||||||
|
Content::Map(v) => {
|
||||||
|
let map = v.into_iter();
|
||||||
|
let mut map_visitor = de::value::MapDeserializer::new(map);
|
||||||
|
let value = try!(visitor.visit_map(&mut map_visitor));
|
||||||
|
try!(map_visitor.end());
|
||||||
|
Ok(value)
|
||||||
|
},
|
||||||
|
Content::Bytes(v) => visitor.visit_byte_buf(v),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||||
|
where V: Visitor
|
||||||
|
{
|
||||||
|
match self {
|
||||||
|
Content::None => visitor.visit_none(),
|
||||||
|
Content::Some(v) => visitor.visit_some(*v),
|
||||||
|
Content::Unit => visitor.visit_unit(),
|
||||||
|
_ => visitor.visit_some(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
|
||||||
|
where V: Visitor
|
||||||
|
{
|
||||||
|
visitor.visit_newtype_struct(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
forward_to_deserialize! {
|
||||||
|
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
|
||||||
|
seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
|
||||||
|
struct_field tuple enum ignored_any
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<E> de::value::ValueDeserializer<E> for Content<E>
|
||||||
|
where E: de::Error
|
||||||
|
{
|
||||||
|
type Deserializer = Self;
|
||||||
|
|
||||||
|
fn into_deserializer(self) -> Self {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Used when deserializing an untagged enum because the content may need to be
|
||||||
|
/// used more than once.
|
||||||
|
impl<'a, E> Deserializer for &'a Content<E>
|
||||||
|
where E: de::Error
|
||||||
|
{
|
||||||
|
type Error = E;
|
||||||
|
|
||||||
|
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||||
|
where V: Visitor
|
||||||
|
{
|
||||||
|
match *self {
|
||||||
|
Content::Bool(v, _) => visitor.visit_bool(v),
|
||||||
|
Content::U8(v) => visitor.visit_u8(v),
|
||||||
|
Content::U16(v) => visitor.visit_u16(v),
|
||||||
|
Content::U32(v) => visitor.visit_u32(v),
|
||||||
|
Content::U64(v) => visitor.visit_u64(v),
|
||||||
|
Content::I8(v) => visitor.visit_i8(v),
|
||||||
|
Content::I16(v) => visitor.visit_i16(v),
|
||||||
|
Content::I32(v) => visitor.visit_i32(v),
|
||||||
|
Content::I64(v) => visitor.visit_i64(v),
|
||||||
|
Content::F32(v) => visitor.visit_f32(v),
|
||||||
|
Content::F64(v) => visitor.visit_f64(v),
|
||||||
|
Content::Char(v) => visitor.visit_char(v),
|
||||||
|
Content::String(ref v) => visitor.visit_str(v),
|
||||||
|
Content::Unit => visitor.visit_unit(),
|
||||||
|
Content::None => visitor.visit_none(),
|
||||||
|
Content::Some(ref v) => visitor.visit_some(&**v),
|
||||||
|
Content::Newtype(ref v) => visitor.visit_newtype_struct(&**v),
|
||||||
|
Content::Seq(ref v) => {
|
||||||
|
let seq = v.into_iter();
|
||||||
|
let mut seq_visitor = de::value::SeqDeserializer::new(seq);
|
||||||
|
let value = try!(visitor.visit_seq(&mut seq_visitor));
|
||||||
|
try!(seq_visitor.end());
|
||||||
|
Ok(value)
|
||||||
|
},
|
||||||
|
Content::Map(ref v) => {
|
||||||
|
let map = v.into_iter().map(|&(ref k, ref v)| (k, v));
|
||||||
|
let mut map_visitor = de::value::MapDeserializer::new(map);
|
||||||
|
let value = try!(visitor.visit_map(&mut map_visitor));
|
||||||
|
try!(map_visitor.end());
|
||||||
|
Ok(value)
|
||||||
|
},
|
||||||
|
Content::Bytes(ref v) => visitor.visit_bytes(v),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||||
|
where V: Visitor
|
||||||
|
{
|
||||||
|
match *self {
|
||||||
|
Content::None => visitor.visit_none(),
|
||||||
|
Content::Some(ref v) => visitor.visit_some(&**v),
|
||||||
|
Content::Unit => visitor.visit_unit(),
|
||||||
|
_ => visitor.visit_some(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
|
||||||
|
where V: Visitor
|
||||||
|
{
|
||||||
|
visitor.visit_newtype_struct(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
forward_to_deserialize! {
|
||||||
|
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
|
||||||
|
seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
|
||||||
|
struct_field tuple enum ignored_any
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, E> de::value::ValueDeserializer<E> for &'a Content<E>
|
||||||
|
where E: de::Error
|
||||||
|
{
|
||||||
|
type Deserializer = Self;
|
||||||
|
|
||||||
|
fn into_deserializer(self) -> Self {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Visitor for deserializing an internally tagged unit variant.
|
||||||
|
///
|
||||||
|
/// Not public API.
|
||||||
|
pub struct InternallyTaggedUnitVisitor<'a> {
|
||||||
|
type_name: &'a str,
|
||||||
|
variant_name: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> InternallyTaggedUnitVisitor<'a> {
|
||||||
|
/// Not public API.
|
||||||
|
pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
|
||||||
|
InternallyTaggedUnitVisitor {
|
||||||
|
type_name: type_name,
|
||||||
|
variant_name: variant_name,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Visitor for InternallyTaggedUnitVisitor<'a> {
|
||||||
|
type Value = ();
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_map<V>(self, _: V) -> Result<(), V::Error>
|
||||||
|
where V: MapVisitor
|
||||||
|
{
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Visitor for deserializing an untagged unit variant.
|
||||||
|
///
|
||||||
|
/// Not public API.
|
||||||
|
pub struct UntaggedUnitVisitor<'a> {
|
||||||
|
type_name: &'a str,
|
||||||
|
variant_name: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> UntaggedUnitVisitor<'a> {
|
||||||
|
/// Not public API.
|
||||||
|
pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
|
||||||
|
UntaggedUnitVisitor {
|
||||||
|
type_name: type_name,
|
||||||
|
variant_name: variant_name,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Visitor for UntaggedUnitVisitor<'a> {
|
||||||
|
type Value = ();
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_unit<E>(self) -> Result<(), E>
|
||||||
|
where E: de::Error
|
||||||
|
{
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
+188
-167
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
#[cfg(all(feature = "unstable", feature = "collections", not(feature = "std")))]
|
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||||
use collections::borrow::Cow;
|
use collections::borrow::Cow;
|
||||||
|
|
||||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||||
@@ -27,11 +27,11 @@ use std::collections::{
|
|||||||
VecDeque,
|
VecDeque,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[cfg(all(feature = "unstable", feature = "collections"))]
|
#[cfg(feature = "collections")]
|
||||||
use collections::enum_set::{CLike, EnumSet};
|
|
||||||
#[cfg(all(feature = "unstable", feature = "collections"))]
|
|
||||||
use collections::borrow::ToOwned;
|
use collections::borrow::ToOwned;
|
||||||
|
|
||||||
|
use core::fmt;
|
||||||
|
#[cfg(feature = "std")]
|
||||||
use core::hash::{Hash, BuildHasher};
|
use core::hash::{Hash, BuildHasher};
|
||||||
use core::marker::PhantomData;
|
use core::marker::PhantomData;
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
@@ -42,15 +42,15 @@ use core::str;
|
|||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
#[cfg(all(feature = "unstable", feature = "alloc", not(feature = "std")))]
|
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||||
use alloc::rc::Rc;
|
use alloc::rc::Rc;
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
#[cfg(all(feature = "unstable", feature = "alloc", not(feature = "std")))]
|
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||||
use alloc::arc::Arc;
|
use alloc::arc::Arc;
|
||||||
|
|
||||||
#[cfg(all(feature = "unstable", feature = "alloc", not(feature = "std")))]
|
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||||
use alloc::boxed::Box;
|
use alloc::boxed::Box;
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
@@ -60,6 +60,7 @@ use std::time::Duration;
|
|||||||
use core::nonzero::{NonZero, Zeroable};
|
use core::nonzero::{NonZero, Zeroable};
|
||||||
|
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(feature = "unstable")]
|
||||||
|
#[allow(deprecated)] // required for impl Deserialize for NonZero<T>
|
||||||
use core::num::Zero;
|
use core::num::Zero;
|
||||||
|
|
||||||
use de::{
|
use de::{
|
||||||
@@ -69,7 +70,7 @@ use de::{
|
|||||||
Error,
|
Error,
|
||||||
MapVisitor,
|
MapVisitor,
|
||||||
SeqVisitor,
|
SeqVisitor,
|
||||||
Type,
|
Unexpected,
|
||||||
VariantVisitor,
|
VariantVisitor,
|
||||||
Visitor,
|
Visitor,
|
||||||
};
|
};
|
||||||
@@ -83,6 +84,10 @@ pub struct UnitVisitor;
|
|||||||
impl Visitor for UnitVisitor {
|
impl Visitor for UnitVisitor {
|
||||||
type Value = ();
|
type Value = ();
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str("unit")
|
||||||
|
}
|
||||||
|
|
||||||
fn visit_unit<E>(self) -> Result<(), E>
|
fn visit_unit<E>(self) -> Result<(), E>
|
||||||
where E: Error,
|
where E: Error,
|
||||||
{
|
{
|
||||||
@@ -112,6 +117,10 @@ pub struct BoolVisitor;
|
|||||||
impl Visitor for BoolVisitor {
|
impl Visitor for BoolVisitor {
|
||||||
type Value = bool;
|
type Value = bool;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str("a boolean")
|
||||||
|
}
|
||||||
|
|
||||||
fn visit_bool<E>(self, v: bool) -> Result<bool, E>
|
fn visit_bool<E>(self, v: bool) -> Result<bool, E>
|
||||||
where E: Error,
|
where E: Error,
|
||||||
{
|
{
|
||||||
@@ -124,7 +133,7 @@ impl Visitor for BoolVisitor {
|
|||||||
match s.trim_matches(::utils::Pattern_White_Space) {
|
match s.trim_matches(::utils::Pattern_White_Space) {
|
||||||
"true" => Ok(true),
|
"true" => Ok(true),
|
||||||
"false" => Ok(false),
|
"false" => Ok(false),
|
||||||
_ => Err(Error::invalid_type(Type::Bool)),
|
_ => Err(Error::invalid_type(Unexpected::Str(s), &self)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -140,81 +149,68 @@ impl Deserialize for bool {
|
|||||||
///////////////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
macro_rules! impl_deserialize_num_method {
|
macro_rules! impl_deserialize_num_method {
|
||||||
($src_ty:ty, $method:ident, $from_method:ident, $ty:expr) => {
|
($ty:ident, $src_ty:ident, $method:ident, $from_method:ident, $group:ident, $group_ty:ident) => {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn $method<E>(self, v: $src_ty) -> Result<T, E>
|
fn $method<E>(self, v: $src_ty) -> Result<$ty, E>
|
||||||
where E: Error,
|
where E: Error,
|
||||||
{
|
{
|
||||||
match FromPrimitive::$from_method(v) {
|
match FromPrimitive::$from_method(v) {
|
||||||
Some(v) => Ok(v),
|
Some(v) => Ok(v),
|
||||||
None => Err(Error::invalid_type($ty)),
|
None => Err(Error::invalid_value(Unexpected::$group(v as $group_ty), &self)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A visitor that produces a primitive type.
|
|
||||||
struct PrimitiveVisitor<T> {
|
|
||||||
marker: PhantomData<T>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> PrimitiveVisitor<T> {
|
|
||||||
/// Construct a new `PrimitiveVisitor`.
|
|
||||||
#[inline]
|
|
||||||
fn new() -> Self {
|
|
||||||
PrimitiveVisitor {
|
|
||||||
marker: PhantomData,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Visitor for PrimitiveVisitor<T>
|
|
||||||
where T: Deserialize + FromPrimitive + str::FromStr
|
|
||||||
{
|
|
||||||
type Value = T;
|
|
||||||
|
|
||||||
impl_deserialize_num_method!(isize, visit_isize, from_isize, Type::Isize);
|
|
||||||
impl_deserialize_num_method!(i8, visit_i8, from_i8, Type::I8);
|
|
||||||
impl_deserialize_num_method!(i16, visit_i16, from_i16, Type::I16);
|
|
||||||
impl_deserialize_num_method!(i32, visit_i32, from_i32, Type::I32);
|
|
||||||
impl_deserialize_num_method!(i64, visit_i64, from_i64, Type::I64);
|
|
||||||
impl_deserialize_num_method!(usize, visit_usize, from_usize, Type::Usize);
|
|
||||||
impl_deserialize_num_method!(u8, visit_u8, from_u8, Type::U8);
|
|
||||||
impl_deserialize_num_method!(u16, visit_u16, from_u16, Type::U16);
|
|
||||||
impl_deserialize_num_method!(u32, visit_u32, from_u32, Type::U32);
|
|
||||||
impl_deserialize_num_method!(u64, visit_u64, from_u64, Type::U64);
|
|
||||||
impl_deserialize_num_method!(f32, visit_f32, from_f32, Type::F32);
|
|
||||||
impl_deserialize_num_method!(f64, visit_f64, from_f64, Type::F64);
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn visit_str<E>(self, s: &str) -> Result<T, E>
|
|
||||||
where E: Error,
|
|
||||||
{
|
|
||||||
str::FromStr::from_str(s.trim_matches(::utils::Pattern_White_Space)).or_else(|_| {
|
|
||||||
Err(Error::invalid_type(Type::Str))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! impl_deserialize_num {
|
macro_rules! impl_deserialize_num {
|
||||||
($ty:ty, $method:ident) => {
|
($ty:ident, $method:ident) => {
|
||||||
impl Deserialize for $ty {
|
impl Deserialize for $ty {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn deserialize<D>(deserializer: D) -> Result<$ty, D::Error>
|
fn deserialize<D>(deserializer: D) -> Result<$ty, D::Error>
|
||||||
where D: Deserializer,
|
where D: Deserializer,
|
||||||
{
|
{
|
||||||
deserializer.$method(PrimitiveVisitor::new())
|
struct PrimitiveVisitor;
|
||||||
|
|
||||||
|
impl Visitor for PrimitiveVisitor {
|
||||||
|
type Value = $ty;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str(stringify!($ty))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl_deserialize_num_method!($ty, i8, visit_i8, from_i8, Signed, i64);
|
||||||
|
impl_deserialize_num_method!($ty, i16, visit_i16, from_i16, Signed, i64);
|
||||||
|
impl_deserialize_num_method!($ty, i32, visit_i32, from_i32, Signed, i64);
|
||||||
|
impl_deserialize_num_method!($ty, i64, visit_i64, from_i64, Signed, i64);
|
||||||
|
impl_deserialize_num_method!($ty, u8, visit_u8, from_u8, Unsigned, u64);
|
||||||
|
impl_deserialize_num_method!($ty, u16, visit_u16, from_u16, Unsigned, u64);
|
||||||
|
impl_deserialize_num_method!($ty, u32, visit_u32, from_u32, Unsigned, u64);
|
||||||
|
impl_deserialize_num_method!($ty, u64, visit_u64, from_u64, Unsigned, u64);
|
||||||
|
impl_deserialize_num_method!($ty, f32, visit_f32, from_f32, Float, f64);
|
||||||
|
impl_deserialize_num_method!($ty, f64, visit_f64, from_f64, Float, f64);
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn visit_str<E>(self, s: &str) -> Result<$ty, E>
|
||||||
|
where E: Error,
|
||||||
|
{
|
||||||
|
str::FromStr::from_str(s.trim_matches(::utils::Pattern_White_Space)).or_else(|_| {
|
||||||
|
Err(Error::invalid_type(Unexpected::Str(s), &self))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
deserializer.$method(PrimitiveVisitor)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl_deserialize_num!(isize, deserialize_isize);
|
impl_deserialize_num!(isize, deserialize_i64);
|
||||||
impl_deserialize_num!(i8, deserialize_i8);
|
impl_deserialize_num!(i8, deserialize_i8);
|
||||||
impl_deserialize_num!(i16, deserialize_i16);
|
impl_deserialize_num!(i16, deserialize_i16);
|
||||||
impl_deserialize_num!(i32, deserialize_i32);
|
impl_deserialize_num!(i32, deserialize_i32);
|
||||||
impl_deserialize_num!(i64, deserialize_i64);
|
impl_deserialize_num!(i64, deserialize_i64);
|
||||||
impl_deserialize_num!(usize, deserialize_usize);
|
impl_deserialize_num!(usize, deserialize_u64);
|
||||||
impl_deserialize_num!(u8, deserialize_u8);
|
impl_deserialize_num!(u8, deserialize_u8);
|
||||||
impl_deserialize_num!(u16, deserialize_u16);
|
impl_deserialize_num!(u16, deserialize_u16);
|
||||||
impl_deserialize_num!(u32, deserialize_u32);
|
impl_deserialize_num!(u32, deserialize_u32);
|
||||||
@@ -229,6 +225,10 @@ struct CharVisitor;
|
|||||||
impl Visitor for CharVisitor {
|
impl Visitor for CharVisitor {
|
||||||
type Value = char;
|
type Value = char;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str("a character")
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn visit_char<E>(self, v: char) -> Result<char, E>
|
fn visit_char<E>(self, v: char) -> Result<char, E>
|
||||||
where E: Error,
|
where E: Error,
|
||||||
@@ -241,14 +241,9 @@ impl Visitor for CharVisitor {
|
|||||||
where E: Error,
|
where E: Error,
|
||||||
{
|
{
|
||||||
let mut iter = v.chars();
|
let mut iter = v.chars();
|
||||||
if let Some(v) = iter.next() {
|
match (iter.next(), iter.next()) {
|
||||||
if iter.next().is_some() {
|
(Some(c), None) => Ok(c),
|
||||||
Err(Error::invalid_type(Type::Char))
|
_ => Err(Error::invalid_value(Unexpected::Str(v), &self)),
|
||||||
} else {
|
|
||||||
Ok(v)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Err(Error::end_of_stream())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -271,6 +266,10 @@ struct StringVisitor;
|
|||||||
impl Visitor for StringVisitor {
|
impl Visitor for StringVisitor {
|
||||||
type Value = String;
|
type Value = String;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str("a string")
|
||||||
|
}
|
||||||
|
|
||||||
fn visit_str<E>(self, v: &str) -> Result<String, E>
|
fn visit_str<E>(self, v: &str) -> Result<String, E>
|
||||||
where E: Error,
|
where E: Error,
|
||||||
{
|
{
|
||||||
@@ -294,7 +293,7 @@ impl Visitor for StringVisitor {
|
|||||||
{
|
{
|
||||||
match str::from_utf8(v) {
|
match str::from_utf8(v) {
|
||||||
Ok(s) => Ok(s.to_owned()),
|
Ok(s) => Ok(s.to_owned()),
|
||||||
Err(_) => Err(Error::invalid_type(Type::String)),
|
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -303,7 +302,7 @@ impl Visitor for StringVisitor {
|
|||||||
{
|
{
|
||||||
match String::from_utf8(v) {
|
match String::from_utf8(v) {
|
||||||
Ok(s) => Ok(s),
|
Ok(s) => Ok(s),
|
||||||
Err(_) => Err(Error::invalid_type(Type::String)),
|
Err(e) => Err(Error::invalid_value(Unexpected::Bytes(&e.into_bytes()), &self)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -328,6 +327,10 @@ impl<
|
|||||||
> Visitor for OptionVisitor<T> {
|
> Visitor for OptionVisitor<T> {
|
||||||
type Value = Option<T>;
|
type Value = Option<T>;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str("option")
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn visit_unit<E>(self) -> Result<Option<T>, E>
|
fn visit_unit<E>(self) -> Result<Option<T>, E>
|
||||||
where E: Error,
|
where E: Error,
|
||||||
@@ -368,6 +371,10 @@ pub struct PhantomDataVisitor<T> {
|
|||||||
impl<T> Visitor for PhantomDataVisitor<T> {
|
impl<T> Visitor for PhantomDataVisitor<T> {
|
||||||
type Value = PhantomData<T>;
|
type Value = PhantomData<T>;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str("unit")
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn visit_unit<E>(self) -> Result<PhantomData<T>, E>
|
fn visit_unit<E>(self) -> Result<PhantomData<T>, E>
|
||||||
where E: Error,
|
where E: Error,
|
||||||
@@ -417,6 +424,10 @@ macro_rules! seq_impl {
|
|||||||
{
|
{
|
||||||
type Value = $ty;
|
type Value = $ty;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str("a sequence")
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn visit_unit<E>(self) -> Result<$ty, E>
|
fn visit_unit<E>(self) -> Result<$ty, E>
|
||||||
where E: Error,
|
where E: Error,
|
||||||
@@ -468,15 +479,6 @@ seq_impl!(
|
|||||||
BTreeSet::new(),
|
BTreeSet::new(),
|
||||||
BTreeSet::insert);
|
BTreeSet::insert);
|
||||||
|
|
||||||
#[cfg(all(feature = "unstable", feature = "collections"))]
|
|
||||||
seq_impl!(
|
|
||||||
EnumSet<T>,
|
|
||||||
EnumSetVisitor<T: Deserialize + CLike>,
|
|
||||||
visitor,
|
|
||||||
EnumSet::new(),
|
|
||||||
EnumSet::new(),
|
|
||||||
EnumSet::insert);
|
|
||||||
|
|
||||||
#[cfg(any(feature = "std", feature = "collections"))]
|
#[cfg(any(feature = "std", feature = "collections"))]
|
||||||
seq_impl!(
|
seq_impl!(
|
||||||
LinkedList<T>,
|
LinkedList<T>,
|
||||||
@@ -531,6 +533,10 @@ impl<A> ArrayVisitor<A> {
|
|||||||
impl<T> Visitor for ArrayVisitor<[T; 0]> where T: Deserialize {
|
impl<T> Visitor for ArrayVisitor<[T; 0]> where T: Deserialize {
|
||||||
type Value = [T; 0];
|
type Value = [T; 0];
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str("an empty array")
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn visit_unit<E>(self) -> Result<[T; 0], E>
|
fn visit_unit<E>(self) -> Result<[T; 0], E>
|
||||||
where E: Error,
|
where E: Error,
|
||||||
@@ -557,11 +563,15 @@ impl<T> Deserialize for [T; 0]
|
|||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! array_impls {
|
macro_rules! array_impls {
|
||||||
($($len:expr => ($($name:ident)+))+) => {
|
($($len:expr => ($($n:tt $name:ident)+))+) => {
|
||||||
$(
|
$(
|
||||||
impl<T> Visitor for ArrayVisitor<[T; $len]> where T: Deserialize {
|
impl<T> Visitor for ArrayVisitor<[T; $len]> where T: Deserialize {
|
||||||
type Value = [T; $len];
|
type Value = [T; $len];
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str(concat!("an array of length ", $len))
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn visit_seq<V>(self, mut visitor: V) -> Result<[T; $len], V::Error>
|
fn visit_seq<V>(self, mut visitor: V) -> Result<[T; $len], V::Error>
|
||||||
where V: SeqVisitor,
|
where V: SeqVisitor,
|
||||||
@@ -569,7 +579,7 @@ macro_rules! array_impls {
|
|||||||
$(
|
$(
|
||||||
let $name = match try!(visitor.visit()) {
|
let $name = match try!(visitor.visit()) {
|
||||||
Some(val) => val,
|
Some(val) => val,
|
||||||
None => return Err(Error::end_of_stream()),
|
None => return Err(Error::invalid_length($n, &self)),
|
||||||
};
|
};
|
||||||
)+
|
)+
|
||||||
|
|
||||||
@@ -591,44 +601,44 @@ macro_rules! array_impls {
|
|||||||
}
|
}
|
||||||
|
|
||||||
array_impls! {
|
array_impls! {
|
||||||
1 => (a)
|
1 => (0 a)
|
||||||
2 => (a b)
|
2 => (0 a 1 b)
|
||||||
3 => (a b c)
|
3 => (0 a 1 b 2 c)
|
||||||
4 => (a b c d)
|
4 => (0 a 1 b 2 c 3 d)
|
||||||
5 => (a b c d e)
|
5 => (0 a 1 b 2 c 3 d 4 e)
|
||||||
6 => (a b c d e f)
|
6 => (0 a 1 b 2 c 3 d 4 e 5 f)
|
||||||
7 => (a b c d e f g)
|
7 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g)
|
||||||
8 => (a b c d e f g h)
|
8 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h)
|
||||||
9 => (a b c d e f g h i)
|
9 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i)
|
||||||
10 => (a b c d e f g h i j)
|
10 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j)
|
||||||
11 => (a b c d e f g h i j k)
|
11 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k)
|
||||||
12 => (a b c d e f g h i j k l)
|
12 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l)
|
||||||
13 => (a b c d e f g h i j k l m)
|
13 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m)
|
||||||
14 => (a b c d e f g h i j k l m n)
|
14 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n)
|
||||||
15 => (a b c d e f g h i j k l m n o)
|
15 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o)
|
||||||
16 => (a b c d e f g h i j k l m n o p)
|
16 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p)
|
||||||
17 => (a b c d e f g h i j k l m n o p q)
|
17 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q)
|
||||||
18 => (a b c d e f g h i j k l m n o p q r)
|
18 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r)
|
||||||
19 => (a b c d e f g h i j k l m n o p q r s)
|
19 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s)
|
||||||
20 => (a b c d e f g h i j k l m n o p q r s t)
|
20 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t)
|
||||||
21 => (a b c d e f g h i j k l m n o p q r s t u)
|
21 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u)
|
||||||
22 => (a b c d e f g h i j k l m n o p q r s t u v)
|
22 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v)
|
||||||
23 => (a b c d e f g h i j k l m n o p q r s t u v w)
|
23 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w)
|
||||||
24 => (a b c d e f g h i j k l m n o p q r s t u v w x)
|
24 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x)
|
||||||
25 => (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)
|
25 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y)
|
||||||
26 => (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)
|
26 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z)
|
||||||
27 => (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)
|
27 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa)
|
||||||
28 => (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)
|
28 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab)
|
||||||
29 => (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)
|
29 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac)
|
||||||
30 => (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)
|
30 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad)
|
||||||
31 => (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)
|
31 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad 30 ae)
|
||||||
32 => (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)
|
32 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad 30 ae 31 af)
|
||||||
}
|
}
|
||||||
|
|
||||||
///////////////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
macro_rules! tuple_impls {
|
macro_rules! tuple_impls {
|
||||||
($($len:expr => $visitor:ident => ($($name:ident)+))+) => {
|
($($len:expr => $visitor:ident => ($($n:tt $name:ident)+))+) => {
|
||||||
$(
|
$(
|
||||||
/// Construct a tuple visitor.
|
/// Construct a tuple visitor.
|
||||||
pub struct $visitor<$($name,)+> {
|
pub struct $visitor<$($name,)+> {
|
||||||
@@ -645,6 +655,10 @@ macro_rules! tuple_impls {
|
|||||||
impl<$($name: Deserialize),+> Visitor for $visitor<$($name,)+> {
|
impl<$($name: Deserialize),+> Visitor for $visitor<$($name,)+> {
|
||||||
type Value = ($($name,)+);
|
type Value = ($($name,)+);
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str(concat!("a tuple of size ", $len))
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
fn visit_seq<V>(self, mut visitor: V) -> Result<($($name,)+), V::Error>
|
fn visit_seq<V>(self, mut visitor: V) -> Result<($($name,)+), V::Error>
|
||||||
@@ -653,7 +667,7 @@ macro_rules! tuple_impls {
|
|||||||
$(
|
$(
|
||||||
let $name = match try!(visitor.visit()) {
|
let $name = match try!(visitor.visit()) {
|
||||||
Some(value) => value,
|
Some(value) => value,
|
||||||
None => return Err(Error::end_of_stream()),
|
None => return Err(Error::invalid_length($n, &self)),
|
||||||
};
|
};
|
||||||
)+
|
)+
|
||||||
|
|
||||||
@@ -674,22 +688,22 @@ macro_rules! tuple_impls {
|
|||||||
}
|
}
|
||||||
|
|
||||||
tuple_impls! {
|
tuple_impls! {
|
||||||
1 => TupleVisitor1 => (T0)
|
1 => TupleVisitor1 => (0 T0)
|
||||||
2 => TupleVisitor2 => (T0 T1)
|
2 => TupleVisitor2 => (0 T0 1 T1)
|
||||||
3 => TupleVisitor3 => (T0 T1 T2)
|
3 => TupleVisitor3 => (0 T0 1 T1 2 T2)
|
||||||
4 => TupleVisitor4 => (T0 T1 T2 T3)
|
4 => TupleVisitor4 => (0 T0 1 T1 2 T2 3 T3)
|
||||||
5 => TupleVisitor5 => (T0 T1 T2 T3 T4)
|
5 => TupleVisitor5 => (0 T0 1 T1 2 T2 3 T3 4 T4)
|
||||||
6 => TupleVisitor6 => (T0 T1 T2 T3 T4 T5)
|
6 => TupleVisitor6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5)
|
||||||
7 => TupleVisitor7 => (T0 T1 T2 T3 T4 T5 T6)
|
7 => TupleVisitor7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6)
|
||||||
8 => TupleVisitor8 => (T0 T1 T2 T3 T4 T5 T6 T7)
|
8 => TupleVisitor8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7)
|
||||||
9 => TupleVisitor9 => (T0 T1 T2 T3 T4 T5 T6 T7 T8)
|
9 => TupleVisitor9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8)
|
||||||
10 => TupleVisitor10 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9)
|
10 => TupleVisitor10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9)
|
||||||
11 => TupleVisitor11 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10)
|
11 => TupleVisitor11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10)
|
||||||
12 => TupleVisitor12 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11)
|
12 => TupleVisitor12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11)
|
||||||
13 => TupleVisitor13 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12)
|
13 => TupleVisitor13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12)
|
||||||
14 => TupleVisitor14 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13)
|
14 => TupleVisitor14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13)
|
||||||
15 => TupleVisitor15 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14)
|
15 => TupleVisitor15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14)
|
||||||
16 => TupleVisitor16 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15)
|
16 => TupleVisitor16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15)
|
||||||
}
|
}
|
||||||
|
|
||||||
///////////////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////////////
|
||||||
@@ -723,6 +737,10 @@ macro_rules! map_impl {
|
|||||||
{
|
{
|
||||||
type Value = $ty;
|
type Value = $ty;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str("a map")
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn visit_unit<E>(self) -> Result<$ty, E>
|
fn visit_unit<E>(self) -> Result<$ty, E>
|
||||||
where E: Error,
|
where E: Error,
|
||||||
@@ -785,7 +803,7 @@ impl Deserialize for net::IpAddr {
|
|||||||
let s = try!(String::deserialize(deserializer));
|
let s = try!(String::deserialize(deserializer));
|
||||||
match s.parse() {
|
match s.parse() {
|
||||||
Ok(s) => Ok(s),
|
Ok(s) => Ok(s),
|
||||||
Err(err) => Err(D::Error::invalid_value(&err.to_string())),
|
Err(err) => Err(D::Error::custom(err)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -798,7 +816,7 @@ impl Deserialize for net::Ipv4Addr {
|
|||||||
let s = try!(String::deserialize(deserializer));
|
let s = try!(String::deserialize(deserializer));
|
||||||
match s.parse() {
|
match s.parse() {
|
||||||
Ok(s) => Ok(s),
|
Ok(s) => Ok(s),
|
||||||
Err(err) => Err(D::Error::invalid_value(&err.to_string())),
|
Err(err) => Err(D::Error::custom(err)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -811,7 +829,7 @@ impl Deserialize for net::Ipv6Addr {
|
|||||||
let s = try!(String::deserialize(deserializer));
|
let s = try!(String::deserialize(deserializer));
|
||||||
match s.parse() {
|
match s.parse() {
|
||||||
Ok(s) => Ok(s),
|
Ok(s) => Ok(s),
|
||||||
Err(err) => Err(D::Error::invalid_value(&err.to_string())),
|
Err(err) => Err(D::Error::custom(err)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -826,7 +844,7 @@ impl Deserialize for net::SocketAddr {
|
|||||||
let s = try!(String::deserialize(deserializer));
|
let s = try!(String::deserialize(deserializer));
|
||||||
match s.parse() {
|
match s.parse() {
|
||||||
Ok(s) => Ok(s),
|
Ok(s) => Ok(s),
|
||||||
Err(err) => Err(D::Error::invalid_value(&err.to_string())),
|
Err(err) => Err(D::Error::custom(err)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -839,7 +857,7 @@ impl Deserialize for net::SocketAddrV4 {
|
|||||||
let s = try!(String::deserialize(deserializer));
|
let s = try!(String::deserialize(deserializer));
|
||||||
match s.parse() {
|
match s.parse() {
|
||||||
Ok(s) => Ok(s),
|
Ok(s) => Ok(s),
|
||||||
Err(err) => Err(D::Error::invalid_value(&err.to_string())),
|
Err(err) => Err(D::Error::custom(err)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -852,7 +870,7 @@ impl Deserialize for net::SocketAddrV6 {
|
|||||||
let s = try!(String::deserialize(deserializer));
|
let s = try!(String::deserialize(deserializer));
|
||||||
match s.parse() {
|
match s.parse() {
|
||||||
Ok(s) => Ok(s),
|
Ok(s) => Ok(s),
|
||||||
Err(err) => Err(D::Error::invalid_value(&err.to_string())),
|
Err(err) => Err(D::Error::custom(err)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -866,6 +884,10 @@ struct PathBufVisitor;
|
|||||||
impl Visitor for PathBufVisitor {
|
impl Visitor for PathBufVisitor {
|
||||||
type Value = path::PathBuf;
|
type Value = path::PathBuf;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str("path string")
|
||||||
|
}
|
||||||
|
|
||||||
fn visit_str<E>(self, v: &str) -> Result<path::PathBuf, E>
|
fn visit_str<E>(self, v: &str) -> Result<path::PathBuf, E>
|
||||||
where E: Error,
|
where E: Error,
|
||||||
{
|
{
|
||||||
@@ -875,7 +897,7 @@ impl Visitor for PathBufVisitor {
|
|||||||
fn visit_string<E>(self, v: String) -> Result<path::PathBuf, E>
|
fn visit_string<E>(self, v: String) -> Result<path::PathBuf, E>
|
||||||
where E: Error,
|
where E: Error,
|
||||||
{
|
{
|
||||||
self.visit_str(&v)
|
Ok(From::from(v))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -977,14 +999,8 @@ impl Deserialize for Duration {
|
|||||||
impl Visitor for FieldVisitor {
|
impl Visitor for FieldVisitor {
|
||||||
type Value = Field;
|
type Value = Field;
|
||||||
|
|
||||||
fn visit_usize<E>(self, value: usize) -> Result<Field, E>
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
where E: Error,
|
formatter.write_str("`secs` or `nanos`")
|
||||||
{
|
|
||||||
match value {
|
|
||||||
0usize => Ok(Field::Secs),
|
|
||||||
1usize => Ok(Field::Nanos),
|
|
||||||
_ => Err(Error::invalid_value("expected a field")),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn visit_str<E>(self, value: &str) -> Result<Field, E>
|
fn visit_str<E>(self, value: &str) -> Result<Field, E>
|
||||||
@@ -993,7 +1009,7 @@ impl Deserialize for Duration {
|
|||||||
match value {
|
match value {
|
||||||
"secs" => Ok(Field::Secs),
|
"secs" => Ok(Field::Secs),
|
||||||
"nanos" => Ok(Field::Nanos),
|
"nanos" => Ok(Field::Nanos),
|
||||||
_ => Err(Error::unknown_field(value)),
|
_ => Err(Error::unknown_field(value, FIELDS)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1005,7 +1021,7 @@ impl Deserialize for Duration {
|
|||||||
b"nanos" => Ok(Field::Nanos),
|
b"nanos" => Ok(Field::Nanos),
|
||||||
_ => {
|
_ => {
|
||||||
let value = String::from_utf8_lossy(value);
|
let value = String::from_utf8_lossy(value);
|
||||||
Err(Error::unknown_field(&value))
|
Err(Error::unknown_field(&value, FIELDS))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1020,19 +1036,23 @@ impl Deserialize for Duration {
|
|||||||
impl Visitor for DurationVisitor {
|
impl Visitor for DurationVisitor {
|
||||||
type Value = Duration;
|
type Value = Duration;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str("struct Duration")
|
||||||
|
}
|
||||||
|
|
||||||
fn visit_seq<V>(self, mut visitor: V) -> Result<Duration, V::Error>
|
fn visit_seq<V>(self, mut visitor: V) -> Result<Duration, V::Error>
|
||||||
where V: SeqVisitor,
|
where V: SeqVisitor,
|
||||||
{
|
{
|
||||||
let secs: u64 = match try!(visitor.visit()) {
|
let secs: u64 = match try!(visitor.visit()) {
|
||||||
Some(value) => value,
|
Some(value) => value,
|
||||||
None => {
|
None => {
|
||||||
return Err(Error::invalid_length(0));
|
return Err(Error::invalid_length(0, &self));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let nanos: u32 = match try!(visitor.visit()) {
|
let nanos: u32 = match try!(visitor.visit()) {
|
||||||
Some(value) => value,
|
Some(value) => value,
|
||||||
None => {
|
None => {
|
||||||
return Err(Error::invalid_length(1));
|
return Err(Error::invalid_length(1, &self));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Ok(Duration::new(secs, nanos))
|
Ok(Duration::new(secs, nanos))
|
||||||
@@ -1061,11 +1081,11 @@ impl Deserialize for Duration {
|
|||||||
}
|
}
|
||||||
let secs = match secs {
|
let secs = match secs {
|
||||||
Some(secs) => secs,
|
Some(secs) => secs,
|
||||||
None => try!(visitor.missing_field("secs")),
|
None => return Err(<V::Error as Error>::missing_field("secs")),
|
||||||
};
|
};
|
||||||
let nanos = match nanos {
|
let nanos = match nanos {
|
||||||
Some(nanos) => nanos,
|
Some(nanos) => nanos,
|
||||||
None => try!(visitor.missing_field("nanos")),
|
None => return Err(<V::Error as Error>::missing_field("nanos")),
|
||||||
};
|
};
|
||||||
Ok(Duration::new(secs, nanos))
|
Ok(Duration::new(secs, nanos))
|
||||||
}
|
}
|
||||||
@@ -1079,11 +1099,12 @@ impl Deserialize for Duration {
|
|||||||
///////////////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(feature = "unstable")]
|
||||||
|
#[allow(deprecated)] // num::Zero is deprecated but there is no replacement
|
||||||
impl<T> Deserialize for NonZero<T> where T: Deserialize + PartialEq + Zeroable + Zero {
|
impl<T> Deserialize for NonZero<T> where T: Deserialize + PartialEq + Zeroable + Zero {
|
||||||
fn deserialize<D>(deserializer: D) -> Result<NonZero<T>, D::Error> where D: Deserializer {
|
fn deserialize<D>(deserializer: D) -> Result<NonZero<T>, D::Error> where D: Deserializer {
|
||||||
let value = try!(Deserialize::deserialize(deserializer));
|
let value = try!(Deserialize::deserialize(deserializer));
|
||||||
if value == Zero::zero() {
|
if value == Zero::zero() {
|
||||||
return Err(Error::invalid_value("expected a non-zero value"))
|
return Err(Error::custom("expected a non-zero value"))
|
||||||
}
|
}
|
||||||
unsafe {
|
unsafe {
|
||||||
Ok(NonZero::new(value))
|
Ok(NonZero::new(value))
|
||||||
@@ -1112,23 +1133,15 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
|
|||||||
impl Visitor for FieldVisitor {
|
impl Visitor for FieldVisitor {
|
||||||
type Value = Field;
|
type Value = Field;
|
||||||
|
|
||||||
#[cfg(any(feature = "std", feature = "collections"))]
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
fn visit_usize<E>(self, value: usize) -> Result<Field, E> where E: Error {
|
formatter.write_str("`Ok` or `Err`")
|
||||||
#[cfg(feature = "collections")]
|
|
||||||
use collections::string::ToString;
|
|
||||||
match value {
|
|
||||||
0 => Ok(Field::Ok),
|
|
||||||
1 => Ok(Field::Err),
|
|
||||||
_ => Err(Error::unknown_field(&value.to_string())),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(not(feature = "std"), not(feature = "collections")))]
|
fn visit_u32<E>(self, value: u32) -> Result<Field, E> where E: Error {
|
||||||
fn visit_usize<E>(self, value: usize) -> Result<Field, E> where E: Error {
|
|
||||||
match value {
|
match value {
|
||||||
0 => Ok(Field::Ok),
|
0 => Ok(Field::Ok),
|
||||||
1 => Ok(Field::Err),
|
1 => Ok(Field::Err),
|
||||||
_ => Err(Error::unknown_field("some number")),
|
_ => Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1136,7 +1149,7 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
|
|||||||
match value {
|
match value {
|
||||||
"Ok" => Ok(Field::Ok),
|
"Ok" => Ok(Field::Ok),
|
||||||
"Err" => Ok(Field::Err),
|
"Err" => Ok(Field::Err),
|
||||||
_ => Err(Error::unknown_field(value)),
|
_ => Err(Error::unknown_variant(value, VARIANTS)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1146,8 +1159,8 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
|
|||||||
b"Err" => Ok(Field::Err),
|
b"Err" => Ok(Field::Err),
|
||||||
_ => {
|
_ => {
|
||||||
match str::from_utf8(value) {
|
match str::from_utf8(value) {
|
||||||
Ok(value) => Err(Error::unknown_field(value)),
|
Ok(value) => Err(Error::unknown_variant(value, VARIANTS)),
|
||||||
Err(_) => Err(Error::invalid_type(Type::String)),
|
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1166,6 +1179,10 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
|
|||||||
{
|
{
|
||||||
type Value = Result<T, E>;
|
type Value = Result<T, E>;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str("enum Result")
|
||||||
|
}
|
||||||
|
|
||||||
fn visit_enum<V>(self, visitor: V) -> Result<Result<T, E>, V::Error>
|
fn visit_enum<V>(self, visitor: V) -> Result<Result<T, E>, V::Error>
|
||||||
where V: EnumVisitor
|
where V: EnumVisitor
|
||||||
{
|
{
|
||||||
@@ -1198,6 +1215,10 @@ impl Deserialize for IgnoredAny {
|
|||||||
impl Visitor for IgnoredAnyVisitor {
|
impl Visitor for IgnoredAnyVisitor {
|
||||||
type Value = IgnoredAny;
|
type Value = IgnoredAny;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
formatter.write_str("anything at all")
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn visit_bool<E>(self, _: bool) -> Result<IgnoredAny, E> {
|
fn visit_bool<E>(self, _: bool) -> Result<IgnoredAny, E> {
|
||||||
Ok(IgnoredAny)
|
Ok(IgnoredAny)
|
||||||
|
|||||||
+1174
-366
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,47 @@
|
|||||||
|
use core::marker::PhantomData;
|
||||||
|
|
||||||
|
use de::{Deserialize, Deserializer, Error, Visitor};
|
||||||
|
|
||||||
|
#[cfg(any(feature = "std", feature = "collections"))]
|
||||||
|
pub use de::content::{
|
||||||
|
Content,
|
||||||
|
TaggedContentVisitor,
|
||||||
|
InternallyTaggedUnitVisitor,
|
||||||
|
UntaggedUnitVisitor,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// If the missing field is of type `Option<T>` then treat is as `None`,
|
||||||
|
/// otherwise it is an error.
|
||||||
|
pub fn missing_field<V, E>(field: &'static str) -> Result<V, E>
|
||||||
|
where V: Deserialize,
|
||||||
|
E: Error
|
||||||
|
{
|
||||||
|
struct MissingFieldDeserializer<E>(&'static str, PhantomData<E>);
|
||||||
|
|
||||||
|
impl<E> Deserializer for MissingFieldDeserializer<E>
|
||||||
|
where E: Error
|
||||||
|
{
|
||||||
|
type Error = E;
|
||||||
|
|
||||||
|
fn deserialize<V>(self, _visitor: V) -> Result<V::Value, E>
|
||||||
|
where V: Visitor
|
||||||
|
{
|
||||||
|
Err(Error::missing_field(self.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E>
|
||||||
|
where V: Visitor
|
||||||
|
{
|
||||||
|
visitor.visit_none()
|
||||||
|
}
|
||||||
|
|
||||||
|
forward_to_deserialize! {
|
||||||
|
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
|
||||||
|
seq_fixed_size bytes byte_buf map unit_struct newtype_struct
|
||||||
|
tuple_struct struct struct_field tuple enum ignored_any
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let deserializer = MissingFieldDeserializer(field, PhantomData);
|
||||||
|
Deserialize::deserialize(deserializer)
|
||||||
|
}
|
||||||
+327
-289
File diff suppressed because it is too large
Load Diff
@@ -1,30 +1,7 @@
|
|||||||
//! A stand-in for `std::error`
|
//! A stand-in for `std::error`
|
||||||
use core::any::TypeId;
|
|
||||||
use core::fmt::{Debug, Display};
|
use core::fmt::{Debug, Display};
|
||||||
|
|
||||||
|
|
||||||
/// A stand-in for `std::error::Error`, which requires no allocation.
|
/// A stand-in for `std::error::Error`, which requires no allocation.
|
||||||
#[cfg(feature = "unstable")]
|
|
||||||
pub trait Error: Debug + Display + ::core::marker::Reflect {
|
|
||||||
/// A short description of the error.
|
|
||||||
///
|
|
||||||
/// The description should not contain newlines or sentence-ending
|
|
||||||
/// punctuation, to facilitate embedding in larger user-facing
|
|
||||||
/// strings.
|
|
||||||
fn description(&self) -> &str;
|
|
||||||
|
|
||||||
/// The lower-level cause of this error, if any.
|
|
||||||
fn cause(&self) -> Option<&Error> { None }
|
|
||||||
|
|
||||||
/// Get the `TypeId` of `self`
|
|
||||||
#[doc(hidden)]
|
|
||||||
fn type_id(&self) -> TypeId where Self: 'static {
|
|
||||||
TypeId::of::<Self>()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A stand-in for `std::error::Error`, which requires no allocation.
|
|
||||||
#[cfg(not(feature = "unstable"))]
|
|
||||||
pub trait Error: Debug + Display {
|
pub trait Error: Debug + Display {
|
||||||
/// A short description of the error.
|
/// A short description of the error.
|
||||||
///
|
///
|
||||||
@@ -35,10 +12,4 @@ pub trait Error: Debug + Display {
|
|||||||
|
|
||||||
/// The lower-level cause of this error, if any.
|
/// The lower-level cause of this error, if any.
|
||||||
fn cause(&self) -> Option<&Error> { None }
|
fn cause(&self) -> Option<&Error> { None }
|
||||||
|
|
||||||
/// Stubbed! Returns type_id of `()`
|
|
||||||
#[doc(hidden)]
|
|
||||||
fn type_id(&self) -> TypeId where Self: 'static {
|
|
||||||
TypeId::of::<()>()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||||
|
use collections::String;
|
||||||
|
|
||||||
|
#[cfg(feature = "std")]
|
||||||
|
use std::borrow::Cow;
|
||||||
|
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||||
|
use collections::borrow::Cow;
|
||||||
|
|
||||||
|
pub use core::default::Default;
|
||||||
|
pub use core::fmt;
|
||||||
|
pub use core::marker::PhantomData;
|
||||||
|
pub use core::option::Option::{self, None, Some};
|
||||||
|
pub use core::result::Result::{self, Ok, Err};
|
||||||
|
|
||||||
|
#[cfg(any(feature = "collections", feature = "std"))]
|
||||||
|
pub fn from_utf8_lossy(bytes: &[u8]) -> Cow<str> {
|
||||||
|
String::from_utf8_lossy(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The generated code calls this like:
|
||||||
|
//
|
||||||
|
// let value = &_serde::export::from_utf8_lossy(bytes);
|
||||||
|
// Err(_serde::de::Error::unknown_variant(value, VARIANTS))
|
||||||
|
//
|
||||||
|
// so it is okay for the return type to be different from the std case as long
|
||||||
|
// as the above works.
|
||||||
|
#[cfg(not(any(feature = "collections", feature = "std")))]
|
||||||
|
pub fn from_utf8_lossy(bytes: &[u8]) -> &str {
|
||||||
|
use core::str;
|
||||||
|
// Three unicode replacement characters if it fails. They look like a
|
||||||
|
// white-on-black question mark. The user will recognize it as invalid
|
||||||
|
// UTF-8.
|
||||||
|
str::from_utf8(bytes).unwrap_or("\u{fffd}\u{fffd}\u{fffd}")
|
||||||
|
}
|
||||||
+76
-27
@@ -1,58 +1,107 @@
|
|||||||
//! Serde Serialization Framework
|
//! # Serde
|
||||||
//!
|
//!
|
||||||
//! Serde is a powerful framework that enables serialization libraries to generically serialize
|
//! Serde is a framework for ***ser***ializing and ***de***serializing Rust data
|
||||||
//! Rust data structures without the overhead of runtime type information. In many situations, the
|
//! structures efficiently and generically.
|
||||||
//! handshake protocol between serializers and serializees can be completely optimized away,
|
|
||||||
//! leaving serde to perform roughly the same speed as a hand written serializer for a specific
|
|
||||||
//! type.
|
|
||||||
//!
|
//!
|
||||||
//! For a detailed tutorial on the different ways to use serde please check out the
|
//! The Serde ecosystem consists of data structures that know how to serialize
|
||||||
//! [github repository](https://github.com/serde-rs/serde)
|
//! and deserialize themselves along with data formats that know how to
|
||||||
|
//! serialize and deserialize other things. Serde provides the layer by which
|
||||||
|
//! these two groups interact with each other, allowing any supported data
|
||||||
|
//! structure to be serialized and deserialized using any supported data format.
|
||||||
|
//!
|
||||||
|
//! See the Serde website https://serde.rs/ for additional documentation and
|
||||||
|
//! usage examples.
|
||||||
|
//!
|
||||||
|
//! ### Design
|
||||||
|
//!
|
||||||
|
//! Where many other languages rely on runtime reflection for serializing data,
|
||||||
|
//! Serde is instead built on Rust's powerful trait system. A data structure
|
||||||
|
//! that knows how to serialize and deserialize itself is one that implements
|
||||||
|
//! Serde's `Serialize` and `Deserialize` traits (or uses Serde's code
|
||||||
|
//! generation to automatically derive implementations at compile time). This
|
||||||
|
//! avoids any overhead of reflection or runtime type information. In fact in
|
||||||
|
//! many situations the interaction between data structure and data format can
|
||||||
|
//! be completely optimized away by the Rust compiler, leaving Serde
|
||||||
|
//! serialization to perform roughly the same speed as a handwritten serializer
|
||||||
|
//! for the specific selection of data structure and data format.
|
||||||
|
//!
|
||||||
|
//! ### Data formats
|
||||||
|
//!
|
||||||
|
//! The following is a partial list of data formats that have been implemented
|
||||||
|
//! for Serde by the community.
|
||||||
|
//!
|
||||||
|
//! - [JSON](https://github.com/serde-rs/json), the ubiquitous JavaScript Object
|
||||||
|
//! Notation used by many HTTP APIs.
|
||||||
|
//! - [Bincode](https://github.com/TyOverby/bincode), a compact binary format
|
||||||
|
//! used for IPC within the Servo rendering engine.
|
||||||
|
//! - [CBOR](https://github.com/pyfisch/cbor), a Concise Binary Object
|
||||||
|
//! Representation designed for small message size without the need for
|
||||||
|
//! version negotiation.
|
||||||
|
//! - [YAML](https://github.com/dtolnay/serde-yaml), a popular human-friendly
|
||||||
|
//! configuration language that ain't markup language.
|
||||||
|
//! - [MessagePack](https://github.com/3Hren/msgpack-rust), an efficient binary
|
||||||
|
//! format that resembles a compact JSON.
|
||||||
|
//! - [TOML](https://github.com/alexcrichton/toml-rs), a minimal configuration
|
||||||
|
//! format used by [Cargo](http://doc.crates.io/manifest.html).
|
||||||
|
//! - [Pickle](https://github.com/birkenfeld/serde-pickle), a format common in
|
||||||
|
//! the Python world.
|
||||||
|
//! - [Hjson](https://github.com/laktak/hjson-rust), a variant of JSON designed
|
||||||
|
//! to be readable and writable by humans.
|
||||||
|
//! - [BSON](https://github.com/zonyitoo/bson-rs), the data storage and network
|
||||||
|
//! transfer format used by MongoDB.
|
||||||
|
//! - [URL](https://github.com/nox/serde_urlencoded), the x-www-form-urlencoded
|
||||||
|
//! format.
|
||||||
|
//! - [XML](https://github.com/serde-rs/xml), the flexible machine-friendly W3C
|
||||||
|
//! standard. *(deserialization only)*
|
||||||
|
//! - [Envy](https://github.com/softprops/envy), a way to deserialize
|
||||||
|
//! environment variables into Rust structs. *(deserialization only)*
|
||||||
|
//! - [Redis](https://github.com/OneSignal/serde-redis), deserialize values from
|
||||||
|
//! Redis when using [redis-rs](https://crates.io/crates/redis).
|
||||||
|
//! *(deserialization only)*
|
||||||
|
|
||||||
#![doc(html_root_url="https://docs.serde.rs")]
|
#![doc(html_root_url="https://docs.serde.rs")]
|
||||||
#![cfg_attr(not(feature = "std"), no_std)]
|
#![cfg_attr(not(feature = "std"), no_std)]
|
||||||
#![cfg_attr(feature = "unstable", feature(reflect_marker, unicode, nonzero, plugin, step_trait, zero_one))]
|
#![cfg_attr(feature = "unstable", feature(nonzero, inclusive_range, zero_one))]
|
||||||
#![cfg_attr(feature = "alloc", feature(alloc))]
|
#![cfg_attr(feature = "alloc", feature(alloc))]
|
||||||
#![cfg_attr(feature = "collections", feature(collections, enumset))]
|
#![cfg_attr(feature = "collections", feature(collections))]
|
||||||
#![cfg_attr(feature = "clippy", plugin(clippy))]
|
#![cfg_attr(feature = "cargo-clippy", allow(linkedlist, type_complexity, doc_markdown))]
|
||||||
#![cfg_attr(feature = "clippy", allow(linkedlist))]
|
|
||||||
|
|
||||||
#![cfg_attr(any(not(feature = "std"), feature = "unstable"), allow(unused_variables, unused_imports, unused_features, dead_code))]
|
|
||||||
|
|
||||||
#![deny(missing_docs)]
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
#[cfg(all(feature = "unstable", feature = "collections"))]
|
#[cfg(feature = "collections")]
|
||||||
extern crate collections;
|
extern crate collections;
|
||||||
|
|
||||||
#[cfg(all(feature = "unstable", feature = "alloc"))]
|
#[cfg(feature = "alloc")]
|
||||||
extern crate alloc;
|
extern crate alloc;
|
||||||
|
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
extern crate core as actual_core;
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
mod core {
|
mod core {
|
||||||
pub use std::{ops, hash, fmt, cmp, marker, mem, i8, i16, i32, i64, u8, u16, u32, u64, isize,
|
pub use std::{ops, hash, fmt, cmp, marker, mem, i8, i16, i32, i64, u8, u16, u32, u64, isize,
|
||||||
usize, f32, f64, char, str, num, slice, iter, cell};
|
usize, f32, f64, char, str, num, slice, iter, cell, default, result, option};
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(feature = "unstable")]
|
||||||
extern crate core;
|
pub use actual_core::nonzero;
|
||||||
#[cfg(feature = "unstable")]
|
|
||||||
pub use self::core::nonzero;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[doc(inline)]
|
||||||
pub use ser::{Serialize, Serializer};
|
pub use ser::{Serialize, Serializer};
|
||||||
|
#[doc(inline)]
|
||||||
pub use de::{Deserialize, Deserializer};
|
pub use de::{Deserialize, Deserializer};
|
||||||
|
|
||||||
#[cfg(not(feature = "std"))]
|
|
||||||
macro_rules! format {
|
|
||||||
($s:expr, $($rest:tt)*) => ($s)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
mod macros;
|
mod macros;
|
||||||
|
|
||||||
pub mod bytes;
|
pub mod bytes;
|
||||||
pub mod de;
|
pub mod de;
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
|
#[doc(hidden)]
|
||||||
pub mod iter;
|
pub mod iter;
|
||||||
pub mod ser;
|
pub mod ser;
|
||||||
#[cfg(not(feature = "std"))]
|
#[cfg_attr(feature = "std", doc(hidden))]
|
||||||
pub mod error;
|
pub mod error;
|
||||||
mod utils;
|
mod utils;
|
||||||
|
|
||||||
|
// Generated code uses these to support no_std. Not public API.
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub mod export;
|
||||||
|
|||||||
+54
-15
@@ -32,9 +32,6 @@ macro_rules! forward_to_deserialize_helper {
|
|||||||
(bool) => {
|
(bool) => {
|
||||||
forward_to_deserialize_method!{deserialize_bool()}
|
forward_to_deserialize_method!{deserialize_bool()}
|
||||||
};
|
};
|
||||||
(usize) => {
|
|
||||||
forward_to_deserialize_method!{deserialize_usize()}
|
|
||||||
};
|
|
||||||
(u8) => {
|
(u8) => {
|
||||||
forward_to_deserialize_method!{deserialize_u8()}
|
forward_to_deserialize_method!{deserialize_u8()}
|
||||||
};
|
};
|
||||||
@@ -47,9 +44,6 @@ macro_rules! forward_to_deserialize_helper {
|
|||||||
(u64) => {
|
(u64) => {
|
||||||
forward_to_deserialize_method!{deserialize_u64()}
|
forward_to_deserialize_method!{deserialize_u64()}
|
||||||
};
|
};
|
||||||
(isize) => {
|
|
||||||
forward_to_deserialize_method!{deserialize_isize()}
|
|
||||||
};
|
|
||||||
(i8) => {
|
(i8) => {
|
||||||
forward_to_deserialize_method!{deserialize_i8()}
|
forward_to_deserialize_method!{deserialize_i8()}
|
||||||
};
|
};
|
||||||
@@ -92,6 +86,9 @@ macro_rules! forward_to_deserialize_helper {
|
|||||||
(bytes) => {
|
(bytes) => {
|
||||||
forward_to_deserialize_method!{deserialize_bytes()}
|
forward_to_deserialize_method!{deserialize_bytes()}
|
||||||
};
|
};
|
||||||
|
(byte_buf) => {
|
||||||
|
forward_to_deserialize_method!{deserialize_byte_buf()}
|
||||||
|
};
|
||||||
(map) => {
|
(map) => {
|
||||||
forward_to_deserialize_method!{deserialize_map()}
|
forward_to_deserialize_method!{deserialize_map()}
|
||||||
};
|
};
|
||||||
@@ -121,28 +118,70 @@ macro_rules! forward_to_deserialize_helper {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Helper to forward `Deserializer` methods to `Deserializer::deserialize`.
|
// Super explicit first paragraph because this shows up at the top level and
|
||||||
/// Every given method ignores all arguments and forwards to `deserialize`.
|
// trips up people who are just looking for basic Serialize / Deserialize
|
||||||
/// Note that `deserialize_enum` simply returns an `Error::invalid_type`; a
|
// documentation.
|
||||||
/// better approach is tracked in [serde-rs/serde#521][1].
|
//
|
||||||
|
/// Helper macro when implementing the `Deserializer` part of a new data format
|
||||||
|
/// for Serde.
|
||||||
///
|
///
|
||||||
/// ```rust,ignore
|
/// Some `Deserializer` implementations for self-describing formats do not care
|
||||||
|
/// what hint the `Visitor` gives them, they just want to blindly call the
|
||||||
|
/// `Visitor` method corresponding to the data they can tell is in the input.
|
||||||
|
/// This requires repetitive implementations of all the `Deserializer` trait
|
||||||
|
/// methods.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// # #[macro_use] extern crate serde;
|
||||||
|
/// # use serde::de::{value, Deserializer, Visitor};
|
||||||
|
/// # pub struct MyDeserializer;
|
||||||
|
/// # impl Deserializer for MyDeserializer {
|
||||||
|
/// # type Error = value::Error;
|
||||||
|
/// # fn deserialize<V>(self, _: V) -> Result<V::Value, Self::Error>
|
||||||
|
/// # where V: Visitor
|
||||||
|
/// # { unimplemented!() }
|
||||||
|
/// #
|
||||||
|
/// #[inline]
|
||||||
|
/// fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||||
|
/// where V: Visitor
|
||||||
|
/// {
|
||||||
|
/// self.deserialize(visitor)
|
||||||
|
/// }
|
||||||
|
/// # forward_to_deserialize! {
|
||||||
|
/// # u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
|
||||||
|
/// # seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
|
||||||
|
/// # tuple_struct struct struct_field tuple enum ignored_any
|
||||||
|
/// # }
|
||||||
|
/// # }
|
||||||
|
/// # fn main() {}
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// The `forward_to_deserialize!` macro implements these simple forwarding
|
||||||
|
/// methods so that they forward directly to `Deserializer::deserialize`. You
|
||||||
|
/// can choose which methods to forward.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// # #[macro_use] extern crate serde;
|
||||||
|
/// # use serde::de::{value, Deserializer, Visitor};
|
||||||
|
/// # pub struct MyDeserializer;
|
||||||
/// impl Deserializer for MyDeserializer {
|
/// impl Deserializer for MyDeserializer {
|
||||||
|
/// # type Error = value::Error;
|
||||||
/// fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
/// fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||||
/// where V: Visitor
|
/// where V: Visitor
|
||||||
/// {
|
/// {
|
||||||
/// /* ... */
|
/// /* ... */
|
||||||
|
/// # let _ = visitor;
|
||||||
|
/// # unimplemented!()
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
/// forward_to_deserialize! {
|
/// forward_to_deserialize! {
|
||||||
/// bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
|
/// bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
|
||||||
/// unit option seq seq_fixed_size bytes map unit_struct newtype_struct
|
/// seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
|
||||||
/// tuple_struct struct struct_field tuple enum ignored_any
|
/// tuple_struct struct struct_field tuple enum ignored_any
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
|
/// # fn main() {}
|
||||||
/// ```
|
/// ```
|
||||||
///
|
|
||||||
/// [1]: https://github.com/serde-rs/serde/issues/521
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! forward_to_deserialize {
|
macro_rules! forward_to_deserialize {
|
||||||
($($func:ident)*) => {
|
($($func:ident)*) => {
|
||||||
|
|||||||
+39
-39
@@ -1,9 +1,3 @@
|
|||||||
//! Implementations for all of Rust's builtin types. Tuples implement the `Serialize` trait if they
|
|
||||||
//! have at most 16 fields. Arrays implement the `Serialize` trait if their length is 32 or less.
|
|
||||||
//! You can always forward array serialization to slice serialization, which works for any length.
|
|
||||||
//! Long tuples are best replaced by tuple structs, for which you can use `derive(Serialize)`. In
|
|
||||||
//! that case the number of fields is irrelevant.
|
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||||
@@ -30,19 +24,16 @@ use collections::{
|
|||||||
Vec,
|
Vec,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[cfg(all(feature = "unstable", feature = "collections"))]
|
#[cfg(feature = "collections")]
|
||||||
use collections::enum_set::{CLike, EnumSet};
|
|
||||||
#[cfg(all(feature = "unstable", feature = "collections"))]
|
|
||||||
use collections::borrow::ToOwned;
|
use collections::borrow::ToOwned;
|
||||||
|
|
||||||
|
#[cfg(feature = "std")]
|
||||||
use core::hash::{Hash, BuildHasher};
|
use core::hash::{Hash, BuildHasher};
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(feature = "unstable")]
|
||||||
use core::iter;
|
use core::iter;
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
use std::net;
|
use std::net;
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(feature = "unstable")]
|
||||||
use core::num;
|
|
||||||
#[cfg(feature = "unstable")]
|
|
||||||
use core::ops;
|
use core::ops;
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
use std::path;
|
use std::path;
|
||||||
@@ -67,14 +58,13 @@ use core::marker::PhantomData;
|
|||||||
use core::nonzero::{NonZero, Zeroable};
|
use core::nonzero::{NonZero, Zeroable};
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
Error,
|
|
||||||
Serialize,
|
Serialize,
|
||||||
SerializeMap,
|
|
||||||
SerializeSeq,
|
SerializeSeq,
|
||||||
SerializeStruct,
|
|
||||||
SerializeTuple,
|
SerializeTuple,
|
||||||
Serializer,
|
Serializer,
|
||||||
};
|
};
|
||||||
|
#[cfg(any(feature = "std", feature = "unstable"))]
|
||||||
|
use super::Error;
|
||||||
|
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(feature = "unstable")]
|
||||||
use super::Iterator;
|
use super::Iterator;
|
||||||
@@ -82,25 +72,25 @@ use super::Iterator;
|
|||||||
///////////////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
macro_rules! impl_visit {
|
macro_rules! impl_visit {
|
||||||
($ty:ty, $method:ident) => {
|
($ty:ty, $method:ident $($cast:tt)*) => {
|
||||||
impl Serialize for $ty {
|
impl Serialize for $ty {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
where S: Serializer,
|
where S: Serializer,
|
||||||
{
|
{
|
||||||
serializer.$method(*self)
|
serializer.$method(*self $($cast)*)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl_visit!(bool, serialize_bool);
|
impl_visit!(bool, serialize_bool);
|
||||||
impl_visit!(isize, serialize_isize);
|
impl_visit!(isize, serialize_i64 as i64);
|
||||||
impl_visit!(i8, serialize_i8);
|
impl_visit!(i8, serialize_i8);
|
||||||
impl_visit!(i16, serialize_i16);
|
impl_visit!(i16, serialize_i16);
|
||||||
impl_visit!(i32, serialize_i32);
|
impl_visit!(i32, serialize_i32);
|
||||||
impl_visit!(i64, serialize_i64);
|
impl_visit!(i64, serialize_i64);
|
||||||
impl_visit!(usize, serialize_usize);
|
impl_visit!(usize, serialize_u64 as u64);
|
||||||
impl_visit!(u8, serialize_u8);
|
impl_visit!(u8, serialize_u8);
|
||||||
impl_visit!(u16, serialize_u16);
|
impl_visit!(u16, serialize_u16);
|
||||||
impl_visit!(u32, serialize_u32);
|
impl_visit!(u32, serialize_u32);
|
||||||
@@ -239,9 +229,9 @@ impl<'a, I> Serialize for Iterator<I>
|
|||||||
where S: Serializer,
|
where S: Serializer,
|
||||||
{
|
{
|
||||||
// FIXME: use specialization to prevent invalidating the object in case of clonable iterators?
|
// FIXME: use specialization to prevent invalidating the object in case of clonable iterators?
|
||||||
let iter = match self.0.borrow_mut().take() {
|
let iter = match self.data.borrow_mut().take() {
|
||||||
Some(iter) => iter.into_iter(),
|
Some(iter) => iter.into_iter(),
|
||||||
None => return Err(S::Error::custom("Iterator used twice")),
|
None => return Err(Error::custom("Iterator used twice")),
|
||||||
};
|
};
|
||||||
let size = match iter.size_hint() {
|
let size = match iter.size_hint() {
|
||||||
(lo, Some(hi)) if lo == hi => Some(lo),
|
(lo, Some(hi)) if lo == hi => Some(lo),
|
||||||
@@ -249,7 +239,7 @@ impl<'a, I> Serialize for Iterator<I>
|
|||||||
};
|
};
|
||||||
let mut seq = try!(serializer.serialize_seq(size));
|
let mut seq = try!(serializer.serialize_seq(size));
|
||||||
for e in iter {
|
for e in iter {
|
||||||
try!(seq.serialize_element(e));
|
try!(seq.serialize_element(&e));
|
||||||
}
|
}
|
||||||
seq.end()
|
seq.end()
|
||||||
}
|
}
|
||||||
@@ -265,7 +255,7 @@ macro_rules! serialize_seq {
|
|||||||
{
|
{
|
||||||
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
|
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
|
||||||
for e in self {
|
for e in self {
|
||||||
try!(seq.serialize_element(e));
|
try!(seq.serialize_element(&e));
|
||||||
}
|
}
|
||||||
seq.end()
|
seq.end()
|
||||||
}
|
}
|
||||||
@@ -286,13 +276,6 @@ impl<T> Serialize for BTreeSet<T>
|
|||||||
serialize_seq!();
|
serialize_seq!();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(feature = "unstable", feature = "collections"))]
|
|
||||||
impl<T> Serialize for EnumSet<T>
|
|
||||||
where T: Serialize + CLike
|
|
||||||
{
|
|
||||||
serialize_seq!();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
impl<T, H> Serialize for HashSet<T, H>
|
impl<T, H> Serialize for HashSet<T, H>
|
||||||
where T: Serialize + Eq + Hash,
|
where T: Serialize + Eq + Hash,
|
||||||
@@ -324,17 +307,33 @@ impl<T> Serialize for VecDeque<T>
|
|||||||
|
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(feature = "unstable")]
|
||||||
impl<A> Serialize for ops::Range<A>
|
impl<A> Serialize for ops::Range<A>
|
||||||
where A: Serialize + Clone + iter::Step + num::One,
|
where ops::Range<A>: ExactSizeIterator + iter::Iterator<Item = A> + Clone,
|
||||||
for<'a> &'a A: ops::Add<&'a A, Output = A>,
|
A: Serialize,
|
||||||
{
|
{
|
||||||
#[inline]
|
#[inline]
|
||||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
where S: Serializer,
|
where S: Serializer,
|
||||||
{
|
{
|
||||||
let len = iter::Step::steps_between(&self.start, &self.end, &A::one());
|
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
|
||||||
let mut seq = try!(serializer.serialize_seq(len));
|
|
||||||
for e in self.clone() {
|
for e in self.clone() {
|
||||||
try!(seq.serialize_element(e));
|
try!(seq.serialize_element(&e));
|
||||||
|
}
|
||||||
|
seq.end()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
impl<A> Serialize for ops::RangeInclusive<A>
|
||||||
|
where ops::RangeInclusive<A>: ExactSizeIterator + iter::Iterator<Item = A> + Clone,
|
||||||
|
A: Serialize,
|
||||||
|
{
|
||||||
|
#[inline]
|
||||||
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
|
where S: Serializer,
|
||||||
|
{
|
||||||
|
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
|
||||||
|
for e in self.clone() {
|
||||||
|
try!(seq.serialize_element(&e));
|
||||||
}
|
}
|
||||||
seq.end()
|
seq.end()
|
||||||
}
|
}
|
||||||
@@ -557,10 +556,10 @@ macro_rules! serialize_map {
|
|||||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
where S: Serializer,
|
where S: Serializer,
|
||||||
{
|
{
|
||||||
|
use super::SerializeMap;
|
||||||
let mut map = try!(serializer.serialize_map(Some(self.len())));
|
let mut map = try!(serializer.serialize_map(Some(self.len())));
|
||||||
for (k, v) in self {
|
for (k, v) in self {
|
||||||
try!(map.serialize_key(k));
|
try!(map.serialize_entry(k, v));
|
||||||
try!(map.serialize_value(v));
|
|
||||||
}
|
}
|
||||||
map.end()
|
map.end()
|
||||||
}
|
}
|
||||||
@@ -679,9 +678,10 @@ impl Serialize for Duration {
|
|||||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
where S: Serializer,
|
where S: Serializer,
|
||||||
{
|
{
|
||||||
|
use super::SerializeStruct;
|
||||||
let mut state = try!(serializer.serialize_struct("Duration", 2));
|
let mut state = try!(serializer.serialize_struct("Duration", 2));
|
||||||
try!(state.serialize_field("secs", self.as_secs()));
|
try!(state.serialize_field("secs", &self.as_secs()));
|
||||||
try!(state.serialize_field("nanos", self.subsec_nanos()));
|
try!(state.serialize_field("nanos", &self.subsec_nanos()));
|
||||||
state.end()
|
state.end()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -756,7 +756,7 @@ impl Serialize for path::Path {
|
|||||||
{
|
{
|
||||||
match self.to_str() {
|
match self.to_str() {
|
||||||
Some(s) => s.serialize(serializer),
|
Some(s) => s.serialize(serializer),
|
||||||
None => Err(Error::invalid_value("Path contains invalid UTF-8 characters")),
|
None => Err(Error::custom("path contains invalid UTF-8 characters")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,177 @@
|
|||||||
|
//! This module contains `Impossible` serializer and its implementations.
|
||||||
|
|
||||||
|
use core::marker::PhantomData;
|
||||||
|
|
||||||
|
use ser::{
|
||||||
|
self,
|
||||||
|
Serialize,
|
||||||
|
SerializeSeq,
|
||||||
|
SerializeTuple,
|
||||||
|
SerializeTupleStruct,
|
||||||
|
SerializeTupleVariant,
|
||||||
|
SerializeMap,
|
||||||
|
SerializeStruct,
|
||||||
|
SerializeStructVariant,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Helper type for implementing a `Serializer` that does not support
|
||||||
|
/// serializing one of the compound types.
|
||||||
|
///
|
||||||
|
/// This type cannot be instantiated, but implements every one of the traits
|
||||||
|
/// corresponding to the `Serializer` compound types: `SerializeSeq`,
|
||||||
|
/// `SerializeTuple`, `SerializeTupleStruct`, `SerializeTupleVariant`,
|
||||||
|
/// `SerializeMap`, `SerializeStruct`, and `SerializeStructVariant`.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// impl Serializer for MySerializer {
|
||||||
|
/// type Ok = ();
|
||||||
|
/// type Error = Error;
|
||||||
|
///
|
||||||
|
/// type SerializeSeq = Impossible<(), Error>;
|
||||||
|
/// /* other associated types */
|
||||||
|
///
|
||||||
|
/// /// This data format does not support serializing sequences.
|
||||||
|
/// fn serialize_seq(self,
|
||||||
|
/// len: Option<usize>)
|
||||||
|
/// -> Result<Self::SerializeSeq, Error> {
|
||||||
|
/// // Given Impossible cannot be instantiated, the only
|
||||||
|
/// // thing we can do here is to return an error.
|
||||||
|
/// Err(...)
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// /* other Serializer methods */
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
pub struct Impossible<Ok, E> {
|
||||||
|
void: Void,
|
||||||
|
_marker: PhantomData<(Ok, E)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Void {}
|
||||||
|
|
||||||
|
impl<Ok, E> SerializeSeq for Impossible<Ok, E>
|
||||||
|
where E: ser::Error,
|
||||||
|
{
|
||||||
|
type Ok = Ok;
|
||||||
|
type Error = E;
|
||||||
|
|
||||||
|
fn serialize_element<T: ?Sized + Serialize>(&mut self,
|
||||||
|
_value: &T)
|
||||||
|
-> Result<(), E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(self) -> Result<Ok, E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Ok, E> SerializeTuple for Impossible<Ok, E>
|
||||||
|
where E: ser::Error,
|
||||||
|
{
|
||||||
|
type Ok = Ok;
|
||||||
|
type Error = E;
|
||||||
|
|
||||||
|
fn serialize_element<T: ?Sized + Serialize>(&mut self,
|
||||||
|
_value: &T)
|
||||||
|
-> Result<(), E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(self) -> Result<Ok, E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Ok, E> SerializeTupleStruct for Impossible<Ok, E>
|
||||||
|
where E: ser::Error,
|
||||||
|
{
|
||||||
|
type Ok = Ok;
|
||||||
|
type Error = E;
|
||||||
|
|
||||||
|
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||||
|
_value: &T)
|
||||||
|
-> Result<(), E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(self) -> Result<Ok, E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Ok, E> SerializeTupleVariant for Impossible<Ok, E>
|
||||||
|
where E: ser::Error,
|
||||||
|
{
|
||||||
|
type Ok = Ok;
|
||||||
|
type Error = E;
|
||||||
|
|
||||||
|
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||||
|
_value: &T)
|
||||||
|
-> Result<(), E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(self) -> Result<Ok, E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Ok, E> SerializeMap for Impossible<Ok, E>
|
||||||
|
where E: ser::Error,
|
||||||
|
{
|
||||||
|
type Ok = Ok;
|
||||||
|
type Error = E;
|
||||||
|
|
||||||
|
fn serialize_key<T: ?Sized + Serialize>(&mut self,
|
||||||
|
_key: &T)
|
||||||
|
-> Result<(), E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_value<T: ?Sized + Serialize>(&mut self,
|
||||||
|
_value: &T)
|
||||||
|
-> Result<(), E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(self) -> Result<Ok, E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Ok, E> SerializeStruct for Impossible<Ok, E>
|
||||||
|
where E: ser::Error,
|
||||||
|
{
|
||||||
|
type Ok = Ok;
|
||||||
|
type Error = E;
|
||||||
|
|
||||||
|
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||||
|
_key: &'static str,
|
||||||
|
_value: &T)
|
||||||
|
-> Result<(), E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(self) -> Result<Ok, E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Ok, E> SerializeStructVariant for Impossible<Ok, E>
|
||||||
|
where E: ser::Error,
|
||||||
|
{
|
||||||
|
type Ok = Ok;
|
||||||
|
type Error = E;
|
||||||
|
|
||||||
|
fn serialize_field<T: ?Sized + Serialize>(&mut self,
|
||||||
|
_key: &'static str,
|
||||||
|
_value: &T)
|
||||||
|
-> Result<(), E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(self) -> Result<Ok, E> {
|
||||||
|
match self.void {}
|
||||||
|
}
|
||||||
|
}
|
||||||
+574
-194
@@ -1,84 +1,254 @@
|
|||||||
//! Generic serialization framework.
|
//! Generic data structure serialization framework.
|
||||||
//! # For Developers who want to serialize objects
|
|
||||||
//! Implement the `Serialize` trait for the type of objects you want to serialize. Call methods of
|
|
||||||
//! the `serializer` object. For which methods to call and how to do so, look at the documentation
|
|
||||||
//! of the `Serializer` trait.
|
|
||||||
//!
|
//!
|
||||||
//! # For Serialization Format Developers
|
//! The two most important traits in this module are `Serialize` and
|
||||||
//! Implement the `Serializer` trait for a structure that contains fields that enable it to write
|
//! `Serializer`.
|
||||||
//! the serialization result to your target. When a method's argument is an object of type
|
//!
|
||||||
//! `Serialize`, you can either forward the serializer object (`self`) or create a new one,
|
//! - **A type that implements `Serialize` is a data structure** that can be
|
||||||
//! depending on the quirks of your format.
|
//! serialized to any data format supported by Serde, and conversely
|
||||||
|
//! - **A type that implements `Serializer` is a data format** that can
|
||||||
|
//! serialize any data structure supported by Serde.
|
||||||
|
//!
|
||||||
|
//! # The Serialize trait
|
||||||
|
//!
|
||||||
|
//! Serde provides `Serialize` implementations for many Rust primitive and
|
||||||
|
//! standard library types. The complete list is below. All of these can be
|
||||||
|
//! serialized using Serde out of the box.
|
||||||
|
//!
|
||||||
|
//! Additionally, Serde provides a procedural macro called `serde_derive` to
|
||||||
|
//! automatically generate `Serialize` implementations for structs and enums in
|
||||||
|
//! your program. See the [codegen section of the manual][codegen] for how to
|
||||||
|
//! use this.
|
||||||
|
//!
|
||||||
|
//! In rare cases it may be necessary to implement `Serialize` manually for some
|
||||||
|
//! type in your program. See the [Implementing `Serialize`][impl-serialize]
|
||||||
|
//! section of the manual for more about this.
|
||||||
|
//!
|
||||||
|
//! Third-party crates may provide `Serialize` implementations for types that
|
||||||
|
//! they expose. For example the `linked-hash-map` crate provides a
|
||||||
|
//! `LinkedHashMap<K, V>` type that is serializable by Serde because the crate
|
||||||
|
//! provides an implementation of `Serialize` for it.
|
||||||
|
//!
|
||||||
|
//! # The Serializer trait
|
||||||
|
//!
|
||||||
|
//! `Serializer` implementations are provided by third-party crates, for example
|
||||||
|
//! [`serde_json`][serde_json], [`serde_yaml`][serde_yaml] and
|
||||||
|
//! [`bincode`][bincode].
|
||||||
|
//!
|
||||||
|
//! A partial list of well-maintained formats is given on the [Serde
|
||||||
|
//! website][data-formats].
|
||||||
|
//!
|
||||||
|
//! # Implementations of Serialize provided by Serde
|
||||||
|
//!
|
||||||
|
//! - **Primitive types**:
|
||||||
|
//! - bool
|
||||||
|
//! - isize, i8, i16, i32, i64
|
||||||
|
//! - usize, u8, u16, u32, u64
|
||||||
|
//! - f32, f64
|
||||||
|
//! - char
|
||||||
|
//! - str
|
||||||
|
//! - &T and &mut T
|
||||||
|
//! - **Compound types**:
|
||||||
|
//! - [T]
|
||||||
|
//! - [T; 0] through [T; 32]
|
||||||
|
//! - tuples up to size 16
|
||||||
|
//! - **Common standard library types**:
|
||||||
|
//! - String
|
||||||
|
//! - Option\<T\>
|
||||||
|
//! - Result\<T, E\>
|
||||||
|
//! - PhantomData\<T\>
|
||||||
|
//! - **Wrapper types**:
|
||||||
|
//! - Box\<T\>
|
||||||
|
//! - Rc\<T\>
|
||||||
|
//! - Arc\<T\>
|
||||||
|
//! - Cow\<'a, T\>
|
||||||
|
//! - **Collection types**:
|
||||||
|
//! - BTreeMap\<K, V\>
|
||||||
|
//! - BTreeSet\<T\>
|
||||||
|
//! - BinaryHeap\<T\>
|
||||||
|
//! - HashMap\<K, V, H\>
|
||||||
|
//! - HashSet\<T, H\>
|
||||||
|
//! - LinkedList\<T\>
|
||||||
|
//! - VecDeque\<T\>
|
||||||
|
//! - Vec\<T\>
|
||||||
|
//! - EnumSet\<T\> (unstable)
|
||||||
|
//! - Range\<T\> (unstable)
|
||||||
|
//! - RangeInclusive\<T\> (unstable)
|
||||||
|
//! - **Miscellaneous standard library types**:
|
||||||
|
//! - Duration
|
||||||
|
//! - Path
|
||||||
|
//! - PathBuf
|
||||||
|
//! - NonZero\<T\> (unstable)
|
||||||
|
//! - **Net types**:
|
||||||
|
//! - IpAddr
|
||||||
|
//! - Ipv4Addr
|
||||||
|
//! - Ipv6Addr
|
||||||
|
//! - SocketAddr
|
||||||
|
//! - SocketAddrV4
|
||||||
|
//! - SocketAddrV6
|
||||||
|
//!
|
||||||
|
//! [codegen]: https://serde.rs/codegen.html
|
||||||
|
//! [impl-serialize]: https://serde.rs/impl-serialize.html
|
||||||
|
//! [serde_json]: https://github.com/serde-rs/json
|
||||||
|
//! [serde_yaml]: https://github.com/dtolnay/serde-yaml
|
||||||
|
//! [bincode]: https://github.com/TyOverby/bincode
|
||||||
|
//! [data-formats]: https://serde.rs/#data-formats
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
use std::error;
|
use std::error;
|
||||||
#[cfg(not(feature = "std"))]
|
#[cfg(not(feature = "std"))]
|
||||||
use error;
|
use error;
|
||||||
|
|
||||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
|
||||||
use collections::String;
|
|
||||||
|
|
||||||
#[cfg(feature = "unstable")]
|
|
||||||
use core::marker::PhantomData;
|
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(feature = "unstable")]
|
||||||
use core::cell::RefCell;
|
use core::cell::RefCell;
|
||||||
|
|
||||||
pub mod impls;
|
use core::fmt::Display;
|
||||||
|
|
||||||
|
mod impls;
|
||||||
|
mod impossible;
|
||||||
|
|
||||||
|
// Helpers used by generated code. Not public API.
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub mod private;
|
||||||
|
|
||||||
|
pub use self::impossible::Impossible;
|
||||||
|
|
||||||
///////////////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
/// `Error` is a trait that allows a `Serialize` to generically create a
|
/// Trait used by `Serialize` implementations to generically construct errors
|
||||||
/// `Serializer` error.
|
/// belonging to the `Serializer` against which they are currently running.
|
||||||
pub trait Error: Sized + error::Error {
|
pub trait Error: Sized + error::Error {
|
||||||
/// Raised when there is a general error when serializing a type.
|
/// Raised when a `Serialize` implementation encounters a general error
|
||||||
#[cfg(any(feature = "std", feature = "collections"))]
|
/// while serializing a type.
|
||||||
fn custom<T: Into<String>>(msg: T) -> Self;
|
///
|
||||||
|
/// The message should not be capitalized and should not end with a period.
|
||||||
/// Raised when there is a general error when serializing a type.
|
///
|
||||||
#[cfg(all(not(feature = "std"), not(feature = "collections")))]
|
/// For example, a filesystem `Path` may refuse to serialize itself if it
|
||||||
fn custom<T: Into<&'static str>>(msg: T) -> Self;
|
/// contains invalid UTF-8 data.
|
||||||
|
///
|
||||||
/// Raised when a `Serialize` was passed an incorrect value.
|
/// ```rust
|
||||||
fn invalid_value(msg: &str) -> Self {
|
/// # use serde::ser::{Serialize, Serializer, Error};
|
||||||
Error::custom(format!("invalid value: {}", msg))
|
/// # struct Path;
|
||||||
}
|
/// # impl Path { fn to_str(&self) -> Option<&str> { unimplemented!() } }
|
||||||
|
/// impl Serialize for Path {
|
||||||
|
/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
|
/// where S: Serializer
|
||||||
|
/// {
|
||||||
|
/// match self.to_str() {
|
||||||
|
/// Some(s) => s.serialize(serializer),
|
||||||
|
/// None => Err(Error::custom("path contains invalid UTF-8 characters")),
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
fn custom<T: Display>(msg: T) -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
///////////////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
/// A trait that describes a type that can be serialized by a `Serializer`.
|
/// A **data structure** that can be serialized into any data format supported
|
||||||
|
/// by Serde.
|
||||||
|
///
|
||||||
|
/// Serde provides `Serialize` implementations for many Rust primitive and
|
||||||
|
/// standard library types. The complete list is [here][ser]. All of these can
|
||||||
|
/// be serialized using Serde out of the box.
|
||||||
|
///
|
||||||
|
/// Additionally, Serde provides a procedural macro called `serde_derive` to
|
||||||
|
/// automatically generate `Serialize` implementations for structs and enums in
|
||||||
|
/// your program. See the [codegen section of the manual][codegen] for how to
|
||||||
|
/// use this.
|
||||||
|
///
|
||||||
|
/// In rare cases it may be necessary to implement `Serialize` manually for some
|
||||||
|
/// type in your program. See the [Implementing `Serialize`][impl-serialize]
|
||||||
|
/// section of the manual for more about this.
|
||||||
|
///
|
||||||
|
/// Third-party crates may provide `Serialize` implementations for types that
|
||||||
|
/// they expose. For example the `linked-hash-map` crate provides a
|
||||||
|
/// `LinkedHashMap<K, V>` type that is serializable by Serde because the crate
|
||||||
|
/// provides an implementation of `Serialize` for it.
|
||||||
|
///
|
||||||
|
/// [ser]: https://docs.serde.rs/serde/ser/index.html
|
||||||
|
/// [codegen]: https://serde.rs/codegen.html
|
||||||
|
/// [impl-serialize]: https://serde.rs/impl-serialize.html
|
||||||
pub trait Serialize {
|
pub trait Serialize {
|
||||||
/// Serializes this value into this serializer.
|
/// Serialize this value into the given Serde serializer.
|
||||||
|
///
|
||||||
|
/// See the [Implementing `Serialize`][impl-serialize] section of the manual
|
||||||
|
/// for more information about how to implement this method.
|
||||||
|
///
|
||||||
|
/// [impl-serialize]: https://serde.rs/impl-serialize.html
|
||||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
where S: Serializer;
|
where S: Serializer;
|
||||||
}
|
}
|
||||||
|
|
||||||
///////////////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
/// A trait that describes a type that can serialize a stream of values into the underlying format.
|
/// A **data format** that can serialize any data structure supported by Serde.
|
||||||
///
|
///
|
||||||
/// # For `Serialize` Developers
|
/// The role of this trait is to define the serialization half of the Serde data
|
||||||
/// Non-aggregate types like integers and strings can be serialized directly by calling the
|
/// model, which is a way to categorize every Rust data structure into one of 28
|
||||||
/// appropriate function. For Aggregate types there's an initial `serialize_T` method that yields
|
/// possible types. Each method of the `Serializer` trait corresponds to one of
|
||||||
/// a State object that you should not interact with. For each part of the aggregate there's a
|
/// the types of the data model.
|
||||||
/// `serialize_T_elt` method that allows you to pass values or key/value pairs. The types of the
|
|
||||||
/// values or the keys may change between calls, but the serialization format may not necessarily
|
|
||||||
/// accept it. The `serialize_T_elt` method also takes a mutable reference to the state object.
|
|
||||||
/// Make sure that you always use the same state object and only the state object that was returned
|
|
||||||
/// by the `serialize_T` method. Finally, when your object is done, call the `serialize_T_end`
|
|
||||||
/// method and pass the state object by value
|
|
||||||
///
|
///
|
||||||
/// # For Serialization Format Developers
|
/// Implementations of `Serialize` map themselves into this data model by
|
||||||
/// If your format has different situations where it accepts different types, create a
|
/// invoking exactly one of the `Serializer` methods.
|
||||||
/// `Serializer` for each situation. You can create the sub-`Serializer` in one of the aggregate
|
///
|
||||||
/// `serialize_T` methods and return it as a state object. Remember to also set the corresponding
|
/// The types that make up the Serde data model are:
|
||||||
/// associated type `TState`. In the `serialize_T_elt` methods you will be given a mutable
|
///
|
||||||
/// reference to that state. You do not need to do any additional checks for the correctness of the
|
/// - 12 primitive types:
|
||||||
/// state object, as it is expected that the user will not modify it. Due to the generic nature
|
/// - bool
|
||||||
/// of the `Serialize` impls, modifying the object is impossible on stable Rust.
|
/// - i8, i16, i32, i64
|
||||||
|
/// - u8, u16, u32, u64
|
||||||
|
/// - f32, f64
|
||||||
|
/// - char
|
||||||
|
/// - string
|
||||||
|
/// - byte array - [u8]
|
||||||
|
/// - option
|
||||||
|
/// - either none or some value
|
||||||
|
/// - unit
|
||||||
|
/// - unit is the type of () in Rust
|
||||||
|
/// - unit_struct
|
||||||
|
/// - for example `struct Unit` or `PhantomData<T>`
|
||||||
|
/// - unit_variant
|
||||||
|
/// - the `E::A` and `E::B` in `enum E { A, B }`
|
||||||
|
/// - newtype_struct
|
||||||
|
/// - for example `struct Millimeters(u8)`
|
||||||
|
/// - newtype_variant
|
||||||
|
/// - the `E::N` in `enum E { N(u8) }`
|
||||||
|
/// - seq
|
||||||
|
/// - a dynamically sized sequence of values, for example `Vec<T>` or
|
||||||
|
/// `HashSet<T>`
|
||||||
|
/// - seq_fixed_size
|
||||||
|
/// - a statically sized sequence of values for which the size will be known
|
||||||
|
/// at deserialization time without looking at the serialized data, for
|
||||||
|
/// example `[u64; 10]`
|
||||||
|
/// - tuple
|
||||||
|
/// - for example `(u8,)` or `(String, u64, Vec<T>)`
|
||||||
|
/// - tuple_struct
|
||||||
|
/// - for example `struct Rgb(u8, u8, u8)`
|
||||||
|
/// - tuple_variant
|
||||||
|
/// - the `E::T` in `enum E { T(u8, u8) }`
|
||||||
|
/// - map
|
||||||
|
/// - for example `BTreeMap<K, V>`
|
||||||
|
/// - struct
|
||||||
|
/// - a key-value pairing in which the keys will be known at deserialization
|
||||||
|
/// time without looking at the serialized data, for example `struct S { r:
|
||||||
|
/// u8, g: u8, b: u8 }`
|
||||||
|
/// - struct_variant
|
||||||
|
/// - the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`
|
||||||
|
///
|
||||||
|
/// Many Serde serializers produce text or binary data as output, for example
|
||||||
|
/// JSON or Bincode. This is not a requirement of the `Serializer` trait, and
|
||||||
|
/// there are serializers that do not produce text or binary output. One example
|
||||||
|
/// is the `serde_json::value::Serializer` (distinct from the main `serde_json`
|
||||||
|
/// serializer) that produces a `serde_json::Value` data structure in memory as
|
||||||
|
/// output.
|
||||||
pub trait Serializer {
|
pub trait Serializer {
|
||||||
/// Trickery to enforce correct use of the `Serialize` trait. Every
|
/// The output type produced by this `Serializer` during successful
|
||||||
/// `Serializer` should set `Ok = ()`.
|
/// serialization. Most serializers that produce text or binary output
|
||||||
|
/// should set `Ok = ()` and serialize into an `io::Write` or buffer
|
||||||
|
/// contained within the `Serializer` instance. Serializers that build
|
||||||
|
/// in-memory data structures may be simplified by using `Ok` to propagate
|
||||||
|
/// the data structure around.
|
||||||
type Ok;
|
type Ok;
|
||||||
|
|
||||||
/// The error type when some error occurs during serialization.
|
/// The error type when some error occurs during serialization.
|
||||||
@@ -112,75 +282,85 @@ pub trait Serializer {
|
|||||||
/// content of the struct variant.
|
/// content of the struct variant.
|
||||||
type SerializeStructVariant: SerializeStructVariant<Ok=Self::Ok, Error=Self::Error>;
|
type SerializeStructVariant: SerializeStructVariant<Ok=Self::Ok, Error=Self::Error>;
|
||||||
|
|
||||||
/// Serializes a `bool` value.
|
/// Serialize a `bool` value.
|
||||||
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>;
|
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes an `isize` value. If the format does not differentiate
|
/// Serialize an `i8` value.
|
||||||
/// between `isize` and `i64`, a reasonable implementation would be to cast
|
///
|
||||||
/// the value to `i64` and forward to `serialize_i64`.
|
/// If the format does not differentiate between `i8` and `i64`, a
|
||||||
fn serialize_isize(self, v: isize) -> Result<Self::Ok, Self::Error>;
|
/// reasonable implementation would be to cast the value to `i64` and
|
||||||
|
/// forward to `serialize_i64`.
|
||||||
/// Serializes an `i8` value. If the format does not differentiate between
|
|
||||||
/// `i8` and `i64`, a reasonable implementation would be to cast the value
|
|
||||||
/// to `i64` and forward to `serialize_i64`.
|
|
||||||
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error>;
|
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes an `i16` value. If the format does not differentiate between
|
/// Serialize an `i16` value.
|
||||||
/// `i16` and `i64`, a reasonable implementation would be to cast the value
|
///
|
||||||
/// to `i64` and forward to `serialize_i64`.
|
/// If the format does not differentiate between `i16` and `i64`, a
|
||||||
|
/// reasonable implementation would be to cast the value to `i64` and
|
||||||
|
/// forward to `serialize_i64`.
|
||||||
fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error>;
|
fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes an `i32` value. If the format does not differentiate between
|
/// Serialize an `i32` value.
|
||||||
/// `i32` and `i64`, a reasonable implementation would be to cast the value
|
///
|
||||||
/// to `i64` and forward to `serialize_i64`.
|
/// If the format does not differentiate between `i32` and `i64`, a
|
||||||
|
/// reasonable implementation would be to cast the value to `i64` and
|
||||||
|
/// forward to `serialize_i64`.
|
||||||
fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error>;
|
fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes an `i64` value.
|
/// Serialize an `i64` value.
|
||||||
fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>;
|
fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes a `usize` value. If the format does not differentiate between
|
/// Serialize a `u8` value.
|
||||||
/// `usize` and `u64`, a reasonable implementation would be to cast the
|
///
|
||||||
/// value to `u64` and forward to `serialize_u64`.
|
/// If the format does not differentiate between `u8` and `u64`, a
|
||||||
fn serialize_usize(self, v: usize) -> Result<Self::Ok, Self::Error>;
|
/// reasonable implementation would be to cast the value to `u64` and
|
||||||
|
/// forward to `serialize_u64`.
|
||||||
/// Serializes a `u8` value. If the format does not differentiate between
|
|
||||||
/// `u8` and `u64`, a reasonable implementation would be to cast the value
|
|
||||||
/// to `u64` and forward to `serialize_u64`.
|
|
||||||
fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error>;
|
fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes a `u16` value. If the format does not differentiate between
|
/// Serialize a `u16` value.
|
||||||
/// `u16` and `u64`, a reasonable implementation would be to cast the value
|
///
|
||||||
/// to `u64` and forward to `serialize_u64`.
|
/// If the format does not differentiate between `u16` and `u64`, a
|
||||||
|
/// reasonable implementation would be to cast the value to `u64` and
|
||||||
|
/// forward to `serialize_u64`.
|
||||||
fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error>;
|
fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes a `u32` value. If the format does not differentiate between
|
/// Serialize a `u32` value.
|
||||||
/// `u32` and `u64`, a reasonable implementation would be to cast the value
|
///
|
||||||
/// to `u64` and forward to `serialize_u64`.
|
/// If the format does not differentiate between `u32` and `u64`, a
|
||||||
|
/// reasonable implementation would be to cast the value to `u64` and
|
||||||
|
/// forward to `serialize_u64`.
|
||||||
fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error>;
|
fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// `Serializes a `u64` value.
|
/// Serialize a `u64` value.
|
||||||
fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>;
|
fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes an `f32` value. If the format does not differentiate between
|
/// Serialize an `f32` value.
|
||||||
/// `f32` and `f64`, a reasonable implementation would be to cast the value
|
///
|
||||||
/// to `f64` and forward to `serialize_f64`.
|
/// If the format does not differentiate between `f32` and `f64`, a
|
||||||
|
/// reasonable implementation would be to cast the value to `f64` and
|
||||||
|
/// forward to `serialize_f64`.
|
||||||
fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error>;
|
fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes an `f64` value.
|
/// Serialize an `f64` value.
|
||||||
fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error>;
|
fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes a character. If the format does not support characters,
|
/// Serialize a character.
|
||||||
/// it is reasonable to serialize it as a single element `str` or a `u32`.
|
///
|
||||||
|
/// If the format does not support characters, it is reasonable to serialize
|
||||||
|
/// it as a single element `str` or a `u32`.
|
||||||
fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error>;
|
fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes a `&str`.
|
/// Serialize a `&str`.
|
||||||
fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error>;
|
fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
|
/// Serialize a chunk of raw byte data.
|
||||||
|
///
|
||||||
/// Enables serializers to serialize byte slices more compactly or more
|
/// Enables serializers to serialize byte slices more compactly or more
|
||||||
/// efficiently than other types of slices. If no efficient implementation
|
/// efficiently than other types of slices. If no efficient implementation
|
||||||
/// is available, a reasonable implementation would be to forward to
|
/// is available, a reasonable implementation would be to forward to
|
||||||
/// `serialize_seq`. If forwarded, the implementation looks usually just like this:
|
/// `serialize_seq`. If forwarded, the implementation looks usually just
|
||||||
/// ```rust
|
/// like this:
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
/// let mut seq = self.serialize_seq(Some(value.len()))?;
|
/// let mut seq = self.serialize_seq(Some(value.len()))?;
|
||||||
/// for b in value {
|
/// for b in value {
|
||||||
/// seq.serialize_element(b)?;
|
/// seq.serialize_element(b)?;
|
||||||
@@ -189,19 +369,40 @@ pub trait Serializer {
|
|||||||
/// ```
|
/// ```
|
||||||
fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error>;
|
fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes a `()` value. It's reasonable to just not serialize anything.
|
/// Serialize a `None` value.
|
||||||
|
fn serialize_none(self) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
|
/// Serialize a `Some(T)` value.
|
||||||
|
fn serialize_some<T: ?Sized + Serialize>(
|
||||||
|
self,
|
||||||
|
value: &T,
|
||||||
|
) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
|
/// Serialize a `()` value.
|
||||||
fn serialize_unit(self) -> Result<Self::Ok, Self::Error>;
|
fn serialize_unit(self) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes a unit struct value. A reasonable implementation would be to
|
/// Serialize a unit struct like `struct Unit` or `PhantomData<T>`.
|
||||||
/// forward to `serialize_unit`.
|
///
|
||||||
|
/// A reasonable implementation would be to forward to `serialize_unit`.
|
||||||
fn serialize_unit_struct(
|
fn serialize_unit_struct(
|
||||||
self,
|
self,
|
||||||
name: &'static str,
|
name: &'static str,
|
||||||
) -> Result<Self::Ok, Self::Error>;
|
) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes a unit variant, otherwise known as a variant with no
|
/// Serialize a unit variant like `E::A` in `enum E { A, B }`.
|
||||||
/// arguments. A reasonable implementation would be to forward to
|
///
|
||||||
/// `serialize_unit`.
|
/// The `name` is the name of the enum, the `variant_index` is the index of
|
||||||
|
/// this variant within the enum, and the `variant` is the name of the
|
||||||
|
/// variant.
|
||||||
|
///
|
||||||
|
/// A reasonable implementation would be to forward to `serialize_unit`.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// match *self {
|
||||||
|
/// E::A => serializer.serialize_unit_variant("E", 0, "A"),
|
||||||
|
/// E::B => serializer.serialize_unit_variant("E", 1, "B"),
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
fn serialize_unit_variant(
|
fn serialize_unit_variant(
|
||||||
self,
|
self,
|
||||||
name: &'static str,
|
name: &'static str,
|
||||||
@@ -209,74 +410,130 @@ pub trait Serializer {
|
|||||||
variant: &'static str,
|
variant: &'static str,
|
||||||
) -> Result<Self::Ok, Self::Error>;
|
) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Allows a tuple struct with a single element, also known as a newtype
|
/// Serialize a newtype struct like `struct Millimeters(u8)`.
|
||||||
/// struct, to be more efficiently serialized than a tuple struct with
|
///
|
||||||
/// multiple items. A reasonable implementation would be to forward to
|
/// Serializers are encouraged to treat newtype structs as insignificant
|
||||||
/// `serialize_tuple_struct` or to just serialize the inner value without wrapping.
|
/// wrappers around the data they contain. A reasonable implementation would
|
||||||
fn serialize_newtype_struct<T: Serialize>(
|
/// be to forward to `value.serialize(self)`.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// serializer.serialize_newtype_struct("Millimeters", &self.0)
|
||||||
|
/// ```
|
||||||
|
fn serialize_newtype_struct<T: ?Sized + Serialize>(
|
||||||
self,
|
self,
|
||||||
name: &'static str,
|
name: &'static str,
|
||||||
value: T,
|
value: &T,
|
||||||
) -> Result<Self::Ok, Self::Error>;
|
) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Allows a variant with a single item to be more efficiently serialized
|
/// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`.
|
||||||
/// than a variant with multiple items. A reasonable implementation would be
|
///
|
||||||
/// to forward to `serialize_tuple_variant`.
|
/// The `name` is the name of the enum, the `variant_index` is the index of
|
||||||
fn serialize_newtype_variant<T: Serialize>(
|
/// this variant within the enum, and the `variant` is the name of the
|
||||||
|
/// variant. The `value` is the data contained within this newtype variant.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// match *self {
|
||||||
|
/// E::N(ref n) => serializer.serialize_newtype_variant("E", 0, "N", n),
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
fn serialize_newtype_variant<T: ?Sized + Serialize>(
|
||||||
self,
|
self,
|
||||||
name: &'static str,
|
name: &'static str,
|
||||||
variant_index: usize,
|
variant_index: usize,
|
||||||
variant: &'static str,
|
variant: &'static str,
|
||||||
value: T,
|
value: &T,
|
||||||
) -> Result<Self::Ok, Self::Error>;
|
) -> Result<Self::Ok, Self::Error>;
|
||||||
|
|
||||||
/// Serializes a `None` value.
|
/// Begin to serialize a dynamically sized sequence. This call must be
|
||||||
fn serialize_none(self) -> Result<Self::Ok, Self::Error>;
|
/// followed by zero or more calls to `serialize_element`, then a call to
|
||||||
|
/// `end`.
|
||||||
/// Serializes a `Some(...)` value.
|
///
|
||||||
fn serialize_some<T: Serialize>(
|
/// The argument is the number of elements in the sequence, which may or may
|
||||||
self,
|
/// not be computable before the sequence is iterated. Some serializers only
|
||||||
value: T,
|
/// support sequences whose length is known up front.
|
||||||
) -> Result<Self::Ok, Self::Error>;
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
/// Begins to serialize a sequence. This call must be followed by zero or
|
/// let mut seq = serializer.serialize_seq(Some(self.len()))?;
|
||||||
/// more calls to `serialize_seq_elt`, then a call to `serialize_seq_end`.
|
/// for element in self {
|
||||||
|
/// seq.serialize_element(element)?;
|
||||||
|
/// }
|
||||||
|
/// seq.end()
|
||||||
|
/// ```
|
||||||
fn serialize_seq(
|
fn serialize_seq(
|
||||||
self,
|
self,
|
||||||
len: Option<usize>,
|
len: Option<usize>,
|
||||||
) -> Result<Self::SerializeSeq, Self::Error>;
|
) -> Result<Self::SerializeSeq, Self::Error>;
|
||||||
|
|
||||||
/// Begins to serialize a sequence whose length will be known at
|
/// Begin to serialize a statically sized sequence whose length will be
|
||||||
/// deserialization time. This call must be followed by zero or more calls
|
/// known at deserialization time without looking at the serialized data.
|
||||||
/// to `serialize_seq_elt`, then a call to `serialize_seq_end`. A reasonable
|
/// This call must be followed by zero or more calls to `serialize_element`,
|
||||||
/// implementation would be to forward to `serialize_seq`.
|
/// then a call to `end`.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// let mut seq = serializer.serialize_seq_fixed_size(self.len())?;
|
||||||
|
/// for element in self {
|
||||||
|
/// seq.serialize_element(element)?;
|
||||||
|
/// }
|
||||||
|
/// seq.end()
|
||||||
|
/// ```
|
||||||
fn serialize_seq_fixed_size(
|
fn serialize_seq_fixed_size(
|
||||||
self,
|
self,
|
||||||
size: usize,
|
size: usize,
|
||||||
) -> Result<Self::SerializeSeq, Self::Error>;
|
) -> Result<Self::SerializeSeq, Self::Error>;
|
||||||
|
|
||||||
/// Begins to serialize a tuple. This call must be followed by zero or more
|
/// Begin to serialize a tuple. This call must be followed by zero or more
|
||||||
/// calls to `serialize_tuple_elt`, then a call to `serialize_tuple_end`. A
|
/// calls to `serialize_field`, then a call to `end`.
|
||||||
/// reasonable implementation would be to forward to `serialize_seq`.
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// let mut tup = serializer.serialize_tuple(3)?;
|
||||||
|
/// tup.serialize_field(&self.0)?;
|
||||||
|
/// tup.serialize_field(&self.1)?;
|
||||||
|
/// tup.serialize_field(&self.2)?;
|
||||||
|
/// tup.end()
|
||||||
|
/// ```
|
||||||
fn serialize_tuple(
|
fn serialize_tuple(
|
||||||
self,
|
self,
|
||||||
len: usize,
|
len: usize,
|
||||||
) -> Result<Self::SerializeTuple, Self::Error>;
|
) -> Result<Self::SerializeTuple, Self::Error>;
|
||||||
|
|
||||||
/// Begins to serialize a tuple struct. This call must be followed by zero
|
/// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This
|
||||||
/// or more calls to `serialize_tuple_struct_elt`, then a call to
|
/// call must be followed by zero or more calls to `serialize_field`, then a
|
||||||
/// `serialize_tuple_struct_end`. A reasonable implementation would be to
|
/// call to `end`.
|
||||||
/// forward to `serialize_tuple`.
|
///
|
||||||
|
/// The `name` is the name of the tuple struct and the `len` is the number
|
||||||
|
/// of data fields that will be serialized.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;
|
||||||
|
/// ts.serialize_field(&self.0)?;
|
||||||
|
/// ts.serialize_field(&self.1)?;
|
||||||
|
/// ts.serialize_field(&self.2)?;
|
||||||
|
/// ts.end()
|
||||||
|
/// ```
|
||||||
fn serialize_tuple_struct(
|
fn serialize_tuple_struct(
|
||||||
self,
|
self,
|
||||||
name: &'static str,
|
name: &'static str,
|
||||||
len: usize,
|
len: usize,
|
||||||
) -> Result<Self::SerializeTupleStruct, Self::Error>;
|
) -> Result<Self::SerializeTupleStruct, Self::Error>;
|
||||||
|
|
||||||
/// Begins to serialize a tuple variant. This call must be followed by zero
|
/// Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8)
|
||||||
/// or more calls to `serialize_tuple_variant_elt`, then a call to
|
/// }`. This call must be followed by zero or more calls to
|
||||||
/// `serialize_tuple_variant_end`. A reasonable implementation would be to
|
/// `serialize_field`, then a call to `end`.
|
||||||
/// forward to `serialize_tuple_struct`.
|
///
|
||||||
|
/// The `name` is the name of the enum, the `variant_index` is the index of
|
||||||
|
/// this variant within the enum, the `variant` is the name of the variant,
|
||||||
|
/// and the `len` is the number of data fields that will be serialized.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// match *self {
|
||||||
|
/// E::T(ref a, ref b) => {
|
||||||
|
/// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;
|
||||||
|
/// tv.serialize_field(a)?;
|
||||||
|
/// tv.serialize_field(b)?;
|
||||||
|
/// tv.end()
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
fn serialize_tuple_variant(
|
fn serialize_tuple_variant(
|
||||||
self,
|
self,
|
||||||
name: &'static str,
|
name: &'static str,
|
||||||
@@ -285,25 +542,64 @@ pub trait Serializer {
|
|||||||
len: usize,
|
len: usize,
|
||||||
) -> Result<Self::SerializeTupleVariant, Self::Error>;
|
) -> Result<Self::SerializeTupleVariant, Self::Error>;
|
||||||
|
|
||||||
/// Begins to serialize a map. This call must be followed by zero or more
|
/// Begin to serialize a map. This call must be followed by zero or more
|
||||||
/// calls to `serialize_map_key` and `serialize_map_value`, then a call to
|
/// calls to `serialize_key` and `serialize_value`, then a call to `end`.
|
||||||
/// `serialize_map_end`.
|
///
|
||||||
|
/// The argument is the number of elements in the map, which may or may not
|
||||||
|
/// be computable before the map is iterated. Some serializers only support
|
||||||
|
/// maps whose length is known up front.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// let mut map = serializer.serialize_map(Some(self.len()))?;
|
||||||
|
/// for (k, v) in self {
|
||||||
|
/// map.serialize_entry(k, v)?;
|
||||||
|
/// }
|
||||||
|
/// map.end()
|
||||||
|
/// ```
|
||||||
fn serialize_map(
|
fn serialize_map(
|
||||||
self,
|
self,
|
||||||
len: Option<usize>,
|
len: Option<usize>,
|
||||||
) -> Result<Self::SerializeMap, Self::Error>;
|
) -> Result<Self::SerializeMap, Self::Error>;
|
||||||
|
|
||||||
/// Begins to serialize a struct. This call must be followed by zero or more
|
/// Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`.
|
||||||
/// calls to `serialize_struct_elt`, then a call to `serialize_struct_end`.
|
/// This call must be followed by zero or more calls to `serialize_field`,
|
||||||
|
/// then a call to `end`.
|
||||||
|
///
|
||||||
|
/// The `name` is the name of the struct and the `len` is the number of
|
||||||
|
/// data fields that will be serialized.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// let mut struc = serializer.serialize_struct("Rgb", 3)?;
|
||||||
|
/// struc.serialize_field("r", &self.r)?;
|
||||||
|
/// struc.serialize_field("g", &self.g)?;
|
||||||
|
/// struc.serialize_field("b", &self.b)?;
|
||||||
|
/// struc.end()
|
||||||
|
/// ```
|
||||||
fn serialize_struct(
|
fn serialize_struct(
|
||||||
self,
|
self,
|
||||||
name: &'static str,
|
name: &'static str,
|
||||||
len: usize,
|
len: usize,
|
||||||
) -> Result<Self::SerializeStruct, Self::Error>;
|
) -> Result<Self::SerializeStruct, Self::Error>;
|
||||||
|
|
||||||
/// Begins to serialize a struct variant. This call must be followed by zero
|
/// Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8,
|
||||||
/// or more calls to `serialize_struct_variant_elt`, then a call to
|
/// g: u8, b: u8 } }`. This call must be followed by zero or more calls to
|
||||||
/// `serialize_struct_variant_end`.
|
/// `serialize_field`, then a call to `end`.
|
||||||
|
///
|
||||||
|
/// The `name` is the name of the enum, the `variant_index` is the index of
|
||||||
|
/// this variant within the enum, the `variant` is the name of the variant,
|
||||||
|
/// and the `len` is the number of data fields that will be serialized.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// match *self {
|
||||||
|
/// E::S { ref r, ref g, ref b } => {
|
||||||
|
/// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?;
|
||||||
|
/// sv.serialize_field("r", r)?;
|
||||||
|
/// sv.serialize_field("g", g)?;
|
||||||
|
/// sv.serialize_field("b", b)?;
|
||||||
|
/// sv.end()
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
fn serialize_struct_variant(
|
fn serialize_struct_variant(
|
||||||
self,
|
self,
|
||||||
name: &'static str,
|
name: &'static str,
|
||||||
@@ -315,134 +611,218 @@ pub trait Serializer {
|
|||||||
|
|
||||||
/// Returned from `Serializer::serialize_seq` and
|
/// Returned from `Serializer::serialize_seq` and
|
||||||
/// `Serializer::serialize_seq_fixed_size`.
|
/// `Serializer::serialize_seq_fixed_size`.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// let mut seq = serializer.serialize_seq(Some(self.len()))?;
|
||||||
|
/// for element in self {
|
||||||
|
/// seq.serialize_element(element)?;
|
||||||
|
/// }
|
||||||
|
/// seq.end()
|
||||||
|
/// ```
|
||||||
pub trait SerializeSeq {
|
pub trait SerializeSeq {
|
||||||
/// Trickery to enforce correct use of the `Serialize` trait. Every
|
/// Must match the `Ok` type of our `Serializer`.
|
||||||
/// `SerializeSeq` should set `Ok = ()`.
|
|
||||||
type Ok;
|
type Ok;
|
||||||
|
|
||||||
/// The error type when some error occurs during serialization.
|
/// Must match the `Error` type of our `Serializer`.
|
||||||
type Error: Error;
|
type Error: Error;
|
||||||
|
|
||||||
/// Serializes a sequence element.
|
/// Serialize a sequence element.
|
||||||
fn serialize_element<T: Serialize>(&mut self, value: T) -> Result<(), Self::Error>;
|
fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||||
|
|
||||||
/// Finishes serializing a sequence.
|
/// Finish serializing a sequence.
|
||||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returned from `Serializer::serialize_tuple`.
|
/// Returned from `Serializer::serialize_tuple`.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// let mut tup = serializer.serialize_tuple(3)?;
|
||||||
|
/// tup.serialize_field(&self.0)?;
|
||||||
|
/// tup.serialize_field(&self.1)?;
|
||||||
|
/// tup.serialize_field(&self.2)?;
|
||||||
|
/// tup.end()
|
||||||
|
/// ```
|
||||||
pub trait SerializeTuple {
|
pub trait SerializeTuple {
|
||||||
/// Trickery to enforce correct use of the `Serialize` trait. Every
|
/// Must match the `Ok` type of our `Serializer`.
|
||||||
/// `SerializeTuple` should set `Ok = ()`.
|
|
||||||
type Ok;
|
type Ok;
|
||||||
|
|
||||||
/// The error type when some error occurs during serialization.
|
/// Must match the `Error` type of our `Serializer`.
|
||||||
type Error: Error;
|
type Error: Error;
|
||||||
|
|
||||||
/// Serializes a tuple element.
|
/// Serialize a tuple element.
|
||||||
fn serialize_element<T: Serialize>(&mut self, value: T) -> Result<(), Self::Error>;
|
fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||||
|
|
||||||
/// Finishes serializing a tuple.
|
/// Finish serializing a tuple.
|
||||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returned from `Serializer::serialize_tuple_struct`.
|
/// Returned from `Serializer::serialize_tuple_struct`.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;
|
||||||
|
/// ts.serialize_field(&self.0)?;
|
||||||
|
/// ts.serialize_field(&self.1)?;
|
||||||
|
/// ts.serialize_field(&self.2)?;
|
||||||
|
/// ts.end()
|
||||||
|
/// ```
|
||||||
pub trait SerializeTupleStruct {
|
pub trait SerializeTupleStruct {
|
||||||
/// Trickery to enforce correct use of the `Serialize` trait. Every
|
/// Must match the `Ok` type of our `Serializer`.
|
||||||
/// `SerializeTupleStruct` should set `Ok = ()`.
|
|
||||||
type Ok;
|
type Ok;
|
||||||
|
|
||||||
/// The error type when some error occurs during serialization.
|
/// Must match the `Error` type of our `Serializer`.
|
||||||
type Error: Error;
|
type Error: Error;
|
||||||
|
|
||||||
/// Serializes a tuple struct element.
|
/// Serialize a tuple struct field.
|
||||||
fn serialize_field<T: Serialize>(&mut self, value: T) -> Result<(), Self::Error>;
|
fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||||
|
|
||||||
/// Finishes serializing a tuple struct.
|
/// Finish serializing a tuple struct.
|
||||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returned from `Serializer::serialize_tuple_variant`.
|
/// Returned from `Serializer::serialize_tuple_variant`.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// match *self {
|
||||||
|
/// E::T(ref a, ref b) => {
|
||||||
|
/// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;
|
||||||
|
/// tv.serialize_field(a)?;
|
||||||
|
/// tv.serialize_field(b)?;
|
||||||
|
/// tv.end()
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
pub trait SerializeTupleVariant {
|
pub trait SerializeTupleVariant {
|
||||||
/// Trickery to enforce correct use of the `Serialize` trait. Every
|
/// Must match the `Ok` type of our `Serializer`.
|
||||||
/// `SerializeTupleVariant` should set `Ok = ()`.
|
|
||||||
type Ok;
|
type Ok;
|
||||||
|
|
||||||
/// The error type when some error occurs during serialization.
|
/// Must match the `Error` type of our `Serializer`.
|
||||||
type Error: Error;
|
type Error: Error;
|
||||||
|
|
||||||
/// Serializes a tuple variant element.
|
/// Serialize a tuple variant field.
|
||||||
fn serialize_field<T: Serialize>(&mut self, value: T) -> Result<(), Self::Error>;
|
fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||||
|
|
||||||
/// Finishes serializing a tuple variant.
|
/// Finish serializing a tuple variant.
|
||||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returned from `Serializer::serialize_map`.
|
/// Returned from `Serializer::serialize_map`.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// let mut map = serializer.serialize_map(Some(self.len()))?;
|
||||||
|
/// for (k, v) in self {
|
||||||
|
/// map.serialize_entry(k, v)?;
|
||||||
|
/// }
|
||||||
|
/// map.end()
|
||||||
|
/// ```
|
||||||
pub trait SerializeMap {
|
pub trait SerializeMap {
|
||||||
/// Trickery to enforce correct use of the `Serialize` trait. Every
|
/// Must match the `Ok` type of our `Serializer`.
|
||||||
/// `SerializeMap` should set `Ok = ()`.
|
|
||||||
type Ok;
|
type Ok;
|
||||||
|
|
||||||
/// The error type when some error occurs during serialization.
|
/// Must match the `Error` type of our `Serializer`.
|
||||||
type Error: Error;
|
type Error: Error;
|
||||||
|
|
||||||
/// Serialize a map key.
|
/// Serialize a map key.
|
||||||
fn serialize_key<T: Serialize>(&mut self, key: T) -> Result<(), Self::Error>;
|
fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), Self::Error>;
|
||||||
|
|
||||||
/// Serialize a map value.
|
/// Serialize a map value.
|
||||||
fn serialize_value<T: Serialize>(&mut self, value: T) -> Result<(), Self::Error>;
|
fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
|
||||||
|
|
||||||
/// Finishes serializing a map.
|
/// Serialize a map entry consisting of a key and a value.
|
||||||
|
///
|
||||||
|
/// Some `Serialize` types are not able to hold a key and value in memory at
|
||||||
|
/// the same time so `SerializeMap` implementations are required to support
|
||||||
|
/// `serialize_key` and `serialize_value` individually. The
|
||||||
|
/// `serialize_entry` method allows serializers to optimize for the case
|
||||||
|
/// where key and value are both available. `Serialize` implementations are
|
||||||
|
/// encouraged to use `serialize_entry` if possible.
|
||||||
|
///
|
||||||
|
/// The default implementation delegates to `serialize_key` and
|
||||||
|
/// `serialize_value`. This is appropriate for serializers that do not care
|
||||||
|
/// about performance or are not able to optimize `serialize_entry` any
|
||||||
|
/// better than this.
|
||||||
|
fn serialize_entry<K: ?Sized + Serialize, V: ?Sized + Serialize>(
|
||||||
|
&mut self,
|
||||||
|
key: &K,
|
||||||
|
value: &V,
|
||||||
|
) -> Result<(), Self::Error> {
|
||||||
|
try!(self.serialize_key(key));
|
||||||
|
self.serialize_value(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finish serializing a map.
|
||||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returned from `Serializer::serialize_struct`.
|
/// Returned from `Serializer::serialize_struct`.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// let mut struc = serializer.serialize_struct("Rgb", 3)?;
|
||||||
|
/// struc.serialize_field("r", &self.r)?;
|
||||||
|
/// struc.serialize_field("g", &self.g)?;
|
||||||
|
/// struc.serialize_field("b", &self.b)?;
|
||||||
|
/// struc.end()
|
||||||
|
/// ```
|
||||||
pub trait SerializeStruct {
|
pub trait SerializeStruct {
|
||||||
/// Trickery to enforce correct use of the `Serialize` trait. Every
|
/// Must match the `Ok` type of our `Serializer`.
|
||||||
/// `SerializeStruct` should set `Ok = ()`.
|
|
||||||
type Ok;
|
type Ok;
|
||||||
|
|
||||||
/// The error type when some error occurs during serialization.
|
/// Must match the `Error` type of our `Serializer`.
|
||||||
type Error: Error;
|
type Error: Error;
|
||||||
|
|
||||||
/// Serializes a struct field.
|
/// Serialize a struct field.
|
||||||
fn serialize_field<V: Serialize>(&mut self, key: &'static str, value: V) -> Result<(), Self::Error>;
|
fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>;
|
||||||
|
|
||||||
/// Finishes serializing a struct.
|
/// Finish serializing a struct.
|
||||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returned from `Serializer::serialize_struct_variant`.
|
/// Returned from `Serializer::serialize_struct_variant`.
|
||||||
|
///
|
||||||
|
/// ```rust,ignore
|
||||||
|
/// match *self {
|
||||||
|
/// E::S { ref r, ref g, ref b } => {
|
||||||
|
/// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?;
|
||||||
|
/// sv.serialize_field("r", r)?;
|
||||||
|
/// sv.serialize_field("g", g)?;
|
||||||
|
/// sv.serialize_field("b", b)?;
|
||||||
|
/// sv.end()
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
pub trait SerializeStructVariant {
|
pub trait SerializeStructVariant {
|
||||||
/// Trickery to enforce correct use of the `Serialize` trait. Every
|
/// Must match the `Ok` type of our `Serializer`.
|
||||||
/// `SerializeStructVariant` should set `Ok = ()`.
|
|
||||||
type Ok;
|
type Ok;
|
||||||
|
|
||||||
/// The error type when some error occurs during serialization.
|
/// Must match the `Error` type of our `Serializer`.
|
||||||
type Error: Error;
|
type Error: Error;
|
||||||
|
|
||||||
/// Serialize a struct variant element.
|
/// Serialize a struct variant field.
|
||||||
fn serialize_field<V: Serialize>(&mut self, key: &'static str, value: V) -> Result<(), Self::Error>;
|
fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>;
|
||||||
|
|
||||||
/// Finishes serializing a struct variant.
|
/// Finish serializing a struct variant.
|
||||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A wrapper type for iterators that implements `Serialize` for iterators whose items implement
|
/// A wrapper type for iterators that implements `Serialize` for iterators whose
|
||||||
/// `Serialize`. Don't use multiple times. Create new versions of this with the `iterator` function
|
/// items implement `Serialize`. Don't use multiple times. Create new versions
|
||||||
/// every time you want to serialize an iterator.
|
/// of this with the `serde::ser::iterator` function every time you want to
|
||||||
|
/// serialize an iterator.
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(feature = "unstable")]
|
||||||
pub struct Iterator<I>(RefCell<Option<I>>)
|
pub struct Iterator<I>
|
||||||
where <I as IntoIterator>::Item: Serialize,
|
where <I as IntoIterator>::Item: Serialize,
|
||||||
I: IntoIterator;
|
I: IntoIterator
|
||||||
|
{
|
||||||
|
data: RefCell<Option<I>>,
|
||||||
|
}
|
||||||
|
|
||||||
/// Creates a temporary type that can be passed to any function expecting a `Serialize` and will
|
/// Create a wrapper type that can be passed to any function expecting a
|
||||||
/// serialize the given iterator as a sequence
|
/// `Serialize` and will serialize the given iterator as a sequence.
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(feature = "unstable")]
|
||||||
pub fn iterator<I>(iter: I) -> Iterator<I>
|
pub fn iterator<I>(iter: I) -> Iterator<I>
|
||||||
where <I as IntoIterator>::Item: Serialize,
|
where <I as IntoIterator>::Item: Serialize,
|
||||||
I: IntoIterator
|
I: IntoIterator
|
||||||
{
|
{
|
||||||
Iterator(RefCell::new(Some(iter)))
|
Iterator {
|
||||||
|
data: RefCell::new(Some(iter)),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,235 @@
|
|||||||
|
use core::fmt::{self, Display};
|
||||||
|
|
||||||
|
use ser::{self, Serialize, Serializer, SerializeMap, SerializeStruct};
|
||||||
|
|
||||||
|
/// Not public API.
|
||||||
|
pub fn serialize_tagged_newtype<S, T>(
|
||||||
|
serializer: S,
|
||||||
|
type_ident: &'static str,
|
||||||
|
variant_ident: &'static str,
|
||||||
|
tag: &'static str,
|
||||||
|
variant_name: &'static str,
|
||||||
|
value: T,
|
||||||
|
) -> Result<S::Ok, S::Error>
|
||||||
|
where S: Serializer,
|
||||||
|
T: Serialize
|
||||||
|
{
|
||||||
|
value.serialize(TaggedSerializer {
|
||||||
|
type_ident: type_ident,
|
||||||
|
variant_ident: variant_ident,
|
||||||
|
tag: tag,
|
||||||
|
variant_name: variant_name,
|
||||||
|
delegate: serializer,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TaggedSerializer<S> {
|
||||||
|
type_ident: &'static str,
|
||||||
|
variant_ident: &'static str,
|
||||||
|
tag: &'static str,
|
||||||
|
variant_name: &'static str,
|
||||||
|
delegate: S,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Unsupported {
|
||||||
|
Boolean,
|
||||||
|
Integer,
|
||||||
|
Float,
|
||||||
|
Char,
|
||||||
|
String,
|
||||||
|
ByteArray,
|
||||||
|
Optional,
|
||||||
|
Unit,
|
||||||
|
UnitStruct,
|
||||||
|
Sequence,
|
||||||
|
Tuple,
|
||||||
|
TupleStruct,
|
||||||
|
Enum,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for Unsupported {
|
||||||
|
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
match *self {
|
||||||
|
Unsupported::Boolean => formatter.write_str("a boolean"),
|
||||||
|
Unsupported::Integer => formatter.write_str("an integer"),
|
||||||
|
Unsupported::Float => formatter.write_str("a float"),
|
||||||
|
Unsupported::Char => formatter.write_str("a char"),
|
||||||
|
Unsupported::String => formatter.write_str("a string"),
|
||||||
|
Unsupported::ByteArray => formatter.write_str("a byte array"),
|
||||||
|
Unsupported::Optional => formatter.write_str("an optional"),
|
||||||
|
Unsupported::Unit => formatter.write_str("unit"),
|
||||||
|
Unsupported::UnitStruct => formatter.write_str("a unit struct"),
|
||||||
|
Unsupported::Sequence => formatter.write_str("a sequence"),
|
||||||
|
Unsupported::Tuple => formatter.write_str("a tuple"),
|
||||||
|
Unsupported::TupleStruct => formatter.write_str("a tuple struct"),
|
||||||
|
Unsupported::Enum => formatter.write_str("an enum"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Error {
|
||||||
|
type_ident: &'static str,
|
||||||
|
variant_ident: &'static str,
|
||||||
|
ty: Unsupported,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for Error {
|
||||||
|
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
write!(formatter,
|
||||||
|
"cannot serialize tagged newtype variant {}::{} containing {}",
|
||||||
|
self.type_ident, self.variant_ident, self.ty)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S> TaggedSerializer<S>
|
||||||
|
where S: Serializer
|
||||||
|
{
|
||||||
|
fn bad_type(self, what: Unsupported) -> S::Error {
|
||||||
|
ser::Error::custom(Error {
|
||||||
|
type_ident: self.type_ident,
|
||||||
|
variant_ident: self.variant_ident,
|
||||||
|
ty: what,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S> Serializer for TaggedSerializer<S>
|
||||||
|
where S: Serializer
|
||||||
|
{
|
||||||
|
type Ok = S::Ok;
|
||||||
|
type Error = S::Error;
|
||||||
|
|
||||||
|
type SerializeSeq = S::SerializeSeq;
|
||||||
|
type SerializeTuple = S::SerializeTuple;
|
||||||
|
type SerializeTupleStruct = S::SerializeTupleStruct;
|
||||||
|
type SerializeTupleVariant = S::SerializeTupleVariant;
|
||||||
|
type SerializeMap = S::SerializeMap;
|
||||||
|
type SerializeStruct = S::SerializeStruct;
|
||||||
|
type SerializeStructVariant = S::SerializeStructVariant;
|
||||||
|
|
||||||
|
fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Boolean))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Integer))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Integer))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Integer))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Integer))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Integer))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Integer))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Integer))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Integer))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Float))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Float))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Char))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::String))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::ByteArray))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Optional))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error>
|
||||||
|
where T: Serialize
|
||||||
|
{
|
||||||
|
Err(self.bad_type(Unsupported::Optional))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Unit))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::UnitStruct))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_unit_variant(self, _: &'static str, _: usize, _: &'static str) -> Result<Self::Ok, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Enum))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_newtype_struct<T: ?Sized>(self, _: &'static str, value: &T) -> Result<Self::Ok, Self::Error>
|
||||||
|
where T: Serialize
|
||||||
|
{
|
||||||
|
value.serialize(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_newtype_variant<T: ?Sized>(self, _: &'static str, _: usize, _: &'static str, _: &T) -> Result<Self::Ok, Self::Error>
|
||||||
|
where T: Serialize
|
||||||
|
{
|
||||||
|
Err(self.bad_type(Unsupported::Enum))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Sequence))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_seq_fixed_size(self, _: usize) -> Result<Self::SerializeSeq, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Sequence))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Tuple))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Result<Self::SerializeTupleStruct, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::TupleStruct))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_tuple_variant(self, _: &'static str, _: usize, _: &'static str, _: usize) -> Result<Self::SerializeTupleVariant, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Enum))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
|
||||||
|
let mut map = try!(self.delegate.serialize_map(len.map(|len| len + 1)));
|
||||||
|
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||||
|
Ok(map)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct, Self::Error> {
|
||||||
|
let mut state = try!(self.delegate.serialize_struct(name, len + 1));
|
||||||
|
try!(state.serialize_field(self.tag, self.variant_name));
|
||||||
|
Ok(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_struct_variant(self, _: &'static str, _: usize, _: &'static str, _: usize) -> Result<Self::SerializeStructVariant, Self::Error> {
|
||||||
|
Err(self.bad_type(Unsupported::Enum))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "serde_codegen"
|
|
||||||
version = "0.9.0-rc1"
|
|
||||||
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"]
|
|
||||||
|
|
||||||
[features]
|
|
||||||
default = ["with-syntex"]
|
|
||||||
unstable = []
|
|
||||||
unstable-testing = ["clippy"]
|
|
||||||
with-syntex = [
|
|
||||||
"syntex",
|
|
||||||
"syntex_syntax",
|
|
||||||
]
|
|
||||||
with-syn = []
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
clippy = { version = "^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,172 +0,0 @@
|
|||||||
#![cfg_attr(feature = "clippy", plugin(clippy))]
|
|
||||||
#![cfg_attr(feature = "clippy", feature(plugin))]
|
|
||||||
#![cfg_attr(feature = "clippy", allow(too_many_arguments))]
|
|
||||||
#![cfg_attr(feature = "clippy", allow(used_underscore_binding))]
|
|
||||||
|
|
||||||
// The `quote!` macro requires deep recursion.
|
|
||||||
#![recursion_limit = "192"]
|
|
||||||
|
|
||||||
extern crate serde_codegen_internals as internals;
|
|
||||||
|
|
||||||
#[cfg(feature = "with-syntex")]
|
|
||||||
extern crate syntex;
|
|
||||||
|
|
||||||
#[cfg(feature = "with-syntex")]
|
|
||||||
#[macro_use]
|
|
||||||
extern crate syntex_syntax as syntax;
|
|
||||||
|
|
||||||
extern crate syn;
|
|
||||||
#[macro_use]
|
|
||||||
extern crate quote;
|
|
||||||
|
|
||||||
#[cfg(feature = "with-syntex")]
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
mod bound;
|
|
||||||
mod de;
|
|
||||||
mod ser;
|
|
||||||
|
|
||||||
#[cfg(feature = "with-syntex")]
|
|
||||||
fn syntex_registry() -> syntex::Registry {
|
|
||||||
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> {
|
|
||||||
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")]
|
|
||||||
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>
|
|
||||||
where S: AsRef<Path>,
|
|
||||||
D: AsRef<Path>,
|
|
||||||
{
|
|
||||||
let src = src.as_ref().to_owned();
|
|
||||||
let dst = dst.as_ref().to_owned();
|
|
||||||
|
|
||||||
let expand_thread = move || {
|
|
||||||
syntex_registry().expand("", src, dst)
|
|
||||||
};
|
|
||||||
|
|
||||||
syntex::with_extra_stack(expand_thread)
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
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);
|
|
||||||
|
|
||||||
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,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "serde_codegen_internals"
|
name = "serde_codegen_internals"
|
||||||
version = "0.11.3"
|
version = "0.13.0"
|
||||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
description = "AST representation used by Serde codegen. Unstable."
|
description = "AST representation used by Serde codegen. Unstable."
|
||||||
@@ -10,9 +10,8 @@ documentation = "https://docs.serde.rs/serde_codegen_internals/"
|
|||||||
keywords = ["serde", "serialization"]
|
keywords = ["serde", "serialization"]
|
||||||
include = ["Cargo.toml", "src/**/*.rs"]
|
include = ["Cargo.toml", "src/**/*.rs"]
|
||||||
|
|
||||||
[features]
|
|
||||||
unstable-testing = ["clippy"]
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
clippy = { version = "^0.*", optional = true }
|
syn = "0.11"
|
||||||
syn = "0.10"
|
|
||||||
|
[badges]
|
||||||
|
travis-ci = { repository = "serde-rs/serde" }
|
||||||
|
|||||||
@@ -92,6 +92,32 @@ pub struct Item {
|
|||||||
deny_unknown_fields: bool,
|
deny_unknown_fields: bool,
|
||||||
ser_bound: Option<Vec<syn::WherePredicate>>,
|
ser_bound: Option<Vec<syn::WherePredicate>>,
|
||||||
de_bound: Option<Vec<syn::WherePredicate>>,
|
de_bound: Option<Vec<syn::WherePredicate>>,
|
||||||
|
tag: EnumTag,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Styles of representing an enum.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum EnumTag {
|
||||||
|
/// The default.
|
||||||
|
///
|
||||||
|
/// ```json
|
||||||
|
/// {"variant1": {"key1": "value1", "key2": "value2"}}
|
||||||
|
/// ```
|
||||||
|
External,
|
||||||
|
|
||||||
|
/// `#[serde(tag = "type")]`
|
||||||
|
///
|
||||||
|
/// ```json
|
||||||
|
/// {"type": "variant1", "key1": "value1", "key2": "value2"}
|
||||||
|
/// ```
|
||||||
|
Internal(String),
|
||||||
|
|
||||||
|
/// `#[serde(untagged)]`
|
||||||
|
///
|
||||||
|
/// ```json
|
||||||
|
/// {"key1": "value1", "key2": "value2"}
|
||||||
|
/// ```
|
||||||
|
None,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Item {
|
impl Item {
|
||||||
@@ -102,6 +128,8 @@ impl Item {
|
|||||||
let mut deny_unknown_fields = BoolAttr::none(cx, "deny_unknown_fields");
|
let mut deny_unknown_fields = BoolAttr::none(cx, "deny_unknown_fields");
|
||||||
let mut ser_bound = Attr::none(cx, "bound");
|
let mut ser_bound = Attr::none(cx, "bound");
|
||||||
let mut de_bound = Attr::none(cx, "bound");
|
let mut de_bound = Attr::none(cx, "bound");
|
||||||
|
let mut untagged = BoolAttr::none(cx, "untagged");
|
||||||
|
let mut internal_tag = Attr::none(cx, "tag");
|
||||||
|
|
||||||
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 {
|
for meta_item in meta_items {
|
||||||
@@ -143,18 +171,70 @@ impl Item {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Parse `#[serde(untagged)]`
|
||||||
|
MetaItem(Word(ref name)) if name == "untagged" => {
|
||||||
|
match item.body {
|
||||||
|
syn::Body::Enum(_) => {
|
||||||
|
untagged.set_true();
|
||||||
|
}
|
||||||
|
syn::Body::Struct(_) => {
|
||||||
|
cx.error("#[serde(untagged)] can only be used on enums")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse `#[serde(tag = "type")]`
|
||||||
|
MetaItem(NameValue(ref name, ref lit)) if name == "tag" => {
|
||||||
|
if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) {
|
||||||
|
match item.body {
|
||||||
|
syn::Body::Enum(_) => {
|
||||||
|
internal_tag.set(s);
|
||||||
|
}
|
||||||
|
syn::Body::Struct(_) => {
|
||||||
|
cx.error("#[serde(tag = \"...\")] can only be used on enums")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
MetaItem(ref meta_item) => {
|
MetaItem(ref meta_item) => {
|
||||||
cx.error(format!("unknown serde container attribute `{}`",
|
cx.error(format!("unknown serde container attribute `{}`",
|
||||||
meta_item.name()));
|
meta_item.name()));
|
||||||
}
|
}
|
||||||
|
|
||||||
Literal(_) => {
|
Literal(_) => {
|
||||||
cx.error(format!("unexpected literal in serde container attribute"));
|
cx.error("unexpected literal in serde container attribute");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let tag = match (untagged.get(), internal_tag.get()) {
|
||||||
|
(false, None) => EnumTag::External,
|
||||||
|
(true, None) => EnumTag::None,
|
||||||
|
(false, Some(tag)) => {
|
||||||
|
// Check that there are no tuple variants.
|
||||||
|
if let syn::Body::Enum(ref variants) = item.body {
|
||||||
|
for variant in variants {
|
||||||
|
match variant.data {
|
||||||
|
syn::VariantData::Struct(_) | syn::VariantData::Unit => {}
|
||||||
|
syn::VariantData::Tuple(ref fields) => {
|
||||||
|
if fields.len() != 1 {
|
||||||
|
cx.error("#[serde(tag = \"...\")] cannot be used with tuple variants");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EnumTag::Internal(tag)
|
||||||
|
}
|
||||||
|
(true, Some(_)) => {
|
||||||
|
cx.error("enum cannot be both untagged and internally tagged");
|
||||||
|
EnumTag::External // doesn't matter, will error
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
Item {
|
Item {
|
||||||
name: Name {
|
name: Name {
|
||||||
serialize: ser_name.get().unwrap_or_else(|| item.ident.to_string()),
|
serialize: ser_name.get().unwrap_or_else(|| item.ident.to_string()),
|
||||||
@@ -163,6 +243,7 @@ impl Item {
|
|||||||
deny_unknown_fields: deny_unknown_fields.get(),
|
deny_unknown_fields: deny_unknown_fields.get(),
|
||||||
ser_bound: ser_bound.get(),
|
ser_bound: ser_bound.get(),
|
||||||
de_bound: de_bound.get(),
|
de_bound: de_bound.get(),
|
||||||
|
tag: tag,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,6 +262,10 @@ impl Item {
|
|||||||
pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
|
pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
|
||||||
self.de_bound.as_ref().map(|vec| &vec[..])
|
self.de_bound.as_ref().map(|vec| &vec[..])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn tag(&self) -> &EnumTag {
|
||||||
|
&self.tag
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Represents variant attribute information
|
/// Represents variant attribute information
|
||||||
@@ -231,7 +316,7 @@ impl Variant {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Literal(_) => {
|
Literal(_) => {
|
||||||
cx.error(format!("unexpected literal in serde variant attribute"));
|
cx.error("unexpected literal in serde variant attribute");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -390,7 +475,7 @@ impl Field {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Literal(_) => {
|
Literal(_) => {
|
||||||
cx.error(format!("unexpected literal in serde field attribute"));
|
cx.error("unexpected literal in serde field attribute");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -404,7 +489,7 @@ impl Field {
|
|||||||
|
|
||||||
Field {
|
Field {
|
||||||
name: Name {
|
name: Name {
|
||||||
serialize: ser_name.get().unwrap_or(ident.clone()),
|
serialize: ser_name.get().unwrap_or_else(|| ident.clone()),
|
||||||
deserialize: de_name.get().unwrap_or(ident),
|
deserialize: de_name.get().unwrap_or(ident),
|
||||||
},
|
},
|
||||||
skip_serializing: skip_serializing.get(),
|
skip_serializing: skip_serializing.get(),
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
#![cfg_attr(feature = "clippy", plugin(clippy))]
|
|
||||||
#![cfg_attr(feature = "clippy", feature(plugin))]
|
|
||||||
|
|
||||||
extern crate syn;
|
extern crate syn;
|
||||||
|
|
||||||
pub mod ast;
|
pub mod ast;
|
||||||
|
|||||||
+11
-12
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "serde_derive"
|
name = "serde_derive"
|
||||||
version = "0.9.0-rc1"
|
version = "0.9.6"
|
||||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]"
|
description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]"
|
||||||
@@ -10,18 +10,17 @@ documentation = "https://serde.rs/codegen.html"
|
|||||||
keywords = ["serde", "serialization"]
|
keywords = ["serde", "serialization"]
|
||||||
include = ["Cargo.toml", "src/**/*.rs"]
|
include = ["Cargo.toml", "src/**/*.rs"]
|
||||||
|
|
||||||
|
[features]
|
||||||
|
unstable = []
|
||||||
|
|
||||||
|
[badges]
|
||||||
|
travis-ci = { repository = "serde-rs/serde" }
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "serde_derive"
|
name = "serde_derive"
|
||||||
proc-macro = true
|
proc-macro = true
|
||||||
|
|
||||||
[dependencies.serde_codegen]
|
[dependencies]
|
||||||
version = "=0.9.0-rc1"
|
quote = "0.3.8"
|
||||||
path = "../serde_codegen"
|
serde_codegen_internals = { version = "=0.13.0", default-features = false, path = "../serde_codegen_internals" }
|
||||||
default-features = false
|
syn = { version = "0.11", features = ["aster", "visit"] }
|
||||||
features = ["with-syn"]
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
compiletest_rs = "^0.2.0"
|
|
||||||
fnv = "1.0"
|
|
||||||
serde = { version = "0.9.0-rc1", path = "../serde" }
|
|
||||||
serde_test = { version = "0.9.0-rc1", path = "../serde_test" }
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use syn::{self, aster, Ident};
|
use syn::{self, aster, Ident};
|
||||||
use quote::Tokens;
|
use quote::{self, Tokens};
|
||||||
|
|
||||||
use bound;
|
use bound;
|
||||||
use internals::ast::{Body, Field, Item, Style, Variant};
|
use internals::ast::{Body, Field, Item, Style, Variant};
|
||||||
@@ -7,7 +7,7 @@ use internals::{self, attr};
|
|||||||
|
|
||||||
use std::iter;
|
use std::iter;
|
||||||
|
|
||||||
pub fn expand_derive_deserialize(item: &syn::MacroInput) -> Result<Tokens, String> {
|
pub fn expand_derive_deserialize(item: &syn::DeriveInput) -> Result<Tokens, String> {
|
||||||
let item = {
|
let item = {
|
||||||
let ctxt = internals::Ctxt::new();
|
let ctxt = internals::Ctxt::new();
|
||||||
let item = Item::from_ast(&ctxt, item);
|
let item = Item::from_ast(&ctxt, item);
|
||||||
@@ -36,7 +36,7 @@ pub fn expand_derive_deserialize(item: &syn::MacroInput) -> Result<Tokens, Strin
|
|||||||
extern crate serde as _serde;
|
extern crate serde as _serde;
|
||||||
#[automatically_derived]
|
#[automatically_derived]
|
||||||
impl #impl_generics _serde::Deserialize for #ty #where_clause {
|
impl #impl_generics _serde::Deserialize for #ty #where_clause {
|
||||||
fn deserialize<__D>(deserializer: __D) -> ::std::result::Result<#ty, __D::Error>
|
fn deserialize<__D>(deserializer: __D) -> _serde::export::Result<#ty, __D::Error>
|
||||||
where __D: _serde::Deserializer
|
where __D: _serde::Deserializer
|
||||||
#body
|
#body
|
||||||
}
|
}
|
||||||
@@ -110,7 +110,8 @@ fn deserialize_body(
|
|||||||
impl_generics,
|
impl_generics,
|
||||||
ty,
|
ty,
|
||||||
fields,
|
fields,
|
||||||
&item.attrs)
|
&item.attrs,
|
||||||
|
None)
|
||||||
}
|
}
|
||||||
Body::Struct(Style::Tuple, ref fields) |
|
Body::Struct(Style::Tuple, ref fields) |
|
||||||
Body::Struct(Style::Newtype, ref fields) => {
|
Body::Struct(Style::Newtype, ref fields) => {
|
||||||
@@ -124,7 +125,8 @@ fn deserialize_body(
|
|||||||
impl_generics,
|
impl_generics,
|
||||||
ty,
|
ty,
|
||||||
fields,
|
fields,
|
||||||
&item.attrs)
|
&item.attrs,
|
||||||
|
None)
|
||||||
}
|
}
|
||||||
Body::Struct(Style::Unit, _) => {
|
Body::Struct(Style::Unit, _) => {
|
||||||
deserialize_unit_struct(
|
deserialize_unit_struct(
|
||||||
@@ -158,11 +160,11 @@ fn deserialize_visitor(generics: &syn::Generics) -> (Tokens, Tokens, Tokens) {
|
|||||||
let phantom_types = generics.lifetimes.iter()
|
let phantom_types = generics.lifetimes.iter()
|
||||||
.map(|lifetime_def| {
|
.map(|lifetime_def| {
|
||||||
let lifetime = &lifetime_def.lifetime;
|
let lifetime = &lifetime_def.lifetime;
|
||||||
quote!(::std::marker::PhantomData<& #lifetime ()>)
|
quote!(_serde::export::PhantomData<& #lifetime ()>)
|
||||||
}).chain(generics.ty_params.iter()
|
}).chain(generics.ty_params.iter()
|
||||||
.map(|ty_param| {
|
.map(|ty_param| {
|
||||||
let ident = &ty_param.ident;
|
let ident = &ty_param.ident;
|
||||||
quote!(::std::marker::PhantomData<#ident>)
|
quote!(_serde::export::PhantomData<#ident>)
|
||||||
}));
|
}));
|
||||||
|
|
||||||
let all_params = generics.lifetimes.iter()
|
let all_params = generics.lifetimes.iter()
|
||||||
@@ -182,7 +184,7 @@ fn deserialize_visitor(generics: &syn::Generics) -> (Tokens, Tokens, Tokens) {
|
|||||||
Some(quote!(::<#(#ty_param_idents),*>))
|
Some(quote!(::<#(#ty_param_idents),*>))
|
||||||
};
|
};
|
||||||
|
|
||||||
let phantom_exprs = iter::repeat(quote!(::std::marker::PhantomData)).take(num_phantoms);
|
let phantom_exprs = iter::repeat(quote!(_serde::export::PhantomData)).take(num_phantoms);
|
||||||
|
|
||||||
(
|
(
|
||||||
quote! {
|
quote! {
|
||||||
@@ -200,24 +202,30 @@ fn deserialize_unit_struct(
|
|||||||
) -> Tokens {
|
) -> Tokens {
|
||||||
let type_name = item_attrs.name().deserialize_name();
|
let type_name = item_attrs.name().deserialize_name();
|
||||||
|
|
||||||
|
let expecting = format!("unit struct {}", type_ident);
|
||||||
|
|
||||||
quote!({
|
quote!({
|
||||||
struct __Visitor;
|
struct __Visitor;
|
||||||
|
|
||||||
impl _serde::de::Visitor for __Visitor {
|
impl _serde::de::Visitor for __Visitor {
|
||||||
type Value = #type_ident;
|
type Value = #type_ident;
|
||||||
|
|
||||||
#[inline]
|
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
|
||||||
fn visit_unit<__E>(self) -> ::std::result::Result<#type_ident, __E>
|
_serde::export::fmt::Formatter::write_str(formatter, #expecting)
|
||||||
where __E: _serde::de::Error,
|
|
||||||
{
|
|
||||||
Ok(#type_ident)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn visit_seq<__V>(self, _: __V) -> ::std::result::Result<#type_ident, __V::Error>
|
fn visit_unit<__E>(self) -> _serde::export::Result<#type_ident, __E>
|
||||||
|
where __E: _serde::de::Error,
|
||||||
|
{
|
||||||
|
_serde::export::Ok(#type_ident)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn visit_seq<__V>(self, _: __V) -> _serde::export::Result<#type_ident, __V::Error>
|
||||||
where __V: _serde::de::SeqVisitor,
|
where __V: _serde::de::SeqVisitor,
|
||||||
{
|
{
|
||||||
Ok(#type_ident)
|
_serde::export::Ok(#type_ident)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,6 +240,7 @@ fn deserialize_tuple(
|
|||||||
ty: syn::Ty,
|
ty: syn::Ty,
|
||||||
fields: &[Field],
|
fields: &[Field],
|
||||||
item_attrs: &attr::Item,
|
item_attrs: &attr::Item,
|
||||||
|
deserializer: Option<Tokens>,
|
||||||
) -> Tokens {
|
) -> Tokens {
|
||||||
let where_clause = &impl_generics.where_clause;
|
let where_clause = &impl_generics.where_clause;
|
||||||
|
|
||||||
@@ -242,6 +251,10 @@ fn deserialize_tuple(
|
|||||||
Some(variant_ident) => quote!(#type_ident::#variant_ident),
|
Some(variant_ident) => quote!(#type_ident::#variant_ident),
|
||||||
None => quote!(#type_ident),
|
None => quote!(#type_ident),
|
||||||
};
|
};
|
||||||
|
let expecting = match variant_ident {
|
||||||
|
Some(variant_ident) => format!("tuple variant {}::{}", type_ident, variant_ident),
|
||||||
|
None => format!("tuple struct {}", type_ident),
|
||||||
|
};
|
||||||
|
|
||||||
let nfields = fields.len();
|
let nfields = fields.len();
|
||||||
|
|
||||||
@@ -264,14 +277,16 @@ fn deserialize_tuple(
|
|||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
|
|
||||||
let dispatch = if is_enum {
|
let dispatch = if let Some(deserializer) = deserializer {
|
||||||
|
quote!(_serde::Deserializer::deserialize(#deserializer, #visitor_expr))
|
||||||
|
} else if is_enum {
|
||||||
quote!(_serde::de::VariantVisitor::visit_tuple(visitor, #nfields, #visitor_expr))
|
quote!(_serde::de::VariantVisitor::visit_tuple(visitor, #nfields, #visitor_expr))
|
||||||
} else if nfields == 1 {
|
} else if nfields == 1 {
|
||||||
let type_name = item_attrs.name().deserialize_name();
|
let type_name = item_attrs.name().deserialize_name();
|
||||||
quote!(deserializer.deserialize_newtype_struct(#type_name, #visitor_expr))
|
quote!(_serde::Deserializer::deserialize_newtype_struct(deserializer, #type_name, #visitor_expr))
|
||||||
} else {
|
} else {
|
||||||
let type_name = item_attrs.name().deserialize_name();
|
let type_name = item_attrs.name().deserialize_name();
|
||||||
quote!(deserializer.deserialize_tuple_struct(#type_name, #nfields, #visitor_expr))
|
quote!(_serde::Deserializer::deserialize_tuple_struct(deserializer, #type_name, #nfields, #visitor_expr))
|
||||||
};
|
};
|
||||||
|
|
||||||
let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing());
|
let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing());
|
||||||
@@ -287,10 +302,14 @@ fn deserialize_tuple(
|
|||||||
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
|
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
|
||||||
type Value = #ty;
|
type Value = #ty;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
|
||||||
|
_serde::export::fmt::Formatter::write_str(formatter, #expecting)
|
||||||
|
}
|
||||||
|
|
||||||
#visit_newtype_struct
|
#visit_newtype_struct
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn visit_seq<__V>(self, #visitor_var: __V) -> ::std::result::Result<#ty, __V::Error>
|
fn visit_seq<__V>(self, #visitor_var: __V) -> _serde::export::Result<#ty, __V::Error>
|
||||||
where __V: _serde::de::SeqVisitor
|
where __V: _serde::de::SeqVisitor
|
||||||
{
|
{
|
||||||
#visit_seq
|
#visit_seq
|
||||||
@@ -310,6 +329,11 @@ fn deserialize_seq(
|
|||||||
) -> Tokens {
|
) -> Tokens {
|
||||||
let vars = (0..fields.len()).map(field_i as fn(_) -> _);
|
let vars = (0..fields.len()).map(field_i as fn(_) -> _);
|
||||||
|
|
||||||
|
let deserialized_count = fields.iter()
|
||||||
|
.filter(|field| !field.attrs.skip_deserializing())
|
||||||
|
.count();
|
||||||
|
let expecting = format!("tuple of {} elements", deserialized_count);
|
||||||
|
|
||||||
let mut index_in_seq = 0usize;
|
let mut index_in_seq = 0usize;
|
||||||
let let_values = vars.clone().zip(fields)
|
let let_values = vars.clone().zip(fields)
|
||||||
.map(|(var, field)| {
|
.map(|(var, field)| {
|
||||||
@@ -322,7 +346,7 @@ fn deserialize_seq(
|
|||||||
let visit = match field.attrs.deserialize_with() {
|
let visit = match field.attrs.deserialize_with() {
|
||||||
None => {
|
None => {
|
||||||
let field_ty = &field.ty;
|
let field_ty = &field.ty;
|
||||||
quote!(try!(visitor.visit::<#field_ty>()))
|
quote!(try!(_serde::de::SeqVisitor::visit::<#field_ty>(&mut visitor)))
|
||||||
}
|
}
|
||||||
Some(path) => {
|
Some(path) => {
|
||||||
let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
|
let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
|
||||||
@@ -330,7 +354,8 @@ fn deserialize_seq(
|
|||||||
quote!({
|
quote!({
|
||||||
#wrapper
|
#wrapper
|
||||||
#wrapper_impl
|
#wrapper_impl
|
||||||
try!(visitor.visit::<#wrapper_ty>()).map(|wrap| wrap.value)
|
try!(_serde::de::SeqVisitor::visit::<#wrapper_ty>(&mut visitor))
|
||||||
|
.map(|wrap| wrap.value)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -338,7 +363,7 @@ fn deserialize_seq(
|
|||||||
let #var = match #visit {
|
let #var = match #visit {
|
||||||
Some(value) => { value },
|
Some(value) => { value },
|
||||||
None => {
|
None => {
|
||||||
return Err(_serde::de::Error::invalid_length(#index_in_seq));
|
return _serde::export::Err(_serde::de::Error::invalid_length(#index_in_seq, &#expecting));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -360,7 +385,7 @@ fn deserialize_seq(
|
|||||||
|
|
||||||
quote! {
|
quote! {
|
||||||
#(#let_values)*
|
#(#let_values)*
|
||||||
Ok(#result)
|
_serde::export::Ok(#result)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -389,10 +414,10 @@ fn deserialize_newtype_struct(
|
|||||||
};
|
};
|
||||||
quote! {
|
quote! {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn visit_newtype_struct<__E>(self, __e: __E) -> ::std::result::Result<Self::Value, __E::Error>
|
fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::export::Result<Self::Value, __E::Error>
|
||||||
where __E: _serde::Deserializer,
|
where __E: _serde::Deserializer,
|
||||||
{
|
{
|
||||||
Ok(#type_path(#value))
|
_serde::export::Ok(#type_path(#value))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -404,7 +429,11 @@ fn deserialize_struct(
|
|||||||
ty: syn::Ty,
|
ty: syn::Ty,
|
||||||
fields: &[Field],
|
fields: &[Field],
|
||||||
item_attrs: &attr::Item,
|
item_attrs: &attr::Item,
|
||||||
|
deserializer: Option<Tokens>,
|
||||||
) -> Tokens {
|
) -> Tokens {
|
||||||
|
let is_enum = variant_ident.is_some();
|
||||||
|
let is_untagged = deserializer.is_some();
|
||||||
|
|
||||||
let where_clause = &impl_generics.where_clause;
|
let where_clause = &impl_generics.where_clause;
|
||||||
|
|
||||||
let (visitor_item, visitor_ty, visitor_expr) = deserialize_visitor(impl_generics);
|
let (visitor_item, visitor_ty, visitor_expr) = deserialize_visitor(impl_generics);
|
||||||
@@ -413,6 +442,10 @@ fn deserialize_struct(
|
|||||||
Some(variant_ident) => quote!(#type_ident::#variant_ident),
|
Some(variant_ident) => quote!(#type_ident::#variant_ident),
|
||||||
None => quote!(#type_ident),
|
None => quote!(#type_ident),
|
||||||
};
|
};
|
||||||
|
let expecting = match variant_ident {
|
||||||
|
Some(variant_ident) => format!("struct variant {}::{}", type_ident, variant_ident),
|
||||||
|
None => format!("struct {}", type_ident),
|
||||||
|
};
|
||||||
|
|
||||||
let visit_seq = deserialize_seq(
|
let visit_seq = deserialize_seq(
|
||||||
type_ident,
|
type_ident,
|
||||||
@@ -430,15 +463,18 @@ fn deserialize_struct(
|
|||||||
item_attrs,
|
item_attrs,
|
||||||
);
|
);
|
||||||
|
|
||||||
let is_enum = variant_ident.is_some();
|
let dispatch = if let Some(deserializer) = deserializer {
|
||||||
let dispatch = if is_enum {
|
quote! {
|
||||||
|
_serde::Deserializer::deserialize(#deserializer, #visitor_expr)
|
||||||
|
}
|
||||||
|
} else if is_enum {
|
||||||
quote! {
|
quote! {
|
||||||
_serde::de::VariantVisitor::visit_struct(visitor, FIELDS, #visitor_expr)
|
_serde::de::VariantVisitor::visit_struct(visitor, FIELDS, #visitor_expr)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let type_name = item_attrs.name().deserialize_name();
|
let type_name = item_attrs.name().deserialize_name();
|
||||||
quote! {
|
quote! {
|
||||||
deserializer.deserialize_struct(#type_name, FIELDS, #visitor_expr)
|
_serde::Deserializer::deserialize_struct(deserializer, #type_name, FIELDS, #visitor_expr)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -449,6 +485,20 @@ fn deserialize_struct(
|
|||||||
quote!(mut visitor)
|
quote!(mut visitor)
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let visit_seq = if is_untagged {
|
||||||
|
// untagged struct variants do not get a visit_seq method
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(quote! {
|
||||||
|
#[inline]
|
||||||
|
fn visit_seq<__V>(self, #visitor_var: __V) -> _serde::export::Result<#ty, __V::Error>
|
||||||
|
where __V: _serde::de::SeqVisitor
|
||||||
|
{
|
||||||
|
#visit_seq
|
||||||
|
}
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
quote!({
|
quote!({
|
||||||
#field_visitor
|
#field_visitor
|
||||||
|
|
||||||
@@ -457,15 +507,14 @@ fn deserialize_struct(
|
|||||||
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
|
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
|
||||||
type Value = #ty;
|
type Value = #ty;
|
||||||
|
|
||||||
#[inline]
|
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
|
||||||
fn visit_seq<__V>(self, #visitor_var: __V) -> ::std::result::Result<#ty, __V::Error>
|
_serde::export::fmt::Formatter::write_str(formatter, #expecting)
|
||||||
where __V: _serde::de::SeqVisitor
|
|
||||||
{
|
|
||||||
#visit_seq
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#visit_seq
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn visit_map<__V>(self, mut visitor: __V) -> ::std::result::Result<#ty, __V::Error>
|
fn visit_map<__V>(self, mut visitor: __V) -> _serde::export::Result<#ty, __V::Error>
|
||||||
where __V: _serde::de::MapVisitor
|
where __V: _serde::de::MapVisitor
|
||||||
{
|
{
|
||||||
#visit_map
|
#visit_map
|
||||||
@@ -484,29 +533,71 @@ fn deserialize_item_enum(
|
|||||||
ty: syn::Ty,
|
ty: syn::Ty,
|
||||||
variants: &[Variant],
|
variants: &[Variant],
|
||||||
item_attrs: &attr::Item
|
item_attrs: &attr::Item
|
||||||
|
) -> Tokens {
|
||||||
|
match *item_attrs.tag() {
|
||||||
|
attr::EnumTag::External => {
|
||||||
|
deserialize_externally_tagged_enum(
|
||||||
|
type_ident,
|
||||||
|
impl_generics,
|
||||||
|
ty,
|
||||||
|
variants,
|
||||||
|
item_attrs,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
attr::EnumTag::Internal(ref tag) => {
|
||||||
|
deserialize_internally_tagged_enum(
|
||||||
|
type_ident,
|
||||||
|
impl_generics,
|
||||||
|
ty,
|
||||||
|
variants,
|
||||||
|
item_attrs,
|
||||||
|
tag,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
attr::EnumTag::None => {
|
||||||
|
deserialize_untagged_enum(
|
||||||
|
type_ident,
|
||||||
|
impl_generics,
|
||||||
|
ty,
|
||||||
|
variants,
|
||||||
|
item_attrs,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_externally_tagged_enum(
|
||||||
|
type_ident: &syn::Ident,
|
||||||
|
impl_generics: &syn::Generics,
|
||||||
|
ty: syn::Ty,
|
||||||
|
variants: &[Variant],
|
||||||
|
item_attrs: &attr::Item,
|
||||||
) -> Tokens {
|
) -> Tokens {
|
||||||
let where_clause = &impl_generics.where_clause;
|
let where_clause = &impl_generics.where_clause;
|
||||||
|
|
||||||
let type_name = item_attrs.name().deserialize_name();
|
let type_name = item_attrs.name().deserialize_name();
|
||||||
|
|
||||||
let variant_names_idents = variants.iter()
|
let expecting = format!("enum {}", type_ident);
|
||||||
|
|
||||||
|
let variant_names_idents: Vec<_> = variants.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.filter(|&(_, variant)| !variant.attrs.skip_deserializing())
|
.filter(|&(_, variant)| !variant.attrs.skip_deserializing())
|
||||||
.map(|(i, variant)| (variant.attrs.name().deserialize_name(), field_i(i)))
|
.map(|(i, variant)| (variant.attrs.name().deserialize_name(), field_i(i)))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
|
let variants_stmt = {
|
||||||
|
let variant_names = variant_names_idents.iter().map(|&(ref name, _)| name);
|
||||||
|
quote! {
|
||||||
|
const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let variant_visitor = deserialize_field_visitor(
|
let variant_visitor = deserialize_field_visitor(
|
||||||
variant_names_idents,
|
variant_names_idents,
|
||||||
item_attrs,
|
item_attrs,
|
||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
|
|
||||||
let variant_names = variants.iter().map(|variant| variant.attrs.name().deserialize_name());
|
|
||||||
|
|
||||||
let variants_stmt = quote! {
|
|
||||||
const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ];
|
|
||||||
};
|
|
||||||
|
|
||||||
// Match arms to extract a variant from a string
|
// Match arms to extract a variant from a string
|
||||||
let variant_arms = variants.iter()
|
let variant_arms = variants.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
@@ -514,7 +605,7 @@ fn deserialize_item_enum(
|
|||||||
.map(|(i, variant)| {
|
.map(|(i, variant)| {
|
||||||
let variant_name = field_i(i);
|
let variant_name = field_i(i);
|
||||||
|
|
||||||
let block = deserialize_variant(
|
let block = deserialize_externally_tagged_variant(
|
||||||
type_ident,
|
type_ident,
|
||||||
impl_generics,
|
impl_generics,
|
||||||
ty.clone(),
|
ty.clone(),
|
||||||
@@ -533,13 +624,14 @@ fn deserialize_item_enum(
|
|||||||
// all variants have `#[serde(skip_deserializing)]`.
|
// all variants have `#[serde(skip_deserializing)]`.
|
||||||
quote! {
|
quote! {
|
||||||
// FIXME: Once we drop support for Rust 1.15:
|
// FIXME: Once we drop support for Rust 1.15:
|
||||||
// let Err(err) = visitor.visit_variant::<__Field>();
|
// let _serde::export::Err(err) = _serde::de::EnumVisitor::visit_variant::<__Field>(visitor);
|
||||||
// Err(err)
|
// _serde::export::Err(err)
|
||||||
visitor.visit_variant::<__Field>().map(|(impossible, _)| match impossible {})
|
_serde::de::EnumVisitor::visit_variant::<__Field>(visitor)
|
||||||
|
.map(|(impossible, _)| match impossible {})
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
quote! {
|
quote! {
|
||||||
match try!(visitor.visit_variant()) {
|
match try!(_serde::de::EnumVisitor::visit_variant(visitor)) {
|
||||||
#(#variant_arms)*
|
#(#variant_arms)*
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -555,7 +647,11 @@ fn deserialize_item_enum(
|
|||||||
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
|
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
|
||||||
type Value = #ty;
|
type Value = #ty;
|
||||||
|
|
||||||
fn visit_enum<__V>(self, visitor: __V) -> ::std::result::Result<#ty, __V::Error>
|
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
|
||||||
|
_serde::export::fmt::Formatter::write_str(formatter, #expecting)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_enum<__V>(self, visitor: __V) -> _serde::export::Result<#ty, __V::Error>
|
||||||
where __V: _serde::de::EnumVisitor,
|
where __V: _serde::de::EnumVisitor,
|
||||||
{
|
{
|
||||||
#match_variant
|
#match_variant
|
||||||
@@ -564,11 +660,115 @@ fn deserialize_item_enum(
|
|||||||
|
|
||||||
#variants_stmt
|
#variants_stmt
|
||||||
|
|
||||||
deserializer.deserialize_enum(#type_name, VARIANTS, #visitor_expr)
|
_serde::Deserializer::deserialize_enum(deserializer, #type_name, VARIANTS, #visitor_expr)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn deserialize_variant(
|
fn deserialize_internally_tagged_enum(
|
||||||
|
type_ident: &syn::Ident,
|
||||||
|
impl_generics: &syn::Generics,
|
||||||
|
ty: syn::Ty,
|
||||||
|
variants: &[Variant],
|
||||||
|
item_attrs: &attr::Item,
|
||||||
|
tag: &str,
|
||||||
|
) -> Tokens {
|
||||||
|
let variant_names_idents: Vec<_> = variants.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|&(_, variant)| !variant.attrs.skip_deserializing())
|
||||||
|
.map(|(i, variant)| (variant.attrs.name().deserialize_name(), field_i(i)))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let variants_stmt = {
|
||||||
|
let variant_names = variant_names_idents.iter().map(|&(ref name, _)| name);
|
||||||
|
quote! {
|
||||||
|
const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let variant_visitor = deserialize_field_visitor(
|
||||||
|
variant_names_idents,
|
||||||
|
item_attrs,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Match arms to extract a variant from a string
|
||||||
|
let variant_arms = variants.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|&(_, variant)| !variant.attrs.skip_deserializing())
|
||||||
|
.map(|(i, variant)| {
|
||||||
|
let variant_name = field_i(i);
|
||||||
|
|
||||||
|
let block = deserialize_internally_tagged_variant(
|
||||||
|
type_ident,
|
||||||
|
impl_generics,
|
||||||
|
ty.clone(),
|
||||||
|
variant,
|
||||||
|
item_attrs,
|
||||||
|
quote!(_tagged.content),
|
||||||
|
);
|
||||||
|
|
||||||
|
quote! {
|
||||||
|
__Field::#variant_name => #block
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
quote!({
|
||||||
|
#variant_visitor
|
||||||
|
|
||||||
|
#variants_stmt
|
||||||
|
|
||||||
|
let _tagged = try!(_serde::Deserializer::deserialize(
|
||||||
|
deserializer,
|
||||||
|
_serde::de::private::TaggedContentVisitor::<__Field, __D::Error>::new(#tag)));
|
||||||
|
|
||||||
|
match _tagged.tag {
|
||||||
|
#(#variant_arms)*
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_untagged_enum(
|
||||||
|
type_ident: &syn::Ident,
|
||||||
|
impl_generics: &syn::Generics,
|
||||||
|
ty: syn::Ty,
|
||||||
|
variants: &[Variant],
|
||||||
|
item_attrs: &attr::Item,
|
||||||
|
) -> Tokens {
|
||||||
|
let attempts = variants.iter()
|
||||||
|
.filter(|variant| !variant.attrs.skip_deserializing())
|
||||||
|
.map(|variant| {
|
||||||
|
deserialize_untagged_variant(
|
||||||
|
type_ident,
|
||||||
|
impl_generics,
|
||||||
|
ty.clone(),
|
||||||
|
variant,
|
||||||
|
item_attrs,
|
||||||
|
quote!(&_content),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
// TODO this message could be better by saving the errors from the failed
|
||||||
|
// attempts. The heuristic used by TOML was to count the number of fields
|
||||||
|
// processed before an error, and use the error that happened after the
|
||||||
|
// largest number of fields. I'm not sure I like that. Maybe it would be
|
||||||
|
// better to save all the errors and combine them into one message that
|
||||||
|
// explains why none of the variants matched.
|
||||||
|
let fallthrough_msg = format!("data did not match any variant of untagged enum {}", type_ident);
|
||||||
|
|
||||||
|
quote!({
|
||||||
|
let _content = try!(<_serde::de::private::Content<__D::Error> as _serde::Deserialize>::deserialize(deserializer));
|
||||||
|
|
||||||
|
#(
|
||||||
|
if let _serde::export::Ok(ok) = #attempts {
|
||||||
|
return _serde::export::Ok(ok);
|
||||||
|
}
|
||||||
|
)*
|
||||||
|
|
||||||
|
_serde::export::Err(_serde::de::Error::custom(#fallthrough_msg))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_externally_tagged_variant(
|
||||||
type_ident: &syn::Ident,
|
type_ident: &syn::Ident,
|
||||||
generics: &syn::Generics,
|
generics: &syn::Generics,
|
||||||
ty: syn::Ty,
|
ty: syn::Ty,
|
||||||
@@ -581,11 +781,11 @@ fn deserialize_variant(
|
|||||||
Style::Unit => {
|
Style::Unit => {
|
||||||
quote!({
|
quote!({
|
||||||
try!(_serde::de::VariantVisitor::visit_unit(visitor));
|
try!(_serde::de::VariantVisitor::visit_unit(visitor));
|
||||||
Ok(#type_ident::#variant_ident)
|
_serde::export::Ok(#type_ident::#variant_ident)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
Style::Newtype => {
|
Style::Newtype => {
|
||||||
deserialize_newtype_variant(
|
deserialize_externally_tagged_newtype_variant(
|
||||||
type_ident,
|
type_ident,
|
||||||
variant_ident,
|
variant_ident,
|
||||||
generics,
|
generics,
|
||||||
@@ -600,6 +800,7 @@ fn deserialize_variant(
|
|||||||
ty,
|
ty,
|
||||||
&variant.fields,
|
&variant.fields,
|
||||||
item_attrs,
|
item_attrs,
|
||||||
|
None,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Style::Struct => {
|
Style::Struct => {
|
||||||
@@ -610,22 +811,115 @@ fn deserialize_variant(
|
|||||||
ty,
|
ty,
|
||||||
&variant.fields,
|
&variant.fields,
|
||||||
item_attrs,
|
item_attrs,
|
||||||
|
None,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn deserialize_newtype_variant(
|
fn deserialize_internally_tagged_variant(
|
||||||
|
type_ident: &syn::Ident,
|
||||||
|
generics: &syn::Generics,
|
||||||
|
ty: syn::Ty,
|
||||||
|
variant: &Variant,
|
||||||
|
item_attrs: &attr::Item,
|
||||||
|
deserializer: Tokens,
|
||||||
|
) -> Tokens {
|
||||||
|
let variant_ident = &variant.ident;
|
||||||
|
|
||||||
|
match variant.style {
|
||||||
|
Style::Unit => {
|
||||||
|
let type_name = type_ident.as_ref();
|
||||||
|
let variant_name = variant.ident.as_ref();
|
||||||
|
quote!({
|
||||||
|
try!(_serde::Deserializer::deserialize(#deserializer, _serde::de::private::InternallyTaggedUnitVisitor::new(#type_name, #variant_name)));
|
||||||
|
_serde::export::Ok(#type_ident::#variant_ident)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Style::Newtype | Style::Struct => {
|
||||||
|
deserialize_untagged_variant(
|
||||||
|
type_ident,
|
||||||
|
generics,
|
||||||
|
ty,
|
||||||
|
variant,
|
||||||
|
item_attrs,
|
||||||
|
deserializer,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Style::Tuple => unreachable!("checked in serde_codegen_internals"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_untagged_variant(
|
||||||
|
type_ident: &syn::Ident,
|
||||||
|
generics: &syn::Generics,
|
||||||
|
ty: syn::Ty,
|
||||||
|
variant: &Variant,
|
||||||
|
item_attrs: &attr::Item,
|
||||||
|
deserializer: Tokens,
|
||||||
|
) -> Tokens {
|
||||||
|
let variant_ident = &variant.ident;
|
||||||
|
|
||||||
|
match variant.style {
|
||||||
|
Style::Unit => {
|
||||||
|
let type_name = type_ident.as_ref();
|
||||||
|
let variant_name = variant.ident.as_ref();
|
||||||
|
quote! {
|
||||||
|
_serde::export::Result::map(
|
||||||
|
_serde::Deserializer::deserialize(
|
||||||
|
#deserializer,
|
||||||
|
_serde::de::private::UntaggedUnitVisitor::new(#type_name, #variant_name)
|
||||||
|
),
|
||||||
|
|()| #type_ident::#variant_ident)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Style::Newtype => {
|
||||||
|
deserialize_untagged_newtype_variant(
|
||||||
|
type_ident,
|
||||||
|
variant_ident,
|
||||||
|
generics,
|
||||||
|
&variant.fields[0],
|
||||||
|
deserializer,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Style::Tuple => {
|
||||||
|
deserialize_tuple(
|
||||||
|
type_ident,
|
||||||
|
Some(variant_ident),
|
||||||
|
generics,
|
||||||
|
ty,
|
||||||
|
&variant.fields,
|
||||||
|
item_attrs,
|
||||||
|
Some(deserializer),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Style::Struct => {
|
||||||
|
deserialize_struct(
|
||||||
|
type_ident,
|
||||||
|
Some(variant_ident),
|
||||||
|
generics,
|
||||||
|
ty,
|
||||||
|
&variant.fields,
|
||||||
|
item_attrs,
|
||||||
|
Some(deserializer),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_externally_tagged_newtype_variant(
|
||||||
type_ident: &syn::Ident,
|
type_ident: &syn::Ident,
|
||||||
variant_ident: &syn::Ident,
|
variant_ident: &syn::Ident,
|
||||||
impl_generics: &syn::Generics,
|
impl_generics: &syn::Generics,
|
||||||
field: &Field,
|
field: &Field,
|
||||||
) -> Tokens {
|
) -> Tokens {
|
||||||
let visit = match field.attrs.deserialize_with() {
|
match field.attrs.deserialize_with() {
|
||||||
None => {
|
None => {
|
||||||
let field_ty = &field.ty;
|
let field_ty = &field.ty;
|
||||||
quote! {
|
quote! {
|
||||||
try!(_serde::de::VariantVisitor::visit_newtype::<#field_ty>(visitor))
|
_serde::export::Result::map(
|
||||||
|
_serde::de::VariantVisitor::visit_newtype::<#field_ty>(visitor),
|
||||||
|
#type_ident::#variant_ident),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(path) => {
|
Some(path) => {
|
||||||
@@ -634,12 +928,41 @@ fn deserialize_newtype_variant(
|
|||||||
quote!({
|
quote!({
|
||||||
#wrapper
|
#wrapper
|
||||||
#wrapper_impl
|
#wrapper_impl
|
||||||
try!(_serde::de::VariantVisitor::visit_newtype::<#wrapper_ty>(visitor)).value
|
_serde::export::Result::map(
|
||||||
|
_serde::de::VariantVisitor::visit_newtype::<#wrapper_ty>(visitor),
|
||||||
|
|_wrapper| #type_ident::#variant_ident(_wrapper.value))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_untagged_newtype_variant(
|
||||||
|
type_ident: &syn::Ident,
|
||||||
|
variant_ident: &syn::Ident,
|
||||||
|
impl_generics: &syn::Generics,
|
||||||
|
field: &Field,
|
||||||
|
deserializer: Tokens,
|
||||||
|
) -> Tokens {
|
||||||
|
match field.attrs.deserialize_with() {
|
||||||
|
None => {
|
||||||
|
let field_ty = &field.ty;
|
||||||
|
quote!({
|
||||||
|
_serde::export::Result::map(
|
||||||
|
<#field_ty as _serde::Deserialize>::deserialize(#deserializer),
|
||||||
|
#type_ident::#variant_ident)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Some(path) => {
|
||||||
|
let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
|
||||||
|
type_ident, impl_generics, field.ty, path);
|
||||||
|
quote!({
|
||||||
|
#wrapper
|
||||||
|
#wrapper_impl
|
||||||
|
_serde::export::Result::map(
|
||||||
|
<#wrapper_ty as _serde::Deserialize>::deserialize(#deserializer),
|
||||||
|
|_wrapper| #type_ident::#variant_ident(_wrapper.value))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
};
|
|
||||||
quote! {
|
|
||||||
Ok(#type_ident::#variant_ident(#visit)),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -648,7 +971,8 @@ fn deserialize_field_visitor(
|
|||||||
item_attrs: &attr::Item,
|
item_attrs: &attr::Item,
|
||||||
is_variant: bool,
|
is_variant: bool,
|
||||||
) -> Tokens {
|
) -> Tokens {
|
||||||
let field_names = fields.iter().map(|&(ref name, _)| name);
|
let field_strs = fields.iter().map(|&(ref name, _)| name);
|
||||||
|
let field_bytes = fields.iter().map(|&(ref name, _)| quote::ByteStr(name));
|
||||||
let field_idents: &Vec<_> = &fields.iter().map(|&(_, ref ident)| ident).collect();
|
let field_idents: &Vec<_> = &fields.iter().map(|&(_, ref ident)| ident).collect();
|
||||||
|
|
||||||
let ignore_variant = if is_variant || item_attrs.deny_unknown_fields() {
|
let ignore_variant = if is_variant || item_attrs.deny_unknown_fields() {
|
||||||
@@ -657,20 +981,51 @@ fn deserialize_field_visitor(
|
|||||||
Some(quote!(__ignore,))
|
Some(quote!(__ignore,))
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let visit_index = if is_variant {
|
||||||
|
let variant_indices = 0u32..;
|
||||||
|
let fallthrough_msg = format!("variant index 0 <= i < {}", fields.len());
|
||||||
|
Some(quote! {
|
||||||
|
fn visit_u32<__E>(self, value: u32) -> _serde::export::Result<__Field, __E>
|
||||||
|
where __E: _serde::de::Error
|
||||||
|
{
|
||||||
|
match value {
|
||||||
|
#(
|
||||||
|
#variant_indices => _serde::export::Ok(__Field::#field_idents),
|
||||||
|
)*
|
||||||
|
_ => _serde::export::Err(_serde::de::Error::invalid_value(
|
||||||
|
_serde::de::Unexpected::Unsigned(value as u64),
|
||||||
|
&#fallthrough_msg))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
let fallthrough_arm = if is_variant {
|
let fallthrough_arm = if is_variant {
|
||||||
quote! {
|
quote! {
|
||||||
Err(_serde::de::Error::unknown_variant(value))
|
_serde::export::Err(_serde::de::Error::unknown_variant(value, VARIANTS))
|
||||||
}
|
}
|
||||||
} else if item_attrs.deny_unknown_fields() {
|
} else if item_attrs.deny_unknown_fields() {
|
||||||
quote! {
|
quote! {
|
||||||
Err(_serde::de::Error::unknown_field(value))
|
_serde::export::Err(_serde::de::Error::unknown_field(value, FIELDS))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
quote! {
|
quote! {
|
||||||
Ok(__Field::__ignore)
|
_serde::export::Ok(__Field::__ignore)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let bytes_to_str = if is_variant || item_attrs.deny_unknown_fields() {
|
||||||
|
Some(quote! {
|
||||||
|
// TODO https://github.com/serde-rs/serde/issues/666
|
||||||
|
// update this to use str::from_utf8(value).unwrap_or("���") on no_std
|
||||||
|
let value = &_serde::export::from_utf8_lossy(value);
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
quote! {
|
quote! {
|
||||||
#[allow(non_camel_case_types)]
|
#[allow(non_camel_case_types)]
|
||||||
enum __Field {
|
enum __Field {
|
||||||
@@ -680,7 +1035,7 @@ fn deserialize_field_visitor(
|
|||||||
|
|
||||||
impl _serde::Deserialize for __Field {
|
impl _serde::Deserialize for __Field {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn deserialize<__D>(deserializer: __D) -> ::std::result::Result<__Field, __D::Error>
|
fn deserialize<__D>(deserializer: __D) -> _serde::export::Result<__Field, __D::Error>
|
||||||
where __D: _serde::Deserializer,
|
where __D: _serde::Deserializer,
|
||||||
{
|
{
|
||||||
struct __FieldVisitor;
|
struct __FieldVisitor;
|
||||||
@@ -688,19 +1043,39 @@ fn deserialize_field_visitor(
|
|||||||
impl _serde::de::Visitor for __FieldVisitor {
|
impl _serde::de::Visitor for __FieldVisitor {
|
||||||
type Value = __Field;
|
type Value = __Field;
|
||||||
|
|
||||||
fn visit_str<__E>(self, value: &str) -> ::std::result::Result<__Field, __E>
|
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
|
||||||
|
_serde::export::fmt::Formatter::write_str(formatter, "field name")
|
||||||
|
}
|
||||||
|
|
||||||
|
#visit_index
|
||||||
|
|
||||||
|
fn visit_str<__E>(self, value: &str) -> _serde::export::Result<__Field, __E>
|
||||||
where __E: _serde::de::Error
|
where __E: _serde::de::Error
|
||||||
{
|
{
|
||||||
match value {
|
match value {
|
||||||
#(
|
#(
|
||||||
#field_names => Ok(__Field::#field_idents),
|
#field_strs => _serde::export::Ok(__Field::#field_idents),
|
||||||
)*
|
)*
|
||||||
_ => #fallthrough_arm
|
_ => #fallthrough_arm
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn visit_bytes<__E>(self, value: &[u8]) -> _serde::export::Result<__Field, __E>
|
||||||
|
where __E: _serde::de::Error
|
||||||
|
{
|
||||||
|
match value {
|
||||||
|
#(
|
||||||
|
#field_bytes => _serde::export::Ok(__Field::#field_idents),
|
||||||
|
)*
|
||||||
|
_ => {
|
||||||
|
#bytes_to_str
|
||||||
|
#fallthrough_arm
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
deserializer.deserialize_struct_field(__FieldVisitor)
|
_serde::Deserializer::deserialize_struct_field(deserializer, __FieldVisitor)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -713,12 +1088,19 @@ fn deserialize_struct_visitor(
|
|||||||
fields: &[Field],
|
fields: &[Field],
|
||||||
item_attrs: &attr::Item,
|
item_attrs: &attr::Item,
|
||||||
) -> (Tokens, Tokens, Tokens) {
|
) -> (Tokens, Tokens, Tokens) {
|
||||||
let field_names_idents = fields.iter()
|
let field_names_idents: Vec<_> = fields.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.filter(|&(_, field)| !field.attrs.skip_deserializing())
|
.filter(|&(_, field)| !field.attrs.skip_deserializing())
|
||||||
.map(|(i, field)| (field.attrs.name().deserialize_name(), field_i(i)))
|
.map(|(i, field)| (field.attrs.name().deserialize_name(), field_i(i)))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
|
let fields_stmt = {
|
||||||
|
let field_names = field_names_idents.iter().map(|&(ref name, _)| name);
|
||||||
|
quote! {
|
||||||
|
const FIELDS: &'static [&'static str] = &[ #(#field_names),* ];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let field_visitor = deserialize_field_visitor(
|
let field_visitor = deserialize_field_visitor(
|
||||||
field_names_idents,
|
field_names_idents,
|
||||||
item_attrs,
|
item_attrs,
|
||||||
@@ -733,11 +1115,6 @@ fn deserialize_struct_visitor(
|
|||||||
item_attrs,
|
item_attrs,
|
||||||
);
|
);
|
||||||
|
|
||||||
let field_names = fields.iter().map(|field| field.attrs.name().deserialize_name());
|
|
||||||
let fields_stmt = quote! {
|
|
||||||
const FIELDS: &'static [&'static str] = &[ #(#field_names),* ];
|
|
||||||
};
|
|
||||||
|
|
||||||
(field_visitor, fields_stmt, visit_map)
|
(field_visitor, fields_stmt, visit_map)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -760,7 +1137,7 @@ fn deserialize_map(
|
|||||||
.map(|&(field, ref name)| {
|
.map(|&(field, ref name)| {
|
||||||
let field_ty = &field.ty;
|
let field_ty = &field.ty;
|
||||||
quote! {
|
quote! {
|
||||||
let mut #name: Option<#field_ty> = None;
|
let mut #name: _serde::export::Option<#field_ty> = _serde::export::None;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -774,7 +1151,7 @@ fn deserialize_map(
|
|||||||
None => {
|
None => {
|
||||||
let field_ty = &field.ty;
|
let field_ty = &field.ty;
|
||||||
quote! {
|
quote! {
|
||||||
try!(visitor.visit_value::<#field_ty>())
|
try!(_serde::de::MapVisitor::visit_value::<#field_ty>(&mut visitor))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(path) => {
|
Some(path) => {
|
||||||
@@ -783,16 +1160,16 @@ fn deserialize_map(
|
|||||||
quote!({
|
quote!({
|
||||||
#wrapper
|
#wrapper
|
||||||
#wrapper_impl
|
#wrapper_impl
|
||||||
try!(visitor.visit_value::<#wrapper_ty>()).value
|
try!(_serde::de::MapVisitor::visit_value::<#wrapper_ty>(&mut visitor)).value
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
quote! {
|
quote! {
|
||||||
__Field::#name => {
|
__Field::#name => {
|
||||||
if #name.is_some() {
|
if _serde::export::Option::is_some(&#name) {
|
||||||
return Err(<__V::Error as _serde::de::Error>::duplicate_field(#deser_name));
|
return _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#deser_name));
|
||||||
}
|
}
|
||||||
#name = Some(#visit);
|
#name = _serde::export::Some(#visit);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -802,7 +1179,7 @@ fn deserialize_map(
|
|||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
Some(quote! {
|
Some(quote! {
|
||||||
_ => { let _ = try!(visitor.visit_value::<_serde::de::impls::IgnoredAny>()); }
|
_ => { let _ = try!(_serde::de::MapVisitor::visit_value::<_serde::de::impls::IgnoredAny>(&mut visitor)); }
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -810,12 +1187,13 @@ fn deserialize_map(
|
|||||||
let match_keys = if item_attrs.deny_unknown_fields() && all_skipped {
|
let match_keys = if item_attrs.deny_unknown_fields() && all_skipped {
|
||||||
quote! {
|
quote! {
|
||||||
// FIXME: Once we drop support for Rust 1.15:
|
// FIXME: Once we drop support for Rust 1.15:
|
||||||
// let None::<__Field> = try!(visitor.visit_key());
|
// let _serde::export::None::<__Field> = try!(_serde::de::MapVisitor::visit_key(&mut visitor));
|
||||||
try!(visitor.visit_key::<__Field>()).map(|impossible| match impossible {});
|
try!(_serde::de::MapVisitor::visit_key::<__Field>(&mut visitor))
|
||||||
|
.map(|impossible| match impossible {});
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
quote! {
|
quote! {
|
||||||
while let Some(key) = try!(visitor.visit_key::<__Field>()) {
|
while let _serde::export::Some(key) = try!(_serde::de::MapVisitor::visit_key::<__Field>(&mut visitor)) {
|
||||||
match key {
|
match key {
|
||||||
#(#value_arms)*
|
#(#value_arms)*
|
||||||
#ignored_arm
|
#ignored_arm
|
||||||
@@ -831,8 +1209,8 @@ fn deserialize_map(
|
|||||||
|
|
||||||
quote! {
|
quote! {
|
||||||
let #name = match #name {
|
let #name = match #name {
|
||||||
Some(#name) => #name,
|
_serde::export::Some(#name) => #name,
|
||||||
None => #missing_expr
|
_serde::export::None => #missing_expr
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -855,7 +1233,7 @@ fn deserialize_map(
|
|||||||
|
|
||||||
#(#extract_values)*
|
#(#extract_values)*
|
||||||
|
|
||||||
Ok(#struct_path { #(#result),* })
|
_serde::export::Ok(#struct_path { #(#result),* })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -893,18 +1271,18 @@ fn wrap_deserialize_with(
|
|||||||
quote! {
|
quote! {
|
||||||
struct __SerdeDeserializeWithStruct #impl_generics #where_clause {
|
struct __SerdeDeserializeWithStruct #impl_generics #where_clause {
|
||||||
value: #field_ty,
|
value: #field_ty,
|
||||||
phantom: ::std::marker::PhantomData<#phantom_ty>,
|
phantom: _serde::export::PhantomData<#phantom_ty>,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
quote! {
|
quote! {
|
||||||
impl #impl_generics _serde::Deserialize for #wrapper_ty #where_clause {
|
impl #impl_generics _serde::Deserialize for #wrapper_ty #where_clause {
|
||||||
fn deserialize<__D>(__d: __D) -> ::std::result::Result<Self, __D::Error>
|
fn deserialize<__D>(__d: __D) -> _serde::export::Result<Self, __D::Error>
|
||||||
where __D: _serde::Deserializer
|
where __D: _serde::Deserializer
|
||||||
{
|
{
|
||||||
let value = try!(#deserialize_with(__d));
|
let value = try!(#deserialize_with(__d));
|
||||||
Ok(__SerdeDeserializeWithStruct {
|
_serde::export::Ok(__SerdeDeserializeWithStruct {
|
||||||
value: value,
|
value: value,
|
||||||
phantom: ::std::marker::PhantomData,
|
phantom: _serde::export::PhantomData,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -916,7 +1294,7 @@ fn wrap_deserialize_with(
|
|||||||
fn expr_is_missing(attrs: &attr::Field) -> Tokens {
|
fn expr_is_missing(attrs: &attr::Field) -> Tokens {
|
||||||
match *attrs.default() {
|
match *attrs.default() {
|
||||||
attr::FieldDefault::Default => {
|
attr::FieldDefault::Default => {
|
||||||
return quote!(::std::default::Default::default());
|
return quote!(_serde::export::Default::default());
|
||||||
}
|
}
|
||||||
attr::FieldDefault::Path(ref path) => {
|
attr::FieldDefault::Path(ref path) => {
|
||||||
return quote!(#path());
|
return quote!(#path());
|
||||||
@@ -928,12 +1306,12 @@ fn expr_is_missing(attrs: &attr::Field) -> Tokens {
|
|||||||
match attrs.deserialize_with() {
|
match attrs.deserialize_with() {
|
||||||
None => {
|
None => {
|
||||||
quote! {
|
quote! {
|
||||||
try!(visitor.missing_field(#name))
|
try!(_serde::de::private::missing_field(#name))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(_) => {
|
Some(_) => {
|
||||||
quote! {
|
quote! {
|
||||||
return Err(<__V::Error as _serde::de::Error>::missing_field(#name))
|
return _serde::export::Err(<__V::Error as _serde::de::Error>::missing_field(#name))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+20
-4
@@ -1,11 +1,26 @@
|
|||||||
extern crate proc_macro;
|
#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
|
||||||
extern crate serde_codegen;
|
#![cfg_attr(feature = "cargo-clippy", allow(used_underscore_binding))]
|
||||||
|
|
||||||
|
// The `quote!` macro requires deep recursion.
|
||||||
|
#![recursion_limit = "192"]
|
||||||
|
|
||||||
|
extern crate syn;
|
||||||
|
#[macro_use]
|
||||||
|
extern crate quote;
|
||||||
|
|
||||||
|
extern crate serde_codegen_internals as internals;
|
||||||
|
|
||||||
|
extern crate proc_macro;
|
||||||
use proc_macro::TokenStream;
|
use proc_macro::TokenStream;
|
||||||
|
|
||||||
|
mod bound;
|
||||||
|
mod de;
|
||||||
|
mod ser;
|
||||||
|
|
||||||
#[proc_macro_derive(Serialize, attributes(serde))]
|
#[proc_macro_derive(Serialize, attributes(serde))]
|
||||||
pub fn derive_serialize(input: TokenStream) -> TokenStream {
|
pub fn derive_serialize(input: TokenStream) -> TokenStream {
|
||||||
match serde_codegen::expand_derive_serialize(&input.to_string()) {
|
let input = syn::parse_derive_input(&input.to_string()).unwrap();
|
||||||
|
match ser::expand_derive_serialize(&input) {
|
||||||
Ok(expanded) => expanded.parse().unwrap(),
|
Ok(expanded) => expanded.parse().unwrap(),
|
||||||
Err(msg) => panic!(msg),
|
Err(msg) => panic!(msg),
|
||||||
}
|
}
|
||||||
@@ -13,7 +28,8 @@ pub fn derive_serialize(input: TokenStream) -> TokenStream {
|
|||||||
|
|
||||||
#[proc_macro_derive(Deserialize, attributes(serde))]
|
#[proc_macro_derive(Deserialize, attributes(serde))]
|
||||||
pub fn derive_deserialize(input: TokenStream) -> TokenStream {
|
pub fn derive_deserialize(input: TokenStream) -> TokenStream {
|
||||||
match serde_codegen::expand_derive_deserialize(&input.to_string()) {
|
let input = syn::parse_derive_input(&input.to_string()).unwrap();
|
||||||
|
match de::expand_derive_deserialize(&input) {
|
||||||
Ok(expanded) => expanded.parse().unwrap(),
|
Ok(expanded) => expanded.parse().unwrap(),
|
||||||
Err(msg) => panic!(msg),
|
Err(msg) => panic!(msg),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use bound;
|
|||||||
use internals::ast::{Body, Field, Item, Style, Variant};
|
use internals::ast::{Body, Field, Item, Style, Variant};
|
||||||
use internals::{self, attr};
|
use internals::{self, attr};
|
||||||
|
|
||||||
pub fn expand_derive_serialize(item: &syn::MacroInput) -> Result<Tokens, String> {
|
pub fn expand_derive_serialize(item: &syn::DeriveInput) -> Result<Tokens, String> {
|
||||||
let ctxt = internals::Ctxt::new();
|
let ctxt = internals::Ctxt::new();
|
||||||
let item = Item::from_ast(&ctxt, item);
|
let item = Item::from_ast(&ctxt, item);
|
||||||
try!(ctxt.check());
|
try!(ctxt.check());
|
||||||
@@ -30,7 +30,7 @@ pub fn expand_derive_serialize(item: &syn::MacroInput) -> Result<Tokens, String>
|
|||||||
extern crate serde as _serde;
|
extern crate serde as _serde;
|
||||||
#[automatically_derived]
|
#[automatically_derived]
|
||||||
impl #impl_generics _serde::Serialize for #ty #where_clause {
|
impl #impl_generics _serde::Serialize for #ty #where_clause {
|
||||||
fn serialize<__S>(&self, _serializer: __S) -> ::std::result::Result<__S::Ok, __S::Error>
|
fn serialize<__S>(&self, _serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error>
|
||||||
where __S: _serde::Serializer
|
where __S: _serde::Serializer
|
||||||
{
|
{
|
||||||
#body
|
#body
|
||||||
@@ -125,7 +125,7 @@ fn serialize_unit_struct(item_attrs: &attr::Item) -> Tokens {
|
|||||||
let type_name = item_attrs.name().serialize_name();
|
let type_name = item_attrs.name().serialize_name();
|
||||||
|
|
||||||
quote! {
|
quote! {
|
||||||
_serializer.serialize_unit_struct(#type_name)
|
_serde::Serializer::serialize_unit_struct(_serializer, #type_name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,7 +144,7 @@ fn serialize_newtype_struct(
|
|||||||
}
|
}
|
||||||
|
|
||||||
quote! {
|
quote! {
|
||||||
_serializer.serialize_newtype_struct(#type_name, #field_expr)
|
_serde::Serializer::serialize_newtype_struct(_serializer, #type_name, #field_expr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,7 +167,7 @@ fn serialize_tuple_struct(
|
|||||||
let let_mut = mut_if(len > 0);
|
let let_mut = mut_if(len > 0);
|
||||||
|
|
||||||
quote! {
|
quote! {
|
||||||
let #let_mut __serde_state = try!(_serializer.serialize_tuple_struct(#type_name, #len));
|
let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple_struct(_serializer, #type_name, #len));
|
||||||
#(#serialize_stmts)*
|
#(#serialize_stmts)*
|
||||||
_serde::ser::SerializeTupleStruct::end(__serde_state)
|
_serde::ser::SerializeTupleStruct::end(__serde_state)
|
||||||
}
|
}
|
||||||
@@ -208,7 +208,7 @@ fn serialize_struct(
|
|||||||
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
|
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
|
||||||
|
|
||||||
quote! {
|
quote! {
|
||||||
let #let_mut __serde_state = try!(_serializer.serialize_struct(#type_name, #len));
|
let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct(_serializer, #type_name, #len));
|
||||||
#(#serialize_fields)*
|
#(#serialize_fields)*
|
||||||
_serde::ser::SerializeStruct::end(__serde_state)
|
_serde::ser::SerializeStruct::end(__serde_state)
|
||||||
}
|
}
|
||||||
@@ -251,16 +251,13 @@ fn serialize_variant(
|
|||||||
variant_index: usize,
|
variant_index: usize,
|
||||||
item_attrs: &attr::Item,
|
item_attrs: &attr::Item,
|
||||||
) -> Tokens {
|
) -> Tokens {
|
||||||
let type_name = item_attrs.name().serialize_name();
|
|
||||||
|
|
||||||
let variant_ident = variant.ident.clone();
|
let variant_ident = variant.ident.clone();
|
||||||
let variant_name = variant.attrs.name().serialize_name();
|
|
||||||
|
|
||||||
if variant.attrs.skip_serializing() {
|
if variant.attrs.skip_serializing() {
|
||||||
let skipped_msg = format!("The enum variant {}::{} cannot be serialized",
|
let skipped_msg = format!("the enum variant {}::{} cannot be serialized",
|
||||||
type_ident, variant_ident);
|
type_ident, variant_ident);
|
||||||
let skipped_err = quote! {
|
let skipped_err = quote! {
|
||||||
Err(_serde::ser::Error::invalid_value(#skipped_msg))
|
_serde::export::Err(_serde::ser::Error::custom(#skipped_msg))
|
||||||
};
|
};
|
||||||
let fields_pat = match variant.style {
|
let fields_pat = match variant.style {
|
||||||
Style::Unit => quote!(),
|
Style::Unit => quote!(),
|
||||||
@@ -271,139 +268,351 @@ fn serialize_variant(
|
|||||||
#type_ident::#variant_ident #fields_pat => #skipped_err,
|
#type_ident::#variant_ident #fields_pat => #skipped_err,
|
||||||
}
|
}
|
||||||
} else { // variant wasn't skipped
|
} else { // variant wasn't skipped
|
||||||
match variant.style {
|
let case = match variant.style {
|
||||||
Style::Unit => {
|
Style::Unit => {
|
||||||
quote! {
|
quote! {
|
||||||
#type_ident::#variant_ident =>
|
#type_ident::#variant_ident
|
||||||
_serde::Serializer::serialize_unit_variant(
|
|
||||||
_serializer,
|
|
||||||
#type_name,
|
|
||||||
#variant_index,
|
|
||||||
#variant_name,
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
Style::Newtype => {
|
Style::Newtype => {
|
||||||
let block = serialize_newtype_variant(
|
|
||||||
type_name,
|
|
||||||
variant_index,
|
|
||||||
variant_name,
|
|
||||||
ty,
|
|
||||||
generics,
|
|
||||||
&variant.fields[0],
|
|
||||||
);
|
|
||||||
|
|
||||||
quote! {
|
quote! {
|
||||||
#type_ident::#variant_ident(ref __simple_value) => #block,
|
#type_ident::#variant_ident(ref __simple_value)
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
Style::Tuple => {
|
Style::Tuple => {
|
||||||
let field_names = (0 .. variant.fields.len())
|
let field_names = (0 .. variant.fields.len())
|
||||||
.map(|i| Ident::new(format!("__field{}", i)));
|
.map(|i| Ident::new(format!("__field{}", i)));
|
||||||
|
|
||||||
let block = serialize_tuple_variant(
|
|
||||||
type_name,
|
|
||||||
variant_index,
|
|
||||||
variant_name,
|
|
||||||
generics,
|
|
||||||
ty,
|
|
||||||
&variant.fields,
|
|
||||||
);
|
|
||||||
|
|
||||||
quote! {
|
quote! {
|
||||||
#type_ident::#variant_ident(#(ref #field_names),*) => { #block }
|
#type_ident::#variant_ident(#(ref #field_names),*)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Style::Struct => {
|
Style::Struct => {
|
||||||
let fields = variant.fields.iter()
|
let fields = variant.fields.iter()
|
||||||
.map(|f| f.ident.clone().expect("struct variant has unnamed fields"));
|
.map(|f| f.ident.clone().expect("struct variant has unnamed fields"));
|
||||||
|
quote! {
|
||||||
|
#type_ident::#variant_ident { #(ref #fields),* }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let block = serialize_struct_variant(
|
let body = match *item_attrs.tag() {
|
||||||
variant_index,
|
attr::EnumTag::External => {
|
||||||
variant_name,
|
serialize_externally_tagged_variant(
|
||||||
generics,
|
generics,
|
||||||
ty,
|
ty,
|
||||||
&variant.fields,
|
variant,
|
||||||
|
variant_index,
|
||||||
item_attrs,
|
item_attrs,
|
||||||
);
|
)
|
||||||
|
}
|
||||||
|
attr::EnumTag::Internal(ref tag) => {
|
||||||
|
serialize_internally_tagged_variant(
|
||||||
|
type_ident.as_ref(),
|
||||||
|
variant_ident.as_ref(),
|
||||||
|
generics,
|
||||||
|
ty,
|
||||||
|
variant,
|
||||||
|
item_attrs,
|
||||||
|
tag,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
attr::EnumTag::None => {
|
||||||
|
serialize_untagged_variant(
|
||||||
|
generics,
|
||||||
|
ty,
|
||||||
|
variant,
|
||||||
|
item_attrs,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
quote! {
|
quote! {
|
||||||
#type_ident::#variant_ident { #(ref #fields),* } => { #block }
|
#case => #body
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_externally_tagged_variant(
|
||||||
|
generics: &syn::Generics,
|
||||||
|
ty: syn::Ty,
|
||||||
|
variant: &Variant,
|
||||||
|
variant_index: usize,
|
||||||
|
item_attrs: &attr::Item,
|
||||||
|
) -> Tokens {
|
||||||
|
let type_name = item_attrs.name().serialize_name();
|
||||||
|
let variant_name = variant.attrs.name().serialize_name();
|
||||||
|
|
||||||
|
match variant.style {
|
||||||
|
Style::Unit => {
|
||||||
|
quote! {
|
||||||
|
_serde::Serializer::serialize_unit_variant(
|
||||||
|
_serializer,
|
||||||
|
#type_name,
|
||||||
|
#variant_index,
|
||||||
|
#variant_name,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Style::Newtype => {
|
||||||
|
let field = &variant.fields[0];
|
||||||
|
let mut field_expr = quote!(__simple_value);
|
||||||
|
if let Some(path) = field.attrs.serialize_with() {
|
||||||
|
field_expr = wrap_serialize_with(
|
||||||
|
&ty, generics, field.ty, path, field_expr);
|
||||||
|
}
|
||||||
|
|
||||||
|
quote! {
|
||||||
|
_serde::Serializer::serialize_newtype_variant(
|
||||||
|
_serializer,
|
||||||
|
#type_name,
|
||||||
|
#variant_index,
|
||||||
|
#variant_name,
|
||||||
|
#field_expr,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Style::Tuple => {
|
||||||
|
let block = serialize_tuple_variant(
|
||||||
|
TupleVariant::ExternallyTagged {
|
||||||
|
type_name: type_name,
|
||||||
|
variant_index: variant_index,
|
||||||
|
variant_name: variant_name,
|
||||||
|
},
|
||||||
|
generics,
|
||||||
|
ty,
|
||||||
|
&variant.fields,
|
||||||
|
);
|
||||||
|
|
||||||
|
quote! {
|
||||||
|
{ #block }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Style::Struct => {
|
||||||
|
let block = serialize_struct_variant(
|
||||||
|
StructVariant::ExternallyTagged {
|
||||||
|
variant_index: variant_index,
|
||||||
|
variant_name: variant_name,
|
||||||
|
},
|
||||||
|
generics,
|
||||||
|
ty,
|
||||||
|
&variant.fields,
|
||||||
|
item_attrs,
|
||||||
|
);
|
||||||
|
|
||||||
|
quote! {
|
||||||
|
{ #block }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serialize_newtype_variant(
|
fn serialize_internally_tagged_variant(
|
||||||
type_name: String,
|
type_ident: &str,
|
||||||
variant_index: usize,
|
variant_ident: &str,
|
||||||
variant_name: String,
|
|
||||||
item_ty: syn::Ty,
|
|
||||||
generics: &syn::Generics,
|
generics: &syn::Generics,
|
||||||
field: &Field,
|
ty: syn::Ty,
|
||||||
|
variant: &Variant,
|
||||||
|
item_attrs: &attr::Item,
|
||||||
|
tag: &str,
|
||||||
) -> Tokens {
|
) -> Tokens {
|
||||||
let mut field_expr = quote!(__simple_value);
|
let type_name = item_attrs.name().serialize_name();
|
||||||
if let Some(path) = field.attrs.serialize_with() {
|
let variant_name = variant.attrs.name().serialize_name();
|
||||||
field_expr = wrap_serialize_with(
|
|
||||||
&item_ty, generics, field.ty, path, field_expr);
|
|
||||||
}
|
|
||||||
|
|
||||||
quote! {
|
match variant.style {
|
||||||
_serde::Serializer::serialize_newtype_variant(
|
Style::Unit => {
|
||||||
_serializer,
|
quote!({
|
||||||
#type_name,
|
let mut __struct = try!(_serde::Serializer::serialize_struct(
|
||||||
#variant_index,
|
_serializer, #type_name, 1));
|
||||||
#variant_name,
|
try!(_serde::ser::SerializeStruct::serialize_field(
|
||||||
#field_expr,
|
&mut __struct, #tag, #variant_name));
|
||||||
)
|
_serde::ser::SerializeStruct::end(__struct)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Style::Newtype => {
|
||||||
|
let field = &variant.fields[0];
|
||||||
|
let mut field_expr = quote!(__simple_value);
|
||||||
|
if let Some(path) = field.attrs.serialize_with() {
|
||||||
|
field_expr = wrap_serialize_with(
|
||||||
|
&ty, generics, field.ty, path, field_expr);
|
||||||
|
}
|
||||||
|
|
||||||
|
quote! {
|
||||||
|
_serde::ser::private::serialize_tagged_newtype(
|
||||||
|
_serializer,
|
||||||
|
#type_ident,
|
||||||
|
#variant_ident,
|
||||||
|
#tag,
|
||||||
|
#variant_name,
|
||||||
|
#field_expr,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Style::Struct => {
|
||||||
|
let block = serialize_struct_variant(
|
||||||
|
StructVariant::InternallyTagged {
|
||||||
|
tag: tag,
|
||||||
|
variant_name: variant_name,
|
||||||
|
},
|
||||||
|
generics,
|
||||||
|
ty,
|
||||||
|
&variant.fields,
|
||||||
|
item_attrs,
|
||||||
|
);
|
||||||
|
|
||||||
|
quote! {
|
||||||
|
{ #block }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Style::Tuple => unreachable!("checked in serde_codegen_internals"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn serialize_untagged_variant(
|
||||||
|
generics: &syn::Generics,
|
||||||
|
ty: syn::Ty,
|
||||||
|
variant: &Variant,
|
||||||
|
item_attrs: &attr::Item,
|
||||||
|
) -> Tokens {
|
||||||
|
match variant.style {
|
||||||
|
Style::Unit => {
|
||||||
|
quote! {
|
||||||
|
_serde::Serializer::serialize_unit(_serializer),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Style::Newtype => {
|
||||||
|
let field = &variant.fields[0];
|
||||||
|
let mut field_expr = quote!(__simple_value);
|
||||||
|
if let Some(path) = field.attrs.serialize_with() {
|
||||||
|
field_expr = wrap_serialize_with(
|
||||||
|
&ty, generics, field.ty, path, field_expr);
|
||||||
|
}
|
||||||
|
|
||||||
|
quote! {
|
||||||
|
_serde::Serialize::serialize(#field_expr, _serializer),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Style::Tuple => {
|
||||||
|
let block = serialize_tuple_variant(
|
||||||
|
TupleVariant::Untagged,
|
||||||
|
generics,
|
||||||
|
ty,
|
||||||
|
&variant.fields,
|
||||||
|
);
|
||||||
|
|
||||||
|
quote! {
|
||||||
|
{ #block }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Style::Struct => {
|
||||||
|
let block = serialize_struct_variant(
|
||||||
|
StructVariant::Untagged,
|
||||||
|
generics,
|
||||||
|
ty,
|
||||||
|
&variant.fields,
|
||||||
|
item_attrs,
|
||||||
|
);
|
||||||
|
|
||||||
|
quote! {
|
||||||
|
{ #block }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum TupleVariant {
|
||||||
|
ExternallyTagged {
|
||||||
|
type_name: String,
|
||||||
|
variant_index: usize,
|
||||||
|
variant_name: String,
|
||||||
|
},
|
||||||
|
Untagged,
|
||||||
|
}
|
||||||
|
|
||||||
fn serialize_tuple_variant(
|
fn serialize_tuple_variant(
|
||||||
type_name: String,
|
context: TupleVariant,
|
||||||
variant_index: usize,
|
|
||||||
variant_name: String,
|
|
||||||
generics: &syn::Generics,
|
generics: &syn::Generics,
|
||||||
structure_ty: syn::Ty,
|
structure_ty: syn::Ty,
|
||||||
fields: &[Field],
|
fields: &[Field],
|
||||||
) -> Tokens {
|
) -> Tokens {
|
||||||
|
let method = match context {
|
||||||
|
TupleVariant::ExternallyTagged{..} => {
|
||||||
|
quote!(_serde::ser::SerializeTupleVariant::serialize_field)
|
||||||
|
}
|
||||||
|
TupleVariant::Untagged => {
|
||||||
|
quote!(_serde::ser::SerializeTuple::serialize_element)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let serialize_stmts = serialize_tuple_struct_visitor(
|
let serialize_stmts = serialize_tuple_struct_visitor(
|
||||||
structure_ty,
|
structure_ty,
|
||||||
fields,
|
fields,
|
||||||
generics,
|
generics,
|
||||||
true,
|
true,
|
||||||
quote!(_serde::ser::SerializeTupleVariant::serialize_field),
|
method,
|
||||||
);
|
);
|
||||||
|
|
||||||
let len = serialize_stmts.len();
|
let len = serialize_stmts.len();
|
||||||
let let_mut = mut_if(len > 0);
|
let let_mut = mut_if(len > 0);
|
||||||
|
|
||||||
quote! {
|
match context {
|
||||||
let #let_mut __serde_state = try!(_serializer.serialize_tuple_variant(
|
TupleVariant::ExternallyTagged { type_name, variant_index, variant_name } => {
|
||||||
#type_name,
|
quote! {
|
||||||
#variant_index,
|
let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple_variant(
|
||||||
#variant_name,
|
_serializer,
|
||||||
#len));
|
#type_name,
|
||||||
#(#serialize_stmts)*
|
#variant_index,
|
||||||
_serde::ser::SerializeTupleVariant::end(__serde_state)
|
#variant_name,
|
||||||
|
#len));
|
||||||
|
#(#serialize_stmts)*
|
||||||
|
_serde::ser::SerializeTupleVariant::end(__serde_state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TupleVariant::Untagged => {
|
||||||
|
quote! {
|
||||||
|
let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple(
|
||||||
|
_serializer,
|
||||||
|
#len));
|
||||||
|
#(#serialize_stmts)*
|
||||||
|
_serde::ser::SerializeTuple::end(__serde_state)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serialize_struct_variant(
|
enum StructVariant<'a> {
|
||||||
variant_index: usize,
|
ExternallyTagged {
|
||||||
variant_name: String,
|
variant_index: usize,
|
||||||
|
variant_name: String,
|
||||||
|
},
|
||||||
|
InternallyTagged {
|
||||||
|
tag: &'a str,
|
||||||
|
variant_name: String,
|
||||||
|
},
|
||||||
|
Untagged,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_struct_variant<'a>(
|
||||||
|
context: StructVariant<'a>,
|
||||||
generics: &syn::Generics,
|
generics: &syn::Generics,
|
||||||
ty: syn::Ty,
|
ty: syn::Ty,
|
||||||
fields: &[Field],
|
fields: &[Field],
|
||||||
item_attrs: &attr::Item,
|
item_attrs: &attr::Item,
|
||||||
) -> Tokens {
|
) -> Tokens {
|
||||||
|
let method = match context {
|
||||||
|
StructVariant::ExternallyTagged{..} => {
|
||||||
|
quote!(_serde::ser::SerializeStructVariant::serialize_field)
|
||||||
|
}
|
||||||
|
StructVariant::InternallyTagged{..} | StructVariant::Untagged => {
|
||||||
|
quote!(_serde::ser::SerializeStruct::serialize_field)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let serialize_fields = serialize_struct_visitor(
|
let serialize_fields = serialize_struct_visitor(
|
||||||
ty.clone(),
|
ty.clone(),
|
||||||
fields,
|
fields,
|
||||||
generics,
|
generics,
|
||||||
true,
|
true,
|
||||||
quote!(_serde::ser::SerializeStructVariant::serialize_field),
|
method,
|
||||||
);
|
);
|
||||||
|
|
||||||
let item_name = item_attrs.name().serialize_name();
|
let item_name = item_attrs.name().serialize_name();
|
||||||
@@ -425,15 +634,47 @@ fn serialize_struct_variant(
|
|||||||
})
|
})
|
||||||
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
|
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
|
||||||
|
|
||||||
quote! {
|
match context {
|
||||||
let #let_mut __serde_state = try!(_serializer.serialize_struct_variant(
|
StructVariant::ExternallyTagged { variant_index, variant_name } => {
|
||||||
#item_name,
|
quote! {
|
||||||
#variant_index,
|
let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct_variant(
|
||||||
#variant_name,
|
_serializer,
|
||||||
#len,
|
#item_name,
|
||||||
));
|
#variant_index,
|
||||||
#(#serialize_fields)*
|
#variant_name,
|
||||||
_serde::ser::SerializeStructVariant::end(__serde_state)
|
#len,
|
||||||
|
));
|
||||||
|
#(#serialize_fields)*
|
||||||
|
_serde::ser::SerializeStructVariant::end(__serde_state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
StructVariant::InternallyTagged { tag, variant_name } => {
|
||||||
|
quote! {
|
||||||
|
let mut __serde_state = try!(_serde::Serializer::serialize_struct(
|
||||||
|
_serializer,
|
||||||
|
#item_name,
|
||||||
|
#len + 1,
|
||||||
|
));
|
||||||
|
try!(_serde::ser::SerializeStruct::serialize_field(
|
||||||
|
&mut __serde_state,
|
||||||
|
#tag,
|
||||||
|
#variant_name,
|
||||||
|
));
|
||||||
|
#(#serialize_fields)*
|
||||||
|
_serde::ser::SerializeStruct::end(__serde_state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
StructVariant::Untagged => {
|
||||||
|
quote! {
|
||||||
|
let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct(
|
||||||
|
_serializer,
|
||||||
|
#item_name,
|
||||||
|
#len,
|
||||||
|
));
|
||||||
|
#(#serialize_fields)*
|
||||||
|
_serde::ser::SerializeStruct::end(__serde_state)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -537,20 +778,20 @@ fn wrap_serialize_with(
|
|||||||
quote!({
|
quote!({
|
||||||
struct __SerializeWith #wrapper_generics #where_clause {
|
struct __SerializeWith #wrapper_generics #where_clause {
|
||||||
value: &'__a #field_ty,
|
value: &'__a #field_ty,
|
||||||
phantom: ::std::marker::PhantomData<#item_ty>,
|
phantom: _serde::export::PhantomData<#item_ty>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl #wrapper_generics _serde::Serialize for #wrapper_ty #where_clause {
|
impl #wrapper_generics _serde::Serialize for #wrapper_ty #where_clause {
|
||||||
fn serialize<__S>(&self, __s: __S) -> ::std::result::Result<__S::Ok, __S::Error>
|
fn serialize<__S>(&self, __s: __S) -> _serde::export::Result<__S::Ok, __S::Error>
|
||||||
where __S: _serde::Serializer
|
where __S: _serde::Serializer
|
||||||
{
|
{
|
||||||
#path(self.value, __s)
|
#path(self.value, __s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
__SerializeWith {
|
&__SerializeWith {
|
||||||
value: #value,
|
value: #value,
|
||||||
phantom: ::std::marker::PhantomData::<#item_ty>,
|
phantom: _serde::export::PhantomData::<#item_ty>,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
extern crate compiletest_rs as compiletest;
|
|
||||||
|
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::env::var;
|
|
||||||
|
|
||||||
fn run_mode(mode: &'static str) {
|
|
||||||
let mut config = compiletest::default_config();
|
|
||||||
|
|
||||||
let cfg_mode = mode.parse().ok().expect("Invalid mode");
|
|
||||||
|
|
||||||
config.target_rustcflags = Some("-L target/debug/ -L target/debug/deps/".to_owned());
|
|
||||||
if let Ok(name) = var::<&str>("TESTNAME") {
|
|
||||||
let s : String = name.to_owned();
|
|
||||||
config.filter = Some(s)
|
|
||||||
}
|
|
||||||
config.mode = cfg_mode;
|
|
||||||
config.src_base = PathBuf::from(format!("tests/{}", mode));
|
|
||||||
|
|
||||||
compiletest::run_tests(&config);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn compile_fail() {
|
|
||||||
run_mode("compile-fail");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn run_pass() {
|
|
||||||
run_mode("run-pass");
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
#![feature(test)]
|
|
||||||
|
|
||||||
#[macro_use]
|
|
||||||
extern crate serde_derive;
|
|
||||||
|
|
||||||
extern crate test;
|
|
||||||
|
|
||||||
include!("../../testing/tests/test.rs.in");
|
|
||||||
|
|
||||||
mod compile_tests;
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "serde_test"
|
name = "serde_test"
|
||||||
version = "0.9.0-rc1"
|
version = "0.9.6"
|
||||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
description = "Token De/Serializer for testing De/Serialize implementations"
|
description = "Token De/Serializer for testing De/Serialize implementations"
|
||||||
@@ -12,4 +12,7 @@ keywords = ["serde", "serialization"]
|
|||||||
include = ["Cargo.toml", "src/**/*.rs"]
|
include = ["Cargo.toml", "src/**/*.rs"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
serde = { version = "0.9.0-rc1", path = "../serde" }
|
serde = { version = "0.9", path = "../serde" }
|
||||||
|
|
||||||
|
[badges]
|
||||||
|
travis-ci = { repository = "serde-rs/serde" }
|
||||||
|
|||||||
+93
-465
@@ -3,6 +3,7 @@ use std::iter;
|
|||||||
use serde::de::{
|
use serde::de::{
|
||||||
self,
|
self,
|
||||||
Deserialize,
|
Deserialize,
|
||||||
|
DeserializeSeed,
|
||||||
EnumVisitor,
|
EnumVisitor,
|
||||||
MapVisitor,
|
MapVisitor,
|
||||||
SeqVisitor,
|
SeqVisitor,
|
||||||
@@ -42,95 +43,33 @@ impl<I> Deserializer<I>
|
|||||||
Err(Error::UnexpectedToken(token))
|
Err(Error::UnexpectedToken(token))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => Err(Error::EndOfStream),
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn visit_seq<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
|
fn visit_seq<V>(&mut self, len: Option<usize>, sep: Token<'static>, end: Token<'static>, visitor: V) -> Result<V::Value, Error>
|
||||||
where V: Visitor,
|
where V: Visitor,
|
||||||
{
|
{
|
||||||
let value = try!(visitor.visit_seq(DeserializerSeqVisitor {
|
let value = try!(visitor.visit_seq(DeserializerSeqVisitor {
|
||||||
de: self,
|
de: self,
|
||||||
len: len,
|
len: len,
|
||||||
|
sep: sep,
|
||||||
|
end: end.clone(),
|
||||||
}));
|
}));
|
||||||
try!(self.expect_token(Token::SeqEnd));
|
try!(self.expect_token(end));
|
||||||
Ok(value)
|
Ok(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn visit_array<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Error>
|
fn visit_map<V>(&mut self, len: Option<usize>, sep: Token<'static>, end: Token<'static>, visitor: V) -> Result<V::Value, Error>
|
||||||
where V: Visitor,
|
|
||||||
{
|
|
||||||
let value = try!(visitor.visit_seq(DeserializerArrayVisitor {
|
|
||||||
de: self,
|
|
||||||
len: len,
|
|
||||||
}));
|
|
||||||
try!(self.expect_token(Token::SeqEnd));
|
|
||||||
Ok(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_tuple<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Error>
|
|
||||||
where V: Visitor,
|
|
||||||
{
|
|
||||||
let value = try!(visitor.visit_seq(DeserializerTupleVisitor {
|
|
||||||
de: self,
|
|
||||||
len: len,
|
|
||||||
}));
|
|
||||||
try!(self.expect_token(Token::TupleEnd));
|
|
||||||
Ok(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_tuple_struct<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Error>
|
|
||||||
where V: Visitor,
|
|
||||||
{
|
|
||||||
let value = try!(visitor.visit_seq(DeserializerTupleStructVisitor {
|
|
||||||
de: self,
|
|
||||||
len: len,
|
|
||||||
}));
|
|
||||||
try!(self.expect_token(Token::TupleStructEnd));
|
|
||||||
Ok(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_variant_seq<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
|
|
||||||
where V: Visitor,
|
|
||||||
{
|
|
||||||
let value = try!(visitor.visit_seq(DeserializerVariantSeqVisitor {
|
|
||||||
de: self,
|
|
||||||
len: len,
|
|
||||||
}));
|
|
||||||
try!(self.expect_token(Token::EnumSeqEnd));
|
|
||||||
Ok(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_map<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
|
|
||||||
where V: Visitor,
|
where V: Visitor,
|
||||||
{
|
{
|
||||||
let value = try!(visitor.visit_map(DeserializerMapVisitor {
|
let value = try!(visitor.visit_map(DeserializerMapVisitor {
|
||||||
de: self,
|
de: self,
|
||||||
len: len,
|
len: len,
|
||||||
|
sep: sep,
|
||||||
|
end: end.clone(),
|
||||||
}));
|
}));
|
||||||
try!(self.expect_token(Token::MapEnd));
|
try!(self.expect_token(end));
|
||||||
Ok(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_struct<V>(&mut self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Error>
|
|
||||||
where V: Visitor,
|
|
||||||
{
|
|
||||||
let value = try!(visitor.visit_map(DeserializerStructVisitor {
|
|
||||||
de: self,
|
|
||||||
len: fields.len(),
|
|
||||||
}));
|
|
||||||
try!(self.expect_token(Token::StructEnd));
|
|
||||||
Ok(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_variant_map<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
|
|
||||||
where V: Visitor,
|
|
||||||
{
|
|
||||||
let value = try!(visitor.visit_map(DeserializerVariantMapVisitor {
|
|
||||||
de: self,
|
|
||||||
len: len,
|
|
||||||
}));
|
|
||||||
try!(self.expect_token(Token::EnumMapEnd));
|
|
||||||
Ok(value)
|
Ok(value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -140,93 +79,9 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
|||||||
{
|
{
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
|
||||||
fn deserialize_seq<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
forward_to_deserialize! {
|
||||||
where __V: de::Visitor {
|
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit
|
||||||
self.deserialize(visitor)
|
seq bytes byte_buf map struct_field ignored_any
|
||||||
}
|
|
||||||
fn deserialize_struct_field<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_map<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_unit<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_bytes<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_ignored_any<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_string<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_str<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_char<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_i64<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_i32<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_i16<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_i8<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_u64<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_u32<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_u16<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_u8<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_f32<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_f64<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_bool<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_usize<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
|
||||||
fn deserialize_isize<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
|
|
||||||
where __V: de::Visitor {
|
|
||||||
self.deserialize(visitor)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
|
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
|
||||||
@@ -234,12 +89,10 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
|||||||
{
|
{
|
||||||
match self.tokens.next() {
|
match self.tokens.next() {
|
||||||
Some(Token::Bool(v)) => visitor.visit_bool(v),
|
Some(Token::Bool(v)) => visitor.visit_bool(v),
|
||||||
Some(Token::Isize(v)) => visitor.visit_isize(v),
|
|
||||||
Some(Token::I8(v)) => visitor.visit_i8(v),
|
Some(Token::I8(v)) => visitor.visit_i8(v),
|
||||||
Some(Token::I16(v)) => visitor.visit_i16(v),
|
Some(Token::I16(v)) => visitor.visit_i16(v),
|
||||||
Some(Token::I32(v)) => visitor.visit_i32(v),
|
Some(Token::I32(v)) => visitor.visit_i32(v),
|
||||||
Some(Token::I64(v)) => visitor.visit_i64(v),
|
Some(Token::I64(v)) => visitor.visit_i64(v),
|
||||||
Some(Token::Usize(v)) => visitor.visit_usize(v),
|
|
||||||
Some(Token::U8(v)) => visitor.visit_u8(v),
|
Some(Token::U8(v)) => visitor.visit_u8(v),
|
||||||
Some(Token::U16(v)) => visitor.visit_u16(v),
|
Some(Token::U16(v)) => visitor.visit_u16(v),
|
||||||
Some(Token::U32(v)) => visitor.visit_u32(v),
|
Some(Token::U32(v)) => visitor.visit_u32(v),
|
||||||
@@ -250,24 +103,31 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
|||||||
Some(Token::Str(v)) => visitor.visit_str(v),
|
Some(Token::Str(v)) => visitor.visit_str(v),
|
||||||
Some(Token::String(v)) => visitor.visit_string(v),
|
Some(Token::String(v)) => visitor.visit_string(v),
|
||||||
Some(Token::Bytes(v)) => visitor.visit_bytes(v),
|
Some(Token::Bytes(v)) => visitor.visit_bytes(v),
|
||||||
|
Some(Token::ByteBuf(v)) => visitor.visit_byte_buf(v),
|
||||||
Some(Token::Option(false)) => visitor.visit_none(),
|
Some(Token::Option(false)) => visitor.visit_none(),
|
||||||
Some(Token::Option(true)) => visitor.visit_some(self),
|
Some(Token::Option(true)) => visitor.visit_some(self),
|
||||||
Some(Token::Unit) => visitor.visit_unit(),
|
Some(Token::Unit) => visitor.visit_unit(),
|
||||||
Some(Token::UnitStruct(name)) => visitor.visit_unit_struct(name),
|
Some(Token::UnitStruct(_name)) => visitor.visit_unit(),
|
||||||
Some(Token::SeqStart(len)) => {
|
Some(Token::SeqStart(len)) => {
|
||||||
self.visit_seq(len, visitor)
|
self.visit_seq(len, Token::SeqSep, Token::SeqEnd, visitor)
|
||||||
}
|
}
|
||||||
Some(Token::SeqArrayStart(len))| Some(Token::TupleStructStart(_, len)) => {
|
Some(Token::SeqArrayStart(len)) => {
|
||||||
self.visit_seq(Some(len), visitor)
|
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||||
|
}
|
||||||
|
Some(Token::TupleStart(len)) => {
|
||||||
|
self.visit_seq(Some(len), Token::TupleSep, Token::TupleEnd, visitor)
|
||||||
|
}
|
||||||
|
Some(Token::TupleStructStart(_, len)) => {
|
||||||
|
self.visit_seq(Some(len), Token::TupleStructSep, Token::TupleStructEnd, visitor)
|
||||||
}
|
}
|
||||||
Some(Token::MapStart(len)) => {
|
Some(Token::MapStart(len)) => {
|
||||||
self.visit_map(len, visitor)
|
self.visit_map(len, Token::MapSep, Token::MapEnd, visitor)
|
||||||
}
|
}
|
||||||
Some(Token::StructStart(_, len)) => {
|
Some(Token::StructStart(_, len)) => {
|
||||||
self.visit_map(Some(len), visitor)
|
self.visit_map(Some(len), Token::StructSep, Token::StructEnd, visitor)
|
||||||
}
|
}
|
||||||
Some(token) => Err(Error::UnexpectedToken(token)),
|
Some(token) => Err(Error::UnexpectedToken(token)),
|
||||||
None => Err(Error::EndOfStream),
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -277,7 +137,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
|||||||
where V: Visitor,
|
where V: Visitor,
|
||||||
{
|
{
|
||||||
match self.tokens.peek() {
|
match self.tokens.peek() {
|
||||||
Some(&Token::Option(false)) => {
|
Some(&Token::Unit) | Some(&Token::Option(false)) => {
|
||||||
self.tokens.next();
|
self.tokens.next();
|
||||||
visitor.visit_none()
|
visitor.visit_none()
|
||||||
}
|
}
|
||||||
@@ -285,12 +145,8 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
|||||||
self.tokens.next();
|
self.tokens.next();
|
||||||
visitor.visit_some(self)
|
visitor.visit_some(self)
|
||||||
}
|
}
|
||||||
Some(&Token::Unit) => {
|
|
||||||
self.tokens.next();
|
|
||||||
visitor.visit_none()
|
|
||||||
}
|
|
||||||
Some(_) => visitor.visit_some(self),
|
Some(_) => visitor.visit_some(self),
|
||||||
None => Err(Error::EndOfStream),
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -320,7 +176,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
|||||||
let token = self.tokens.next().unwrap();
|
let token = self.tokens.next().unwrap();
|
||||||
Err(Error::UnexpectedToken(token))
|
Err(Error::UnexpectedToken(token))
|
||||||
}
|
}
|
||||||
None => { return Err(Error::EndOfStream); }
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -337,7 +193,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(_) => self.deserialize(visitor),
|
Some(_) => self.deserialize(visitor),
|
||||||
None => Err(Error::EndOfStream),
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -356,7 +212,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(_) => self.deserialize(visitor),
|
Some(_) => self.deserialize(visitor),
|
||||||
None => Err(Error::EndOfStream),
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -368,10 +224,10 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
|||||||
match self.tokens.peek() {
|
match self.tokens.peek() {
|
||||||
Some(&Token::SeqArrayStart(_)) => {
|
Some(&Token::SeqArrayStart(_)) => {
|
||||||
self.tokens.next();
|
self.tokens.next();
|
||||||
self.visit_array(len, visitor)
|
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||||
}
|
}
|
||||||
Some(_) => self.deserialize(visitor),
|
Some(_) => self.deserialize(visitor),
|
||||||
None => Err(Error::EndOfStream),
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -381,32 +237,28 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
|||||||
where V: Visitor,
|
where V: Visitor,
|
||||||
{
|
{
|
||||||
match self.tokens.peek() {
|
match self.tokens.peek() {
|
||||||
Some(&Token::Unit) => {
|
Some(&Token::Unit) | Some(&Token::UnitStruct(_)) => {
|
||||||
self.tokens.next();
|
|
||||||
visitor.visit_unit()
|
|
||||||
}
|
|
||||||
Some(&Token::UnitStruct(_)) => {
|
|
||||||
self.tokens.next();
|
self.tokens.next();
|
||||||
visitor.visit_unit()
|
visitor.visit_unit()
|
||||||
}
|
}
|
||||||
Some(&Token::SeqStart(_)) => {
|
Some(&Token::SeqStart(_)) => {
|
||||||
self.tokens.next();
|
self.tokens.next();
|
||||||
self.visit_seq(Some(len), visitor)
|
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||||
}
|
}
|
||||||
Some(&Token::SeqArrayStart(_)) => {
|
Some(&Token::SeqArrayStart(_)) => {
|
||||||
self.tokens.next();
|
self.tokens.next();
|
||||||
self.visit_array(len, visitor)
|
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||||
}
|
}
|
||||||
Some(&Token::TupleStart(_)) => {
|
Some(&Token::TupleStart(_)) => {
|
||||||
self.tokens.next();
|
self.tokens.next();
|
||||||
self.visit_tuple(len, visitor)
|
self.visit_seq(Some(len), Token::TupleSep, Token::TupleEnd, visitor)
|
||||||
}
|
}
|
||||||
Some(&Token::TupleStructStart(_, _)) => {
|
Some(&Token::TupleStructStart(_, _)) => {
|
||||||
self.tokens.next();
|
self.tokens.next();
|
||||||
self.visit_tuple_struct(len, visitor)
|
self.visit_seq(Some(len), Token::TupleStructSep, Token::TupleStructEnd, visitor)
|
||||||
}
|
}
|
||||||
Some(_) => self.deserialize(visitor),
|
Some(_) => self.deserialize(visitor),
|
||||||
None => Err(Error::EndOfStream),
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -431,26 +283,26 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
|||||||
}
|
}
|
||||||
Some(&Token::SeqStart(_)) => {
|
Some(&Token::SeqStart(_)) => {
|
||||||
self.tokens.next();
|
self.tokens.next();
|
||||||
self.visit_seq(Some(len), visitor)
|
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||||
}
|
}
|
||||||
Some(&Token::SeqArrayStart(_)) => {
|
Some(&Token::SeqArrayStart(_)) => {
|
||||||
self.tokens.next();
|
self.tokens.next();
|
||||||
self.visit_array(len, visitor)
|
self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||||
}
|
}
|
||||||
Some(&Token::TupleStart(_)) => {
|
Some(&Token::TupleStart(_)) => {
|
||||||
self.tokens.next();
|
self.tokens.next();
|
||||||
self.visit_tuple(len, visitor)
|
self.visit_seq(Some(len), Token::TupleSep, Token::TupleEnd, visitor)
|
||||||
}
|
}
|
||||||
Some(&Token::TupleStructStart(n, _)) => {
|
Some(&Token::TupleStructStart(n, _)) => {
|
||||||
self.tokens.next();
|
self.tokens.next();
|
||||||
if name == n {
|
if name == n {
|
||||||
self.visit_tuple_struct(len, visitor)
|
self.visit_seq(Some(len), Token::TupleStructSep, Token::TupleStructEnd, visitor)
|
||||||
} else {
|
} else {
|
||||||
Err(Error::InvalidName(n))
|
Err(Error::InvalidName(n))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(_) => self.deserialize(visitor),
|
Some(_) => self.deserialize(visitor),
|
||||||
None => Err(Error::EndOfStream),
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -464,17 +316,17 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
|||||||
Some(&Token::StructStart(n, _)) => {
|
Some(&Token::StructStart(n, _)) => {
|
||||||
self.tokens.next();
|
self.tokens.next();
|
||||||
if name == n {
|
if name == n {
|
||||||
self.visit_struct(fields, visitor)
|
self.visit_map(Some(fields.len()), Token::StructSep, Token::StructEnd, visitor)
|
||||||
} else {
|
} else {
|
||||||
Err(Error::InvalidName(n))
|
Err(Error::InvalidName(n))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(&Token::MapStart(_)) => {
|
Some(&Token::MapStart(_)) => {
|
||||||
self.tokens.next();
|
self.tokens.next();
|
||||||
self.visit_map(Some(fields.len()), visitor)
|
self.visit_map(Some(fields.len()), Token::MapSep, Token::MapEnd, visitor)
|
||||||
}
|
}
|
||||||
Some(_) => self.deserialize(visitor),
|
Some(_) => self.deserialize(visitor),
|
||||||
None => Err(Error::EndOfStream),
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -484,6 +336,8 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
|
|||||||
struct DeserializerSeqVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
struct DeserializerSeqVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||||
de: &'a mut Deserializer<I>,
|
de: &'a mut Deserializer<I>,
|
||||||
len: Option<usize>,
|
len: Option<usize>,
|
||||||
|
sep: Token<'static>,
|
||||||
|
end: Token<'static>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, I> SeqVisitor for DeserializerSeqVisitor<'a, I>
|
impl<'a, I> SeqVisitor for DeserializerSeqVisitor<'a, I>
|
||||||
@@ -491,162 +345,19 @@ impl<'a, I> SeqVisitor for DeserializerSeqVisitor<'a, I>
|
|||||||
{
|
{
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
|
||||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
|
||||||
where T: Deserialize,
|
where T: DeserializeSeed,
|
||||||
{
|
{
|
||||||
match self.de.tokens.peek() {
|
if self.de.tokens.peek() == Some(&self.end) {
|
||||||
Some(&Token::SeqSep) => {
|
return Ok(None);
|
||||||
self.de.tokens.next();
|
|
||||||
self.len = self.len.map(|len| len - 1);
|
|
||||||
Deserialize::deserialize(&mut *self.de).map(Some)
|
|
||||||
}
|
|
||||||
Some(&Token::SeqEnd) => Ok(None),
|
|
||||||
Some(_) => {
|
|
||||||
let token = self.de.tokens.next().unwrap();
|
|
||||||
Err(Error::UnexpectedToken(token))
|
|
||||||
}
|
|
||||||
None => Err(Error::EndOfStream),
|
|
||||||
}
|
}
|
||||||
}
|
match self.de.tokens.next() {
|
||||||
|
Some(ref token) if *token == self.sep => {
|
||||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
self.len = self.len.map(|len| len.saturating_sub(1));
|
||||||
let len = self.len.unwrap_or(0);
|
seed.deserialize(&mut *self.de).map(Some)
|
||||||
(len, self.len)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
struct DeserializerArrayVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
|
||||||
de: &'a mut Deserializer<I>,
|
|
||||||
len: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, I> SeqVisitor for DeserializerArrayVisitor<'a, I>
|
|
||||||
where I: Iterator<Item=Token<'static>>,
|
|
||||||
{
|
|
||||||
type Error = Error;
|
|
||||||
|
|
||||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
|
||||||
where T: Deserialize,
|
|
||||||
{
|
|
||||||
match self.de.tokens.peek() {
|
|
||||||
Some(&Token::SeqSep) => {
|
|
||||||
self.de.tokens.next();
|
|
||||||
self.len -= 1;
|
|
||||||
Deserialize::deserialize(&mut *self.de).map(Some)
|
|
||||||
}
|
}
|
||||||
Some(&Token::SeqEnd) => Ok(None),
|
Some(other) => Err(Error::UnexpectedToken(other)),
|
||||||
Some(_) => {
|
None => Err(Error::EndOfTokens),
|
||||||
let token = self.de.tokens.next().unwrap();
|
|
||||||
Err(Error::UnexpectedToken(token))
|
|
||||||
}
|
|
||||||
None => Err(Error::EndOfStream),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
|
||||||
(self.len, Some(self.len))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
struct DeserializerTupleVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
|
||||||
de: &'a mut Deserializer<I>,
|
|
||||||
len: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, I> SeqVisitor for DeserializerTupleVisitor<'a, I>
|
|
||||||
where I: Iterator<Item=Token<'static>>,
|
|
||||||
{
|
|
||||||
type Error = Error;
|
|
||||||
|
|
||||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
|
||||||
where T: Deserialize,
|
|
||||||
{
|
|
||||||
match self.de.tokens.peek() {
|
|
||||||
Some(&Token::TupleSep) => {
|
|
||||||
self.de.tokens.next();
|
|
||||||
self.len -= 1;
|
|
||||||
Deserialize::deserialize(&mut *self.de).map(Some)
|
|
||||||
}
|
|
||||||
Some(&Token::TupleEnd) => Ok(None),
|
|
||||||
Some(_) => {
|
|
||||||
let token = self.de.tokens.next().unwrap();
|
|
||||||
Err(Error::UnexpectedToken(token))
|
|
||||||
}
|
|
||||||
None => Err(Error::EndOfStream),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
|
||||||
(self.len, Some(self.len))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
struct DeserializerTupleStructVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
|
||||||
de: &'a mut Deserializer<I>,
|
|
||||||
len: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, I> SeqVisitor for DeserializerTupleStructVisitor<'a, I>
|
|
||||||
where I: Iterator<Item=Token<'static>>,
|
|
||||||
{
|
|
||||||
type Error = Error;
|
|
||||||
|
|
||||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
|
||||||
where T: Deserialize,
|
|
||||||
{
|
|
||||||
match self.de.tokens.peek() {
|
|
||||||
Some(&Token::TupleStructSep) => {
|
|
||||||
self.de.tokens.next();
|
|
||||||
self.len -= 1;
|
|
||||||
Deserialize::deserialize(&mut *self.de).map(Some)
|
|
||||||
}
|
|
||||||
Some(&Token::TupleStructEnd) => Ok(None),
|
|
||||||
Some(_) => {
|
|
||||||
let token = self.de.tokens.next().unwrap();
|
|
||||||
Err(Error::UnexpectedToken(token))
|
|
||||||
}
|
|
||||||
None => Err(Error::EndOfStream),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
|
||||||
(self.len, Some(self.len))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
struct DeserializerVariantSeqVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
|
||||||
de: &'a mut Deserializer<I>,
|
|
||||||
len: Option<usize>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, I> SeqVisitor for DeserializerVariantSeqVisitor<'a, I>
|
|
||||||
where I: Iterator<Item=Token<'static>>,
|
|
||||||
{
|
|
||||||
type Error = Error;
|
|
||||||
|
|
||||||
fn visit<T>(&mut self) -> Result<Option<T>, Error>
|
|
||||||
where T: Deserialize,
|
|
||||||
{
|
|
||||||
match self.de.tokens.peek() {
|
|
||||||
Some(&Token::EnumSeqSep) => {
|
|
||||||
self.de.tokens.next();
|
|
||||||
self.len = self.len.map(|len| len - 1);
|
|
||||||
Deserialize::deserialize(&mut *self.de).map(Some)
|
|
||||||
}
|
|
||||||
Some(&Token::EnumSeqEnd) => Ok(None),
|
|
||||||
Some(_) => {
|
|
||||||
let token = self.de.tokens.next().unwrap();
|
|
||||||
Err(Error::UnexpectedToken(token))
|
|
||||||
}
|
|
||||||
None => Err(Error::EndOfStream),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -661,6 +372,8 @@ impl<'a, I> SeqVisitor for DeserializerVariantSeqVisitor<'a, I>
|
|||||||
struct DeserializerMapVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
struct DeserializerMapVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||||
de: &'a mut Deserializer<I>,
|
de: &'a mut Deserializer<I>,
|
||||||
len: Option<usize>,
|
len: Option<usize>,
|
||||||
|
sep: Token<'static>,
|
||||||
|
end: Token<'static>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
|
impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
|
||||||
@@ -668,28 +381,26 @@ impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
|
|||||||
{
|
{
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
|
||||||
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
|
fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
|
||||||
where K: Deserialize,
|
where K: DeserializeSeed,
|
||||||
{
|
{
|
||||||
match self.de.tokens.peek() {
|
if self.de.tokens.peek() == Some(&self.end) {
|
||||||
Some(&Token::MapSep) => {
|
return Ok(None);
|
||||||
self.de.tokens.next();
|
}
|
||||||
self.len = self.len.map(|len| if len > 0 { len - 1} else { 0 });
|
match self.de.tokens.next() {
|
||||||
Deserialize::deserialize(&mut *self.de).map(Some)
|
Some(ref token) if *token == self.sep => {
|
||||||
|
self.len = self.len.map(|len| len.saturating_sub(1));
|
||||||
|
seed.deserialize(&mut *self.de).map(Some)
|
||||||
}
|
}
|
||||||
Some(&Token::MapEnd) => Ok(None),
|
Some(other) => Err(Error::UnexpectedToken(other)),
|
||||||
Some(_) => {
|
None => Err(Error::EndOfTokens),
|
||||||
let token = self.de.tokens.next().unwrap();
|
|
||||||
Err(Error::UnexpectedToken(token))
|
|
||||||
}
|
|
||||||
None => Err(Error::EndOfStream),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn visit_value<V>(&mut self) -> Result<V, Error>
|
fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
|
||||||
where V: Deserialize,
|
where V: DeserializeSeed,
|
||||||
{
|
{
|
||||||
Deserialize::deserialize(&mut *self.de)
|
seed.deserialize(&mut *self.de)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||||
@@ -700,47 +411,6 @@ impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
|
|||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
struct DeserializerStructVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
|
||||||
de: &'a mut Deserializer<I>,
|
|
||||||
len: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, I> MapVisitor for DeserializerStructVisitor<'a, I>
|
|
||||||
where I: Iterator<Item=Token<'static>>,
|
|
||||||
{
|
|
||||||
type Error = Error;
|
|
||||||
|
|
||||||
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
|
|
||||||
where K: Deserialize,
|
|
||||||
{
|
|
||||||
match self.de.tokens.peek() {
|
|
||||||
Some(&Token::StructSep) => {
|
|
||||||
self.de.tokens.next();
|
|
||||||
self.len = self.len.saturating_sub(1);
|
|
||||||
Deserialize::deserialize(&mut *self.de).map(Some)
|
|
||||||
}
|
|
||||||
Some(&Token::StructEnd) => Ok(None),
|
|
||||||
Some(_) => {
|
|
||||||
let token = self.de.tokens.next().unwrap();
|
|
||||||
Err(Error::UnexpectedToken(token))
|
|
||||||
}
|
|
||||||
None => Err(Error::EndOfStream),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_value<V>(&mut self) -> Result<V, Error>
|
|
||||||
where V: Deserialize,
|
|
||||||
{
|
|
||||||
Deserialize::deserialize(&mut *self.de)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
|
||||||
(self.len, Some(self.len))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
struct DeserializerEnumVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
struct DeserializerEnumVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
||||||
de: &'a mut Deserializer<I>,
|
de: &'a mut Deserializer<I>,
|
||||||
}
|
}
|
||||||
@@ -751,8 +421,8 @@ impl<'a, I> EnumVisitor for DeserializerEnumVisitor<'a, I>
|
|||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Variant = Self;
|
type Variant = Self;
|
||||||
|
|
||||||
fn visit_variant<V>(self) -> Result<(V, Self), Error>
|
fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self), Error>
|
||||||
where V: Deserialize,
|
where V: DeserializeSeed,
|
||||||
{
|
{
|
||||||
match self.de.tokens.peek() {
|
match self.de.tokens.peek() {
|
||||||
Some(&Token::EnumUnit(_, v))
|
Some(&Token::EnumUnit(_, v))
|
||||||
@@ -760,14 +430,14 @@ impl<'a, I> EnumVisitor for DeserializerEnumVisitor<'a, I>
|
|||||||
| Some(&Token::EnumSeqStart(_, v, _))
|
| Some(&Token::EnumSeqStart(_, v, _))
|
||||||
| Some(&Token::EnumMapStart(_, v, _)) => {
|
| Some(&Token::EnumMapStart(_, v, _)) => {
|
||||||
let de = v.into_deserializer();
|
let de = v.into_deserializer();
|
||||||
let value = try!(Deserialize::deserialize(de));
|
let value = try!(seed.deserialize(de));
|
||||||
Ok((value, self))
|
Ok((value, self))
|
||||||
}
|
}
|
||||||
Some(_) => {
|
Some(_) => {
|
||||||
let value = try!(Deserialize::deserialize(&mut *self.de));
|
let value = try!(seed.deserialize(&mut *self.de));
|
||||||
Ok((value, self))
|
Ok((value, self))
|
||||||
}
|
}
|
||||||
None => Err(Error::EndOfStream),
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -786,22 +456,22 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
|
|||||||
Some(_) => {
|
Some(_) => {
|
||||||
Deserialize::deserialize(self.de)
|
Deserialize::deserialize(self.de)
|
||||||
}
|
}
|
||||||
None => Err(Error::EndOfStream),
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn visit_newtype<T>(self) -> Result<T, Self::Error>
|
fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
|
||||||
where T: Deserialize,
|
where T: DeserializeSeed,
|
||||||
{
|
{
|
||||||
match self.de.tokens.peek() {
|
match self.de.tokens.peek() {
|
||||||
Some(&Token::EnumNewType(_, _)) => {
|
Some(&Token::EnumNewType(_, _)) => {
|
||||||
self.de.tokens.next();
|
self.de.tokens.next();
|
||||||
Deserialize::deserialize(self.de)
|
seed.deserialize(self.de)
|
||||||
}
|
}
|
||||||
Some(_) => {
|
Some(_) => {
|
||||||
Deserialize::deserialize(self.de)
|
seed.deserialize(self.de)
|
||||||
}
|
}
|
||||||
None => Err(Error::EndOfStream),
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -815,7 +485,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
|
|||||||
let token = self.de.tokens.next().unwrap();
|
let token = self.de.tokens.next().unwrap();
|
||||||
|
|
||||||
if len == enum_len {
|
if len == enum_len {
|
||||||
self.de.visit_variant_seq(Some(len), visitor)
|
self.de.visit_seq(Some(len), Token::EnumSeqSep, Token::EnumSeqEnd, visitor)
|
||||||
} else {
|
} else {
|
||||||
Err(Error::UnexpectedToken(token))
|
Err(Error::UnexpectedToken(token))
|
||||||
}
|
}
|
||||||
@@ -824,7 +494,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
|
|||||||
let token = self.de.tokens.next().unwrap();
|
let token = self.de.tokens.next().unwrap();
|
||||||
|
|
||||||
if len == enum_len {
|
if len == enum_len {
|
||||||
self.de.visit_seq(Some(len), visitor)
|
self.de.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
|
||||||
} else {
|
} else {
|
||||||
Err(Error::UnexpectedToken(token))
|
Err(Error::UnexpectedToken(token))
|
||||||
}
|
}
|
||||||
@@ -832,7 +502,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
|
|||||||
Some(_) => {
|
Some(_) => {
|
||||||
de::Deserializer::deserialize(self.de, visitor)
|
de::Deserializer::deserialize(self.de, visitor)
|
||||||
}
|
}
|
||||||
None => Err(Error::EndOfStream),
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -846,7 +516,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
|
|||||||
let token = self.de.tokens.next().unwrap();
|
let token = self.de.tokens.next().unwrap();
|
||||||
|
|
||||||
if fields.len() == enum_len {
|
if fields.len() == enum_len {
|
||||||
self.de.visit_variant_map(Some(fields.len()), visitor)
|
self.de.visit_map(Some(fields.len()), Token::EnumMapSep, Token::EnumMapEnd, visitor)
|
||||||
} else {
|
} else {
|
||||||
Err(Error::UnexpectedToken(token))
|
Err(Error::UnexpectedToken(token))
|
||||||
}
|
}
|
||||||
@@ -855,7 +525,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
|
|||||||
let token = self.de.tokens.next().unwrap();
|
let token = self.de.tokens.next().unwrap();
|
||||||
|
|
||||||
if fields.len() == enum_len {
|
if fields.len() == enum_len {
|
||||||
self.de.visit_map(Some(fields.len()), visitor)
|
self.de.visit_map(Some(fields.len()), Token::MapSep, Token::MapEnd, visitor)
|
||||||
} else {
|
} else {
|
||||||
Err(Error::UnexpectedToken(token))
|
Err(Error::UnexpectedToken(token))
|
||||||
}
|
}
|
||||||
@@ -863,49 +533,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
|
|||||||
Some(_) => {
|
Some(_) => {
|
||||||
de::Deserializer::deserialize(self.de, visitor)
|
de::Deserializer::deserialize(self.de, visitor)
|
||||||
}
|
}
|
||||||
None => Err(Error::EndOfStream),
|
None => Err(Error::EndOfTokens),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
struct DeserializerVariantMapVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
|
|
||||||
de: &'a mut Deserializer<I>,
|
|
||||||
len: Option<usize>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, I> MapVisitor for DeserializerVariantMapVisitor<'a, I>
|
|
||||||
where I: Iterator<Item=Token<'static>>,
|
|
||||||
{
|
|
||||||
type Error = Error;
|
|
||||||
|
|
||||||
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
|
|
||||||
where K: Deserialize,
|
|
||||||
{
|
|
||||||
match self.de.tokens.peek() {
|
|
||||||
Some(&Token::EnumMapSep) => {
|
|
||||||
self.de.tokens.next();
|
|
||||||
self.len = self.len.map(|len| if len > 0 { len - 1} else { 0 });
|
|
||||||
Deserialize::deserialize(&mut *self.de).map(Some)
|
|
||||||
}
|
|
||||||
Some(&Token::EnumMapEnd) => Ok(None),
|
|
||||||
Some(_) => {
|
|
||||||
let token = self.de.tokens.next().unwrap();
|
|
||||||
Err(Error::UnexpectedToken(token))
|
|
||||||
}
|
|
||||||
None => Err(Error::EndOfStream),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_value<V>(&mut self) -> Result<V, Error>
|
|
||||||
where V: Deserialize,
|
|
||||||
{
|
|
||||||
Deserialize::deserialize(&mut *self.de)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
|
||||||
let len = self.len.unwrap_or(0);
|
|
||||||
(len, self.len)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+21
-60
@@ -1,4 +1,5 @@
|
|||||||
use std::{error, fmt};
|
use std::error;
|
||||||
|
use std::fmt::{self, Display};
|
||||||
|
|
||||||
use serde::{ser, de};
|
use serde::{ser, de};
|
||||||
|
|
||||||
@@ -6,82 +7,42 @@ use token::Token;
|
|||||||
|
|
||||||
#[derive(Clone, PartialEq, Debug)]
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
// Shared
|
Message(String),
|
||||||
Custom(String),
|
|
||||||
InvalidValue(String),
|
|
||||||
|
|
||||||
// De
|
|
||||||
EndOfStream,
|
|
||||||
InvalidType(de::Type),
|
|
||||||
InvalidLength(usize),
|
|
||||||
UnknownVariant(String),
|
|
||||||
UnknownField(String),
|
|
||||||
MissingField(&'static str),
|
|
||||||
DuplicateField(&'static str),
|
|
||||||
InvalidName(&'static str),
|
InvalidName(&'static str),
|
||||||
UnexpectedToken(Token<'static>),
|
UnexpectedToken(Token<'static>),
|
||||||
|
EndOfTokens,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ser::Error for Error {
|
impl ser::Error for Error {
|
||||||
fn custom<T: Into<String>>(msg: T) -> Error {
|
fn custom<T: Display>(msg: T) -> Error {
|
||||||
Error::Custom(msg.into())
|
Error::Message(msg.to_string())
|
||||||
}
|
|
||||||
|
|
||||||
fn invalid_value(msg: &str) -> Error {
|
|
||||||
Error::InvalidValue(msg.to_owned())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl de::Error for Error {
|
impl de::Error for Error {
|
||||||
fn custom<T: Into<String>>(msg: T) -> Error {
|
fn custom<T: Display>(msg: T) -> Error {
|
||||||
Error::Custom(msg.into())
|
Error::Message(msg.to_string())
|
||||||
}
|
|
||||||
|
|
||||||
fn end_of_stream() -> Error {
|
|
||||||
Error::EndOfStream
|
|
||||||
}
|
|
||||||
|
|
||||||
fn invalid_type(ty: de::Type) -> Error {
|
|
||||||
Error::InvalidType(ty)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn invalid_value(msg: &str) -> Error {
|
|
||||||
Error::InvalidValue(msg.to_owned())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn invalid_length(len: usize) -> Error {
|
|
||||||
Error::InvalidLength(len)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn unknown_variant(variant: &str) -> Error {
|
|
||||||
Error::UnknownVariant(variant.to_owned())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn unknown_field(field: &str) -> Error {
|
|
||||||
Error::UnknownField(field.to_owned())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn missing_field(field: &'static str) -> Error {
|
|
||||||
Error::MissingField(field)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn duplicate_field(field: &'static str) -> Error {
|
|
||||||
Error::DuplicateField(field)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for Error {
|
impl fmt::Display for Error {
|
||||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||||
formatter.write_str(format!("{:?}", self).as_ref())
|
match *self {
|
||||||
|
Error::Message(ref msg) => formatter.write_str(msg),
|
||||||
|
Error::InvalidName(name) => write!(formatter, "invalid name `{}`", name),
|
||||||
|
Error::UnexpectedToken(_) => formatter.write_str("unexpected token"),
|
||||||
|
Error::EndOfTokens => formatter.write_str("end of tokens"),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl error::Error for Error {
|
impl error::Error for Error {
|
||||||
fn description(&self) -> &str {
|
fn description(&self) -> &str {
|
||||||
"Serde Error"
|
match *self {
|
||||||
}
|
Error::Message(ref msg) => msg,
|
||||||
|
Error::InvalidName(_) => "invalid name",
|
||||||
fn cause(&self) -> Option<&error::Error> {
|
Error::UnexpectedToken(_) => "unexpected token",
|
||||||
None
|
Error::EndOfTokens => "end of tokens",
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
#[macro_use]
|
||||||
extern crate serde;
|
extern crate serde;
|
||||||
|
|
||||||
mod assert;
|
mod assert;
|
||||||
|
|||||||
+18
-28
@@ -46,11 +46,6 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serialize_isize(self, v: isize) -> Result<(), Error> {
|
|
||||||
assert_eq!(self.tokens.next(), Some(&Token::Isize(v)));
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn serialize_i8(self, v: i8) -> Result<(), Error> {
|
fn serialize_i8(self, v: i8) -> Result<(), Error> {
|
||||||
assert_eq!(self.tokens.next(), Some(&Token::I8(v)));
|
assert_eq!(self.tokens.next(), Some(&Token::I8(v)));
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -71,11 +66,6 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serialize_usize(self, v: usize) -> Result<(), Error> {
|
|
||||||
assert_eq!(self.tokens.next(), Some(&Token::Usize(v)));
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn serialize_u8(self, v: u8) -> Result<(), Error> {
|
fn serialize_u8(self, v: u8) -> Result<(), Error> {
|
||||||
assert_eq!(self.tokens.next(), Some(&Token::U8(v)));
|
assert_eq!(self.tokens.next(), Some(&Token::U8(v)));
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -139,20 +129,20 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serialize_newtype_struct<T>(self,
|
fn serialize_newtype_struct<T: ?Sized>(self,
|
||||||
name: &'static str,
|
name: &'static str,
|
||||||
value: T) -> Result<(), Error>
|
value: &T) -> Result<(), Error>
|
||||||
where T: Serialize,
|
where T: Serialize,
|
||||||
{
|
{
|
||||||
assert_eq!(self.tokens.next(), Some(&Token::StructNewType(name)));
|
assert_eq!(self.tokens.next(), Some(&Token::StructNewType(name)));
|
||||||
value.serialize(self)
|
value.serialize(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serialize_newtype_variant<T>(self,
|
fn serialize_newtype_variant<T: ?Sized>(self,
|
||||||
name: &str,
|
name: &str,
|
||||||
_variant_index: usize,
|
_variant_index: usize,
|
||||||
variant: &str,
|
variant: &str,
|
||||||
value: T) -> Result<(), Error>
|
value: &T) -> Result<(), Error>
|
||||||
where T: Serialize,
|
where T: Serialize,
|
||||||
{
|
{
|
||||||
assert_eq!(self.tokens.next(), Some(&Token::EnumNewType(name, variant)));
|
assert_eq!(self.tokens.next(), Some(&Token::EnumNewType(name, variant)));
|
||||||
@@ -164,8 +154,8 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serialize_some<V>(self, value: V) -> Result<(), Error>
|
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<(), Error>
|
||||||
where V: Serialize,
|
where T: Serialize,
|
||||||
{
|
{
|
||||||
assert_eq!(self.tokens.next(), Some(&Token::Option(true)));
|
assert_eq!(self.tokens.next(), Some(&Token::Option(true)));
|
||||||
value.serialize(self)
|
value.serialize(self)
|
||||||
@@ -228,7 +218,7 @@ impl<'s, 'a, I> ser::SerializeSeq for &'s mut Serializer<'a, I>
|
|||||||
type Ok = ();
|
type Ok = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
|
||||||
fn serialize_element<T>(&mut self, value: T) -> Result<(), Error>
|
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||||
where T: Serialize
|
where T: Serialize
|
||||||
{
|
{
|
||||||
assert_eq!(self.tokens.next(), Some(&Token::SeqSep));
|
assert_eq!(self.tokens.next(), Some(&Token::SeqSep));
|
||||||
@@ -247,7 +237,7 @@ impl<'s, 'a, I> ser::SerializeTuple for &'s mut Serializer<'a, I>
|
|||||||
type Ok = ();
|
type Ok = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
|
||||||
fn serialize_element<T>(&mut self, value: T) -> Result<(), Error>
|
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||||
where T: Serialize
|
where T: Serialize
|
||||||
{
|
{
|
||||||
assert_eq!(self.tokens.next(), Some(&Token::TupleSep));
|
assert_eq!(self.tokens.next(), Some(&Token::TupleSep));
|
||||||
@@ -266,7 +256,7 @@ impl<'s, 'a, I> ser::SerializeTupleStruct for &'s mut Serializer<'a, I>
|
|||||||
type Ok = ();
|
type Ok = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
|
||||||
fn serialize_field<T>(&mut self, value: T) -> Result<(), Error>
|
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||||
where T: Serialize
|
where T: Serialize
|
||||||
{
|
{
|
||||||
assert_eq!(self.tokens.next(), Some(&Token::TupleStructSep));
|
assert_eq!(self.tokens.next(), Some(&Token::TupleStructSep));
|
||||||
@@ -285,7 +275,7 @@ impl<'s, 'a, I> ser::SerializeTupleVariant for &'s mut Serializer<'a, I>
|
|||||||
type Ok = ();
|
type Ok = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
|
||||||
fn serialize_field<T>(&mut self, value: T) -> Result<(), Error>
|
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||||
where T: Serialize
|
where T: Serialize
|
||||||
{
|
{
|
||||||
assert_eq!(self.tokens.next(), Some(&Token::EnumSeqSep));
|
assert_eq!(self.tokens.next(), Some(&Token::EnumSeqSep));
|
||||||
@@ -304,12 +294,12 @@ impl<'s, 'a, I> ser::SerializeMap for &'s mut Serializer<'a, I>
|
|||||||
type Ok = ();
|
type Ok = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
|
||||||
fn serialize_key<T>(&mut self, key: T) -> Result<(), Self::Error> where T: Serialize {
|
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error> where T: Serialize {
|
||||||
assert_eq!(self.tokens.next(), Some(&Token::MapSep));
|
assert_eq!(self.tokens.next(), Some(&Token::MapSep));
|
||||||
key.serialize(&mut **self)
|
key.serialize(&mut **self)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serialize_value<T>(&mut self, value: T) -> Result<(), Self::Error> where T: Serialize {
|
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize {
|
||||||
value.serialize(&mut **self)
|
value.serialize(&mut **self)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -325,7 +315,7 @@ impl<'s, 'a, I> ser::SerializeStruct for &'s mut Serializer<'a, I>
|
|||||||
type Ok = ();
|
type Ok = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
|
||||||
fn serialize_field<V>(&mut self, key: &'static str, value: V) -> Result<(), Self::Error> where V: Serialize {
|
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> where T: Serialize {
|
||||||
assert_eq!(self.tokens.next(), Some(&Token::StructSep));
|
assert_eq!(self.tokens.next(), Some(&Token::StructSep));
|
||||||
try!(key.serialize(&mut **self));
|
try!(key.serialize(&mut **self));
|
||||||
value.serialize(&mut **self)
|
value.serialize(&mut **self)
|
||||||
@@ -343,7 +333,7 @@ impl<'s, 'a, I> ser::SerializeStructVariant for &'s mut Serializer<'a, I>
|
|||||||
type Ok = ();
|
type Ok = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
|
||||||
fn serialize_field<V>(&mut self, key: &'static str, value: V) -> Result<(), Self::Error> where V: Serialize {
|
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> where T: Serialize {
|
||||||
assert_eq!(self.tokens.next(), Some(&Token::EnumMapSep));
|
assert_eq!(self.tokens.next(), Some(&Token::EnumMapSep));
|
||||||
try!(key.serialize(&mut **self));
|
try!(key.serialize(&mut **self));
|
||||||
value.serialize(&mut **self)
|
value.serialize(&mut **self)
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
#[derive(Clone, PartialEq, Debug)]
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
pub enum Token<'a> {
|
pub enum Token<'a> {
|
||||||
Bool(bool),
|
Bool(bool),
|
||||||
Isize(isize),
|
|
||||||
I8(i8),
|
I8(i8),
|
||||||
I16(i16),
|
I16(i16),
|
||||||
I32(i32),
|
I32(i32),
|
||||||
I64(i64),
|
I64(i64),
|
||||||
Usize(usize),
|
|
||||||
U8(u8),
|
U8(u8),
|
||||||
U16(u16),
|
U16(u16),
|
||||||
U32(u32),
|
U32(u32),
|
||||||
@@ -17,6 +15,7 @@ pub enum Token<'a> {
|
|||||||
Str(&'a str),
|
Str(&'a str),
|
||||||
String(String),
|
String(String),
|
||||||
Bytes(&'a [u8]),
|
Bytes(&'a [u8]),
|
||||||
|
ByteBuf(Vec<u8>),
|
||||||
|
|
||||||
Option(bool),
|
Option(bool),
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "serde_testing"
|
name = "serde_test_suite"
|
||||||
version = "0.9.0-rc1"
|
version = "0.0.0"
|
||||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
description = "A generic serialization/deserialization framework"
|
description = "A generic serialization/deserialization framework"
|
||||||
@@ -9,23 +9,23 @@ repository = "https://github.com/serde-rs/serde"
|
|||||||
documentation = "https://docs.serde.rs/serde/"
|
documentation = "https://docs.serde.rs/serde/"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
keywords = ["serialization"]
|
keywords = ["serialization"]
|
||||||
build = "build.rs"
|
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
unstable-testing = ["clippy", "serde/unstable-testing", "serde_codegen/unstable-testing"]
|
unstable-testing = [
|
||||||
|
"compiletest_rs",
|
||||||
[build-dependencies]
|
"serde/unstable-testing",
|
||||||
serde_codegen = { path = "../serde_codegen", features = ["with-syntex"] }
|
]
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
fnv = "1.0"
|
fnv = "1.0"
|
||||||
rustc-serialize = "^0.3.16"
|
rustc-serialize = "0.3.16"
|
||||||
serde = { path = "../serde" }
|
serde = { path = "../serde" }
|
||||||
|
serde_derive = { path = "../serde_derive" }
|
||||||
serde_test = { path = "../serde_test" }
|
serde_test = { path = "../serde_test" }
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
clippy = { version = "^0.*", optional = true }
|
compiletest_rs = { version = "0.2", optional = true }
|
||||||
|
|
||||||
[[test]]
|
[[test]]
|
||||||
name = "test"
|
name = "test"
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
[package]
|
||||||
|
name = "serde_test_suite_deps"
|
||||||
|
version = "0.0.0"
|
||||||
|
authors = ["David Tolnay <dtolnay@gmail.com>"]
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[workspace]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
serde = { path = "../../serde" }
|
||||||
|
serde_derive = { path = "../../serde_derive" }
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
[package]
|
||||||
|
name = "serde_derive_tests_no_std"
|
||||||
|
version = "0.0.0"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
serde = { path = "../../serde", default-features = false }
|
||||||
|
serde_derive = { path = "../../serde_derive" }
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
#![feature(lang_items, start, libc)]
|
||||||
|
#![no_std]
|
||||||
|
|
||||||
|
extern crate libc;
|
||||||
|
|
||||||
|
#[start]
|
||||||
|
fn start(_argc: isize, _argv: *const *const u8) -> isize {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
|
||||||
|
#[lang = "eh_personality"]
|
||||||
|
#[no_mangle]
|
||||||
|
pub extern fn rust_eh_personality() {}
|
||||||
|
|
||||||
|
#[lang = "eh_unwind_resume"]
|
||||||
|
#[no_mangle]
|
||||||
|
pub extern fn rust_eh_unwind_resume() {}
|
||||||
|
|
||||||
|
#[lang = "panic_fmt"]
|
||||||
|
#[no_mangle]
|
||||||
|
pub extern fn rust_begin_panic(_msg: core::fmt::Arguments,
|
||||||
|
_file: &'static str,
|
||||||
|
_line: u32) -> ! {
|
||||||
|
unsafe {
|
||||||
|
libc::abort()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//////////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
#[macro_use]
|
||||||
|
extern crate serde_derive;
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct Unit;
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct Newtype(u8);
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct Tuple(u8, u8);
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct Struct { f: u8 }
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Enum {
|
||||||
|
Unit,
|
||||||
|
Newtype(u8),
|
||||||
|
Tuple(u8, u8),
|
||||||
|
Struct { f: u8 },
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#[macro_use]
|
||||||
|
extern crate serde_derive;
|
||||||
|
|
||||||
|
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||||
|
#[serde(tag = "type")] //~^ HELP: #[serde(tag = "...")] cannot be used with tuple variants
|
||||||
|
enum E {
|
||||||
|
Tuple(u8, u8),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
#[macro_use]
|
||||||
|
extern crate serde_derive;
|
||||||
|
|
||||||
|
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||||
|
#[serde(tag = "type")] //~^ HELP: #[serde(tag = "...")] can only be used on enums
|
||||||
|
struct S;
|
||||||
|
|
||||||
|
fn main() {}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
#[macro_use]
|
||||||
|
extern crate serde_derive;
|
||||||
|
|
||||||
|
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||||
|
#[serde(untagged)]
|
||||||
|
#[serde(tag = "type")] //~^^ HELP: enum cannot be both untagged and internally tagged
|
||||||
|
enum E {
|
||||||
|
A(u8),
|
||||||
|
B(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
#[macro_use]
|
||||||
|
extern crate serde_derive;
|
||||||
|
|
||||||
|
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
|
||||||
|
#[serde(untagged)] //~^ HELP: #[serde(untagged)] can only be used on enums
|
||||||
|
struct S;
|
||||||
|
|
||||||
|
fn main() {}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
extern crate compiletest_rs as compiletest;
|
||||||
|
|
||||||
|
use std::env;
|
||||||
|
|
||||||
|
fn run_mode(mode: &'static str) {
|
||||||
|
let mut config = compiletest::default_config();
|
||||||
|
|
||||||
|
config.mode = mode.parse().expect("invalid mode");
|
||||||
|
config.target_rustcflags = Some("-L deps/target/debug/deps".to_owned());
|
||||||
|
if let Ok(name) = env::var("TESTNAME") {
|
||||||
|
config.filter = Some(name);
|
||||||
|
}
|
||||||
|
config.src_base = format!("tests/{}", mode).into();
|
||||||
|
|
||||||
|
compiletest::run_tests(&config);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn compile_fail() {
|
||||||
|
run_mode("compile-fail");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn run_pass() {
|
||||||
|
run_mode("run-pass");
|
||||||
|
}
|
||||||
@@ -1,31 +1,3 @@
|
|||||||
#[macro_export]
|
|
||||||
macro_rules! declare_ser_tests {
|
|
||||||
($($name:ident { $($value:expr => $tokens:expr,)+ })+) => {
|
|
||||||
$(
|
|
||||||
#[test]
|
|
||||||
fn $name() {
|
|
||||||
$(
|
|
||||||
assert_ser_tokens(&$value, $tokens);
|
|
||||||
)+
|
|
||||||
}
|
|
||||||
)+
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[macro_export]
|
|
||||||
macro_rules! btreemap {
|
|
||||||
() => {
|
|
||||||
BTreeMap::new()
|
|
||||||
};
|
|
||||||
($($key:expr => $value:expr),+) => {
|
|
||||||
{
|
|
||||||
let mut map = BTreeMap::new();
|
|
||||||
$(map.insert($key, $value);)+
|
|
||||||
map
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! btreeset {
|
macro_rules! btreeset {
|
||||||
() => {
|
() => {
|
||||||
BTreeSet::new()
|
BTreeSet::new()
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
#![cfg_attr(feature = "unstable-testing", feature(test, non_ascii_idents))]
|
||||||
|
|
||||||
|
#[cfg(feature = "unstable-testing")]
|
||||||
|
extern crate test;
|
||||||
|
|
||||||
|
#[macro_use]
|
||||||
|
extern crate serde_derive;
|
||||||
|
|
||||||
|
extern crate serde;
|
||||||
|
extern crate serde_test;
|
||||||
|
|
||||||
|
#[macro_use]
|
||||||
|
mod macros;
|
||||||
|
|
||||||
|
mod test_annotations;
|
||||||
|
mod test_bytes;
|
||||||
|
mod test_de;
|
||||||
|
mod test_gen;
|
||||||
|
mod test_macros;
|
||||||
|
mod test_ser;
|
||||||
|
|
||||||
|
#[cfg(feature = "unstable-testing")]
|
||||||
|
mod compiletest;
|
||||||
@@ -145,7 +145,7 @@ fn test_default_enum() {
|
|||||||
assert_de_tokens(
|
assert_de_tokens(
|
||||||
&DefaultEnum::Struct { a1: 1, a2: 2, a3: 3, a4: 0, a5: 123 },
|
&DefaultEnum::Struct { a1: 1, a2: 2, a3: 3, a4: 0, a5: 123 },
|
||||||
&[
|
&[
|
||||||
Token::EnumMapStart("DefaultEnum", "Struct", 5),
|
Token::EnumMapStart("DefaultEnum", "Struct", 3),
|
||||||
|
|
||||||
Token::EnumMapSep,
|
Token::EnumMapSep,
|
||||||
Token::Str("a1"),
|
Token::Str("a1"),
|
||||||
@@ -174,7 +174,7 @@ fn test_default_enum() {
|
|||||||
assert_de_tokens(
|
assert_de_tokens(
|
||||||
&DefaultEnum::Struct { a1: 1, a2: 0, a3: 123, a4: 0, a5: 123 },
|
&DefaultEnum::Struct { a1: 1, a2: 0, a3: 123, a4: 0, a5: 123 },
|
||||||
&[
|
&[
|
||||||
Token::EnumMapStart("DefaultEnum", "Struct", 5),
|
Token::EnumMapStart("DefaultEnum", "Struct", 3),
|
||||||
|
|
||||||
Token::EnumMapSep,
|
Token::EnumMapSep,
|
||||||
Token::Str("a1"),
|
Token::Str("a1"),
|
||||||
@@ -343,7 +343,7 @@ fn test_ignore_unknown() {
|
|||||||
Token::StructSep,
|
Token::StructSep,
|
||||||
Token::Str("whoops"),
|
Token::Str("whoops"),
|
||||||
],
|
],
|
||||||
Error::UnknownField("whoops".to_owned())
|
Error::Message("unknown field `whoops`, expected `a1`".to_owned())
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -905,7 +905,7 @@ fn test_missing_renamed_field_struct() {
|
|||||||
|
|
||||||
Token::StructEnd,
|
Token::StructEnd,
|
||||||
],
|
],
|
||||||
Error::MissingField("a3"),
|
Error::Message("missing field `a3`".to_owned()),
|
||||||
);
|
);
|
||||||
|
|
||||||
assert_de_tokens_error::<RenameStructSerializeDeserialize>(
|
assert_de_tokens_error::<RenameStructSerializeDeserialize>(
|
||||||
@@ -918,7 +918,7 @@ fn test_missing_renamed_field_struct() {
|
|||||||
|
|
||||||
Token::StructEnd,
|
Token::StructEnd,
|
||||||
],
|
],
|
||||||
Error::MissingField("a5"),
|
Error::Message("missing field `a5`".to_owned()),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -930,7 +930,7 @@ fn test_missing_renamed_field_enum() {
|
|||||||
|
|
||||||
Token::EnumMapEnd,
|
Token::EnumMapEnd,
|
||||||
],
|
],
|
||||||
Error::MissingField("b"),
|
Error::Message("missing field `b`".to_owned()),
|
||||||
);
|
);
|
||||||
|
|
||||||
assert_de_tokens_error::<RenameEnumSerializeDeserialize<i8>>(
|
assert_de_tokens_error::<RenameEnumSerializeDeserialize<i8>>(
|
||||||
@@ -943,7 +943,7 @@ fn test_missing_renamed_field_enum() {
|
|||||||
|
|
||||||
Token::EnumMapEnd,
|
Token::EnumMapEnd,
|
||||||
],
|
],
|
||||||
Error::MissingField("d"),
|
Error::Message("missing field `d`".to_owned()),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -962,7 +962,7 @@ fn test_invalid_length_enum() {
|
|||||||
Token::I32(1),
|
Token::I32(1),
|
||||||
Token::EnumSeqEnd,
|
Token::EnumSeqEnd,
|
||||||
],
|
],
|
||||||
Error::InvalidLength(1),
|
Error::Message("invalid length 1, expected tuple of 3 elements".to_owned()),
|
||||||
);
|
);
|
||||||
assert_de_tokens_error::<InvalidLengthEnum>(
|
assert_de_tokens_error::<InvalidLengthEnum>(
|
||||||
&[
|
&[
|
||||||
@@ -971,6 +971,6 @@ fn test_invalid_length_enum() {
|
|||||||
Token::I32(1),
|
Token::I32(1),
|
||||||
Token::EnumSeqEnd,
|
Token::EnumSeqEnd,
|
||||||
],
|
],
|
||||||
Error::InvalidLength(1),
|
Error::Message("invalid length 1, expected tuple of 2 elements".to_owned()),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -15,6 +15,7 @@ fn test_bytes() {
|
|||||||
fn test_byte_buf() {
|
fn test_byte_buf() {
|
||||||
let empty = ByteBuf::new();
|
let empty = ByteBuf::new();
|
||||||
assert_tokens(&empty, &[Token::Bytes(b"")]);
|
assert_tokens(&empty, &[Token::Bytes(b"")]);
|
||||||
|
assert_de_tokens(&empty, &[Token::ByteBuf(Vec::new())]);
|
||||||
assert_de_tokens(&empty, &[Token::Str("")]);
|
assert_de_tokens(&empty, &[Token::Str("")]);
|
||||||
assert_de_tokens(&empty, &[Token::String(String::new())]);
|
assert_de_tokens(&empty, &[Token::String(String::new())]);
|
||||||
assert_de_tokens(&empty, &[
|
assert_de_tokens(&empty, &[
|
||||||
@@ -28,6 +29,7 @@ fn test_byte_buf() {
|
|||||||
|
|
||||||
let buf = ByteBuf::from(vec![65, 66, 67]);
|
let buf = ByteBuf::from(vec![65, 66, 67]);
|
||||||
assert_tokens(&buf, &[Token::Bytes(b"ABC")]);
|
assert_tokens(&buf, &[Token::Bytes(b"ABC")]);
|
||||||
|
assert_de_tokens(&buf, &[Token::ByteBuf(vec![65, 66, 67])]);
|
||||||
assert_de_tokens(&buf, &[Token::Str("ABC")]);
|
assert_de_tokens(&buf, &[Token::Str("ABC")]);
|
||||||
assert_de_tokens(&buf, &[Token::String("ABC".to_owned())]);
|
assert_de_tokens(&buf, &[Token::String("ABC".to_owned())]);
|
||||||
assert_de_tokens(&buf, &[
|
assert_de_tokens(&buf, &[
|
||||||
@@ -3,7 +3,7 @@ use std::net;
|
|||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use serde::de::{Deserialize, Type};
|
use serde::Deserialize;
|
||||||
|
|
||||||
extern crate fnv;
|
extern crate fnv;
|
||||||
use self::fnv::FnvHasher;
|
use self::fnv::FnvHasher;
|
||||||
@@ -97,7 +97,7 @@ macro_rules! declare_tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! declare_error_tests {
|
macro_rules! declare_error_tests {
|
||||||
($($name:ident<$target:ident> { $tokens:expr, $expected:expr, })+) => {
|
($($name:ident<$target:ty> { $tokens:expr, $expected:expr, })+) => {
|
||||||
$(
|
$(
|
||||||
#[test]
|
#[test]
|
||||||
fn $name() {
|
fn $name() {
|
||||||
@@ -155,12 +155,10 @@ declare_tests! {
|
|||||||
false => &[Token::Bool(false)],
|
false => &[Token::Bool(false)],
|
||||||
}
|
}
|
||||||
test_isize {
|
test_isize {
|
||||||
0isize => &[Token::Isize(0)],
|
|
||||||
0isize => &[Token::I8(0)],
|
0isize => &[Token::I8(0)],
|
||||||
0isize => &[Token::I16(0)],
|
0isize => &[Token::I16(0)],
|
||||||
0isize => &[Token::I32(0)],
|
0isize => &[Token::I32(0)],
|
||||||
0isize => &[Token::I64(0)],
|
0isize => &[Token::I64(0)],
|
||||||
0isize => &[Token::Usize(0)],
|
|
||||||
0isize => &[Token::U8(0)],
|
0isize => &[Token::U8(0)],
|
||||||
0isize => &[Token::U16(0)],
|
0isize => &[Token::U16(0)],
|
||||||
0isize => &[Token::U32(0)],
|
0isize => &[Token::U32(0)],
|
||||||
@@ -169,14 +167,12 @@ declare_tests! {
|
|||||||
0isize => &[Token::F64(0.)],
|
0isize => &[Token::F64(0.)],
|
||||||
}
|
}
|
||||||
test_ints {
|
test_ints {
|
||||||
0isize => &[Token::Isize(0)],
|
|
||||||
0i8 => &[Token::I8(0)],
|
0i8 => &[Token::I8(0)],
|
||||||
0i16 => &[Token::I16(0)],
|
0i16 => &[Token::I16(0)],
|
||||||
0i32 => &[Token::I32(0)],
|
0i32 => &[Token::I32(0)],
|
||||||
0i64 => &[Token::I64(0)],
|
0i64 => &[Token::I64(0)],
|
||||||
}
|
}
|
||||||
test_uints {
|
test_uints {
|
||||||
0usize => &[Token::Usize(0)],
|
|
||||||
0u8 => &[Token::U8(0)],
|
0u8 => &[Token::U8(0)],
|
||||||
0u16 => &[Token::U16(0)],
|
0u16 => &[Token::U16(0)],
|
||||||
0u32 => &[Token::U32(0)],
|
0u32 => &[Token::U32(0)],
|
||||||
@@ -229,7 +225,7 @@ declare_tests! {
|
|||||||
],
|
],
|
||||||
() => &[
|
() => &[
|
||||||
Token::TupleStructStart("Anything", 0),
|
Token::TupleStructStart("Anything", 0),
|
||||||
Token::SeqEnd,
|
Token::TupleStructEnd,
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
test_unit_struct {
|
test_unit_struct {
|
||||||
@@ -334,7 +330,7 @@ declare_tests! {
|
|||||||
],
|
],
|
||||||
BTreeSet::<isize>::new() => &[
|
BTreeSet::<isize>::new() => &[
|
||||||
Token::TupleStructStart("Anything", 0),
|
Token::TupleStructStart("Anything", 0),
|
||||||
Token::SeqEnd,
|
Token::TupleStructEnd,
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
test_hashset {
|
test_hashset {
|
||||||
@@ -362,7 +358,7 @@ declare_tests! {
|
|||||||
],
|
],
|
||||||
HashSet::<isize>::new() => &[
|
HashSet::<isize>::new() => &[
|
||||||
Token::TupleStructStart("Anything", 0),
|
Token::TupleStructStart("Anything", 0),
|
||||||
Token::SeqEnd,
|
Token::TupleStructEnd,
|
||||||
],
|
],
|
||||||
hashset![FnvHasher @ 1, 2, 3] => &[
|
hashset![FnvHasher @ 1, 2, 3] => &[
|
||||||
Token::SeqStart(Some(3)),
|
Token::SeqStart(Some(3)),
|
||||||
@@ -412,7 +408,7 @@ declare_tests! {
|
|||||||
],
|
],
|
||||||
Vec::<isize>::new() => &[
|
Vec::<isize>::new() => &[
|
||||||
Token::TupleStructStart("Anything", 0),
|
Token::TupleStructStart("Anything", 0),
|
||||||
Token::SeqEnd,
|
Token::TupleStructEnd,
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
test_array {
|
test_array {
|
||||||
@@ -476,7 +472,7 @@ declare_tests! {
|
|||||||
],
|
],
|
||||||
[0; 0] => &[
|
[0; 0] => &[
|
||||||
Token::TupleStructStart("Anything", 0),
|
Token::TupleStructStart("Anything", 0),
|
||||||
Token::SeqEnd,
|
Token::TupleStructEnd,
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
test_tuple {
|
test_tuple {
|
||||||
@@ -568,7 +564,7 @@ declare_tests! {
|
|||||||
],
|
],
|
||||||
BTreeMap::<isize, isize>::new() => &[
|
BTreeMap::<isize, isize>::new() => &[
|
||||||
Token::StructStart("Anything", 0),
|
Token::StructStart("Anything", 0),
|
||||||
Token::MapEnd,
|
Token::StructEnd,
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
test_hashmap {
|
test_hashmap {
|
||||||
@@ -622,7 +618,7 @@ declare_tests! {
|
|||||||
],
|
],
|
||||||
HashMap::<isize, isize>::new() => &[
|
HashMap::<isize, isize>::new() => &[
|
||||||
Token::StructStart("Anything", 0),
|
Token::StructStart("Anything", 0),
|
||||||
Token::MapEnd,
|
Token::StructEnd,
|
||||||
],
|
],
|
||||||
hashmap![FnvHasher @ 1 => 2, 3 => 4] => &[
|
hashmap![FnvHasher @ 1 => 2, 3 => 4] => &[
|
||||||
Token::MapStart(Some(2)),
|
Token::MapStart(Some(2)),
|
||||||
@@ -774,6 +770,20 @@ declare_tests! {
|
|||||||
Token::EnumMapEnd,
|
Token::EnumMapEnd,
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
test_enum_unit_usize {
|
||||||
|
Enum::Unit => &[
|
||||||
|
Token::EnumStart("Enum"),
|
||||||
|
Token::U32(0),
|
||||||
|
Token::Unit,
|
||||||
|
],
|
||||||
|
}
|
||||||
|
test_enum_unit_bytes {
|
||||||
|
Enum::Unit => &[
|
||||||
|
Token::EnumStart("Enum"),
|
||||||
|
Token::Bytes(b"Unit"),
|
||||||
|
Token::Unit,
|
||||||
|
],
|
||||||
|
}
|
||||||
test_box {
|
test_box {
|
||||||
Box::new(0i32) => &[Token::I32(0)],
|
Box::new(0i32) => &[Token::I32(0)],
|
||||||
}
|
}
|
||||||
@@ -849,7 +859,7 @@ declare_error_tests! {
|
|||||||
Token::StructSep,
|
Token::StructSep,
|
||||||
Token::Str("d"),
|
Token::Str("d"),
|
||||||
],
|
],
|
||||||
Error::UnknownField("d".to_owned()),
|
Error::Message("unknown field `d`, expected `a`".to_owned()),
|
||||||
}
|
}
|
||||||
test_skipped_field_is_unknown<StructDenyUnknown> {
|
test_skipped_field_is_unknown<StructDenyUnknown> {
|
||||||
&[
|
&[
|
||||||
@@ -857,7 +867,7 @@ declare_error_tests! {
|
|||||||
Token::StructSep,
|
Token::StructSep,
|
||||||
Token::Str("b"),
|
Token::Str("b"),
|
||||||
],
|
],
|
||||||
Error::UnknownField("b".to_owned()),
|
Error::Message("unknown field `b`, expected `a`".to_owned()),
|
||||||
}
|
}
|
||||||
test_skip_all_deny_unknown<StructSkipAllDenyUnknown> {
|
test_skip_all_deny_unknown<StructSkipAllDenyUnknown> {
|
||||||
&[
|
&[
|
||||||
@@ -865,25 +875,25 @@ declare_error_tests! {
|
|||||||
Token::StructSep,
|
Token::StructSep,
|
||||||
Token::Str("a"),
|
Token::Str("a"),
|
||||||
],
|
],
|
||||||
Error::UnknownField("a".to_owned()),
|
Error::Message("unknown field `a`, there are no fields".to_owned()),
|
||||||
}
|
}
|
||||||
test_unknown_variant<Enum> {
|
test_unknown_variant<Enum> {
|
||||||
&[
|
&[
|
||||||
Token::EnumUnit("Enum", "Foo"),
|
Token::EnumUnit("Enum", "Foo"),
|
||||||
],
|
],
|
||||||
Error::UnknownVariant("Foo".to_owned()),
|
Error::Message("unknown variant `Foo`, expected one of `Unit`, `Simple`, `Seq`, `Map`".to_owned()),
|
||||||
}
|
}
|
||||||
test_enum_skipped_variant<Enum> {
|
test_enum_skipped_variant<Enum> {
|
||||||
&[
|
&[
|
||||||
Token::EnumUnit("Enum", "Skipped"),
|
Token::EnumUnit("Enum", "Skipped"),
|
||||||
],
|
],
|
||||||
Error::UnknownVariant("Skipped".to_owned()),
|
Error::Message("unknown variant `Skipped`, expected one of `Unit`, `Simple`, `Seq`, `Map`".to_owned()),
|
||||||
}
|
}
|
||||||
test_enum_skip_all<EnumSkipAll> {
|
test_enum_skip_all<EnumSkipAll> {
|
||||||
&[
|
&[
|
||||||
Token::EnumUnit("EnumSkipAll", "Skipped"),
|
Token::EnumUnit("EnumSkipAll", "Skipped"),
|
||||||
],
|
],
|
||||||
Error::UnknownVariant("Skipped".to_owned()),
|
Error::Message("unknown variant `Skipped`, there are no variants".to_owned()),
|
||||||
}
|
}
|
||||||
test_struct_seq_too_long<Struct> {
|
test_struct_seq_too_long<Struct> {
|
||||||
&[
|
&[
|
||||||
@@ -904,7 +914,7 @@ declare_error_tests! {
|
|||||||
Token::MapSep,
|
Token::MapSep,
|
||||||
Token::Str("a"),
|
Token::Str("a"),
|
||||||
],
|
],
|
||||||
Error::DuplicateField("a"),
|
Error::Message("duplicate field `a`".to_owned()),
|
||||||
}
|
}
|
||||||
test_duplicate_field_enum<Enum> {
|
test_duplicate_field_enum<Enum> {
|
||||||
&[
|
&[
|
||||||
@@ -916,22 +926,32 @@ declare_error_tests! {
|
|||||||
Token::EnumMapSep,
|
Token::EnumMapSep,
|
||||||
Token::Str("a"),
|
Token::Str("a"),
|
||||||
],
|
],
|
||||||
Error::DuplicateField("a"),
|
Error::Message("duplicate field `a`".to_owned()),
|
||||||
}
|
}
|
||||||
test_enum_unit_usize<Enum> {
|
test_enum_out_of_range<Enum> {
|
||||||
&[
|
&[
|
||||||
Token::EnumStart("Enum"),
|
Token::EnumStart("Enum"),
|
||||||
Token::Usize(0),
|
Token::U32(4),
|
||||||
Token::Unit,
|
Token::Unit,
|
||||||
],
|
],
|
||||||
Error::InvalidType(Type::U64),
|
Error::Message("invalid value: integer `4`, expected variant index 0 <= i < 4".into()),
|
||||||
}
|
}
|
||||||
test_enum_unit_bytes<Enum> {
|
test_short_tuple<(u8, u8, u8)> {
|
||||||
&[
|
&[
|
||||||
Token::EnumStart("Enum"),
|
Token::TupleStart(1),
|
||||||
Token::Bytes(b"Unit"),
|
Token::TupleSep,
|
||||||
Token::Unit,
|
Token::U8(1),
|
||||||
|
Token::TupleEnd,
|
||||||
],
|
],
|
||||||
Error::InvalidType(Type::Bytes),
|
Error::Message("invalid length 1, expected a tuple of size 3".into()),
|
||||||
|
}
|
||||||
|
test_short_array<[u8; 3]> {
|
||||||
|
&[
|
||||||
|
Token::SeqStart(Some(1)),
|
||||||
|
Token::SeqSep,
|
||||||
|
Token::U8(1),
|
||||||
|
Token::SeqEnd,
|
||||||
|
],
|
||||||
|
Error::Message("invalid length 1, expected an array of length 3".into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -8,11 +8,15 @@ use self::serde::de::{Deserialize, Deserializer};
|
|||||||
|
|
||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
use std::result::Result as StdResult;
|
||||||
|
|
||||||
// Try to trip up the generated code if it fails to use fully qualified paths.
|
// Try to trip up the generated code if it fails to use fully qualified paths.
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
struct Result;
|
struct Result;
|
||||||
use std::result::Result as StdResult;
|
#[allow(dead_code)]
|
||||||
|
struct Ok;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
struct Err;
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
@@ -1,11 +1,14 @@
|
|||||||
extern crate serde_test;
|
extern crate serde_test;
|
||||||
use self::serde_test::{
|
use self::serde_test::{
|
||||||
|
Error,
|
||||||
Token,
|
Token,
|
||||||
assert_tokens,
|
assert_tokens,
|
||||||
assert_ser_tokens,
|
assert_ser_tokens,
|
||||||
assert_de_tokens,
|
assert_de_tokens,
|
||||||
|
assert_de_tokens_error,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
|
||||||
// That tests that the derived Serialize implementation doesn't trigger
|
// That tests that the derived Serialize implementation doesn't trigger
|
||||||
@@ -625,3 +628,256 @@ fn test_enum_state_field() {
|
|||||||
]
|
]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_untagged_enum() {
|
||||||
|
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(untagged)]
|
||||||
|
enum Untagged {
|
||||||
|
A {
|
||||||
|
a: u8,
|
||||||
|
},
|
||||||
|
B {
|
||||||
|
b: u8,
|
||||||
|
},
|
||||||
|
C,
|
||||||
|
D(u8),
|
||||||
|
E(String),
|
||||||
|
F(u8, u8),
|
||||||
|
}
|
||||||
|
|
||||||
|
assert_tokens(
|
||||||
|
&Untagged::A { a: 1 },
|
||||||
|
&[
|
||||||
|
Token::StructStart("Untagged", 1),
|
||||||
|
|
||||||
|
Token::StructSep,
|
||||||
|
Token::Str("a"),
|
||||||
|
Token::U8(1),
|
||||||
|
|
||||||
|
Token::StructEnd,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_tokens(
|
||||||
|
&Untagged::B { b: 2 },
|
||||||
|
&[
|
||||||
|
Token::StructStart("Untagged", 1),
|
||||||
|
|
||||||
|
Token::StructSep,
|
||||||
|
Token::Str("b"),
|
||||||
|
Token::U8(2),
|
||||||
|
|
||||||
|
Token::StructEnd,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_tokens(
|
||||||
|
&Untagged::C,
|
||||||
|
&[
|
||||||
|
Token::Unit,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_tokens(
|
||||||
|
&Untagged::D(4),
|
||||||
|
&[
|
||||||
|
Token::U8(4),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert_tokens(
|
||||||
|
&Untagged::E("e".to_owned()),
|
||||||
|
&[
|
||||||
|
Token::Str("e"),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_tokens(
|
||||||
|
&Untagged::F(1, 2),
|
||||||
|
&[
|
||||||
|
Token::TupleStart(2),
|
||||||
|
|
||||||
|
Token::TupleSep,
|
||||||
|
Token::U8(1),
|
||||||
|
|
||||||
|
Token::TupleSep,
|
||||||
|
Token::U8(2),
|
||||||
|
|
||||||
|
Token::TupleEnd,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_de_tokens_error::<Untagged>(
|
||||||
|
&[
|
||||||
|
Token::Option(false),
|
||||||
|
],
|
||||||
|
Error::Message("data did not match any variant of untagged enum Untagged".to_owned()),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_de_tokens_error::<Untagged>(
|
||||||
|
&[
|
||||||
|
Token::TupleStart(1),
|
||||||
|
|
||||||
|
Token::TupleSep,
|
||||||
|
Token::U8(1),
|
||||||
|
|
||||||
|
Token::TupleEnd,
|
||||||
|
],
|
||||||
|
Error::Message("data did not match any variant of untagged enum Untagged".to_owned()),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_de_tokens_error::<Untagged>(
|
||||||
|
&[
|
||||||
|
Token::TupleStart(3),
|
||||||
|
|
||||||
|
Token::TupleSep,
|
||||||
|
Token::U8(1),
|
||||||
|
|
||||||
|
Token::TupleSep,
|
||||||
|
Token::U8(2),
|
||||||
|
|
||||||
|
Token::TupleSep,
|
||||||
|
Token::U8(3),
|
||||||
|
|
||||||
|
Token::TupleEnd,
|
||||||
|
],
|
||||||
|
Error::Message("data did not match any variant of untagged enum Untagged".to_owned()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_internally_tagged_enum() {
|
||||||
|
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
struct Newtype(BTreeMap<String, String>);
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
struct Struct {
|
||||||
|
f: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "type")]
|
||||||
|
enum InternallyTagged {
|
||||||
|
A {
|
||||||
|
a: u8,
|
||||||
|
},
|
||||||
|
B {
|
||||||
|
b: u8,
|
||||||
|
},
|
||||||
|
C,
|
||||||
|
D(BTreeMap<String, String>),
|
||||||
|
E(Newtype),
|
||||||
|
F(Struct),
|
||||||
|
}
|
||||||
|
|
||||||
|
assert_tokens(
|
||||||
|
&InternallyTagged::A { a: 1 },
|
||||||
|
&[
|
||||||
|
Token::StructStart("InternallyTagged", 2),
|
||||||
|
|
||||||
|
Token::StructSep,
|
||||||
|
Token::Str("type"),
|
||||||
|
Token::Str("A"),
|
||||||
|
|
||||||
|
Token::StructSep,
|
||||||
|
Token::Str("a"),
|
||||||
|
Token::U8(1),
|
||||||
|
|
||||||
|
Token::StructEnd,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_tokens(
|
||||||
|
&InternallyTagged::B { b: 2 },
|
||||||
|
&[
|
||||||
|
Token::StructStart("InternallyTagged", 2),
|
||||||
|
|
||||||
|
Token::StructSep,
|
||||||
|
Token::Str("type"),
|
||||||
|
Token::Str("B"),
|
||||||
|
|
||||||
|
Token::StructSep,
|
||||||
|
Token::Str("b"),
|
||||||
|
Token::U8(2),
|
||||||
|
|
||||||
|
Token::StructEnd,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_tokens(
|
||||||
|
&InternallyTagged::C,
|
||||||
|
&[
|
||||||
|
Token::StructStart("InternallyTagged", 1),
|
||||||
|
|
||||||
|
Token::StructSep,
|
||||||
|
Token::Str("type"),
|
||||||
|
Token::Str("C"),
|
||||||
|
|
||||||
|
Token::StructEnd,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_tokens(
|
||||||
|
&InternallyTagged::D(BTreeMap::new()),
|
||||||
|
&[
|
||||||
|
Token::MapStart(Some(1)),
|
||||||
|
|
||||||
|
Token::MapSep,
|
||||||
|
Token::Str("type"),
|
||||||
|
Token::Str("D"),
|
||||||
|
|
||||||
|
Token::MapEnd,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_tokens(
|
||||||
|
&InternallyTagged::E(Newtype(BTreeMap::new())),
|
||||||
|
&[
|
||||||
|
Token::MapStart(Some(1)),
|
||||||
|
|
||||||
|
Token::MapSep,
|
||||||
|
Token::Str("type"),
|
||||||
|
Token::Str("E"),
|
||||||
|
|
||||||
|
Token::MapEnd,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_tokens(
|
||||||
|
&InternallyTagged::F(Struct { f: 6 }),
|
||||||
|
&[
|
||||||
|
Token::StructStart("Struct", 2),
|
||||||
|
|
||||||
|
Token::StructSep,
|
||||||
|
Token::Str("type"),
|
||||||
|
Token::Str("F"),
|
||||||
|
|
||||||
|
Token::StructSep,
|
||||||
|
Token::Str("f"),
|
||||||
|
Token::U8(6),
|
||||||
|
|
||||||
|
Token::StructEnd,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_de_tokens_error::<InternallyTagged>(
|
||||||
|
&[
|
||||||
|
Token::MapStart(Some(0)),
|
||||||
|
Token::MapEnd,
|
||||||
|
],
|
||||||
|
Error::Message("missing field `type`".to_owned()),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_de_tokens_error::<InternallyTagged>(
|
||||||
|
&[
|
||||||
|
Token::MapStart(Some(1)),
|
||||||
|
|
||||||
|
Token::MapSep,
|
||||||
|
Token::Str("type"),
|
||||||
|
Token::Str("Z"),
|
||||||
|
|
||||||
|
Token::MapEnd,
|
||||||
|
],
|
||||||
|
Error::Message("unknown variant `Z`, expected one of `A`, `B`, `C`, `D`, `E`, `F`".to_owned()),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -51,7 +51,20 @@ enum Enum {
|
|||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
//////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
declare_ser_tests! {
|
macro_rules! declare_tests {
|
||||||
|
($($name:ident { $($value:expr => $tokens:expr,)+ })+) => {
|
||||||
|
$(
|
||||||
|
#[test]
|
||||||
|
fn $name() {
|
||||||
|
$(
|
||||||
|
assert_ser_tokens(&$value, $tokens);
|
||||||
|
)+
|
||||||
|
}
|
||||||
|
)+
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
declare_tests! {
|
||||||
test_unit {
|
test_unit {
|
||||||
() => &[Token::Unit],
|
() => &[Token::Unit],
|
||||||
}
|
}
|
||||||
@@ -60,14 +73,12 @@ declare_ser_tests! {
|
|||||||
false => &[Token::Bool(false)],
|
false => &[Token::Bool(false)],
|
||||||
}
|
}
|
||||||
test_isizes {
|
test_isizes {
|
||||||
0isize => &[Token::Isize(0)],
|
|
||||||
0i8 => &[Token::I8(0)],
|
0i8 => &[Token::I8(0)],
|
||||||
0i16 => &[Token::I16(0)],
|
0i16 => &[Token::I16(0)],
|
||||||
0i32 => &[Token::I32(0)],
|
0i32 => &[Token::I32(0)],
|
||||||
0i64 => &[Token::I64(0)],
|
0i64 => &[Token::I64(0)],
|
||||||
}
|
}
|
||||||
test_usizes {
|
test_usizes {
|
||||||
0usize => &[Token::Usize(0)],
|
|
||||||
0u8 => &[Token::U8(0)],
|
0u8 => &[Token::U8(0)],
|
||||||
0u16 => &[Token::U16(0)],
|
0u16 => &[Token::U16(0)],
|
||||||
0u32 => &[Token::U32(0)],
|
0u32 => &[Token::U32(0)],
|
||||||
@@ -432,7 +443,7 @@ fn test_cannot_serialize_paths() {
|
|||||||
assert_ser_tokens_error(
|
assert_ser_tokens_error(
|
||||||
&Path::new(path),
|
&Path::new(path),
|
||||||
&[],
|
&[],
|
||||||
Error::InvalidValue("Path contains invalid UTF-8 characters".to_owned()));
|
Error::Message("path contains invalid UTF-8 characters".to_owned()));
|
||||||
|
|
||||||
let mut path_buf = PathBuf::new();
|
let mut path_buf = PathBuf::new();
|
||||||
path_buf.push(path);
|
path_buf.push(path);
|
||||||
@@ -440,7 +451,7 @@ fn test_cannot_serialize_paths() {
|
|||||||
assert_ser_tokens_error(
|
assert_ser_tokens_error(
|
||||||
&path_buf,
|
&path_buf,
|
||||||
&[],
|
&[],
|
||||||
Error::InvalidValue("Path contains invalid UTF-8 characters".to_owned()));
|
Error::Message("path contains invalid UTF-8 characters".to_owned()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -448,17 +459,17 @@ fn test_enum_skipped() {
|
|||||||
assert_ser_tokens_error(
|
assert_ser_tokens_error(
|
||||||
&Enum::SkippedUnit,
|
&Enum::SkippedUnit,
|
||||||
&[],
|
&[],
|
||||||
Error::InvalidValue("The enum variant Enum::SkippedUnit cannot be serialized".to_owned()));
|
Error::Message("the enum variant Enum::SkippedUnit cannot be serialized".to_owned()));
|
||||||
assert_ser_tokens_error(
|
assert_ser_tokens_error(
|
||||||
&Enum::SkippedOne(42),
|
&Enum::SkippedOne(42),
|
||||||
&[],
|
&[],
|
||||||
Error::InvalidValue("The enum variant Enum::SkippedOne cannot be serialized".to_owned()));
|
Error::Message("the enum variant Enum::SkippedOne cannot be serialized".to_owned()));
|
||||||
assert_ser_tokens_error(
|
assert_ser_tokens_error(
|
||||||
&Enum::SkippedSeq(1, 2),
|
&Enum::SkippedSeq(1, 2),
|
||||||
&[],
|
&[],
|
||||||
Error::InvalidValue("The enum variant Enum::SkippedSeq cannot be serialized".to_owned()));
|
Error::Message("the enum variant Enum::SkippedSeq cannot be serialized".to_owned()));
|
||||||
assert_ser_tokens_error(
|
assert_ser_tokens_error(
|
||||||
&Enum::SkippedMap { _a: 1, _b: 2 },
|
&Enum::SkippedMap { _a: 1, _b: 2 },
|
||||||
&[],
|
&[],
|
||||||
Error::InvalidValue("The enum variant Enum::SkippedMap cannot be serialized".to_owned()));
|
Error::Message("the enum variant Enum::SkippedMap cannot be serialized".to_owned()));
|
||||||
}
|
}
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
extern crate serde_codegen;
|
|
||||||
|
|
||||||
use std::env;
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let out_dir = env::var_os("OUT_DIR").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,6 +0,0 @@
|
|||||||
#![cfg_attr(feature = "clippy", feature(plugin))]
|
|
||||||
#![cfg_attr(feature = "clippy", plugin(clippy))]
|
|
||||||
|
|
||||||
#![cfg_attr(feature = "unstable-testing", feature(non_ascii_idents))]
|
|
||||||
|
|
||||||
include!(concat!(env!("OUT_DIR"), "/test.rs"));
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
extern crate serde;
|
|
||||||
extern crate serde_test;
|
|
||||||
|
|
||||||
#[macro_use]
|
|
||||||
mod macros;
|
|
||||||
|
|
||||||
mod test_annotations;
|
|
||||||
mod test_bytes;
|
|
||||||
mod test_de;
|
|
||||||
mod test_gen;
|
|
||||||
mod test_macros;
|
|
||||||
mod test_ser;
|
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
|
||||||
|
channel() {
|
||||||
|
if [ -n "${TRAVIS}" ]; then
|
||||||
|
if [ "${TRAVIS_RUST_VERSION}" = "${CHANNEL}" ]; then
|
||||||
|
pwd
|
||||||
|
(set -x; cargo "$@")
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
pwd
|
||||||
|
(set -x; cargo "+${CHANNEL}" "$@")
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
if [ -n "${CLIPPY}" ]; then
|
||||||
|
# cached installation will not work on a later nightly
|
||||||
|
if [ -n "${TRAVIS}" ] && ! cargo install clippy --debug --force; then
|
||||||
|
echo "COULD NOT COMPILE CLIPPY, IGNORING CLIPPY TESTS"
|
||||||
|
exit
|
||||||
|
fi
|
||||||
|
|
||||||
|
cd "$DIR/serde"
|
||||||
|
cargo clippy --features unstable-testing -- -Dclippy
|
||||||
|
|
||||||
|
cd "$DIR/serde_derive"
|
||||||
|
cargo clippy --features unstable-testing -- -Dclippy
|
||||||
|
|
||||||
|
cd "$DIR/test_suite"
|
||||||
|
cargo clippy --features unstable-testing -- -Dclippy
|
||||||
|
|
||||||
|
cd "$DIR/test_suite/no_std"
|
||||||
|
cargo clippy -- -Dclippy
|
||||||
|
else
|
||||||
|
CHANNEL=nightly
|
||||||
|
cargo clean
|
||||||
|
cd "$DIR/serde"
|
||||||
|
channel build
|
||||||
|
channel build --no-default-features
|
||||||
|
channel build --no-default-features --features alloc
|
||||||
|
channel build --no-default-features --features collections
|
||||||
|
channel test --features unstable-testing
|
||||||
|
cd "$DIR/test_suite/deps"
|
||||||
|
channel build
|
||||||
|
cd "$DIR/test_suite"
|
||||||
|
channel test --features unstable-testing
|
||||||
|
cd "$DIR/test_suite/no_std"
|
||||||
|
channel build
|
||||||
|
|
||||||
|
CHANNEL=beta
|
||||||
|
cargo clean
|
||||||
|
cd "$DIR/serde"
|
||||||
|
channel build
|
||||||
|
cd "$DIR/test_suite"
|
||||||
|
channel test
|
||||||
|
|
||||||
|
CHANNEL=stable
|
||||||
|
cargo clean
|
||||||
|
cd "$DIR/serde"
|
||||||
|
channel build
|
||||||
|
channel build --no-default-features
|
||||||
|
|
||||||
|
CHANNEL=1.13.0
|
||||||
|
cargo clean
|
||||||
|
cd "$DIR/serde"
|
||||||
|
channel build
|
||||||
|
channel build --no-default-features
|
||||||
|
fi
|
||||||
Reference in New Issue
Block a user