mirror of
https://github.com/pezkuwichain/serde.git
synced 2026-04-22 21:48:02 +00:00
Compare commits
178 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 797d049db5 | |||
| d61a373f12 | |||
| e0eea551b4 | |||
| c650a92bf7 | |||
| f218f4d7bf | |||
| 8c0a2015be | |||
| 4773863e3a | |||
| 80cd9c7617 | |||
| 436cafb0a3 | |||
| 98bb02e9b4 | |||
| 142439088c | |||
| ce81288235 | |||
| 88d5fe6bfd | |||
| 9a2c352025 | |||
| 61c90cb8cb | |||
| 66e8b0a0cd | |||
| 9e7a3437d9 | |||
| 7ac8d4f9ae | |||
| 501bae42f5 | |||
| 7a0397451e | |||
| 16787318d1 | |||
| f4ae0888c8 | |||
| 213071fe5c | |||
| cfd26c6fda | |||
| 23fa83941e | |||
| 88f5b9511d | |||
| d537f1e1f0 | |||
| f6ac232580 | |||
| aad7a7987f | |||
| b24ad76880 | |||
| 5796f1a0f5 | |||
| 6437167930 | |||
| f98daaa250 | |||
| b8a40551a2 | |||
| 40db31691a | |||
| ab68132b1f | |||
| e70bbd9dde | |||
| d5e5c520ac | |||
| 1b9a096fa7 | |||
| 39e05ffad2 | |||
| 78fab25c5c | |||
| 2a557a1e36 | |||
| ab0848f780 | |||
| 2b1303f59c | |||
| 7f9ba155cb | |||
| a4e0c2f055 | |||
| 3bbf70575b | |||
| ad680cbd44 | |||
| ff0cfb1f1f | |||
| 9b08915a18 | |||
| 501aa3ee1d | |||
| eebf0f8db8 | |||
| a7e4911ddb | |||
| eb08f037f5 | |||
| aa03fd5d1a | |||
| e198afb0c1 | |||
| bc8de251cf | |||
| 99e8686189 | |||
| 826f656e28 | |||
| ab7c003b64 | |||
| 422191fcb0 | |||
| 4ba748c902 | |||
| 14ed6f2dab | |||
| 30606a43aa | |||
| 9be3d32016 | |||
| 5daf1b89a1 | |||
| f8f5d0ca2f | |||
| 57873cce28 | |||
| 4ed0362c8e | |||
| 4cecaf8d02 | |||
| 50c696aabe | |||
| 2f58a20bc6 | |||
| 030459a040 | |||
| e9b530a000 | |||
| ea1a729088 | |||
| 857dcea774 | |||
| b98a9a8f9b | |||
| 3b135431fd | |||
| 945d12c0b4 | |||
| e36915300f | |||
| 85c05d301a | |||
| c2474bf6ee | |||
| a52f436788 | |||
| ad3335e5d6 | |||
| 4b00de0e22 | |||
| 8403fa018e | |||
| 0e9f1b42de | |||
| 0085d05e55 | |||
| 2eed855bff | |||
| c3eced410f | |||
| 8a630fea7c | |||
| 2e597ed3f0 | |||
| 0963121beb | |||
| 15b2714058 | |||
| 9ce107de25 | |||
| e47284c0e0 | |||
| 800620e2aa | |||
| 40c670e625 | |||
| ba260b0e5f | |||
| 8452e313cc | |||
| 0dccbb1f11 | |||
| deca49315a | |||
| 95407a4ca5 | |||
| 2fe9a860cd | |||
| e67d941b78 | |||
| d4042872f5 | |||
| 64af86b830 | |||
| 370c8a91cb | |||
| 972da59ebc | |||
| a42008f695 | |||
| e4ea2a56e9 | |||
| 7650a48fdd | |||
| d665a2f2b2 | |||
| 44e23254c9 | |||
| 552971196d | |||
| 0681cd5003 | |||
| d965367238 | |||
| a6df35b3d2 | |||
| 9fc180e62f | |||
| 5b815b7001 | |||
| 4831482695 | |||
| d3e5dd9cd7 | |||
| 26098ed877 | |||
| 42ed62cf24 | |||
| 9f0973aff7 | |||
| ccec002bf3 | |||
| f36a1e0895 | |||
| e6487cf6fa | |||
| 4f2e8d5dbb | |||
| 1c2a4bff1c | |||
| 85bccf42b6 | |||
| 959fee024f | |||
| 8ede8c8e2a | |||
| 83537c95e1 | |||
| fa9057fa31 | |||
| 0084d82a50 | |||
| b504b08782 | |||
| 775e8154e7 | |||
| 9c679d9082 | |||
| b0f9d2a0ba | |||
| f39b1db96a | |||
| 9ecb0839de | |||
| 8a4c116812 | |||
| 1d3e921ba6 | |||
| 8e8694261b | |||
| 4fdba725fe | |||
| 75eed8cdde | |||
| 6801a13650 | |||
| 25ab84d4b9 | |||
| e43d3f3e4f | |||
| b37d47c987 | |||
| eec7101894 | |||
| 5dd327fb02 | |||
| fd3d1396d3 | |||
| c47b4c8e0b | |||
| 2d793b82f6 | |||
| 237be46e29 | |||
| 3d7aad1e7b | |||
| e792874369 | |||
| 1669c69714 | |||
| 4d5e450054 | |||
| 26b22e647d | |||
| cda1fc46b0 | |||
| c68b959696 | |||
| eab80172e4 | |||
| c1259fbc87 | |||
| 58e30eaee4 | |||
| bafa941004 | |||
| f347b2d363 | |||
| 3f9fc49cca | |||
| c913527944 | |||
| 8fafc7420c | |||
| bea1c5b0f5 | |||
| aa37caf216 | |||
| 2440b59aae | |||
| 873cfbe9ab | |||
| c96efcb87a | |||
| b53026a21b |
+52
-31
@@ -1,45 +1,66 @@
|
||||
# Contributing to Serde
|
||||
|
||||
Serde welcomes contribution from everyone. Here are the guidelines if you are
|
||||
thinking of helping us:
|
||||
Serde welcomes contribution from everyone in the form of suggestions, bug
|
||||
reports, pull requests, and feedback. This document gives some guidance if you
|
||||
are thinking of helping us.
|
||||
|
||||
## Contributions
|
||||
Please reach out here in a GitHub issue or in the #serde IRC channel on
|
||||
[`irc.mozilla.org`] if we can do anything to help you contribute.
|
||||
|
||||
Contributions to Serde or its dependencies should be made in the form of GitHub
|
||||
pull requests. Each pull request will be reviewed by a core contributor
|
||||
(someone with permission to land patches) and either landed in the main tree or
|
||||
given feedback for changes that would be required. All contributions should
|
||||
follow this format, even those from core contributors.
|
||||
[`irc.mozilla.org`]: https://wiki.mozilla.org/IRC
|
||||
|
||||
Should you wish to work on an issue, please claim it first by commenting on
|
||||
the GitHub issue that you want to work on it. This is to prevent duplicated
|
||||
efforts from contributors on the same issue.
|
||||
## Submitting bug reports and feature requests
|
||||
|
||||
## Pull Request Checklist
|
||||
Serde development is spread across lots of repositories, but this serde-rs/serde
|
||||
repository is always a safe choice for opening any issues related to Serde.
|
||||
|
||||
- Branch from the master branch and, if needed, rebase to the current master
|
||||
branch before submitting your pull request. If it doesn't merge cleanly with
|
||||
master you may be asked to rebase your changes.
|
||||
When reporting a bug or asking for help, please include enough details so that
|
||||
the people helping you can reproduce the behavior you are seeing. For some tips
|
||||
on how to approach this, read about how to produce a [Minimal, Complete, and
|
||||
Verifiable example].
|
||||
|
||||
- Commits should be as small as possible, while ensuring that each commit is
|
||||
correct independently (i.e., each commit should compile and pass tests).
|
||||
[Minimal, Complete, and Verifiable example]: https://stackoverflow.com/help/mcve
|
||||
|
||||
- If your patch is not getting reviewed or you need a specific person to review
|
||||
it, you can @-reply a reviewer asking for a review in the pull request or a
|
||||
comment, or you can ask for a review in `#serde` on `irc.mozilla.org`.
|
||||
When making a feature request, please make it clear what problem you intend to
|
||||
solve with the feature, any ideas for how Serde could support solving that
|
||||
problem, any possible alternatives, and any disadvantages.
|
||||
|
||||
- Add tests relevant to the fixed bug or new feature.
|
||||
## Running the test suite
|
||||
|
||||
We encourage you to check that the test suite passes locally before submitting a
|
||||
pull request with your changes. If anything does not pass, typically it will be
|
||||
easier to iterate and fix it locally than waiting for the CI servers to run
|
||||
tests for you.
|
||||
|
||||
##### In the [`serde`] directory
|
||||
|
||||
```sh
|
||||
# Test all the example code in Serde documentation
|
||||
cargo test
|
||||
```
|
||||
|
||||
##### In the [`test_suite/deps`] directory
|
||||
|
||||
```sh
|
||||
# This is a prerequisite for running the full test suite
|
||||
cargo clean && cargo update && cargo build
|
||||
```
|
||||
|
||||
##### In the [`test_suite`] directory
|
||||
|
||||
```sh
|
||||
# Run the full test suite, including tests of unstable functionality
|
||||
cargo test --features unstable
|
||||
```
|
||||
|
||||
[`serde`]: https://github.com/serde-rs/serde/tree/master/serde
|
||||
[`test_suite/deps`]: https://github.com/serde-rs/serde/tree/master/test_suite/deps
|
||||
[`test_suite`]: https://github.com/serde-rs/serde/tree/master/test_suite
|
||||
|
||||
## Conduct
|
||||
|
||||
In all Serde-related forums, we follow the [Rust Code of
|
||||
Conduct](https://www.rust-lang.org/conduct.html). For escalation or moderation
|
||||
issues, please contact Erick (erick.tryzelaar@gmail.com) instead of the Rust
|
||||
moderation team.
|
||||
In all Serde-related forums, we follow the [Rust Code of Conduct]. For
|
||||
escalation or moderation issues please contact Erick (erick.tryzelaar@gmail.com)
|
||||
instead of the Rust moderation team.
|
||||
|
||||
## Communication
|
||||
|
||||
Beyond opening tickets on the
|
||||
[serde-rs/serde](https://github.com/serde-rs/serde) project, Serde contributors
|
||||
frequent the `#serde` channel on
|
||||
[`irc.mozilla.org`](https://wiki.mozilla.org/IRC).
|
||||
[Rust Code of Conduct]: https://www.rust-lang.org/conduct.html
|
||||
|
||||
@@ -5,5 +5,4 @@ members = [
|
||||
"serde_derive_internals",
|
||||
"serde_test",
|
||||
"test_suite",
|
||||
"test_suite/no_std",
|
||||
]
|
||||
|
||||
@@ -20,9 +20,30 @@ You may be looking for:
|
||||
|
||||
## Serde in action
|
||||
|
||||
<a href="http://play.integer32.com/?gist=9003c5b88c1f4989941925d7190c6eec" target="_blank">
|
||||
<img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png">
|
||||
</a>
|
||||
<details>
|
||||
<summary>
|
||||
Click to show Cargo.toml.
|
||||
<a href="http://play.integer32.com/?gist=9003c5b88c1f4989941925d7190c6eec" target="_blank">Run this code in the playground.</a>
|
||||
</summary>
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
|
||||
# The core APIs, including the Serialize and Deserialize traits. Always
|
||||
# required when using Serde.
|
||||
serde = "1.0"
|
||||
|
||||
# Support for #[derive(Serialize, Deserialize)]. Required if you want Serde
|
||||
# to work for structs and enums defined in your crate.
|
||||
serde_derive = "1.0"
|
||||
|
||||
# Each data format lives in its own crate; the sample code below uses JSON
|
||||
# but you may be using a different one.
|
||||
serde_json = "1.0"
|
||||
```
|
||||
|
||||
</details>
|
||||
<p></p>
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
|
||||
+4
-11
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde"
|
||||
version = "1.0.1" # remember to update html_root_url
|
||||
version = "1.0.22" # remember to update html_root_url
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "A generic serialization/deserialization framework"
|
||||
@@ -48,22 +48,15 @@ std = []
|
||||
# https://github.com/serde-rs/serde/issues/812
|
||||
unstable = []
|
||||
|
||||
# Provide impls for types that require memory allocation like Box<T> and Rc<T>.
|
||||
# This is a subset of std but may be enabled without depending on all of std.
|
||||
# Provide impls for types in the Rust core allocation and collections library
|
||||
# including String, Box<T>, Vec<T>, and Cow<T>. This is a subset of std but may
|
||||
# be enabled without depending on all of std.
|
||||
#
|
||||
# Requires a dependency on the unstable core allocation library:
|
||||
#
|
||||
# https://doc.rust-lang.org/alloc/
|
||||
alloc = ["unstable"]
|
||||
|
||||
# Provide impls for collection types like String and Cow<T>. This is a subset of
|
||||
# std but may be enabled without depending on all of std.
|
||||
#
|
||||
# Requires a dependency on the unstable collections library:
|
||||
#
|
||||
# https://doc.rust-lang.org/collections/
|
||||
collections = ["alloc"]
|
||||
|
||||
# Opt into impls for Rc<T> and Arc<T>. Serializing and deserializing these types
|
||||
# does not preserve identity and may result in multiple copies of the same data.
|
||||
# Be sure that this is what you want before enabling this feature.
|
||||
|
||||
+429
-192
@@ -11,12 +11,12 @@ use lib::*;
|
||||
use de::{Deserialize, Deserializer, EnumAccess, Error, SeqAccess, Unexpected, VariantAccess,
|
||||
Visitor};
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
use de::MapAccess;
|
||||
|
||||
use de::from_primitive::FromPrimitive;
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
use private::de::size_hint;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
@@ -208,10 +208,10 @@ impl<'de> Deserialize<'de> for char {
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
struct StringVisitor;
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'de> Visitor<'de> for StringVisitor {
|
||||
type Value = String;
|
||||
|
||||
@@ -254,7 +254,7 @@ impl<'de> Visitor<'de> for StringVisitor {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'de> Deserialize<'de> for String {
|
||||
fn deserialize<D>(deserializer: D) -> Result<String, D::Error>
|
||||
where
|
||||
@@ -400,16 +400,22 @@ impl<'de> Deserialize<'de> for CString {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "std", feature = "unstable"))]
|
||||
impl<'de> Deserialize<'de> for Box<CStr> {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
CString::deserialize(deserializer).map(CString::into_boxed_c_str)
|
||||
macro_rules! forwarded_impl {
|
||||
(( $($id: ident),* ), $ty: ty, $func: expr) => {
|
||||
impl<'de $(, $id : Deserialize<'de>,)*> Deserialize<'de> for $ty {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Deserialize::deserialize(deserializer).map($func)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "std", feature = "unstable"))]
|
||||
forwarded_impl!((), Box<CStr>, CString::into_boxed_c_str);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct OptionVisitor<T> {
|
||||
@@ -497,7 +503,7 @@ impl<'de, T> Deserialize<'de> for PhantomData<T> {
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
macro_rules! seq_impl {
|
||||
(
|
||||
$ty:ident < T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)* >,
|
||||
@@ -552,7 +558,7 @@ macro_rules! seq_impl {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(
|
||||
BinaryHeap<T: Ord>,
|
||||
seq,
|
||||
@@ -560,7 +566,7 @@ seq_impl!(
|
||||
BinaryHeap::with_capacity(size_hint::cautious(seq.size_hint())),
|
||||
BinaryHeap::push);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(
|
||||
BTreeSet<T: Eq + Ord>,
|
||||
seq,
|
||||
@@ -568,7 +574,7 @@ seq_impl!(
|
||||
BTreeSet::new(),
|
||||
BTreeSet::insert);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(
|
||||
LinkedList<T>,
|
||||
seq,
|
||||
@@ -584,7 +590,7 @@ seq_impl!(
|
||||
HashSet::with_capacity_and_hasher(size_hint::cautious(seq.size_hint()), S::default()),
|
||||
HashSet::insert);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(
|
||||
Vec<T>,
|
||||
seq,
|
||||
@@ -592,7 +598,7 @@ seq_impl!(
|
||||
Vec::with_capacity(size_hint::cautious(seq.size_hint())),
|
||||
Vec::push);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(
|
||||
VecDeque<T>,
|
||||
seq,
|
||||
@@ -790,7 +796,7 @@ tuple_impls! {
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
macro_rules! map_impl {
|
||||
(
|
||||
$ty:ident < K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)* >,
|
||||
@@ -846,7 +852,7 @@ macro_rules! map_impl {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
map_impl!(
|
||||
BTreeMap<K: Ord, V>,
|
||||
map,
|
||||
@@ -863,40 +869,247 @@ map_impl!(
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
macro_rules! parse_impl {
|
||||
($ty:ty) => {
|
||||
macro_rules! parse_ip_impl {
|
||||
($ty:ty; $size: expr) => {
|
||||
impl<'de> Deserialize<'de> for $ty {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = try!(String::deserialize(deserializer));
|
||||
s.parse().map_err(Error::custom)
|
||||
if deserializer.is_human_readable() {
|
||||
let s = try!(String::deserialize(deserializer));
|
||||
s.parse().map_err(Error::custom)
|
||||
} else {
|
||||
<[u8; $size]>::deserialize(deserializer).map(<$ty>::from)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
parse_impl!(net::IpAddr);
|
||||
macro_rules! variant_identifier {
|
||||
(
|
||||
$name_kind: ident ( $($variant: ident; $bytes: expr; $index: expr),* )
|
||||
$expecting_message: expr,
|
||||
$variants_name: ident
|
||||
) => {
|
||||
enum $name_kind {
|
||||
$( $variant ),*
|
||||
}
|
||||
|
||||
static $variants_name: &'static [&'static str] = &[ $( stringify!($variant) ),*];
|
||||
|
||||
impl<'de> Deserialize<'de> for $name_kind {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
struct KindVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for KindVisitor {
|
||||
type Value = $name_kind;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str($expecting_message)
|
||||
}
|
||||
|
||||
fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
match value {
|
||||
$(
|
||||
$index => Ok($name_kind :: $variant),
|
||||
)*
|
||||
_ => Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self),),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
match value {
|
||||
$(
|
||||
stringify!($variant) => Ok($name_kind :: $variant),
|
||||
)*
|
||||
_ => Err(Error::unknown_variant(value, $variants_name)),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
match value {
|
||||
$(
|
||||
$bytes => Ok($name_kind :: $variant),
|
||||
)*
|
||||
_ => {
|
||||
match str::from_utf8(value) {
|
||||
Ok(value) => Err(Error::unknown_variant(value, $variants_name)),
|
||||
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
deserializer.deserialize_identifier(KindVisitor)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
parse_impl!(net::Ipv4Addr);
|
||||
macro_rules! deserialize_enum {
|
||||
(
|
||||
$name: ident $name_kind: ident ( $($variant: ident; $bytes: expr; $index: expr),* )
|
||||
$expecting_message: expr,
|
||||
$deserializer: expr
|
||||
) => {
|
||||
variant_identifier!{
|
||||
$name_kind ( $($variant; $bytes; $index),* )
|
||||
$expecting_message,
|
||||
VARIANTS
|
||||
}
|
||||
|
||||
struct EnumVisitor;
|
||||
impl<'de> Visitor<'de> for EnumVisitor {
|
||||
type Value = $name;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str(concat!("a ", stringify!($name)))
|
||||
}
|
||||
|
||||
|
||||
fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
|
||||
where
|
||||
A: EnumAccess<'de>,
|
||||
{
|
||||
match try!(data.variant()) {
|
||||
$(
|
||||
($name_kind :: $variant, v) => v.newtype_variant().map($name :: $variant),
|
||||
)*
|
||||
}
|
||||
}
|
||||
}
|
||||
$deserializer.deserialize_enum(stringify!($name), VARIANTS, EnumVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
parse_impl!(net::Ipv6Addr);
|
||||
impl<'de> Deserialize<'de> for net::IpAddr {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
if deserializer.is_human_readable() {
|
||||
let s = try!(String::deserialize(deserializer));
|
||||
s.parse().map_err(Error::custom)
|
||||
} else {
|
||||
use lib::net::IpAddr;
|
||||
deserialize_enum!{
|
||||
IpAddr IpAddrKind (V4; b"V4"; 0, V6; b"V6"; 1)
|
||||
"`V4` or `V6`",
|
||||
deserializer
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
parse_impl!(net::SocketAddr);
|
||||
parse_ip_impl!(net::Ipv4Addr; 4);
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
parse_impl!(net::SocketAddrV4);
|
||||
parse_ip_impl!(net::Ipv6Addr; 16);
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
parse_impl!(net::SocketAddrV6);
|
||||
macro_rules! parse_socket_impl {
|
||||
($ty:ty, $new: expr) => {
|
||||
impl<'de> Deserialize<'de> for $ty {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
if deserializer.is_human_readable() {
|
||||
let s = try!(String::deserialize(deserializer));
|
||||
s.parse().map_err(Error::custom)
|
||||
} else {
|
||||
<(_, u16)>::deserialize(deserializer).map(|(ip, port)| $new(ip, port))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<'de> Deserialize<'de> for net::SocketAddr {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
if deserializer.is_human_readable() {
|
||||
let s = try!(String::deserialize(deserializer));
|
||||
s.parse().map_err(Error::custom)
|
||||
} else {
|
||||
use lib::net::SocketAddr;
|
||||
deserialize_enum!{
|
||||
SocketAddr SocketAddrKind (V4; b"V4"; 0, V6; b"V6"; 1)
|
||||
"`V4` or `V6`",
|
||||
deserializer
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
parse_socket_impl!(net::SocketAddrV4, net::SocketAddrV4::new);
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
parse_socket_impl!(net::SocketAddrV6, |ip, port| net::SocketAddrV6::new(ip, port, 0, 0));
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
struct PathVisitor;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<'a> Visitor<'a> for PathVisitor {
|
||||
type Value = &'a Path;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("a borrowed path")
|
||||
}
|
||||
|
||||
fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
Ok(v.as_ref())
|
||||
}
|
||||
|
||||
fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
str::from_utf8(v)
|
||||
.map(AsRef::as_ref)
|
||||
.map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<'de: 'a, 'a> Deserialize<'de> for &'a Path {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_str(PathVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
struct PathBufVisitor;
|
||||
|
||||
@@ -940,70 +1153,10 @@ impl<'de> Deserialize<'de> for PathBuf {
|
||||
// #[derive(Deserialize)]
|
||||
// #[serde(variant_identifier)]
|
||||
#[cfg(all(feature = "std", any(unix, windows)))]
|
||||
enum OsStringKind {
|
||||
Unix,
|
||||
Windows,
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "std", any(unix, windows)))]
|
||||
static OSSTR_VARIANTS: &'static [&'static str] = &["Unix", "Windows"];
|
||||
|
||||
#[cfg(all(feature = "std", any(unix, windows)))]
|
||||
impl<'de> Deserialize<'de> for OsStringKind {
|
||||
fn deserialize<D>(deserializer: D) -> Result<OsStringKind, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
struct KindVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for KindVisitor {
|
||||
type Value = OsStringKind;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("`Unix` or `Windows`")
|
||||
}
|
||||
|
||||
fn visit_u32<E>(self, value: u32) -> Result<OsStringKind, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
match value {
|
||||
0 => Ok(OsStringKind::Unix),
|
||||
1 => Ok(OsStringKind::Windows),
|
||||
_ => Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self),),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, value: &str) -> Result<OsStringKind, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
match value {
|
||||
"Unix" => Ok(OsStringKind::Unix),
|
||||
"Windows" => Ok(OsStringKind::Windows),
|
||||
_ => Err(Error::unknown_variant(value, OSSTR_VARIANTS)),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_bytes<E>(self, value: &[u8]) -> Result<OsStringKind, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
match value {
|
||||
b"Unix" => Ok(OsStringKind::Unix),
|
||||
b"Windows" => Ok(OsStringKind::Windows),
|
||||
_ => {
|
||||
match str::from_utf8(value) {
|
||||
Ok(value) => Err(Error::unknown_variant(value, OSSTR_VARIANTS)),
|
||||
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
deserializer.deserialize_identifier(KindVisitor)
|
||||
}
|
||||
variant_identifier!{
|
||||
OsStringKind (Unix; b"Unix"; 0, Windows; b"Windows"; 1)
|
||||
"`Unix` or `Windows`",
|
||||
OSSTR_VARIANTS
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "std", any(unix, windows)))]
|
||||
@@ -1060,68 +1213,21 @@ impl<'de> Deserialize<'de> for OsString {
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'de, T> Deserialize<'de> for Box<T>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Box<T>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
T::deserialize(deserializer).map(Box::new)
|
||||
}
|
||||
}
|
||||
forwarded_impl!((T), Box<T>, Box::new);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'de, T> Deserialize<'de> for Box<[T]>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Box<[T]>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Vec::<T>::deserialize(deserializer).map(Vec::into_boxed_slice)
|
||||
}
|
||||
}
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
forwarded_impl!((T), Box<[T]>, Vec::into_boxed_slice);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
impl<'de> Deserialize<'de> for Box<str> {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
String::deserialize(deserializer).map(String::into_boxed_str)
|
||||
}
|
||||
}
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
forwarded_impl!((), Box<str>, String::into_boxed_str);
|
||||
|
||||
#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
impl<'de, T> Deserialize<'de> for Arc<T>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Arc<T>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
T::deserialize(deserializer).map(Arc::new)
|
||||
}
|
||||
}
|
||||
#[cfg(all(not(feature = "unstable"), feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
forwarded_impl!((T), Arc<T>, Arc::new);
|
||||
|
||||
#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
impl<'de, T> Deserialize<'de> for Rc<T>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Rc<T>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
T::deserialize(deserializer).map(Rc::new)
|
||||
}
|
||||
}
|
||||
#[cfg(all(not(feature = "unstable"), feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
forwarded_impl!((T), Rc<T>, Rc::new);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'de, 'a, T: ?Sized> Deserialize<'de> for Cow<'a, T>
|
||||
where
|
||||
T: ToOwned,
|
||||
@@ -1138,6 +1244,31 @@ where
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(all(feature = "unstable", feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
macro_rules! box_forwarded_impl {
|
||||
($t:ident) => {
|
||||
impl<'de, T: ?Sized> Deserialize<'de> for $t<T>
|
||||
where
|
||||
Box<T>: Deserialize<'de>,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Box::deserialize(deserializer).map(Into::into)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "unstable", feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
box_forwarded_impl!(Rc);
|
||||
|
||||
#[cfg(all(feature = "unstable", feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
box_forwarded_impl!(Arc);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<'de, T> Deserialize<'de> for Cell<T>
|
||||
where
|
||||
T: Deserialize<'de> + Copy,
|
||||
@@ -1150,43 +1281,13 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, T> Deserialize<'de> for RefCell<T>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<RefCell<T>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
T::deserialize(deserializer).map(RefCell::new)
|
||||
}
|
||||
}
|
||||
forwarded_impl!((T), RefCell<T>, RefCell::new);
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<'de, T> Deserialize<'de> for Mutex<T>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Mutex<T>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
T::deserialize(deserializer).map(Mutex::new)
|
||||
}
|
||||
}
|
||||
forwarded_impl!((T), Mutex<T>, Mutex::new);
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<'de, T> Deserialize<'de> for RwLock<T>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<RwLock<T>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
T::deserialize(deserializer).map(RwLock::new)
|
||||
}
|
||||
}
|
||||
forwarded_impl!((T), RwLock<T>, RwLock::new);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -1326,6 +1427,132 @@ impl<'de> Deserialize<'de> for Duration {
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<'de> Deserialize<'de> for SystemTime {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
// Reuse duration
|
||||
enum Field {
|
||||
Secs,
|
||||
Nanos,
|
||||
};
|
||||
|
||||
impl<'de> Deserialize<'de> for Field {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
struct FieldVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for FieldVisitor {
|
||||
type Value = Field;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("`secs_since_epoch` or `nanos_since_epoch`")
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, value: &str) -> Result<Field, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
match value {
|
||||
"secs_since_epoch" => Ok(Field::Secs),
|
||||
"nanos_since_epoch" => Ok(Field::Nanos),
|
||||
_ => Err(Error::unknown_field(value, FIELDS)),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
match value {
|
||||
b"secs_since_epoch" => Ok(Field::Secs),
|
||||
b"nanos_since_epoch" => Ok(Field::Nanos),
|
||||
_ => {
|
||||
let value = String::from_utf8_lossy(value);
|
||||
Err(Error::unknown_field(&value, FIELDS))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
deserializer.deserialize_identifier(FieldVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
struct DurationVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for DurationVisitor {
|
||||
type Value = Duration;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("struct SystemTime")
|
||||
}
|
||||
|
||||
fn visit_seq<A>(self, mut seq: A) -> Result<Duration, A::Error>
|
||||
where
|
||||
A: SeqAccess<'de>,
|
||||
{
|
||||
let secs: u64 = match try!(seq.next_element()) {
|
||||
Some(value) => value,
|
||||
None => {
|
||||
return Err(Error::invalid_length(0, &self));
|
||||
}
|
||||
};
|
||||
let nanos: u32 = match try!(seq.next_element()) {
|
||||
Some(value) => value,
|
||||
None => {
|
||||
return Err(Error::invalid_length(1, &self));
|
||||
}
|
||||
};
|
||||
Ok(Duration::new(secs, nanos))
|
||||
}
|
||||
|
||||
fn visit_map<A>(self, mut map: A) -> Result<Duration, A::Error>
|
||||
where
|
||||
A: MapAccess<'de>,
|
||||
{
|
||||
let mut secs: Option<u64> = None;
|
||||
let mut nanos: Option<u32> = None;
|
||||
while let Some(key) = try!(map.next_key()) {
|
||||
match key {
|
||||
Field::Secs => {
|
||||
if secs.is_some() {
|
||||
return Err(<A::Error as Error>::duplicate_field("secs_since_epoch"));
|
||||
}
|
||||
secs = Some(try!(map.next_value()));
|
||||
}
|
||||
Field::Nanos => {
|
||||
if nanos.is_some() {
|
||||
return Err(<A::Error as Error>::duplicate_field("nanos_since_epoch"));
|
||||
}
|
||||
nanos = Some(try!(map.next_value()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let secs = match secs {
|
||||
Some(secs) => secs,
|
||||
None => return Err(<A::Error as Error>::missing_field("secs_since_epoch")),
|
||||
};
|
||||
let nanos = match nanos {
|
||||
Some(nanos) => nanos,
|
||||
None => return Err(<A::Error as Error>::missing_field("nanos_since_epoch")),
|
||||
};
|
||||
Ok(Duration::new(secs, nanos))
|
||||
}
|
||||
}
|
||||
|
||||
const FIELDS: &'static [&'static str] = &["secs_since_epoch", "nanos_since_epoch"];
|
||||
let duration = try!(deserializer.deserialize_struct("SystemTime", FIELDS, DurationVisitor));
|
||||
Ok(UNIX_EPOCH + duration)
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Similar to:
|
||||
//
|
||||
// #[derive(Deserialize)]
|
||||
@@ -1480,14 +1707,9 @@ where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let value = try!(Deserialize::deserialize(deserializer));
|
||||
unsafe {
|
||||
let ptr = &value as *const T as *const u8;
|
||||
if slice::from_raw_parts(ptr, mem::size_of::<T>()).iter().all(|&b| b == 0) {
|
||||
return Err(Error::custom("expected a non-zero value"));
|
||||
}
|
||||
// Waiting for a safe way to construct NonZero<T>:
|
||||
// https://github.com/rust-lang/rust/issues/27730#issuecomment-269726075
|
||||
Ok(NonZero::new(value))
|
||||
match NonZero::new(value) {
|
||||
Some(nonzero) => Ok(nonzero),
|
||||
None => Err(Error::custom("expected a non-zero value")),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1603,3 +1825,18 @@ where
|
||||
deserializer.deserialize_enum("Result", VARIANTS, ResultVisitor(PhantomData))
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<'de, T> Deserialize<'de> for Wrapping<T>
|
||||
where
|
||||
T: Deserialize<'de>
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Wrapping<T>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Deserialize::deserialize(deserializer).map(Wrapping)
|
||||
}
|
||||
}
|
||||
|
||||
+73
-4
@@ -94,6 +94,7 @@
|
||||
//! - OsString
|
||||
//! - **Miscellaneous standard library types**:
|
||||
//! - Duration
|
||||
//! - SystemTime
|
||||
//! - Path
|
||||
//! - PathBuf
|
||||
//! - Range\<T\>
|
||||
@@ -1010,6 +1011,74 @@ pub trait Deserializer<'de>: Sized {
|
||||
fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>;
|
||||
|
||||
/// Determine whether `Deserialize` implementations should expect to
|
||||
/// deserialize their human-readable form.
|
||||
///
|
||||
/// Some types have a human-readable form that may be somewhat expensive to
|
||||
/// construct, as well as a binary form that is compact and efficient.
|
||||
/// Generally text-based formats like JSON and YAML will prefer to use the
|
||||
/// human-readable one and binary formats like Bincode will prefer the
|
||||
/// compact one.
|
||||
///
|
||||
/// ```
|
||||
/// # use std::ops::Add;
|
||||
/// # use std::str::FromStr;
|
||||
/// #
|
||||
/// # struct Timestamp;
|
||||
/// #
|
||||
/// # impl Timestamp {
|
||||
/// # const EPOCH: Timestamp = Timestamp;
|
||||
/// # }
|
||||
/// #
|
||||
/// # impl FromStr for Timestamp {
|
||||
/// # type Err = String;
|
||||
/// # fn from_str(_: &str) -> Result<Self, Self::Err> {
|
||||
/// # unimplemented!()
|
||||
/// # }
|
||||
/// # }
|
||||
/// #
|
||||
/// # struct Duration;
|
||||
/// #
|
||||
/// # impl Duration {
|
||||
/// # fn seconds(_: u64) -> Self { unimplemented!() }
|
||||
/// # }
|
||||
/// #
|
||||
/// # impl Add<Duration> for Timestamp {
|
||||
/// # type Output = Timestamp;
|
||||
/// # fn add(self, _: Duration) -> Self::Output {
|
||||
/// # unimplemented!()
|
||||
/// # }
|
||||
/// # }
|
||||
/// #
|
||||
/// use serde::de::{self, Deserialize, Deserializer};
|
||||
///
|
||||
/// impl<'de> Deserialize<'de> for Timestamp {
|
||||
/// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
/// where D: Deserializer<'de>
|
||||
/// {
|
||||
/// if deserializer.is_human_readable() {
|
||||
/// // Deserialize from a human-readable string like "2015-05-15T17:01:00Z".
|
||||
/// let s = String::deserialize(deserializer)?;
|
||||
/// Timestamp::from_str(&s).map_err(de::Error::custom)
|
||||
/// } else {
|
||||
/// // Deserialize from a compact binary representation, seconds since
|
||||
/// // the Unix epoch.
|
||||
/// let n = u64::deserialize(deserializer)?;
|
||||
/// Ok(Timestamp::EPOCH + Duration::seconds(n))
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The default implementation of this method returns `true`. Data formats
|
||||
/// may override this to `false` to request a compact form for types that
|
||||
/// support one. Note that modifying this method to change a format from
|
||||
/// human-readable to compact or vice versa should be regarded as a breaking
|
||||
/// change, as a value serialized in human-readable mode is not required to
|
||||
/// deserialize from the same data in compact mode.
|
||||
#[inline]
|
||||
fn is_human_readable(&self) -> bool { true }
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
@@ -1119,7 +1188,7 @@ pub trait Visitor<'de>: Sized {
|
||||
self.visit_i64(v as i64)
|
||||
}
|
||||
|
||||
/// The input contains an `i32`.
|
||||
/// The input contains an `i64`.
|
||||
///
|
||||
/// The default implementation fails with a type error.
|
||||
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
|
||||
@@ -1262,7 +1331,7 @@ pub trait Visitor<'de>: Sized {
|
||||
/// The default implementation forwards to `visit_str` and then drops the
|
||||
/// `String`.
|
||||
#[inline]
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
@@ -1321,7 +1390,7 @@ pub trait Visitor<'de>: Sized {
|
||||
///
|
||||
/// The default implementation forwards to `visit_bytes` and then drops the
|
||||
/// `Vec<u8>`.
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
@@ -1423,7 +1492,7 @@ pub trait SeqAccess<'de> {
|
||||
/// `Ok(None)` if there are no more remaining items.
|
||||
///
|
||||
/// `Deserialize` implementations should typically use
|
||||
/// `SeqAcccess::next_element` instead.
|
||||
/// `SeqAccess::next_element` instead.
|
||||
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
|
||||
where
|
||||
T: DeserializeSeed<'de>;
|
||||
|
||||
+135
-24
@@ -51,13 +51,13 @@ pub struct Error {
|
||||
err: ErrorImpl,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
type ErrorImpl = Box<str>;
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
type ErrorImpl = ();
|
||||
|
||||
impl de::Error for Error {
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
fn custom<T>(msg: T) -> Self
|
||||
where
|
||||
T: Display,
|
||||
@@ -65,7 +65,7 @@ impl de::Error for Error {
|
||||
Error { err: msg.to_string().into_boxed_str() }
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
fn custom<T>(msg: T) -> Self
|
||||
where
|
||||
T: Display,
|
||||
@@ -85,12 +85,12 @@ impl ser::Error for Error {
|
||||
}
|
||||
|
||||
impl Display for Error {
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||
formatter.write_str(&self.err)
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||
formatter.write_str("Serde deserialization error")
|
||||
}
|
||||
@@ -355,15 +355,84 @@ where
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// A deserializer holding a `&str` with a lifetime tied to another
|
||||
/// deserializer.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BorrowedStrDeserializer<'de, E> {
|
||||
value: &'de str,
|
||||
marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<'de, E> BorrowedStrDeserializer<'de, E> {
|
||||
/// Create a new borrowed deserializer from the given string.
|
||||
pub fn new(value: &'de str) -> BorrowedStrDeserializer<'de, E> {
|
||||
BorrowedStrDeserializer {
|
||||
value: value,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, E> de::Deserializer<'de> for BorrowedStrDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_borrowed_str(self.value)
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(
|
||||
self,
|
||||
name: &str,
|
||||
variants: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: de::Visitor<'de>,
|
||||
{
|
||||
let _ = name;
|
||||
let _ = variants;
|
||||
visitor.visit_enum(self)
|
||||
}
|
||||
|
||||
forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
|
||||
byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
|
||||
map struct identifier ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, E> de::EnumAccess<'de> for BorrowedStrDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
type Error = E;
|
||||
type Variant = private::UnitOnly<E>;
|
||||
|
||||
fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
|
||||
where
|
||||
T: de::DeserializeSeed<'de>,
|
||||
{
|
||||
seed.deserialize(self).map(private::unit_only)
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// A deserializer holding a `String`.
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StringDeserializer<E> {
|
||||
value: String,
|
||||
marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'de, E> IntoDeserializer<'de, E> for String
|
||||
where
|
||||
E: de::Error,
|
||||
@@ -378,7 +447,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'de, E> de::Deserializer<'de> for StringDeserializer<E>
|
||||
where
|
||||
E: de::Error,
|
||||
@@ -413,7 +482,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'de, 'a, E> de::EnumAccess<'de> for StringDeserializer<E>
|
||||
where
|
||||
E: de::Error,
|
||||
@@ -432,14 +501,14 @@ where
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// A deserializer holding a `Cow<str>`.
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CowStrDeserializer<'a, E> {
|
||||
value: Cow<'a, str>,
|
||||
marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'de, 'a, E> IntoDeserializer<'de, E> for Cow<'a, str>
|
||||
where
|
||||
E: de::Error,
|
||||
@@ -454,7 +523,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'de, 'a, E> de::Deserializer<'de> for CowStrDeserializer<'a, E>
|
||||
where
|
||||
E: de::Error,
|
||||
@@ -492,7 +561,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'de, 'a, E> de::EnumAccess<'de> for CowStrDeserializer<'a, E>
|
||||
where
|
||||
E: de::Error,
|
||||
@@ -510,6 +579,46 @@ where
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// A deserializer holding a `&[u8]` with a lifetime tied to another
|
||||
/// deserializer.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BorrowedBytesDeserializer<'de, E> {
|
||||
value: &'de [u8],
|
||||
marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<'de, E> BorrowedBytesDeserializer<'de, E> {
|
||||
/// Create a new borrowed deserializer from the given byte slice.
|
||||
pub fn new(value: &'de [u8]) -> BorrowedBytesDeserializer<'de, E> {
|
||||
BorrowedBytesDeserializer {
|
||||
value: value,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, E> de::Deserializer<'de> for BorrowedBytesDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_borrowed_bytes(self.value)
|
||||
}
|
||||
|
||||
forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
|
||||
byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
|
||||
map struct identifier ignored_any enum
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// A deserializer that iterates over a sequence.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SeqDeserializer<I, E> {
|
||||
@@ -618,26 +727,26 @@ impl Expected for ExpectedInSeq {
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'de, T, E> IntoDeserializer<'de, E> for Vec<T>
|
||||
where
|
||||
T: IntoDeserializer<'de, E>,
|
||||
E: de::Error,
|
||||
{
|
||||
type Deserializer = SeqDeserializer<<Vec<T> as IntoIterator>::IntoIter, E>;
|
||||
type Deserializer = SeqDeserializer<<Self as IntoIterator>::IntoIter, E>;
|
||||
|
||||
fn into_deserializer(self) -> Self::Deserializer {
|
||||
SeqDeserializer::new(self.into_iter())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'de, T, E> IntoDeserializer<'de, E> for BTreeSet<T>
|
||||
where
|
||||
T: IntoDeserializer<'de, E> + Eq + Ord,
|
||||
E: de::Error,
|
||||
{
|
||||
type Deserializer = SeqDeserializer<<BTreeSet<T> as IntoIterator>::IntoIter, E>;
|
||||
type Deserializer = SeqDeserializer<<Self as IntoIterator>::IntoIter, E>;
|
||||
|
||||
fn into_deserializer(self) -> Self::Deserializer {
|
||||
SeqDeserializer::new(self.into_iter())
|
||||
@@ -645,12 +754,13 @@ where
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<'de, T, E> IntoDeserializer<'de, E> for HashSet<T>
|
||||
impl<'de, T, S, E> IntoDeserializer<'de, E> for HashSet<T, S>
|
||||
where
|
||||
T: IntoDeserializer<'de, E> + Eq + Hash,
|
||||
S: BuildHasher,
|
||||
E: de::Error,
|
||||
{
|
||||
type Deserializer = SeqDeserializer<<HashSet<T> as IntoIterator>::IntoIter, E>;
|
||||
type Deserializer = SeqDeserializer<<Self as IntoIterator>::IntoIter, E>;
|
||||
|
||||
fn into_deserializer(self) -> Self::Deserializer {
|
||||
SeqDeserializer::new(self.into_iter())
|
||||
@@ -1036,14 +1146,14 @@ impl Expected for ExpectedInMap {
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'de, K, V, E> IntoDeserializer<'de, E> for BTreeMap<K, V>
|
||||
where
|
||||
K: IntoDeserializer<'de, E> + Eq + Ord,
|
||||
V: IntoDeserializer<'de, E>,
|
||||
E: de::Error,
|
||||
{
|
||||
type Deserializer = MapDeserializer<'de, <BTreeMap<K, V> as IntoIterator>::IntoIter, E>;
|
||||
type Deserializer = MapDeserializer<'de, <Self as IntoIterator>::IntoIter, E>;
|
||||
|
||||
fn into_deserializer(self) -> Self::Deserializer {
|
||||
MapDeserializer::new(self.into_iter())
|
||||
@@ -1051,13 +1161,14 @@ where
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<'de, K, V, E> IntoDeserializer<'de, E> for HashMap<K, V>
|
||||
impl<'de, K, V, S, E> IntoDeserializer<'de, E> for HashMap<K, V, S>
|
||||
where
|
||||
K: IntoDeserializer<'de, E> + Eq + Hash,
|
||||
V: IntoDeserializer<'de, E>,
|
||||
S: BuildHasher,
|
||||
E: de::Error,
|
||||
{
|
||||
type Deserializer = MapDeserializer<'de, <HashMap<K, V> as IntoIterator>::IntoIter, E>;
|
||||
type Deserializer = MapDeserializer<'de, <Self as IntoIterator>::IntoIter, E>;
|
||||
|
||||
fn into_deserializer(self) -> Self::Deserializer {
|
||||
MapDeserializer::new(self.into_iter())
|
||||
|
||||
+2
-2
@@ -19,7 +19,7 @@ pub use self::string::from_utf8_lossy;
|
||||
mod string {
|
||||
use lib::*;
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub fn from_utf8_lossy(bytes: &[u8]) -> Cow<str> {
|
||||
String::from_utf8_lossy(bytes)
|
||||
}
|
||||
@@ -31,7 +31,7 @@ mod string {
|
||||
//
|
||||
// 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 = "std", feature = "collections")))]
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
pub fn from_utf8_lossy(bytes: &[u8]) -> &str {
|
||||
// Three unicode replacement characters if it fails. They look like a
|
||||
// white-on-black question mark. The user will recognize it as invalid
|
||||
|
||||
+49
-23
@@ -79,7 +79,7 @@
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Serde types in rustdoc of other crates get linked to here.
|
||||
#![doc(html_root_url = "https://docs.rs/serde/1.0.1")]
|
||||
#![doc(html_root_url = "https://docs.rs/serde/1.0.22")]
|
||||
|
||||
// Support using Serde without the standard library!
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
@@ -89,33 +89,57 @@
|
||||
//
|
||||
// https://github.com/serde-rs/serde/issues/812
|
||||
#![cfg_attr(feature = "unstable", feature(nonzero, specialization))]
|
||||
#![cfg_attr(all(feature = "std", feature = "unstable"), feature(into_boxed_c_str))]
|
||||
#![cfg_attr(feature = "alloc", feature(alloc))]
|
||||
#![cfg_attr(feature = "collections", feature(collections))]
|
||||
|
||||
// Whitelisted clippy lints.
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(doc_markdown))]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(linkedlist))]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(type_complexity))]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(zero_prefixed_literal))]
|
||||
#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))]
|
||||
// Whitelisted clippy lints
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(
|
||||
cast_lossless,
|
||||
const_static_lifetime,
|
||||
doc_markdown,
|
||||
linkedlist,
|
||||
needless_pass_by_value,
|
||||
type_complexity,
|
||||
unreadable_literal,
|
||||
zero_prefixed_literal,
|
||||
))]
|
||||
// Whitelisted clippy_pedantic lints
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(
|
||||
// integer and float ser/de requires these sorts of casts
|
||||
cast_possible_truncation,
|
||||
cast_possible_wrap,
|
||||
cast_precision_loss,
|
||||
cast_sign_loss,
|
||||
// simplifies some macros
|
||||
invalid_upcast_comparisons,
|
||||
// things are often more readable this way
|
||||
option_unwrap_used,
|
||||
result_unwrap_used,
|
||||
shadow_reuse,
|
||||
single_match_else,
|
||||
stutter,
|
||||
use_self,
|
||||
// not practical
|
||||
missing_docs_in_private_items,
|
||||
// alternative is not stable
|
||||
empty_enum,
|
||||
use_debug,
|
||||
))]
|
||||
|
||||
// Blacklisted Rust lints.
|
||||
#![deny(missing_docs, unused_imports)]
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "collections")]
|
||||
extern crate collections;
|
||||
|
||||
#[cfg(feature = "alloc")]
|
||||
extern crate alloc;
|
||||
|
||||
#[cfg(all(feature = "unstable", feature = "std"))]
|
||||
extern crate core;
|
||||
|
||||
/// A facade around all the types we need from the `std`, `core`, `alloc`, and
|
||||
/// `collections` crates. This avoids elaborate import wrangling having to
|
||||
/// happen in every module.
|
||||
/// A facade around all the types we need from the `std`, `core`, and `alloc`
|
||||
/// crates. This avoids elaborate import wrangling having to happen in every
|
||||
/// module.
|
||||
mod lib {
|
||||
mod core {
|
||||
#[cfg(feature = "std")]
|
||||
@@ -140,18 +164,18 @@ mod lib {
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::borrow::{Cow, ToOwned};
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
pub use collections::borrow::{Cow, ToOwned};
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
pub use alloc::borrow::{Cow, ToOwned};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::string::String;
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
pub use collections::string::{String, ToString};
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
pub use alloc::string::{String, ToString};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::vec::Vec;
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
pub use collections::vec::Vec;
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
pub use alloc::vec::Vec;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::boxed::Box;
|
||||
@@ -170,8 +194,8 @@ mod lib {
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::collections::{BinaryHeap, BTreeMap, BTreeSet, LinkedList, VecDeque};
|
||||
#[cfg(all(feature = "collections", not(feature = "std")))]
|
||||
pub use collections::{BinaryHeap, BTreeMap, BTreeSet, LinkedList, VecDeque};
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
pub use alloc::{BinaryHeap, BTreeMap, BTreeSet, LinkedList, VecDeque};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::{error, net};
|
||||
@@ -185,9 +209,11 @@ mod lib {
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::io::Write;
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::num::Wrapping;
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::path::{Path, PathBuf};
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::time::Duration;
|
||||
pub use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::sync::{Mutex, RwLock};
|
||||
|
||||
|
||||
+296
-131
File diff suppressed because it is too large
Load Diff
+16
-16
@@ -10,7 +10,7 @@ use lib::*;
|
||||
|
||||
use ser::{self, Serialize, Serializer, SerializeMap, SerializeStruct, Impossible};
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
use self::content::{SerializeTupleVariantAsMapValue, SerializeStructVariantAsMapValue};
|
||||
|
||||
/// Used to check that serde(getter) attributes return the expected type.
|
||||
@@ -60,11 +60,10 @@ enum Unsupported {
|
||||
ByteArray,
|
||||
Optional,
|
||||
Unit,
|
||||
UnitStruct,
|
||||
Sequence,
|
||||
Tuple,
|
||||
TupleStruct,
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
Enum,
|
||||
}
|
||||
|
||||
@@ -79,11 +78,10 @@ impl Display for Unsupported {
|
||||
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"),
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
Unsupported::Enum => formatter.write_str("an enum"),
|
||||
}
|
||||
}
|
||||
@@ -117,14 +115,14 @@ where
|
||||
type SerializeMap = S::SerializeMap;
|
||||
type SerializeStruct = S::SerializeStruct;
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
type SerializeTupleVariant = Impossible<S::Ok, S::Error>;
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
type SerializeTupleVariant = SerializeTupleVariantAsMapValue<S::SerializeMap>;
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
type SerializeStructVariant = Impossible<S::Ok, S::Error>;
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
type SerializeStructVariant = SerializeStructVariantAsMapValue<S::SerializeMap>;
|
||||
|
||||
fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
|
||||
@@ -199,7 +197,9 @@ where
|
||||
}
|
||||
|
||||
fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::UnitStruct))
|
||||
let mut map = try!(self.delegate.serialize_map(Some(1)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
map.end()
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(
|
||||
@@ -257,7 +257,7 @@ where
|
||||
Err(self.bad_type(Unsupported::TupleStruct))
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
fn serialize_tuple_variant(
|
||||
self,
|
||||
_: &'static str,
|
||||
@@ -270,7 +270,7 @@ where
|
||||
Err(self.bad_type(Unsupported::Enum))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
fn serialize_tuple_variant(
|
||||
self,
|
||||
_: &'static str,
|
||||
@@ -300,7 +300,7 @@ where
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
fn serialize_struct_variant(
|
||||
self,
|
||||
_: &'static str,
|
||||
@@ -313,7 +313,7 @@ where
|
||||
Err(self.bad_type(Unsupported::Enum))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
fn serialize_struct_variant(
|
||||
self,
|
||||
_: &'static str,
|
||||
@@ -327,7 +327,7 @@ where
|
||||
Ok(SerializeStructVariantAsMapValue::new(map, inner_variant, len),)
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
fn collect_str<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Display,
|
||||
@@ -363,7 +363,7 @@ impl Display for Error {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
mod content {
|
||||
use lib::*;
|
||||
|
||||
|
||||
+110
-31
@@ -56,7 +56,7 @@ impl Serialize for str {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl Serialize for String {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
@@ -177,6 +177,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
macro_rules! seq_impl {
|
||||
($ty:ident < T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound:ident)* >) => {
|
||||
impl<T $(, $typaram)*> Serialize for $ty<T $(, $typaram)*>
|
||||
@@ -195,22 +196,22 @@ macro_rules! seq_impl {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(BinaryHeap<T: Ord>);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(BTreeSet<T: Ord>);
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
seq_impl!(HashSet<T: Eq + Hash, H: BuildHasher>);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(LinkedList<T>);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(Vec<T>);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(VecDeque<T>);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
@@ -290,6 +291,7 @@ tuple_impls! {
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
macro_rules! map_impl {
|
||||
($ty:ident < K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound:ident)* >) => {
|
||||
impl<K, V $(, $typaram)*> Serialize for $ty<K, V $(, $typaram)*>
|
||||
@@ -309,7 +311,7 @@ macro_rules! map_impl {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
map_impl!(BTreeMap<K: Ord, V>);
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
@@ -338,19 +340,29 @@ deref_impl!(<'a, T: ?Sized> Serialize for &'a mut T where T: Serialize);
|
||||
deref_impl!(<T: ?Sized> Serialize for Box<T> where T: Serialize);
|
||||
|
||||
#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
deref_impl!(<T> Serialize for Rc<T> where T: Serialize);
|
||||
deref_impl!(<T: ?Sized> Serialize for Rc<T> where T: Serialize);
|
||||
|
||||
#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
deref_impl!(<T> Serialize for Arc<T> where T: Serialize);
|
||||
deref_impl!(<T: ?Sized> Serialize for Arc<T> where T: Serialize);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
deref_impl!(<'a, T: ?Sized> Serialize for Cow<'a, T> where T: Serialize + ToOwned);
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
deref_impl!(<T> Serialize for NonZero<T> where T: Serialize + Zeroable);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
impl<T> Serialize for NonZero<T>
|
||||
where
|
||||
T: Serialize + Zeroable + Clone,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
self.clone().get().serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Serialize for Cell<T>
|
||||
where
|
||||
T: Serialize + Copy,
|
||||
@@ -445,6 +457,23 @@ impl Serialize for Duration {
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl Serialize for SystemTime {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
use super::SerializeStruct;
|
||||
let duration_since_epoch = self.duration_since(UNIX_EPOCH).expect("SystemTime must be later than UNIX_EPOCH");
|
||||
let mut state = try!(serializer.serialize_struct("SystemTime", 2));
|
||||
try!(state.serialize_field("secs_since_epoch", &duration_since_epoch.as_secs()));
|
||||
try!(state.serialize_field("nanos_since_epoch", &duration_since_epoch.subsec_nanos()));
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// Serialize a value that implements `Display` as a string, when that string is
|
||||
/// statically known to never have more than a constant `MAX_LEN` bytes.
|
||||
///
|
||||
@@ -477,9 +506,18 @@ impl Serialize for net::IpAddr {
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
match *self {
|
||||
net::IpAddr::V4(ref a) => a.serialize(serializer),
|
||||
net::IpAddr::V6(ref a) => a.serialize(serializer),
|
||||
if serializer.is_human_readable() {
|
||||
match *self {
|
||||
net::IpAddr::V4(ref a) => a.serialize(serializer),
|
||||
net::IpAddr::V6(ref a) => a.serialize(serializer),
|
||||
}
|
||||
} else {
|
||||
match *self {
|
||||
net::IpAddr::V4(ref a) =>
|
||||
serializer.serialize_newtype_variant("IpAddr", 0, "V4", a),
|
||||
net::IpAddr::V6(ref a) =>
|
||||
serializer.serialize_newtype_variant("IpAddr", 1, "V6", a),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -490,9 +528,13 @@ impl Serialize for net::Ipv4Addr {
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
/// "101.102.103.104".len()
|
||||
const MAX_LEN: usize = 15;
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
if serializer.is_human_readable() {
|
||||
const MAX_LEN: usize = 15;
|
||||
debug_assert_eq!(MAX_LEN, "101.102.103.104".len());
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
} else {
|
||||
self.octets().serialize(serializer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -502,9 +544,13 @@ impl Serialize for net::Ipv6Addr {
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
/// "1000:1002:1003:1004:1005:1006:1007:1008".len()
|
||||
const MAX_LEN: usize = 39;
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
if serializer.is_human_readable() {
|
||||
const MAX_LEN: usize = 39;
|
||||
debug_assert_eq!(MAX_LEN, "1001:1002:1003:1004:1005:1006:1007:1008".len());
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
} else {
|
||||
self.octets().serialize(serializer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -514,9 +560,18 @@ impl Serialize for net::SocketAddr {
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
match *self {
|
||||
net::SocketAddr::V4(ref addr) => addr.serialize(serializer),
|
||||
net::SocketAddr::V6(ref addr) => addr.serialize(serializer),
|
||||
if serializer.is_human_readable() {
|
||||
match *self {
|
||||
net::SocketAddr::V4(ref addr) => addr.serialize(serializer),
|
||||
net::SocketAddr::V6(ref addr) => addr.serialize(serializer),
|
||||
}
|
||||
} else {
|
||||
match *self {
|
||||
net::SocketAddr::V4(ref addr) =>
|
||||
serializer.serialize_newtype_variant("SocketAddr", 0, "V4", addr),
|
||||
net::SocketAddr::V6(ref addr) =>
|
||||
serializer.serialize_newtype_variant("SocketAddr", 1, "V6", addr),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -527,9 +582,13 @@ impl Serialize for net::SocketAddrV4 {
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
/// "101.102.103.104:65000".len()
|
||||
const MAX_LEN: usize = 21;
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
if serializer.is_human_readable() {
|
||||
const MAX_LEN: usize = 21;
|
||||
debug_assert_eq!(MAX_LEN, "101.102.103.104:65000".len());
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
} else {
|
||||
(self.ip(), self.port()).serialize(serializer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -539,9 +598,13 @@ impl Serialize for net::SocketAddrV6 {
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
/// "[1000:1002:1003:1004:1005:1006:1007:1008]:65000".len()
|
||||
const MAX_LEN: usize = 47;
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
if serializer.is_human_readable() {
|
||||
const MAX_LEN: usize = 47;
|
||||
debug_assert_eq!(MAX_LEN, "[1001:1002:1003:1004:1005:1006:1007:1008]:65000".len());
|
||||
serialize_display_bounded_length!(self, MAX_LEN, serializer)
|
||||
} else {
|
||||
(self.ip(), self.port()).serialize(serializer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -601,3 +664,19 @@ impl Serialize for OsString {
|
||||
self.as_os_str().serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T> Serialize for Wrapping<T>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
self.0.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
+67
-2
@@ -89,6 +89,7 @@
|
||||
//! - OsString
|
||||
//! - **Miscellaneous standard library types**:
|
||||
//! - Duration
|
||||
//! - SystemTime
|
||||
//! - Path
|
||||
//! - PathBuf
|
||||
//! - Range\<T\>
|
||||
@@ -1321,7 +1322,7 @@ pub trait Serializer: Sized {
|
||||
///
|
||||
/// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
|
||||
/// [`serialize_str`]: #tymethod.serialize_str
|
||||
#[cfg(any(feature = "std", feature = "collections"))]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Display,
|
||||
@@ -1358,10 +1359,60 @@ pub trait Serializer: Sized {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[cfg(not(any(feature = "std", feature = "collections")))]
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Display;
|
||||
|
||||
/// Determine whether `Serialize` implementations should serialize in
|
||||
/// human-readable form.
|
||||
///
|
||||
/// Some types have a human-readable form that may be somewhat expensive to
|
||||
/// construct, as well as a binary form that is compact and efficient.
|
||||
/// Generally text-based formats like JSON and YAML will prefer to use the
|
||||
/// human-readable one and binary formats like Bincode will prefer the
|
||||
/// compact one.
|
||||
///
|
||||
/// ```
|
||||
/// # use std::fmt::{self, Display};
|
||||
/// #
|
||||
/// # struct Timestamp;
|
||||
/// #
|
||||
/// # impl Timestamp {
|
||||
/// # fn seconds_since_epoch(&self) -> u64 { unimplemented!() }
|
||||
/// # }
|
||||
/// #
|
||||
/// # impl Display for Timestamp {
|
||||
/// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
/// # unimplemented!()
|
||||
/// # }
|
||||
/// # }
|
||||
/// #
|
||||
/// use serde::{Serialize, Serializer};
|
||||
///
|
||||
/// impl Serialize for Timestamp {
|
||||
/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
/// where S: Serializer
|
||||
/// {
|
||||
/// if serializer.is_human_readable() {
|
||||
/// // Serialize to a human-readable string "2015-05-15T17:01:00Z".
|
||||
/// self.to_string().serialize(serializer)
|
||||
/// } else {
|
||||
/// // Serialize to a compact binary representation.
|
||||
/// self.seconds_since_epoch().serialize(serializer)
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The default implementation of this method returns `true`. Data formats
|
||||
/// may override this to `false` to request a compact form for types that
|
||||
/// support one. Note that modifying this method to change a format from
|
||||
/// human-readable to compact or vice versa should be regarded as a breaking
|
||||
/// change, as a value serialized in human-readable mode is not required to
|
||||
/// deserialize from the same data in compact mode.
|
||||
#[inline]
|
||||
fn is_human_readable(&self) -> bool { true }
|
||||
}
|
||||
|
||||
/// Returned from `Serializer::serialize_seq`.
|
||||
@@ -1726,6 +1777,13 @@ pub trait SerializeStruct {
|
||||
where
|
||||
T: Serialize;
|
||||
|
||||
/// Indicate that a struct field has been skipped.
|
||||
#[inline]
|
||||
fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
|
||||
let _ = key;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Finish serializing a struct.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
@@ -1771,6 +1829,13 @@ pub trait SerializeStructVariant {
|
||||
where
|
||||
T: Serialize;
|
||||
|
||||
/// Indicate that a struct variant field has been skipped.
|
||||
#[inline]
|
||||
fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
|
||||
let _ = key;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Finish serializing a struct variant.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde_derive"
|
||||
version = "1.0.1" # remember to update html_root_url
|
||||
version = "1.0.22" # remember to update html_root_url
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]"
|
||||
@@ -20,5 +20,8 @@ proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
quote = "0.3.8"
|
||||
serde_derive_internals = { version = "=0.15.0", default-features = false, path = "../serde_derive_internals" }
|
||||
serde_derive_internals = { version = "=0.17.0", default-features = false, path = "../serde_derive_internals" }
|
||||
syn = { version = "0.11", features = ["visit"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde = { version = "1.0", path = "../serde" }
|
||||
|
||||
+28
-10
@@ -10,12 +10,12 @@ use std::collections::HashSet;
|
||||
|
||||
use syn::{self, visit};
|
||||
|
||||
use internals::ast::Container;
|
||||
use internals::ast::{Body, Container};
|
||||
use internals::attr;
|
||||
|
||||
macro_rules! path {
|
||||
($($path:tt)+) => {
|
||||
syn::parse_path(stringify!($($path)+)).unwrap()
|
||||
syn::parse_path(quote!($($path)+).as_str()).unwrap()
|
||||
};
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ pub fn with_bound<F>(
|
||||
bound: &syn::Path,
|
||||
) -> syn::Generics
|
||||
where
|
||||
F: Fn(&attr::Field) -> bool,
|
||||
F: Fn(&attr::Field, Option<&attr::Variant>) -> bool,
|
||||
{
|
||||
struct FindTyParams {
|
||||
// Set of all generic type parameters on the current struct (A, B, C in
|
||||
@@ -116,6 +116,14 @@ where
|
||||
}
|
||||
visit::walk_path(self, path);
|
||||
}
|
||||
|
||||
// Type parameter should not be considered used by a macro path.
|
||||
//
|
||||
// struct TypeMacro<T> {
|
||||
// mac: T!(),
|
||||
// marker: PhantomData<T>,
|
||||
// }
|
||||
fn visit_mac(&mut self, _mac: &syn::Mac) {}
|
||||
}
|
||||
|
||||
let all_ty_params: HashSet<_> = generics
|
||||
@@ -124,17 +132,27 @@ where
|
||||
.map(|ty_param| ty_param.ident.clone())
|
||||
.collect();
|
||||
|
||||
let relevant_tys = cont.body
|
||||
.all_fields()
|
||||
.filter(|&field| filter(&field.attrs))
|
||||
.map(|field| &field.ty);
|
||||
|
||||
let mut visitor = FindTyParams {
|
||||
all_ty_params: all_ty_params,
|
||||
relevant_ty_params: HashSet::new(),
|
||||
};
|
||||
for ty in relevant_tys {
|
||||
visit::walk_ty(&mut visitor, ty);
|
||||
match cont.body {
|
||||
Body::Enum(ref variants) => {
|
||||
for variant in variants.iter() {
|
||||
let relevant_fields = variant
|
||||
.fields
|
||||
.iter()
|
||||
.filter(|field| filter(&field.attrs, Some(&variant.attrs)));
|
||||
for field in relevant_fields {
|
||||
visit::walk_ty(&mut visitor, field.ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
Body::Struct(_, ref fields) => {
|
||||
for field in fields.iter().filter(|field| filter(&field.attrs, None)) {
|
||||
visit::walk_ty(&mut visitor, field.ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let new_predicates = generics
|
||||
|
||||
+312
-113
@@ -23,28 +23,28 @@ pub fn expand_derive_deserialize(input: &syn::DeriveInput) -> Result<Tokens, Str
|
||||
|
||||
let ident = &cont.ident;
|
||||
let params = Parameters::new(&cont);
|
||||
let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(¶ms);
|
||||
let dummy_const = Ident::new(format!("_IMPL_DESERIALIZE_FOR_{}", ident));
|
||||
let body = Stmts(deserialize_body(&cont, ¶ms));
|
||||
let delife = params.borrowed.de_lifetime();
|
||||
|
||||
let impl_block = if let Some(remote) = cont.attrs.remote() {
|
||||
let (impl_generics, ty_generics, where_clause) = cont.generics.split_for_impl();
|
||||
let de_lifetime = params.de_lifetime_def();
|
||||
let vis = &input.vis;
|
||||
quote! {
|
||||
impl #impl_generics #ident #ty_generics #where_clause {
|
||||
fn deserialize<#de_lifetime, __D>(__deserializer: __D) -> _serde::export::Result<#remote #ty_generics, __D::Error>
|
||||
where __D: _serde::Deserializer<'de>
|
||||
impl #de_impl_generics #ident #ty_generics #where_clause {
|
||||
#vis fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<#remote #ty_generics, __D::Error>
|
||||
where __D: _serde::Deserializer<#delife>
|
||||
{
|
||||
#body
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(¶ms);
|
||||
quote! {
|
||||
#[automatically_derived]
|
||||
impl #de_impl_generics _serde::Deserialize<'de> for #ident #ty_generics #where_clause {
|
||||
impl #de_impl_generics _serde::Deserialize<#delife> for #ident #ty_generics #where_clause {
|
||||
fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error>
|
||||
where __D: _serde::Deserializer<'de>
|
||||
where __D: _serde::Deserializer<#delife>
|
||||
{
|
||||
#body
|
||||
}
|
||||
@@ -76,7 +76,7 @@ struct Parameters {
|
||||
|
||||
/// Lifetimes borrowed from the deserializer. These will become bounds on
|
||||
/// the `'de` lifetime of the deserializer.
|
||||
borrowed: BTreeSet<syn::Lifetime>,
|
||||
borrowed: BorrowedLifetimes,
|
||||
|
||||
/// At least one field has a serde(getter) attribute, implying that the
|
||||
/// remote type has a private field.
|
||||
@@ -90,8 +90,8 @@ impl Parameters {
|
||||
Some(remote) => remote.clone(),
|
||||
None => cont.ident.clone().into(),
|
||||
};
|
||||
let generics = build_generics(cont);
|
||||
let borrowed = borrowed_lifetimes(cont);
|
||||
let generics = build_generics(cont, &borrowed);
|
||||
let has_getter = cont.body.has_getter();
|
||||
|
||||
Parameters {
|
||||
@@ -108,20 +108,12 @@ impl Parameters {
|
||||
fn type_name(&self) -> &str {
|
||||
self.this.segments.last().unwrap().ident.as_ref()
|
||||
}
|
||||
|
||||
fn de_lifetime_def(&self) -> syn::LifetimeDef {
|
||||
syn::LifetimeDef {
|
||||
attrs: Vec::new(),
|
||||
lifetime: syn::Lifetime::new("'de"),
|
||||
bounds: self.borrowed.iter().cloned().collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// All the generics in the input, plus a bound `T: Deserialize` for each generic
|
||||
// field type that will be deserialized by us, plus a bound `T: Default` for
|
||||
// each generic field type that will be set to a default value.
|
||||
fn build_generics(cont: &Container) -> syn::Generics {
|
||||
fn build_generics(cont: &Container, borrowed: &BorrowedLifetimes) -> syn::Generics {
|
||||
let generics = bound::without_defaults(cont.generics);
|
||||
|
||||
let generics = bound::with_where_predicates_from_fields(cont, &generics, attr::Field::de_bound);
|
||||
@@ -137,11 +129,12 @@ fn build_generics(cont: &Container) -> syn::Generics {
|
||||
attr::Default::Path(_) => generics,
|
||||
};
|
||||
|
||||
let delife = borrowed.de_lifetime();
|
||||
let generics = bound::with_bound(
|
||||
cont,
|
||||
&generics,
|
||||
needs_deserialize_bound,
|
||||
&path!(_serde::Deserialize<'de>),
|
||||
&path!(_serde::Deserialize<#delife>),
|
||||
);
|
||||
|
||||
bound::with_bound(
|
||||
@@ -158,14 +151,44 @@ fn build_generics(cont: &Container) -> syn::Generics {
|
||||
// deserialized by us so we do not generate a bound. Fields with a `bound`
|
||||
// attribute specify their own bound so we do not generate one. All other fields
|
||||
// may need a `T: Deserialize` bound where T is the type of the field.
|
||||
fn needs_deserialize_bound(attrs: &attr::Field) -> bool {
|
||||
!attrs.skip_deserializing() && attrs.deserialize_with().is_none() && attrs.de_bound().is_none()
|
||||
fn needs_deserialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool {
|
||||
!field.skip_deserializing() &&
|
||||
field.deserialize_with().is_none() &&
|
||||
field.de_bound().is_none() &&
|
||||
variant.map_or(true, |variant| variant.deserialize_with().is_none())
|
||||
}
|
||||
|
||||
// Fields with a `default` attribute (not `default=...`), and fields with a
|
||||
// `skip_deserializing` attribute that do not also have `default=...`.
|
||||
fn requires_default(attrs: &attr::Field) -> bool {
|
||||
attrs.default() == &attr::Default::Default
|
||||
fn requires_default(field: &attr::Field, _variant: Option<&attr::Variant>) -> bool {
|
||||
field.default() == &attr::Default::Default
|
||||
}
|
||||
|
||||
enum BorrowedLifetimes {
|
||||
Borrowed(BTreeSet<syn::Lifetime>),
|
||||
Static,
|
||||
}
|
||||
|
||||
impl BorrowedLifetimes {
|
||||
fn de_lifetime(&self) -> syn::Lifetime {
|
||||
match *self {
|
||||
BorrowedLifetimes::Borrowed(_) => syn::Lifetime::new("'de"),
|
||||
BorrowedLifetimes::Static => syn::Lifetime::new("'static"),
|
||||
}
|
||||
}
|
||||
|
||||
fn de_lifetime_def(&self) -> Option<syn::LifetimeDef> {
|
||||
match *self {
|
||||
BorrowedLifetimes::Borrowed(ref bounds) => {
|
||||
Some(syn::LifetimeDef {
|
||||
attrs: Vec::new(),
|
||||
lifetime: syn::Lifetime::new("'de"),
|
||||
bounds: bounds.iter().cloned().collect(),
|
||||
})
|
||||
}
|
||||
BorrowedLifetimes::Static => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The union of lifetimes borrowed by each field of the container.
|
||||
@@ -174,12 +197,21 @@ fn requires_default(attrs: &attr::Field) -> bool {
|
||||
// lifetimes `'a` and `'b` are borrowed but `'c` is not, the impl is:
|
||||
//
|
||||
// impl<'de: 'a + 'b, 'a, 'b, 'c> Deserialize<'de> for S<'a, 'b, 'c>
|
||||
fn borrowed_lifetimes(cont: &Container) -> BTreeSet<syn::Lifetime> {
|
||||
//
|
||||
// If any borrowed lifetime is `'static`, then `'de: 'static` would be redundant
|
||||
// and we use plain `'static` instead of `'de`.
|
||||
fn borrowed_lifetimes(cont: &Container) -> BorrowedLifetimes {
|
||||
let mut lifetimes = BTreeSet::new();
|
||||
for field in cont.body.all_fields() {
|
||||
lifetimes.extend(field.attrs.borrowed_lifetimes().iter().cloned());
|
||||
if !field.attrs.skip_deserializing() {
|
||||
lifetimes.extend(field.attrs.borrowed_lifetimes().iter().cloned());
|
||||
}
|
||||
}
|
||||
if lifetimes.iter().any(|b| b.ident == "'static") {
|
||||
BorrowedLifetimes::Static
|
||||
} else {
|
||||
BorrowedLifetimes::Borrowed(lifetimes)
|
||||
}
|
||||
lifetimes
|
||||
}
|
||||
|
||||
fn deserialize_body(cont: &Container, params: &Parameters) -> Fragment {
|
||||
@@ -192,7 +224,7 @@ fn deserialize_body(cont: &Container, params: &Parameters) -> Fragment {
|
||||
if fields.iter().any(|field| field.ident.is_none()) {
|
||||
panic!("struct has unnamed fields");
|
||||
}
|
||||
deserialize_struct(None, params, fields, &cont.attrs, None)
|
||||
deserialize_struct(None, params, fields, &cont.attrs, None, Untagged::No)
|
||||
}
|
||||
Body::Struct(Style::Tuple, ref fields) |
|
||||
Body::Struct(Style::Newtype, ref fields) => {
|
||||
@@ -258,6 +290,7 @@ fn deserialize_tuple(
|
||||
) -> Fragment {
|
||||
let this = ¶ms.this;
|
||||
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params,);
|
||||
let delife = params.borrowed.de_lifetime();
|
||||
|
||||
// If there are getters (implying private fields), construct the local type
|
||||
// and use an `Into` conversion to get the remote type. If there are no
|
||||
@@ -319,10 +352,10 @@ fn deserialize_tuple(
|
||||
quote_block! {
|
||||
struct __Visitor #de_impl_generics #where_clause {
|
||||
marker: _serde::export::PhantomData<#this #ty_generics>,
|
||||
lifetime: _serde::export::PhantomData<&'de ()>,
|
||||
lifetime: _serde::export::PhantomData<&#delife ()>,
|
||||
}
|
||||
|
||||
impl #de_impl_generics _serde::de::Visitor<'de> for __Visitor #de_ty_generics #where_clause {
|
||||
impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause {
|
||||
type Value = #this #ty_generics;
|
||||
|
||||
fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result {
|
||||
@@ -333,7 +366,7 @@ fn deserialize_tuple(
|
||||
|
||||
#[inline]
|
||||
fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error>
|
||||
where __A: _serde::de::SeqAccess<'de>
|
||||
where __A: _serde::de::SeqAccess<#delife>
|
||||
{
|
||||
#visit_seq
|
||||
}
|
||||
@@ -373,7 +406,7 @@ fn deserialize_seq(
|
||||
quote!(try!(_serde::de::SeqAccess::next_element::<#field_ty>(&mut __seq)))
|
||||
}
|
||||
Some(path) => {
|
||||
let (wrapper, wrapper_ty) = wrap_deserialize_with(
|
||||
let (wrapper, wrapper_ty) = wrap_deserialize_field_with(
|
||||
params, field.ty, path);
|
||||
quote!({
|
||||
#wrapper
|
||||
@@ -385,8 +418,8 @@ fn deserialize_seq(
|
||||
};
|
||||
let assign = quote! {
|
||||
let #var = match #visit {
|
||||
Some(__value) => __value,
|
||||
None => {
|
||||
_serde::export::Some(__value) => __value,
|
||||
_serde::export::None => {
|
||||
return _serde::export::Err(_serde::de::Error::invalid_length(#index_in_seq, &#expecting));
|
||||
}
|
||||
};
|
||||
@@ -421,6 +454,8 @@ fn deserialize_seq(
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct(type_path: &Tokens, params: &Parameters, field: &Field) -> Tokens {
|
||||
let delife = params.borrowed.de_lifetime();
|
||||
|
||||
let value = match field.attrs.deserialize_with() {
|
||||
None => {
|
||||
let field_ty = &field.ty;
|
||||
@@ -429,7 +464,7 @@ fn deserialize_newtype_struct(type_path: &Tokens, params: &Parameters, field: &F
|
||||
}
|
||||
}
|
||||
Some(path) => {
|
||||
let (wrapper, wrapper_ty) = wrap_deserialize_with(params, field.ty, path);
|
||||
let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path);
|
||||
quote!({
|
||||
#wrapper
|
||||
try!(<#wrapper_ty as _serde::Deserialize>::deserialize(__e)).value
|
||||
@@ -448,25 +483,31 @@ fn deserialize_newtype_struct(type_path: &Tokens, params: &Parameters, field: &F
|
||||
quote! {
|
||||
#[inline]
|
||||
fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::export::Result<Self::Value, __E::Error>
|
||||
where __E: _serde::Deserializer<'de>
|
||||
where __E: _serde::Deserializer<#delife>
|
||||
{
|
||||
_serde::export::Ok(#result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Untagged {
|
||||
Yes,
|
||||
No,
|
||||
}
|
||||
|
||||
fn deserialize_struct(
|
||||
variant_ident: Option<&syn::Ident>,
|
||||
params: &Parameters,
|
||||
fields: &[Field],
|
||||
cattrs: &attr::Container,
|
||||
deserializer: Option<Tokens>,
|
||||
untagged: Untagged,
|
||||
) -> Fragment {
|
||||
let is_enum = variant_ident.is_some();
|
||||
let is_untagged = deserializer.is_some();
|
||||
|
||||
let this = ¶ms.this;
|
||||
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params,);
|
||||
let delife = params.borrowed.de_lifetime();
|
||||
|
||||
// If there are getters (implying private fields), construct the local type
|
||||
// and use an `Into` conversion to get the remote type. If there are no
|
||||
@@ -525,18 +566,19 @@ fn deserialize_struct(
|
||||
quote!(mut __seq)
|
||||
};
|
||||
|
||||
let visit_seq = if is_untagged {
|
||||
// untagged struct variants do not get a visit_seq method
|
||||
None
|
||||
} else {
|
||||
Some(quote! {
|
||||
#[inline]
|
||||
fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error>
|
||||
where __A: _serde::de::SeqAccess<'de>
|
||||
{
|
||||
#visit_seq
|
||||
}
|
||||
})
|
||||
// untagged struct variants do not get a visit_seq method
|
||||
let visit_seq = match untagged {
|
||||
Untagged::Yes => None,
|
||||
Untagged::No => {
|
||||
Some(quote! {
|
||||
#[inline]
|
||||
fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error>
|
||||
where __A: _serde::de::SeqAccess<#delife>
|
||||
{
|
||||
#visit_seq
|
||||
}
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
quote_block! {
|
||||
@@ -544,10 +586,10 @@ fn deserialize_struct(
|
||||
|
||||
struct __Visitor #de_impl_generics #where_clause {
|
||||
marker: _serde::export::PhantomData<#this #ty_generics>,
|
||||
lifetime: _serde::export::PhantomData<&'de ()>,
|
||||
lifetime: _serde::export::PhantomData<&#delife ()>,
|
||||
}
|
||||
|
||||
impl #de_impl_generics _serde::de::Visitor<'de> for __Visitor #de_ty_generics #where_clause {
|
||||
impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause {
|
||||
type Value = #this #ty_generics;
|
||||
|
||||
fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result {
|
||||
@@ -558,7 +600,7 @@ fn deserialize_struct(
|
||||
|
||||
#[inline]
|
||||
fn visit_map<__A>(self, mut __map: __A) -> _serde::export::Result<Self::Value, __A::Error>
|
||||
where __A: _serde::de::MapAccess<'de>
|
||||
where __A: _serde::de::MapAccess<#delife>
|
||||
{
|
||||
#visit_map
|
||||
}
|
||||
@@ -595,6 +637,7 @@ fn deserialize_externally_tagged_enum(
|
||||
) -> Fragment {
|
||||
let this = ¶ms.this;
|
||||
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params,);
|
||||
let delife = params.borrowed.de_lifetime();
|
||||
|
||||
let type_name = cattrs.name().deserialize_name();
|
||||
|
||||
@@ -660,10 +703,10 @@ fn deserialize_externally_tagged_enum(
|
||||
|
||||
struct __Visitor #de_impl_generics #where_clause {
|
||||
marker: _serde::export::PhantomData<#this #ty_generics>,
|
||||
lifetime: _serde::export::PhantomData<&'de ()>,
|
||||
lifetime: _serde::export::PhantomData<&#delife ()>,
|
||||
}
|
||||
|
||||
impl #de_impl_generics _serde::de::Visitor<'de> for __Visitor #de_ty_generics #where_clause {
|
||||
impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause {
|
||||
type Value = #this #ty_generics;
|
||||
|
||||
fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result {
|
||||
@@ -671,7 +714,7 @@ fn deserialize_externally_tagged_enum(
|
||||
}
|
||||
|
||||
fn visit_enum<__A>(self, __data: __A) -> _serde::export::Result<Self::Value, __A::Error>
|
||||
where __A: _serde::de::EnumAccess<'de>
|
||||
where __A: _serde::de::EnumAccess<#delife>
|
||||
{
|
||||
#match_variant
|
||||
}
|
||||
@@ -752,6 +795,7 @@ fn deserialize_adjacently_tagged_enum(
|
||||
) -> Fragment {
|
||||
let this = ¶ms.this;
|
||||
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params,);
|
||||
let delife = params.borrowed.de_lifetime();
|
||||
|
||||
let variant_names_idents: Vec<_> = variants
|
||||
.iter()
|
||||
@@ -795,9 +839,18 @@ fn deserialize_adjacently_tagged_enum(
|
||||
|
||||
let expecting = format!("adjacently tagged enum {}", params.type_name());
|
||||
let type_name = cattrs.name().deserialize_name();
|
||||
let deny_unknown_fields = cattrs.deny_unknown_fields();
|
||||
|
||||
// If unknown fields are allowed, we pick the visitor that can step over
|
||||
// those. Otherwise we pick the visitor that fails on unknown keys.
|
||||
let field_visitor_ty = if deny_unknown_fields {
|
||||
quote! { _serde::private::de::TagOrContentFieldVisitor }
|
||||
} else {
|
||||
quote! { _serde::private::de::TagContentOtherFieldVisitor }
|
||||
};
|
||||
|
||||
let tag_or_content = quote! {
|
||||
_serde::private::de::TagOrContentFieldVisitor {
|
||||
#field_visitor_ty {
|
||||
tag: #tag,
|
||||
content: #content,
|
||||
}
|
||||
@@ -844,9 +897,46 @@ fn deserialize_adjacently_tagged_enum(
|
||||
};
|
||||
}
|
||||
|
||||
let visit_third_key = quote! {
|
||||
// Visit the third key in the map, hopefully there isn't one.
|
||||
match try!(_serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content)) {
|
||||
// Advance the map by one key, returning early in case of error.
|
||||
let next_key = quote! {
|
||||
try!(_serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content))
|
||||
};
|
||||
|
||||
// When allowing unknown fields, we want to transparently step through keys
|
||||
// we don't care about until we find `tag`, `content`, or run out of keys.
|
||||
let next_relevant_key = if deny_unknown_fields {
|
||||
next_key
|
||||
} else {
|
||||
quote! {
|
||||
{
|
||||
let mut __rk : _serde::export::Option<_serde::private::de::TagOrContentField> = _serde::export::None;
|
||||
while let _serde::export::Some(__k) = #next_key {
|
||||
match __k {
|
||||
_serde::private::de::TagContentOtherField::Other => {
|
||||
try!(_serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map));
|
||||
continue;
|
||||
},
|
||||
_serde::private::de::TagContentOtherField::Tag => {
|
||||
__rk = _serde::export::Some(_serde::private::de::TagOrContentField::Tag);
|
||||
break;
|
||||
}
|
||||
_serde::private::de::TagContentOtherField::Content => {
|
||||
__rk = _serde::export::Some(_serde::private::de::TagOrContentField::Content);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
__rk
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Step through remaining keys, looking for duplicates of previously-seen
|
||||
// keys. When unknown fields are denied, any key that isn't a duplicate will
|
||||
// at this point immediately produce an error.
|
||||
let visit_remaining_keys = quote! {
|
||||
match #next_relevant_key {
|
||||
_serde::export::Some(_serde::private::de::TagOrContentField::Tag) => {
|
||||
_serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag))
|
||||
}
|
||||
@@ -865,14 +955,14 @@ fn deserialize_adjacently_tagged_enum(
|
||||
struct __Seed #de_impl_generics #where_clause {
|
||||
field: __Field,
|
||||
marker: _serde::export::PhantomData<#this #ty_generics>,
|
||||
lifetime: _serde::export::PhantomData<&'de ()>,
|
||||
lifetime: _serde::export::PhantomData<&#delife ()>,
|
||||
}
|
||||
|
||||
impl #de_impl_generics _serde::de::DeserializeSeed<'de> for __Seed #de_ty_generics #where_clause {
|
||||
impl #de_impl_generics _serde::de::DeserializeSeed<#delife> for __Seed #de_ty_generics #where_clause {
|
||||
type Value = #this #ty_generics;
|
||||
|
||||
fn deserialize<__D>(self, __deserializer: __D) -> _serde::export::Result<Self::Value, __D::Error>
|
||||
where __D: _serde::Deserializer<'de>
|
||||
where __D: _serde::Deserializer<#delife>
|
||||
{
|
||||
match self.field {
|
||||
#(#variant_arms)*
|
||||
@@ -882,10 +972,10 @@ fn deserialize_adjacently_tagged_enum(
|
||||
|
||||
struct __Visitor #de_impl_generics #where_clause {
|
||||
marker: _serde::export::PhantomData<#this #ty_generics>,
|
||||
lifetime: _serde::export::PhantomData<&'de ()>,
|
||||
lifetime: _serde::export::PhantomData<&#delife ()>,
|
||||
}
|
||||
|
||||
impl #de_impl_generics _serde::de::Visitor<'de> for __Visitor #de_ty_generics #where_clause {
|
||||
impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause {
|
||||
type Value = #this #ty_generics;
|
||||
|
||||
fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result {
|
||||
@@ -893,16 +983,16 @@ fn deserialize_adjacently_tagged_enum(
|
||||
}
|
||||
|
||||
fn visit_map<__A>(self, mut __map: __A) -> _serde::export::Result<Self::Value, __A::Error>
|
||||
where __A: _serde::de::MapAccess<'de>
|
||||
where __A: _serde::de::MapAccess<#delife>
|
||||
{
|
||||
// Visit the first key.
|
||||
match try!(_serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content)) {
|
||||
// Visit the first relevant key.
|
||||
match #next_relevant_key {
|
||||
// First key is the tag.
|
||||
_serde::export::Some(_serde::private::de::TagOrContentField::Tag) => {
|
||||
// Parse the tag.
|
||||
let __field = try!(_serde::de::MapAccess::next_value(&mut __map));
|
||||
// Visit the second key.
|
||||
match try!(_serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content)) {
|
||||
match #next_relevant_key {
|
||||
// Second key is a duplicate of the tag.
|
||||
_serde::export::Some(_serde::private::de::TagOrContentField::Tag) => {
|
||||
_serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag))
|
||||
@@ -915,8 +1005,8 @@ fn deserialize_adjacently_tagged_enum(
|
||||
marker: _serde::export::PhantomData,
|
||||
lifetime: _serde::export::PhantomData,
|
||||
}));
|
||||
// Visit the third key, hopefully there isn't one.
|
||||
#visit_third_key
|
||||
// Visit remaining keys, looking for duplicates.
|
||||
#visit_remaining_keys
|
||||
}
|
||||
// There is no second key; might be okay if the we have a unit variant.
|
||||
_serde::export::None => #missing_content
|
||||
@@ -927,7 +1017,7 @@ fn deserialize_adjacently_tagged_enum(
|
||||
// Buffer up the content.
|
||||
let __content = try!(_serde::de::MapAccess::next_value::<_serde::private::de::Content>(&mut __map));
|
||||
// Visit the second key.
|
||||
match try!(_serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content)) {
|
||||
match #next_relevant_key {
|
||||
// Second key is the tag.
|
||||
_serde::export::Some(_serde::private::de::TagOrContentField::Tag) => {
|
||||
let __deserializer = _serde::private::de::ContentDeserializer::<__A::Error>::new(__content);
|
||||
@@ -936,8 +1026,8 @@ fn deserialize_adjacently_tagged_enum(
|
||||
// Deserialize the buffered content now that we know the variant.
|
||||
#(#variant_arms)*
|
||||
});
|
||||
// Visit the third key, hopefully there isn't one.
|
||||
#visit_third_key
|
||||
// Visit remaining keys, looking for duplicates.
|
||||
#visit_remaining_keys
|
||||
}
|
||||
// Second key is a duplicate of the content.
|
||||
_serde::export::Some(_serde::private::de::TagOrContentField::Content) => {
|
||||
@@ -957,7 +1047,7 @@ fn deserialize_adjacently_tagged_enum(
|
||||
}
|
||||
|
||||
fn visit_seq<__A>(self, mut __seq: __A) -> _serde::export::Result<Self::Value, __A::Error>
|
||||
where __A: _serde::de::SeqAccess<'de>
|
||||
where __A: _serde::de::SeqAccess<#delife>
|
||||
{
|
||||
// Visit the first element - the tag.
|
||||
match try!(_serde::de::SeqAccess::next_element(&mut __seq)) {
|
||||
@@ -1039,6 +1129,16 @@ fn deserialize_externally_tagged_variant(
|
||||
variant: &Variant,
|
||||
cattrs: &attr::Container,
|
||||
) -> Fragment {
|
||||
if let Some(path) = variant.attrs.deserialize_with() {
|
||||
let (wrapper, wrapper_ty, unwrap_fn) =
|
||||
wrap_deserialize_variant_with(params, &variant, path);
|
||||
return quote_block! {
|
||||
#wrapper
|
||||
_serde::export::Result::map(
|
||||
_serde::de::VariantAccess::newtype_variant::<#wrapper_ty>(__variant), #unwrap_fn)
|
||||
};
|
||||
}
|
||||
|
||||
let variant_ident = &variant.ident;
|
||||
|
||||
match variant.style {
|
||||
@@ -1056,7 +1156,7 @@ fn deserialize_externally_tagged_variant(
|
||||
deserialize_tuple(Some(variant_ident), params, &variant.fields, cattrs, None)
|
||||
}
|
||||
Style::Struct => {
|
||||
deserialize_struct(Some(variant_ident), params, &variant.fields, cattrs, None)
|
||||
deserialize_struct(Some(variant_ident), params, &variant.fields, cattrs, None, Untagged::No)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1067,6 +1167,10 @@ fn deserialize_internally_tagged_variant(
|
||||
cattrs: &attr::Container,
|
||||
deserializer: Tokens,
|
||||
) -> Fragment {
|
||||
if variant.attrs.deserialize_with().is_some() {
|
||||
return deserialize_untagged_variant(params, variant, cattrs, deserializer);
|
||||
}
|
||||
|
||||
let variant_ident = &variant.ident;
|
||||
|
||||
match variant.style {
|
||||
@@ -1079,8 +1183,23 @@ fn deserialize_internally_tagged_variant(
|
||||
_serde::export::Ok(#this::#variant_ident)
|
||||
}
|
||||
}
|
||||
Style::Newtype | Style::Struct => {
|
||||
deserialize_untagged_variant(params, variant, cattrs, deserializer)
|
||||
Style::Newtype => {
|
||||
deserialize_untagged_newtype_variant(
|
||||
variant_ident,
|
||||
params,
|
||||
&variant.fields[0],
|
||||
deserializer,
|
||||
)
|
||||
}
|
||||
Style::Struct => {
|
||||
deserialize_struct(
|
||||
Some(variant_ident),
|
||||
params,
|
||||
&variant.fields,
|
||||
cattrs,
|
||||
Some(deserializer),
|
||||
Untagged::No,
|
||||
)
|
||||
}
|
||||
Style::Tuple => unreachable!("checked in serde_derive_internals"),
|
||||
}
|
||||
@@ -1092,6 +1211,16 @@ fn deserialize_untagged_variant(
|
||||
cattrs: &attr::Container,
|
||||
deserializer: Tokens,
|
||||
) -> Fragment {
|
||||
if let Some(path) = variant.attrs.deserialize_with() {
|
||||
let (wrapper, wrapper_ty, unwrap_fn) =
|
||||
wrap_deserialize_variant_with(params, &variant, path);
|
||||
return quote_block! {
|
||||
#wrapper
|
||||
_serde::export::Result::map(
|
||||
<#wrapper_ty as _serde::Deserialize>::deserialize(#deserializer), #unwrap_fn)
|
||||
};
|
||||
}
|
||||
|
||||
let variant_ident = &variant.ident;
|
||||
|
||||
match variant.style {
|
||||
@@ -1132,6 +1261,7 @@ fn deserialize_untagged_variant(
|
||||
&variant.fields,
|
||||
cattrs,
|
||||
Some(deserializer),
|
||||
Untagged::Yes,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1153,7 +1283,7 @@ fn deserialize_externally_tagged_newtype_variant(
|
||||
}
|
||||
}
|
||||
Some(path) => {
|
||||
let (wrapper, wrapper_ty) = wrap_deserialize_with(params, field.ty, path);
|
||||
let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path);
|
||||
quote_block! {
|
||||
#wrapper
|
||||
_serde::export::Result::map(
|
||||
@@ -1181,7 +1311,7 @@ fn deserialize_untagged_newtype_variant(
|
||||
}
|
||||
}
|
||||
Some(path) => {
|
||||
let (wrapper, wrapper_ty) = wrap_deserialize_with(params, field.ty, path);
|
||||
let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path);
|
||||
quote_block! {
|
||||
#wrapper
|
||||
_serde::export::Result::map(
|
||||
@@ -1294,6 +1424,7 @@ fn deserialize_custom_identifier(
|
||||
};
|
||||
|
||||
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params,);
|
||||
let delife = params.borrowed.de_lifetime();
|
||||
let visitor_impl =
|
||||
Stmts(deserialize_identifier(this.clone(), &names_idents, is_variant, fallthrough),);
|
||||
|
||||
@@ -1302,10 +1433,10 @@ fn deserialize_custom_identifier(
|
||||
|
||||
struct __FieldVisitor #de_impl_generics #where_clause {
|
||||
marker: _serde::export::PhantomData<#this #ty_generics>,
|
||||
lifetime: _serde::export::PhantomData<&'de ()>,
|
||||
lifetime: _serde::export::PhantomData<&#delife ()>,
|
||||
}
|
||||
|
||||
impl #de_impl_generics _serde::de::Visitor<'de> for __FieldVisitor #de_ty_generics #where_clause {
|
||||
impl #de_impl_generics _serde::de::Visitor<#delife> for __FieldVisitor #de_ty_generics #where_clause {
|
||||
type Value = #this #ty_generics;
|
||||
|
||||
#visitor_impl
|
||||
@@ -1339,26 +1470,27 @@ fn deserialize_identifier(
|
||||
"field identifier"
|
||||
};
|
||||
|
||||
let visit_index = if is_variant {
|
||||
let variant_indices = 0u32..;
|
||||
let fallthrough_msg = format!("variant index 0 <= i < {}", fields.len());
|
||||
let visit_index = quote! {
|
||||
fn visit_u32<__E>(self, __value: u32) -> _serde::export::Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
match __value {
|
||||
#(
|
||||
#variant_indices => _serde::export::Ok(#constructors),
|
||||
)*
|
||||
_ => _serde::export::Err(_serde::de::Error::invalid_value(
|
||||
_serde::de::Unexpected::Unsigned(__value as u64),
|
||||
&#fallthrough_msg))
|
||||
}
|
||||
}
|
||||
};
|
||||
Some(visit_index)
|
||||
let index_expecting = if is_variant {
|
||||
"variant"
|
||||
} else {
|
||||
None
|
||||
"field"
|
||||
};
|
||||
|
||||
let variant_indices = 0u64..;
|
||||
let fallthrough_msg = format!("{} index 0 <= i < {}", index_expecting, fields.len());
|
||||
let visit_index = quote! {
|
||||
fn visit_u64<__E>(self, __value: u64) -> _serde::export::Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
match __value {
|
||||
#(
|
||||
#variant_indices => _serde::export::Ok(#constructors),
|
||||
)*
|
||||
_ => _serde::export::Err(_serde::de::Error::invalid_value(
|
||||
_serde::de::Unexpected::Unsigned(__value),
|
||||
&#fallthrough_msg))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let bytes_to_str = if fallthrough.is_some() {
|
||||
@@ -1483,7 +1615,7 @@ fn deserialize_map(
|
||||
}
|
||||
}
|
||||
Some(path) => {
|
||||
let (wrapper, wrapper_ty) = wrap_deserialize_with(
|
||||
let (wrapper, wrapper_ty) = wrap_deserialize_field_with(
|
||||
params, field.ty, path);
|
||||
quote!({
|
||||
#wrapper
|
||||
@@ -1616,22 +1748,23 @@ fn field_i(i: usize) -> Ident {
|
||||
/// in a trait to prevent it from accessing the internal `Deserialize` state.
|
||||
fn wrap_deserialize_with(
|
||||
params: &Parameters,
|
||||
field_ty: &syn::Ty,
|
||||
value_ty: Tokens,
|
||||
deserialize_with: &syn::Path,
|
||||
) -> (Tokens, Tokens) {
|
||||
let this = ¶ms.this;
|
||||
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params,);
|
||||
let delife = params.borrowed.de_lifetime();
|
||||
|
||||
let wrapper = quote! {
|
||||
struct __DeserializeWith #de_impl_generics #where_clause {
|
||||
value: #field_ty,
|
||||
value: #value_ty,
|
||||
phantom: _serde::export::PhantomData<#this #ty_generics>,
|
||||
lifetime: _serde::export::PhantomData<&'de ()>,
|
||||
lifetime: _serde::export::PhantomData<&#delife ()>,
|
||||
}
|
||||
|
||||
impl #de_impl_generics _serde::Deserialize<'de> for __DeserializeWith #de_ty_generics #where_clause {
|
||||
impl #de_impl_generics _serde::Deserialize<#delife> for __DeserializeWith #de_ty_generics #where_clause {
|
||||
fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error>
|
||||
where __D: _serde::Deserializer<'de>
|
||||
where __D: _serde::Deserializer<#delife>
|
||||
{
|
||||
_serde::export::Ok(__DeserializeWith {
|
||||
value: try!(#deserialize_with(__deserializer)),
|
||||
@@ -1647,6 +1780,68 @@ fn wrap_deserialize_with(
|
||||
(wrapper, wrapper_ty)
|
||||
}
|
||||
|
||||
fn wrap_deserialize_field_with(
|
||||
params: &Parameters,
|
||||
field_ty: &syn::Ty,
|
||||
deserialize_with: &syn::Path,
|
||||
) -> (Tokens, Tokens) {
|
||||
wrap_deserialize_with(params, quote!(#field_ty), deserialize_with)
|
||||
}
|
||||
|
||||
fn wrap_deserialize_variant_with(
|
||||
params: &Parameters,
|
||||
variant: &Variant,
|
||||
deserialize_with: &syn::Path,
|
||||
) -> (Tokens, Tokens, Tokens) {
|
||||
let this = ¶ms.this;
|
||||
let variant_ident = &variant.ident;
|
||||
|
||||
let field_tys = variant.fields.iter().map(|field| field.ty);
|
||||
let (wrapper, wrapper_ty) =
|
||||
wrap_deserialize_with(params, quote!((#(#field_tys),*)), deserialize_with);
|
||||
|
||||
let field_access = (0..variant.fields.len()).map(|n| Ident::new(format!("{}", n)));
|
||||
let unwrap_fn = match variant.style {
|
||||
Style::Struct => {
|
||||
let field_idents = variant.fields.iter().map(|field| field.ident.as_ref().unwrap());
|
||||
quote! {
|
||||
{
|
||||
|__wrap| {
|
||||
#this::#variant_ident { #(#field_idents: __wrap.value.#field_access),* }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Style::Tuple => {
|
||||
quote! {
|
||||
{
|
||||
|__wrap| {
|
||||
#this::#variant_ident(#(__wrap.value.#field_access),*)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Style::Newtype => {
|
||||
quote! {
|
||||
{
|
||||
|__wrap| {
|
||||
#this::#variant_ident(__wrap.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Style::Unit => {
|
||||
quote! {
|
||||
{
|
||||
|__wrap| { #this::#variant_ident }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
(wrapper, wrapper_ty, unwrap_fn)
|
||||
}
|
||||
|
||||
fn expr_is_missing(field: &Field, cattrs: &attr::Container) -> Fragment {
|
||||
match *field.attrs.default() {
|
||||
attr::Default::Default => {
|
||||
@@ -1687,20 +1882,24 @@ struct DeImplGenerics<'a>(&'a Parameters);
|
||||
impl<'a> ToTokens for DeImplGenerics<'a> {
|
||||
fn to_tokens(&self, tokens: &mut Tokens) {
|
||||
let mut generics = self.0.generics.clone();
|
||||
generics.lifetimes.insert(0, self.0.de_lifetime_def());
|
||||
if let Some(de_lifetime) = self.0.borrowed.de_lifetime_def() {
|
||||
generics.lifetimes.insert(0, de_lifetime);
|
||||
}
|
||||
let (impl_generics, _, _) = generics.split_for_impl();
|
||||
impl_generics.to_tokens(tokens);
|
||||
}
|
||||
}
|
||||
|
||||
struct DeTyGenerics<'a>(&'a syn::Generics);
|
||||
struct DeTyGenerics<'a>(&'a Parameters);
|
||||
|
||||
impl<'a> ToTokens for DeTyGenerics<'a> {
|
||||
fn to_tokens(&self, tokens: &mut Tokens) {
|
||||
let mut generics = self.0.clone();
|
||||
generics
|
||||
.lifetimes
|
||||
.insert(0, syn::LifetimeDef::new("'de"));
|
||||
let mut generics = self.0.generics.clone();
|
||||
if self.0.borrowed.de_lifetime_def().is_some() {
|
||||
generics
|
||||
.lifetimes
|
||||
.insert(0, syn::LifetimeDef::new("'de"));
|
||||
}
|
||||
let (_, ty_generics, _) = generics.split_for_impl();
|
||||
ty_generics.to_tokens(tokens);
|
||||
}
|
||||
@@ -1709,7 +1908,7 @@ impl<'a> ToTokens for DeTyGenerics<'a> {
|
||||
fn split_with_de_lifetime(params: &Parameters,)
|
||||
-> (DeImplGenerics, DeTyGenerics, syn::TyGenerics, &syn::WhereClause) {
|
||||
let de_impl_generics = DeImplGenerics(¶ms);
|
||||
let de_ty_generics = DeTyGenerics(¶ms.generics);
|
||||
let de_ty_generics = DeTyGenerics(¶ms);
|
||||
let (_, ty_generics, where_clause) = params.generics.split_for_impl();
|
||||
(de_impl_generics, de_ty_generics, ty_generics, where_clause)
|
||||
}
|
||||
|
||||
@@ -8,15 +8,21 @@
|
||||
|
||||
//! This crate provides Serde's two derive macros.
|
||||
//!
|
||||
//! ```rust,ignore
|
||||
//! ```rust
|
||||
//! # #[macro_use]
|
||||
//! # extern crate serde_derive;
|
||||
//! #
|
||||
//! #[derive(Serialize, Deserialize)]
|
||||
//! # struct S;
|
||||
//! #
|
||||
//! # fn main() {}
|
||||
//! ```
|
||||
//!
|
||||
//! Please refer to [https://serde.rs/derive.html] for how to set this up.
|
||||
//!
|
||||
//! [https://serde.rs/derive.html]: https://serde.rs/derive.html
|
||||
|
||||
#![doc(html_root_url = "https://docs.rs/serde_derive/1.0.1")]
|
||||
#![doc(html_root_url = "https://docs.rs/serde_derive/1.0.22")]
|
||||
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(used_underscore_binding))]
|
||||
|
||||
+162
-53
@@ -29,9 +29,10 @@ pub fn expand_derive_serialize(input: &syn::DeriveInput) -> Result<Tokens, Strin
|
||||
let body = Stmts(serialize_body(&cont, ¶ms));
|
||||
|
||||
let impl_block = if let Some(remote) = cont.attrs.remote() {
|
||||
let vis = &input.vis;
|
||||
quote! {
|
||||
impl #impl_generics #ident #ty_generics #where_clause {
|
||||
fn serialize<__S>(__self: &#remote #ty_generics, __serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error>
|
||||
#vis fn serialize<__S>(__self: &#remote #ty_generics, __serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error>
|
||||
where __S: _serde::Serializer
|
||||
{
|
||||
#body
|
||||
@@ -142,12 +143,16 @@ fn build_generics(cont: &Container) -> syn::Generics {
|
||||
}
|
||||
}
|
||||
|
||||
// Fields with a `skip_serializing` or `serialize_with` attribute are not
|
||||
// serialized by us so we do not generate a bound. Fields with a `bound`
|
||||
// attribute specify their own bound so we do not generate one. All other fields
|
||||
// may need a `T: Serialize` bound where T is the type of the field.
|
||||
fn needs_serialize_bound(attrs: &attr::Field) -> bool {
|
||||
!attrs.skip_serializing() && attrs.serialize_with().is_none() && attrs.ser_bound().is_none()
|
||||
// Fields with a `skip_serializing` or `serialize_with` attribute, or which
|
||||
// belong to a variant with a `serialize_with` attribute, are not serialized by
|
||||
// us so we do not generate a bound. Fields with a `bound` attribute specify
|
||||
// their own bound so we do not generate one. All other fields may need a `T:
|
||||
// Serialize` bound where T is the type of the field.
|
||||
fn needs_serialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool {
|
||||
!field.skip_serializing() &&
|
||||
field.serialize_with().is_none() &&
|
||||
field.ser_bound().is_none() &&
|
||||
variant.map_or(true, |variant| variant.serialize_with().is_none())
|
||||
}
|
||||
|
||||
fn serialize_body(cont: &Container, params: &Parameters) -> Fragment {
|
||||
@@ -202,7 +207,7 @@ fn serialize_newtype_struct(
|
||||
|
||||
let mut field_expr = get_field(params, field, 0);
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
|
||||
field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
quote_expr! {
|
||||
@@ -241,6 +246,7 @@ fn serialize_struct(params: &Parameters, fields: &[Field], cattrs: &attr::Contai
|
||||
params,
|
||||
false,
|
||||
quote!(_serde::ser::SerializeStruct::serialize_field),
|
||||
quote!(_serde::ser::SerializeStruct::skip_field),
|
||||
);
|
||||
|
||||
let type_name = cattrs.name().serialize_name();
|
||||
@@ -394,6 +400,19 @@ fn serialize_externally_tagged_variant(
|
||||
let type_name = cattrs.name().serialize_name();
|
||||
let variant_name = variant.attrs.name().serialize_name();
|
||||
|
||||
if let Some(path) = variant.attrs.serialize_with() {
|
||||
let ser = wrap_serialize_variant_with(params, path, &variant);
|
||||
return quote_expr! {
|
||||
_serde::Serializer::serialize_newtype_variant(
|
||||
__serializer,
|
||||
#type_name,
|
||||
#variant_index,
|
||||
#variant_name,
|
||||
#ser,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
match variant.style {
|
||||
Style::Unit => {
|
||||
quote_expr! {
|
||||
@@ -409,7 +428,7 @@ fn serialize_externally_tagged_variant(
|
||||
let field = &variant.fields[0];
|
||||
let mut field_expr = quote!(__field0);
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
|
||||
field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
quote_expr! {
|
||||
@@ -459,6 +478,20 @@ fn serialize_internally_tagged_variant(
|
||||
let enum_ident_str = params.type_name();
|
||||
let variant_ident_str = variant.ident.as_ref();
|
||||
|
||||
if let Some(path) = variant.attrs.serialize_with() {
|
||||
let ser = wrap_serialize_variant_with(params, path, &variant);
|
||||
return quote_expr! {
|
||||
_serde::private::ser::serialize_tagged_newtype(
|
||||
__serializer,
|
||||
#enum_ident_str,
|
||||
#variant_ident_str,
|
||||
#tag,
|
||||
#variant_name,
|
||||
#ser,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
match variant.style {
|
||||
Style::Unit => {
|
||||
quote_block! {
|
||||
@@ -473,7 +506,7 @@ fn serialize_internally_tagged_variant(
|
||||
let field = &variant.fields[0];
|
||||
let mut field_expr = quote!(__field0);
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
|
||||
field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
quote_expr! {
|
||||
@@ -514,44 +547,57 @@ fn serialize_adjacently_tagged_variant(
|
||||
let variant_name = variant.attrs.name().serialize_name();
|
||||
|
||||
let inner = Stmts(
|
||||
match variant.style {
|
||||
Style::Unit => {
|
||||
return quote_block! {
|
||||
let mut __struct = try!(_serde::Serializer::serialize_struct(
|
||||
__serializer, #type_name, 1));
|
||||
try!(_serde::ser::SerializeStruct::serialize_field(
|
||||
&mut __struct, #tag, #variant_name));
|
||||
_serde::ser::SerializeStruct::end(__struct)
|
||||
};
|
||||
if let Some(path) = variant.attrs.serialize_with() {
|
||||
let ser = wrap_serialize_variant_with(params, path, &variant);
|
||||
quote_expr! {
|
||||
_serde::Serialize::serialize(#ser, __serializer)
|
||||
}
|
||||
Style::Newtype => {
|
||||
let field = &variant.fields[0];
|
||||
let mut field_expr = quote!(__field0);
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
|
||||
} else {
|
||||
match variant.style {
|
||||
Style::Unit => {
|
||||
return quote_block! {
|
||||
let mut __struct = try!(_serde::Serializer::serialize_struct(
|
||||
__serializer, #type_name, 1));
|
||||
try!(_serde::ser::SerializeStruct::serialize_field(
|
||||
&mut __struct, #tag, #variant_name));
|
||||
_serde::ser::SerializeStruct::end(__struct)
|
||||
};
|
||||
}
|
||||
Style::Newtype => {
|
||||
let field = &variant.fields[0];
|
||||
let mut field_expr = quote!(__field0);
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
quote_expr! {
|
||||
_serde::Serialize::serialize(#field_expr, __serializer)
|
||||
quote_expr! {
|
||||
_serde::Serialize::serialize(#field_expr, __serializer)
|
||||
}
|
||||
}
|
||||
Style::Tuple => {
|
||||
serialize_tuple_variant(TupleVariant::Untagged, params, &variant.fields)
|
||||
}
|
||||
Style::Struct => {
|
||||
serialize_struct_variant(
|
||||
StructVariant::Untagged,
|
||||
params,
|
||||
&variant.fields,
|
||||
&variant_name,
|
||||
)
|
||||
}
|
||||
}
|
||||
Style::Tuple => {
|
||||
serialize_tuple_variant(TupleVariant::Untagged, params, &variant.fields)
|
||||
}
|
||||
Style::Struct => {
|
||||
serialize_struct_variant(
|
||||
StructVariant::Untagged,
|
||||
params,
|
||||
&variant.fields,
|
||||
&variant_name,
|
||||
)
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
let fields_ty = variant.fields.iter().map(|f| &f.ty);
|
||||
let ref fields_ident: Vec<_> = match variant.style {
|
||||
Style::Unit => unreachable!(),
|
||||
Style::Unit => {
|
||||
if variant.attrs.serialize_with().is_some() {
|
||||
vec![]
|
||||
} else {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
Style::Newtype => vec![Ident::new("__field0")],
|
||||
Style::Tuple => {
|
||||
(0..variant.fields.len())
|
||||
@@ -575,7 +621,11 @@ fn serialize_adjacently_tagged_variant(
|
||||
|
||||
let (_, ty_generics, where_clause) = params.generics.split_for_impl();
|
||||
|
||||
let wrapper_generics = bound::with_lifetime_bound(¶ms.generics, "'__a");
|
||||
let wrapper_generics = if let Style::Unit = variant.style {
|
||||
params.generics.clone()
|
||||
} else {
|
||||
bound::with_lifetime_bound(¶ms.generics, "'__a")
|
||||
};
|
||||
let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl();
|
||||
|
||||
quote_block! {
|
||||
@@ -611,6 +661,13 @@ fn serialize_untagged_variant(
|
||||
variant: &Variant,
|
||||
cattrs: &attr::Container,
|
||||
) -> Fragment {
|
||||
if let Some(path) = variant.attrs.serialize_with() {
|
||||
let ser = wrap_serialize_variant_with(params, path, &variant);
|
||||
return quote_expr! {
|
||||
_serde::Serialize::serialize(#ser, __serializer)
|
||||
};
|
||||
}
|
||||
|
||||
match variant.style {
|
||||
Style::Unit => {
|
||||
quote_expr! {
|
||||
@@ -621,7 +678,7 @@ fn serialize_untagged_variant(
|
||||
let field = &variant.fields[0];
|
||||
let mut field_expr = quote!(__field0);
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
|
||||
field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
quote_expr! {
|
||||
@@ -706,15 +763,23 @@ fn serialize_struct_variant<'a>(
|
||||
fields: &[Field],
|
||||
name: &str,
|
||||
) -> Fragment {
|
||||
let method = match context {
|
||||
let (method, skip_method) = match context {
|
||||
StructVariant::ExternallyTagged { .. } => {
|
||||
quote!(_serde::ser::SerializeStructVariant::serialize_field)
|
||||
(
|
||||
quote!(_serde::ser::SerializeStructVariant::serialize_field),
|
||||
quote!(_serde::ser::SerializeStructVariant::skip_field),
|
||||
)
|
||||
}
|
||||
StructVariant::InternallyTagged { .. } |
|
||||
StructVariant::Untagged => quote!(_serde::ser::SerializeStruct::serialize_field),
|
||||
StructVariant::Untagged => {
|
||||
(
|
||||
quote!(_serde::ser::SerializeStruct::serialize_field),
|
||||
quote!(_serde::ser::SerializeStruct::skip_field),
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
let serialize_fields = serialize_struct_visitor(fields, params, true, method);
|
||||
let serialize_fields = serialize_struct_visitor(fields, params, true, method, skip_method);
|
||||
|
||||
let mut serialized_fields = fields
|
||||
.iter()
|
||||
@@ -807,7 +872,7 @@ fn serialize_tuple_struct_visitor(
|
||||
.map(|path| quote!(#path(#field_expr)));
|
||||
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
|
||||
field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
let ser = quote! {
|
||||
@@ -828,6 +893,7 @@ fn serialize_struct_visitor(
|
||||
params: &Parameters,
|
||||
is_enum: bool,
|
||||
func: Tokens,
|
||||
skip_func: Tokens,
|
||||
) -> Vec<Tokens> {
|
||||
fields
|
||||
.iter()
|
||||
@@ -849,7 +915,7 @@ fn serialize_struct_visitor(
|
||||
.map(|path| quote!(#path(#field_expr)));
|
||||
|
||||
if let Some(path) = field.attrs.serialize_with() {
|
||||
field_expr = wrap_serialize_with(params, field.ty, path, field_expr)
|
||||
field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr);
|
||||
}
|
||||
|
||||
let ser = quote! {
|
||||
@@ -858,28 +924,71 @@ fn serialize_struct_visitor(
|
||||
|
||||
match skip {
|
||||
None => ser,
|
||||
Some(skip) => quote!(if !#skip { #ser }),
|
||||
Some(skip) => {
|
||||
quote! {
|
||||
if !#skip {
|
||||
#ser
|
||||
} else {
|
||||
try!(#skip_func(&mut __serde_state, #key_expr));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn wrap_serialize_with(
|
||||
fn wrap_serialize_field_with(
|
||||
params: &Parameters,
|
||||
field_ty: &syn::Ty,
|
||||
serialize_with: &syn::Path,
|
||||
value: Tokens,
|
||||
field_expr: Tokens,
|
||||
) -> Tokens {
|
||||
wrap_serialize_with(params,
|
||||
serialize_with,
|
||||
&[field_ty],
|
||||
&[quote!(#field_expr)])
|
||||
}
|
||||
|
||||
fn wrap_serialize_variant_with(
|
||||
params: &Parameters,
|
||||
serialize_with: &syn::Path,
|
||||
variant: &Variant,
|
||||
) -> Tokens {
|
||||
let field_tys: Vec<_> = variant.fields.iter().map(|field| field.ty).collect();
|
||||
let field_exprs: Vec<_> = variant.fields.iter()
|
||||
.enumerate()
|
||||
.map(|(i, field)| {
|
||||
let id = field.ident.as_ref().map_or_else(|| Ident::new(format!("__field{}", i)),
|
||||
|id| id.clone());
|
||||
quote!(#id)
|
||||
})
|
||||
.collect();
|
||||
wrap_serialize_with(params, serialize_with, field_tys.as_slice(), field_exprs.as_slice())
|
||||
}
|
||||
|
||||
fn wrap_serialize_with(
|
||||
params: &Parameters,
|
||||
serialize_with: &syn::Path,
|
||||
field_tys: &[&syn::Ty],
|
||||
field_exprs: &[Tokens],
|
||||
) -> Tokens {
|
||||
let this = ¶ms.this;
|
||||
let (_, ty_generics, where_clause) = params.generics.split_for_impl();
|
||||
|
||||
let wrapper_generics = bound::with_lifetime_bound(¶ms.generics, "'__a");
|
||||
let wrapper_generics = if field_exprs.len() == 0 {
|
||||
params.generics.clone()
|
||||
} else {
|
||||
bound::with_lifetime_bound(¶ms.generics, "'__a")
|
||||
};
|
||||
let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl();
|
||||
|
||||
let field_access = (0..field_exprs.len()).map(|n| Ident::new(format!("{}", n)));
|
||||
|
||||
quote!({
|
||||
struct __SerializeWith #wrapper_impl_generics #where_clause {
|
||||
value: &'__a #field_ty,
|
||||
values: (#(&'__a #field_tys, )*),
|
||||
phantom: _serde::export::PhantomData<#this #ty_generics>,
|
||||
}
|
||||
|
||||
@@ -887,12 +996,12 @@ fn wrap_serialize_with(
|
||||
fn serialize<__S>(&self, __s: __S) -> _serde::export::Result<__S::Ok, __S::Error>
|
||||
where __S: _serde::Serializer
|
||||
{
|
||||
#serialize_with(self.value, __s)
|
||||
#serialize_with(#(self.values.#field_access, )* __s)
|
||||
}
|
||||
}
|
||||
|
||||
&__SerializeWith {
|
||||
value: #value,
|
||||
values: (#(#field_exprs, )*),
|
||||
phantom: _serde::export::PhantomData::<#this #ty_generics>,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde_derive_internals"
|
||||
version = "0.15.0" # remember to update html_root_url
|
||||
version = "0.17.0" # remember to update html_root_url
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "AST representation used by Serde derive macros. Unstable."
|
||||
|
||||
@@ -45,13 +45,13 @@ pub enum Style {
|
||||
}
|
||||
|
||||
impl<'a> Container<'a> {
|
||||
pub fn from_ast(cx: &Ctxt, item: &'a syn::MacroInput) -> Container<'a> {
|
||||
pub fn from_ast(cx: &Ctxt, item: &'a syn::DeriveInput) -> Container<'a> {
|
||||
let attrs = attr::Container::from_ast(cx, item);
|
||||
|
||||
let mut body = match item.body {
|
||||
syn::Body::Enum(ref variants) => Body::Enum(enum_from_ast(cx, variants)),
|
||||
syn::Body::Struct(ref variant_data) => {
|
||||
let (style, fields) = struct_from_ast(cx, variant_data);
|
||||
let (style, fields) = struct_from_ast(cx, variant_data, None);
|
||||
Body::Struct(style, fields)
|
||||
}
|
||||
};
|
||||
@@ -103,10 +103,11 @@ fn enum_from_ast<'a>(cx: &Ctxt, variants: &'a [syn::Variant]) -> Vec<Variant<'a>
|
||||
.iter()
|
||||
.map(
|
||||
|variant| {
|
||||
let (style, fields) = struct_from_ast(cx, &variant.data);
|
||||
let attrs = attr::Variant::from_ast(cx, variant);
|
||||
let (style, fields) = struct_from_ast(cx, &variant.data, Some(&attrs));
|
||||
Variant {
|
||||
ident: variant.ident.clone(),
|
||||
attrs: attr::Variant::from_ast(cx, variant),
|
||||
attrs: attrs,
|
||||
style: style,
|
||||
fields: fields,
|
||||
}
|
||||
@@ -115,18 +116,18 @@ fn enum_from_ast<'a>(cx: &Ctxt, variants: &'a [syn::Variant]) -> Vec<Variant<'a>
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn struct_from_ast<'a>(cx: &Ctxt, data: &'a syn::VariantData) -> (Style, Vec<Field<'a>>) {
|
||||
fn struct_from_ast<'a>(cx: &Ctxt, data: &'a syn::VariantData, attrs: Option<&attr::Variant>) -> (Style, Vec<Field<'a>>) {
|
||||
match *data {
|
||||
syn::VariantData::Struct(ref fields) => (Style::Struct, fields_from_ast(cx, fields)),
|
||||
syn::VariantData::Struct(ref fields) => (Style::Struct, fields_from_ast(cx, fields, attrs)),
|
||||
syn::VariantData::Tuple(ref fields) if fields.len() == 1 => {
|
||||
(Style::Newtype, fields_from_ast(cx, fields))
|
||||
(Style::Newtype, fields_from_ast(cx, fields, attrs))
|
||||
}
|
||||
syn::VariantData::Tuple(ref fields) => (Style::Tuple, fields_from_ast(cx, fields)),
|
||||
syn::VariantData::Tuple(ref fields) => (Style::Tuple, fields_from_ast(cx, fields, attrs)),
|
||||
syn::VariantData::Unit => (Style::Unit, Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn fields_from_ast<'a>(cx: &Ctxt, fields: &'a [syn::Field]) -> Vec<Field<'a>> {
|
||||
fn fields_from_ast<'a>(cx: &Ctxt, fields: &'a [syn::Field], attrs: Option<&attr::Variant>) -> Vec<Field<'a>> {
|
||||
fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -134,7 +135,7 @@ fn fields_from_ast<'a>(cx: &Ctxt, fields: &'a [syn::Field]) -> Vec<Field<'a>> {
|
||||
|(i, field)| {
|
||||
Field {
|
||||
ident: field.ident.clone(),
|
||||
attrs: attr::Field::from_ast(cx, i, field),
|
||||
attrs: attr::Field::from_ast(cx, i, field, attrs),
|
||||
ty: &field.ty,
|
||||
}
|
||||
},
|
||||
|
||||
@@ -166,7 +166,7 @@ pub enum Identifier {
|
||||
|
||||
impl Container {
|
||||
/// Extract out the `#[serde(...)]` attributes from an item.
|
||||
pub fn from_ast(cx: &Ctxt, item: &syn::MacroInput) -> Self {
|
||||
pub fn from_ast(cx: &Ctxt, item: &syn::DeriveInput) -> Self {
|
||||
let mut ser_name = Attr::none(cx, "rename");
|
||||
let mut de_name = Attr::none(cx, "rename");
|
||||
let mut deny_unknown_fields = BoolAttr::none(cx, "deny_unknown_fields");
|
||||
@@ -421,7 +421,7 @@ impl Container {
|
||||
|
||||
fn decide_tag(
|
||||
cx: &Ctxt,
|
||||
item: &syn::MacroInput,
|
||||
item: &syn::DeriveInput,
|
||||
untagged: BoolAttr,
|
||||
internal_tag: Attr<String>,
|
||||
content: Attr<String>,
|
||||
@@ -477,7 +477,7 @@ fn decide_tag(
|
||||
|
||||
fn decide_identifier(
|
||||
cx: &Ctxt,
|
||||
item: &syn::MacroInput,
|
||||
item: &syn::DeriveInput,
|
||||
field_identifier: BoolAttr,
|
||||
variant_identifier: BoolAttr,
|
||||
) -> Identifier {
|
||||
@@ -510,6 +510,9 @@ pub struct Variant {
|
||||
skip_deserializing: bool,
|
||||
skip_serializing: bool,
|
||||
other: bool,
|
||||
serialize_with: Option<syn::Path>,
|
||||
deserialize_with: Option<syn::Path>,
|
||||
borrow: Option<syn::MetaItem>,
|
||||
}
|
||||
|
||||
impl Variant {
|
||||
@@ -520,6 +523,9 @@ impl Variant {
|
||||
let mut skip_serializing = BoolAttr::none(cx, "skip_serializing");
|
||||
let mut rename_all = Attr::none(cx, "rename_all");
|
||||
let mut other = BoolAttr::none(cx, "other");
|
||||
let mut serialize_with = Attr::none(cx, "serialize_with");
|
||||
let mut deserialize_with = Attr::none(cx, "deserialize_with");
|
||||
let mut borrow = Attr::none(cx, "borrow");
|
||||
|
||||
for meta_items in variant.attrs.iter().filter_map(get_serde_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
@@ -569,6 +575,44 @@ impl Variant {
|
||||
other.set_true();
|
||||
}
|
||||
|
||||
// Parse `#[serde(with = "...")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
|
||||
let mut ser_path = path.clone();
|
||||
ser_path.segments.push("serialize".into());
|
||||
serialize_with.set(ser_path);
|
||||
let mut de_path = path;
|
||||
de_path.segments.push("deserialize".into());
|
||||
deserialize_with.set(de_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(serialize_with = "...")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "serialize_with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
|
||||
serialize_with.set(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(deserialize_with = "...")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "deserialize_with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
|
||||
deserialize_with.set(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Defer `#[serde(borrow)]` and `#[serde(borrow = "'a + 'b")]`
|
||||
MetaItem(ref mi) if mi.name() == "borrow" => {
|
||||
match variant.data {
|
||||
syn::VariantData::Tuple(ref fields) if fields.len() == 1 => {
|
||||
borrow.set(mi.clone());
|
||||
}
|
||||
_ => {
|
||||
cx.error("#[serde(borrow)] may only be used on newtype variants");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MetaItem(ref meta_item) => {
|
||||
cx.error(format!("unknown serde variant attribute `{}`", meta_item.name()));
|
||||
}
|
||||
@@ -595,6 +639,9 @@ impl Variant {
|
||||
skip_deserializing: skip_deserializing.get(),
|
||||
skip_serializing: skip_serializing.get(),
|
||||
other: other.get(),
|
||||
serialize_with: serialize_with.get(),
|
||||
deserialize_with: deserialize_with.get(),
|
||||
borrow: borrow.get(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -626,6 +673,14 @@ impl Variant {
|
||||
pub fn other(&self) -> bool {
|
||||
self.other
|
||||
}
|
||||
|
||||
pub fn serialize_with(&self) -> Option<&syn::Path> {
|
||||
self.serialize_with.as_ref()
|
||||
}
|
||||
|
||||
pub fn deserialize_with(&self) -> Option<&syn::Path> {
|
||||
self.deserialize_with.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents field attribute information
|
||||
@@ -659,7 +714,7 @@ pub enum Default {
|
||||
|
||||
impl Field {
|
||||
/// Extract out the `#[serde(...)]` attributes from a struct field.
|
||||
pub fn from_ast(cx: &Ctxt, index: usize, field: &syn::Field) -> Self {
|
||||
pub fn from_ast(cx: &Ctxt, index: usize, field: &syn::Field, attrs: Option<&Variant>) -> Self {
|
||||
let mut ser_name = Attr::none(cx, "rename");
|
||||
let mut de_name = Attr::none(cx, "rename");
|
||||
let mut skip_serializing = BoolAttr::none(cx, "skip_serializing");
|
||||
@@ -678,7 +733,13 @@ impl Field {
|
||||
None => index.to_string(),
|
||||
};
|
||||
|
||||
for meta_items in field.attrs.iter().filter_map(get_serde_meta_items) {
|
||||
let variant_borrow = attrs
|
||||
.map(|variant| &variant.borrow)
|
||||
.unwrap_or(&None)
|
||||
.as_ref()
|
||||
.map(|borrow| vec![MetaItem(borrow.clone())]);
|
||||
|
||||
for meta_items in field.attrs.iter().filter_map(get_serde_meta_items).chain(variant_borrow) {
|
||||
for meta_item in meta_items {
|
||||
match meta_item {
|
||||
// Parse `#[serde(rename = "foo")]`
|
||||
@@ -719,6 +780,12 @@ impl Field {
|
||||
skip_deserializing.set_true();
|
||||
}
|
||||
|
||||
// Parse `#[serde(skip)]`
|
||||
MetaItem(Word(ref name)) if name == "skip" => {
|
||||
skip_serializing.set_true();
|
||||
skip_deserializing.set_true();
|
||||
},
|
||||
|
||||
// Parse `#[serde(skip_serializing_if = "...")]`
|
||||
MetaItem(NameValue(ref name, ref lit)) if name == "skip_serializing_if" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
|
||||
|
||||
@@ -6,7 +6,10 @@
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
// See https://users.rust-lang.org/t/psa-dealing-with-warning-unused-import-std-ascii-asciiext-in-today-s-nightly/13726
|
||||
#[allow(unused_imports)]
|
||||
use std::ascii::AsciiExt;
|
||||
|
||||
use std::str::FromStr;
|
||||
|
||||
use self::RenameRule::*;
|
||||
@@ -27,6 +30,8 @@ pub enum RenameRule {
|
||||
ScreamingSnakeCase,
|
||||
/// Rename direct children to "kebab-case" style.
|
||||
KebabCase,
|
||||
/// Rename direct children to "SCREAMING-KEBAB-CASE" style.
|
||||
ScreamingKebabCase
|
||||
}
|
||||
|
||||
impl RenameRule {
|
||||
@@ -47,6 +52,7 @@ impl RenameRule {
|
||||
}
|
||||
ScreamingSnakeCase => SnakeCase.apply_to_variant(variant).to_ascii_uppercase(),
|
||||
KebabCase => SnakeCase.apply_to_variant(variant).replace('_', "-"),
|
||||
ScreamingKebabCase => ScreamingSnakeCase.apply_to_variant(variant).replace('_', "-")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,6 +80,7 @@ impl RenameRule {
|
||||
}
|
||||
ScreamingSnakeCase => field.to_ascii_uppercase(),
|
||||
KebabCase => field.replace('_', "-"),
|
||||
ScreamingKebabCase => ScreamingSnakeCase.apply_to_field(field).replace('_', "-")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,6 +96,7 @@ impl FromStr for RenameRule {
|
||||
"snake_case" => Ok(SnakeCase),
|
||||
"SCREAMING_SNAKE_CASE" => Ok(ScreamingSnakeCase),
|
||||
"kebab-case" => Ok(KebabCase),
|
||||
"SCREAMING-KEBAB-CASE" => Ok(ScreamingKebabCase),
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
@@ -96,12 +104,12 @@ impl FromStr for RenameRule {
|
||||
|
||||
#[test]
|
||||
fn rename_variants() {
|
||||
for &(original, lower, camel, snake, screaming, kebab) in
|
||||
for &(original, lower, camel, snake, screaming, kebab, screaming_kebab) in
|
||||
&[
|
||||
("Outcome", "outcome", "outcome", "outcome", "OUTCOME", "outcome"),
|
||||
("VeryTasty", "verytasty", "veryTasty", "very_tasty", "VERY_TASTY", "very-tasty"),
|
||||
("A", "a", "a", "a", "A", "a"),
|
||||
("Z42", "z42", "z42", "z42", "Z42", "z42"),
|
||||
("Outcome", "outcome", "outcome", "outcome", "OUTCOME", "outcome", "OUTCOME"),
|
||||
("VeryTasty", "verytasty", "veryTasty", "very_tasty", "VERY_TASTY", "very-tasty", "VERY-TASTY"),
|
||||
("A", "a", "a", "a", "A", "a", "A"),
|
||||
("Z42", "z42", "z42", "z42", "Z42", "z42", "Z42"),
|
||||
] {
|
||||
assert_eq!(None.apply_to_variant(original), original);
|
||||
assert_eq!(LowerCase.apply_to_variant(original), lower);
|
||||
@@ -110,17 +118,18 @@ fn rename_variants() {
|
||||
assert_eq!(SnakeCase.apply_to_variant(original), snake);
|
||||
assert_eq!(ScreamingSnakeCase.apply_to_variant(original), screaming);
|
||||
assert_eq!(KebabCase.apply_to_variant(original), kebab);
|
||||
assert_eq!(ScreamingKebabCase.apply_to_variant(original), screaming_kebab);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_fields() {
|
||||
for &(original, pascal, camel, screaming, kebab) in
|
||||
for &(original, pascal, camel, screaming, kebab, screaming_kebab) in
|
||||
&[
|
||||
("outcome", "Outcome", "outcome", "OUTCOME", "outcome"),
|
||||
("very_tasty", "VeryTasty", "veryTasty", "VERY_TASTY", "very-tasty"),
|
||||
("a", "A", "a", "A", "a"),
|
||||
("z42", "Z42", "z42", "Z42", "z42"),
|
||||
("outcome", "Outcome", "outcome", "OUTCOME", "outcome", "OUTCOME"),
|
||||
("very_tasty", "VeryTasty", "veryTasty", "VERY_TASTY", "very-tasty", "VERY-TASTY"),
|
||||
("a", "A", "a", "A", "a", "A"),
|
||||
("z42", "Z42", "z42", "Z42", "z42", "Z42"),
|
||||
] {
|
||||
assert_eq!(None.apply_to_field(original), original);
|
||||
assert_eq!(PascalCase.apply_to_field(original), pascal);
|
||||
@@ -128,5 +137,6 @@ fn rename_fields() {
|
||||
assert_eq!(SnakeCase.apply_to_field(original), original);
|
||||
assert_eq!(ScreamingSnakeCase.apply_to_field(original), screaming);
|
||||
assert_eq!(KebabCase.apply_to_field(original), kebab);
|
||||
assert_eq!(ScreamingKebabCase.apply_to_field(original), screaming_kebab);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ use Ctxt;
|
||||
pub fn check(cx: &Ctxt, cont: &Container) {
|
||||
check_getter(cx, cont);
|
||||
check_identifier(cx, cont);
|
||||
check_variant_skip_attrs(cx, cont);
|
||||
}
|
||||
|
||||
/// Getters are only allowed inside structs (not enums) with the `remote`
|
||||
@@ -94,3 +95,58 @@ fn check_identifier(cx: &Ctxt, cont: &Container) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Skip-(de)serializing attributes are not allowed on variants marked
|
||||
/// (de)serialize_with.
|
||||
fn check_variant_skip_attrs(cx: &Ctxt, cont: &Container) {
|
||||
let variants = match cont.body {
|
||||
Body::Enum(ref variants) => variants,
|
||||
Body::Struct(_, _) => {
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
for variant in variants.iter() {
|
||||
if variant.attrs.serialize_with().is_some() {
|
||||
if variant.attrs.skip_serializing() {
|
||||
cx.error(format!("variant `{}` cannot have both #[serde(serialize_with)] and \
|
||||
#[serde(skip_serializing)]", variant.ident));
|
||||
}
|
||||
|
||||
for (i, field) in variant.fields.iter().enumerate() {
|
||||
let ident = field.ident.as_ref().map_or_else(|| format!("{}", i),
|
||||
|ident| format!("`{}`", ident));
|
||||
|
||||
if field.attrs.skip_serializing() {
|
||||
cx.error(format!("variant `{}` cannot have both #[serde(serialize_with)] and \
|
||||
a field {} marked with #[serde(skip_serializing)]",
|
||||
variant.ident, ident));
|
||||
}
|
||||
|
||||
if field.attrs.skip_serializing_if().is_some() {
|
||||
cx.error(format!("variant `{}` cannot have both #[serde(serialize_with)] and \
|
||||
a field {} marked with #[serde(skip_serializing_if)]",
|
||||
variant.ident, ident));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if variant.attrs.deserialize_with().is_some() {
|
||||
if variant.attrs.skip_deserializing() {
|
||||
cx.error(format!("variant `{}` cannot have both #[serde(deserialize_with)] and \
|
||||
#[serde(skip_deserializing)]", variant.ident));
|
||||
}
|
||||
|
||||
for (i, field) in variant.fields.iter().enumerate() {
|
||||
if field.attrs.skip_deserializing() {
|
||||
let ident = field.ident.as_ref().map_or_else(|| format!("{}", i),
|
||||
|ident| format!("`{}`", ident));
|
||||
|
||||
cx.error(format!("variant `{}` cannot have both #[serde(deserialize_with)] \
|
||||
and a field {} marked with #[serde(skip_deserializing)]",
|
||||
variant.ident, ident));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#![doc(html_root_url = "https://docs.rs/serde_derive_internals/0.15.0")]
|
||||
#![doc(html_root_url = "https://docs.rs/serde_derive_internals/0.17.0")]
|
||||
|
||||
extern crate syn;
|
||||
#[macro_use]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde_test"
|
||||
version = "1.0.1" # remember to update html_root_url
|
||||
version = "1.0.22" # remember to update html_root_url
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"]
|
||||
license = "MIT/Apache-2.0"
|
||||
description = "Token De/Serializer for testing De/Serialize implementations"
|
||||
@@ -12,10 +12,10 @@ readme = "README.md"
|
||||
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", path = "../serde" }
|
||||
serde = { version = "1.0.16", path = "../serde" }
|
||||
|
||||
[dev-dependencies]
|
||||
serde = { version = "1.0", path = "../serde", features = ["rc"] }
|
||||
serde = { version = "1.0.16", path = "../serde", features = ["rc"] }
|
||||
serde_derive = { version = "1.0", path = "../serde_derive" }
|
||||
|
||||
[badges]
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
use serde::{Serialize, Deserialize};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use de::Deserializer;
|
||||
use ser::Serializer;
|
||||
@@ -215,7 +215,7 @@ where
|
||||
///
|
||||
/// assert_de_tokens_error::<S>(
|
||||
/// &[
|
||||
/// Token::Struct { name: "S", len: 1 },
|
||||
/// Token::Struct { name: "S", len: 2 },
|
||||
/// Token::Str("x"),
|
||||
/// ],
|
||||
/// "unknown field `x`, expected `a` or `b`",
|
||||
|
||||
@@ -0,0 +1,661 @@
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use serde::ser::{SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant,
|
||||
SerializeTuple, SerializeTupleStruct, SerializeTupleVariant};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct Readable<T: ?Sized>(T);
|
||||
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct Compact<T: ?Sized>(T);
|
||||
|
||||
/// Trait to determine whether a value is represented in human-readable or
|
||||
/// compact form.
|
||||
///
|
||||
/// ```
|
||||
/// extern crate serde;
|
||||
/// extern crate serde_test;
|
||||
///
|
||||
/// use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
/// use serde_test::{Configure, Token, assert_tokens};
|
||||
///
|
||||
/// #[derive(Debug, PartialEq)]
|
||||
/// struct Example(u8, u8);
|
||||
///
|
||||
/// impl Serialize for Example {
|
||||
/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
/// where S: Serializer,
|
||||
/// {
|
||||
/// if serializer.is_human_readable() {
|
||||
/// format!("{}.{}", self.0, self.1).serialize(serializer)
|
||||
/// } else {
|
||||
/// (self.0, self.1).serialize(serializer)
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// impl<'de> Deserialize<'de> for Example {
|
||||
/// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
/// where D: Deserializer<'de>,
|
||||
/// {
|
||||
/// use serde::de::Error;
|
||||
/// if deserializer.is_human_readable() {
|
||||
/// let s = String::deserialize(deserializer)?;
|
||||
/// let parts: Vec<_> = s.split('.').collect();
|
||||
/// Ok(Example(
|
||||
/// parts[0].parse().map_err(D::Error::custom)?,
|
||||
/// parts[1].parse().map_err(D::Error::custom)?,
|
||||
/// ))
|
||||
/// } else {
|
||||
/// let (x, y) = Deserialize::deserialize(deserializer)?;
|
||||
/// Ok(Example(x, y))
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// assert_tokens(
|
||||
/// &Example(1, 0).compact(),
|
||||
/// &[
|
||||
/// Token::Tuple { len: 2 },
|
||||
/// Token::U8(1),
|
||||
/// Token::U8(0),
|
||||
/// Token::TupleEnd,
|
||||
/// ],
|
||||
/// );
|
||||
/// assert_tokens(
|
||||
/// &Example(1, 0).readable(),
|
||||
/// &[
|
||||
/// Token::Str("1.0"),
|
||||
/// ],
|
||||
/// );
|
||||
/// }
|
||||
/// ```
|
||||
pub trait Configure {
|
||||
/// Marks `self` as using `is_human_readable == true`
|
||||
fn readable(self) -> Readable<Self> where Self: Sized {
|
||||
Readable(self)
|
||||
}
|
||||
/// Marks `self` as using `is_human_readable == false`
|
||||
fn compact(self) -> Compact<Self> where Self: Sized {
|
||||
Compact(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ?Sized> Configure for T {}
|
||||
|
||||
impl<T: ?Sized> Serialize for Readable<T>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
self.0.serialize(Readable(serializer))
|
||||
}
|
||||
}
|
||||
impl<T: ?Sized> Serialize for Compact<T>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
self.0.serialize(Compact(serializer))
|
||||
}
|
||||
}
|
||||
impl<'de, T> Deserialize<'de> for Readable<T>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
T::deserialize(Readable(deserializer)).map(Readable)
|
||||
}
|
||||
}
|
||||
impl<'de, T> Deserialize<'de> for Compact<T>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
T::deserialize(Compact(deserializer)).map(Compact)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, T> DeserializeSeed<'de> for Readable<T>
|
||||
where
|
||||
T: DeserializeSeed<'de>,
|
||||
{
|
||||
type Value = T::Value;
|
||||
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
self.0.deserialize(Readable(deserializer))
|
||||
}
|
||||
}
|
||||
impl<'de, T> DeserializeSeed<'de> for Compact<T>
|
||||
where
|
||||
T: DeserializeSeed<'de>,
|
||||
{
|
||||
type Value = T::Value;
|
||||
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
self.0.deserialize(Compact(deserializer))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
macro_rules! forward_method {
|
||||
($name: ident (self $(, $arg: ident : $arg_type: ty)* ) -> $return_type: ty) => {
|
||||
fn $name (self $(, $arg : $arg_type)* ) -> $return_type {
|
||||
(self.0).$name( $($arg),* )
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! forward_serialize_methods {
|
||||
( $( $name: ident $arg_type: ty ),* ) => {
|
||||
$(
|
||||
forward_method!($name(self, v : $arg_type) -> Result<Self::Ok, Self::Error>);
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! impl_serializer {
|
||||
($wrapper: ident, $is_human_readable : expr) => {
|
||||
impl<S> Serializer for $wrapper<S>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
|
||||
type SerializeSeq = $wrapper<S::SerializeSeq>;
|
||||
type SerializeTuple = $wrapper<S::SerializeTuple>;
|
||||
type SerializeTupleStruct = $wrapper<S::SerializeTupleStruct>;
|
||||
type SerializeTupleVariant = $wrapper<S::SerializeTupleVariant>;
|
||||
type SerializeMap = $wrapper<S::SerializeMap>;
|
||||
type SerializeStruct = $wrapper<S::SerializeStruct>;
|
||||
type SerializeStructVariant = $wrapper<S::SerializeStructVariant>;
|
||||
|
||||
fn is_human_readable(&self) -> bool {
|
||||
$is_human_readable
|
||||
}
|
||||
|
||||
|
||||
forward_serialize_methods!{
|
||||
serialize_bool bool,
|
||||
serialize_i8 i8,
|
||||
serialize_i16 i16,
|
||||
serialize_i32 i32,
|
||||
serialize_i64 i64,
|
||||
serialize_u8 u8,
|
||||
serialize_u16 u16,
|
||||
serialize_u32 u32,
|
||||
serialize_u64 u64,
|
||||
serialize_f32 f32,
|
||||
serialize_f64 f64,
|
||||
serialize_char char,
|
||||
serialize_str &str,
|
||||
serialize_bytes &[u8],
|
||||
serialize_unit_struct &'static str
|
||||
|
||||
}
|
||||
|
||||
fn serialize_unit(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize_unit()
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: u32,
|
||||
variant: &'static str,
|
||||
) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize_unit_variant(name, variant_index, variant)
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized>(
|
||||
self,
|
||||
name: &'static str,
|
||||
value: &T,
|
||||
) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_newtype_struct(name, &$wrapper(value))
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: ?Sized>(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: u32,
|
||||
variant: &'static str,
|
||||
value: &T,
|
||||
) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0
|
||||
.serialize_newtype_variant(name, variant_index, variant, &$wrapper(value))
|
||||
}
|
||||
|
||||
fn serialize_none(self) -> Result<S::Ok, Self::Error> {
|
||||
self.0.serialize_none()
|
||||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<S::Ok, Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_some(&$wrapper(value))
|
||||
}
|
||||
|
||||
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
|
||||
self.0.serialize_seq(len).map($wrapper)
|
||||
}
|
||||
|
||||
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
|
||||
self.0.serialize_tuple(len).map($wrapper)
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(
|
||||
self,
|
||||
name: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTupleStruct, Self::Error> {
|
||||
self.0.serialize_tuple_struct(name, len).map($wrapper)
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: u32,
|
||||
variant: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTupleVariant, Self::Error> {
|
||||
self.0
|
||||
.serialize_tuple_variant(name, variant_index, variant, len)
|
||||
.map($wrapper)
|
||||
}
|
||||
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
|
||||
self.0.serialize_map(len).map($wrapper)
|
||||
}
|
||||
|
||||
fn serialize_struct(
|
||||
self,
|
||||
name: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStruct, Self::Error> {
|
||||
self.0.serialize_struct(name, len).map($wrapper)
|
||||
}
|
||||
|
||||
fn serialize_struct_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: u32,
|
||||
variant: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStructVariant, Self::Error> {
|
||||
self.0
|
||||
.serialize_struct_variant(name, variant_index, variant, len)
|
||||
.map($wrapper)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SerializeSeq for $wrapper<S>
|
||||
where
|
||||
S: SerializeSeq,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_element(&$wrapper(value))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SerializeTuple for $wrapper<S>
|
||||
where
|
||||
S: SerializeTuple,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_element(&$wrapper(value))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SerializeTupleStruct for $wrapper<S>
|
||||
where
|
||||
S: SerializeTupleStruct,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_field(&$wrapper(value))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SerializeTupleVariant for $wrapper<S>
|
||||
where
|
||||
S: SerializeTupleVariant,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_field(&$wrapper(value))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SerializeMap for $wrapper<S>
|
||||
where
|
||||
S: SerializeMap,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_key(&$wrapper(key))
|
||||
}
|
||||
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_value(&$wrapper(value))
|
||||
}
|
||||
fn serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<(), S::Error>
|
||||
where
|
||||
K: Serialize,
|
||||
V: Serialize,
|
||||
{
|
||||
self.0.serialize_entry(key, &$wrapper(value))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SerializeStruct for $wrapper<S>
|
||||
where
|
||||
S: SerializeStruct,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_field<T: ?Sized>(&mut self, name: &'static str, field: &T) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_field(name, &$wrapper(field))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SerializeStructVariant for $wrapper<S>
|
||||
where
|
||||
S: SerializeStructVariant,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_field<T: ?Sized>(&mut self, name: &'static str, field: &T) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_field(name, &$wrapper(field))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl_serializer!(Readable, true);
|
||||
impl_serializer!(Compact, false);
|
||||
|
||||
|
||||
use serde::de::{Visitor, EnumAccess, VariantAccess, MapAccess, DeserializeSeed, SeqAccess, Error};
|
||||
|
||||
macro_rules! forward_deserialize_methods {
|
||||
( $wrapper : ident ( $( $name: ident ),* ) ) => {
|
||||
$(
|
||||
fn $name<V>(self, visitor: V) -> Result<V::Value, D::Error> where V: Visitor<'de> {
|
||||
(self.0).$name($wrapper(visitor))
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
macro_rules! impl_deserializer {
|
||||
($wrapper : ident, $is_human_readable : expr) => {
|
||||
impl <'de, D> Deserializer<'de> for $wrapper<D> where D: Deserializer<'de> {
|
||||
type Error = D::Error;
|
||||
|
||||
forward_deserialize_methods! {
|
||||
$wrapper (
|
||||
deserialize_any,
|
||||
deserialize_bool,
|
||||
deserialize_u8,
|
||||
deserialize_u16,
|
||||
deserialize_u32,
|
||||
deserialize_u64,
|
||||
deserialize_i8,
|
||||
deserialize_i16,
|
||||
deserialize_i32,
|
||||
deserialize_i64,
|
||||
deserialize_f32,
|
||||
deserialize_f64,
|
||||
deserialize_char,
|
||||
deserialize_str,
|
||||
deserialize_string,
|
||||
deserialize_bytes,
|
||||
deserialize_byte_buf,
|
||||
deserialize_option,
|
||||
deserialize_unit,
|
||||
deserialize_seq,
|
||||
deserialize_map,
|
||||
deserialize_identifier,
|
||||
deserialize_ignored_any
|
||||
)
|
||||
}
|
||||
|
||||
fn deserialize_unit_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value, D::Error> where V: Visitor<'de> {
|
||||
self.0.deserialize_unit_struct(name, $wrapper(visitor))
|
||||
}
|
||||
fn deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value, D::Error> where V: Visitor<'de> {
|
||||
self.0.deserialize_newtype_struct(name, $wrapper(visitor))
|
||||
}
|
||||
fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, D::Error> where V: Visitor<'de> {
|
||||
self.0.deserialize_tuple(len, $wrapper(visitor))
|
||||
}
|
||||
fn deserialize_tuple_struct<V>(self, name: &'static str, len: usize, visitor: V) -> Result<V::Value, D::Error> where V: Visitor<'de> {
|
||||
self.0.deserialize_tuple_struct(name, len, $wrapper(visitor))
|
||||
}
|
||||
fn deserialize_struct<V>(self, name: &'static str, fields: &'static [&'static str], visitor: V) -> Result<V::Value, D::Error> where V: Visitor<'de> {
|
||||
self.0.deserialize_struct(name, fields, $wrapper(visitor))
|
||||
}
|
||||
fn deserialize_enum<V>(self, name: &'static str, variants: &'static [&'static str], visitor: V) -> Result<V::Value, D::Error> where V: Visitor<'de> {
|
||||
self.0.deserialize_enum(name, variants, $wrapper(visitor))
|
||||
}
|
||||
|
||||
fn is_human_readable(&self) -> bool {
|
||||
$is_human_readable
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, D> Visitor<'de> for $wrapper<D> where D: Visitor<'de> {
|
||||
type Value = D::Value;
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.0.expecting(formatter)
|
||||
}
|
||||
fn visit_bool<E>(self, v: bool) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_bool(v)
|
||||
}
|
||||
fn visit_i8<E>(self, v: i8) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_i8(v)
|
||||
}
|
||||
fn visit_i16<E>(self, v: i16) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_i16(v)
|
||||
}
|
||||
fn visit_i32<E>(self, v: i32) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_i32(v)
|
||||
}
|
||||
fn visit_i64<E>(self, v: i64) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_i64(v)
|
||||
}
|
||||
fn visit_u8<E>(self, v: u8) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_u8(v)
|
||||
}
|
||||
fn visit_u16<E>(self, v: u16) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_u16(v)
|
||||
}
|
||||
fn visit_u32<E>(self, v: u32) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_u32(v)
|
||||
}
|
||||
fn visit_u64<E>(self, v: u64) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_u64(v)
|
||||
}
|
||||
fn visit_f32<E>(self, v: f32) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_f32(v)
|
||||
}
|
||||
fn visit_f64<E>(self, v: f64) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_f64(v)
|
||||
}
|
||||
fn visit_char<E>(self, v: char) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_char(v)
|
||||
}
|
||||
fn visit_str<E>(self, v: &str) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_str(v)
|
||||
}
|
||||
fn visit_borrowed_str<E>(self, v: &'de str) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_borrowed_str(v)
|
||||
}
|
||||
fn visit_string<E>(self, v: String) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_string(v)
|
||||
}
|
||||
fn visit_bytes<E>(self, v: &[u8]) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_bytes(v)
|
||||
}
|
||||
fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_borrowed_bytes(v)
|
||||
}
|
||||
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_byte_buf(v)
|
||||
}
|
||||
fn visit_none<E>(self) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_none()
|
||||
}
|
||||
fn visit_some<D2>(self, deserializer: D2) -> Result<Self::Value, D2::Error> where D2: Deserializer<'de> {
|
||||
self.0.visit_some($wrapper(deserializer))
|
||||
}
|
||||
fn visit_unit<E>(self) -> Result<D::Value, E> where E: Error {
|
||||
self.0.visit_unit()
|
||||
}
|
||||
fn visit_newtype_struct<D2>(self, deserializer: D2) -> Result<Self::Value, D2::Error> where D2: Deserializer<'de> {
|
||||
self.0.visit_newtype_struct($wrapper(deserializer))
|
||||
}
|
||||
fn visit_seq<V>(self, seq: V) -> Result<D::Value, V::Error> where V: SeqAccess<'de> {
|
||||
self.0.visit_seq($wrapper(seq))
|
||||
}
|
||||
fn visit_map<V>(self, map: V) -> Result<D::Value, V::Error> where V: MapAccess<'de> {
|
||||
self.0.visit_map($wrapper(map))
|
||||
}
|
||||
fn visit_enum<V>(self, data: V) -> Result<D::Value, V::Error> where V: EnumAccess<'de> {
|
||||
self.0.visit_enum($wrapper(data))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, D> SeqAccess<'de> for $wrapper<D> where D: SeqAccess<'de> {
|
||||
type Error = D::Error;
|
||||
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, D::Error> where T: DeserializeSeed<'de> {
|
||||
self.0.next_element_seed($wrapper(seed))
|
||||
}
|
||||
fn size_hint(&self) -> Option<usize> {
|
||||
self.0.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, D> MapAccess<'de> for $wrapper<D> where D: MapAccess<'de> {
|
||||
type Error = D::Error;
|
||||
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, D::Error> where K: DeserializeSeed<'de> {
|
||||
self.0.next_key_seed($wrapper(seed))
|
||||
}
|
||||
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, D::Error> where V: DeserializeSeed<'de> {
|
||||
self.0.next_value_seed($wrapper(seed))
|
||||
}
|
||||
fn size_hint(&self) -> Option<usize> {
|
||||
self.0.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, D> EnumAccess<'de> for $wrapper<D> where D: EnumAccess<'de> {
|
||||
type Error = D::Error;
|
||||
type Variant = $wrapper<D::Variant>;
|
||||
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> where V: DeserializeSeed<'de> {
|
||||
self.0.variant_seed($wrapper(seed)).map(|(value, variant)| (value, $wrapper(variant)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, D> VariantAccess<'de> for $wrapper<D> where D: VariantAccess<'de> {
|
||||
type Error = D::Error;
|
||||
fn unit_variant(self) -> Result<(), D::Error> {
|
||||
self.0.unit_variant()
|
||||
}
|
||||
fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, D::Error> where T: DeserializeSeed<'de> {
|
||||
self.0.newtype_variant_seed($wrapper(seed))
|
||||
}
|
||||
fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, D::Error> where V: Visitor<'de> {
|
||||
self.0.tuple_variant(len, $wrapper(visitor))
|
||||
}
|
||||
fn struct_variant<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, D::Error> where V: Visitor<'de> {
|
||||
self.0.struct_variant(fields, $wrapper(visitor))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl_deserializer!(Readable, true);
|
||||
impl_deserializer!(Compact, false);
|
||||
+43
-37
@@ -100,7 +100,7 @@ impl<'de> Deserializer<'de> {
|
||||
DeserializerSeqVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
end: end.clone(),
|
||||
end: end,
|
||||
},
|
||||
)
|
||||
);
|
||||
@@ -122,7 +122,7 @@ impl<'de> Deserializer<'de> {
|
||||
DeserializerMapVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
end: end.clone(),
|
||||
end: end,
|
||||
},
|
||||
)
|
||||
);
|
||||
@@ -165,15 +165,14 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
|
||||
Token::ByteBuf(v) => visitor.visit_byte_buf(v.to_vec()),
|
||||
Token::None => visitor.visit_none(),
|
||||
Token::Some => visitor.visit_some(self),
|
||||
Token::Unit => visitor.visit_unit(),
|
||||
Token::UnitStruct { name: _ } => visitor.visit_unit(),
|
||||
Token::NewtypeStruct { name: _ } => visitor.visit_newtype_struct(self),
|
||||
Token::Unit | Token::UnitStruct { .. } => visitor.visit_unit(),
|
||||
Token::NewtypeStruct { .. } => visitor.visit_newtype_struct(self),
|
||||
Token::Seq { len } => self.visit_seq(len, Token::SeqEnd, visitor),
|
||||
Token::Tuple { len } => self.visit_seq(Some(len), Token::TupleEnd, visitor),
|
||||
Token::TupleStruct { name: _, len } => self.visit_seq(Some(len), Token::TupleStructEnd, visitor),
|
||||
Token::TupleStruct { len, .. } => self.visit_seq(Some(len), Token::TupleStructEnd, visitor),
|
||||
Token::Map { len } => self.visit_map(len, Token::MapEnd, visitor),
|
||||
Token::Struct { name: _, len } => self.visit_map(Some(len), Token::StructEnd, visitor),
|
||||
Token::Enum { name: _ } => {
|
||||
Token::Struct { len, .. } => self.visit_map(Some(len), Token::StructEnd, visitor),
|
||||
Token::Enum { .. } => {
|
||||
let variant = self.next_token();
|
||||
let next = self.peek_token();
|
||||
match (variant, next) {
|
||||
@@ -195,14 +194,14 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Token::UnitVariant { name: _, variant } => visitor.visit_str(variant),
|
||||
Token::NewtypeVariant { name: _, variant } => {
|
||||
Token::UnitVariant { variant, .. } => visitor.visit_str(variant),
|
||||
Token::NewtypeVariant { variant, .. } => {
|
||||
visitor.visit_map(EnumMapVisitor::new(self, Token::Str(variant), EnumFormat::Any),)
|
||||
}
|
||||
Token::TupleVariant { name: _, variant, len: _ } => {
|
||||
Token::TupleVariant { variant, .. } => {
|
||||
visitor.visit_map(EnumMapVisitor::new(self, Token::Str(variant), EnumFormat::Seq),)
|
||||
}
|
||||
Token::StructVariant { name: _, variant, len: _ } => {
|
||||
Token::StructVariant { variant, .. } => {
|
||||
visitor.visit_map(EnumMapVisitor::new(self, Token::Str(variant), EnumFormat::Map),)
|
||||
}
|
||||
Token::SeqEnd | Token::TupleEnd | Token::TupleStructEnd | Token::MapEnd |
|
||||
@@ -245,10 +244,10 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
|
||||
|
||||
visitor.visit_enum(DeserializerEnumVisitor { de: self })
|
||||
}
|
||||
Token::UnitVariant { name: n, variant: _ } |
|
||||
Token::NewtypeVariant { name: n, variant: _ } |
|
||||
Token::TupleVariant { name: n, variant: _, len: _ } |
|
||||
Token::StructVariant { name: n, variant: _, len: _ } if name == n => {
|
||||
Token::UnitVariant { name: n, .. } |
|
||||
Token::NewtypeVariant { name: n, .. } |
|
||||
Token::TupleVariant { name: n, .. } |
|
||||
Token::StructVariant { name: n, .. } if name == n => {
|
||||
visitor.visit_enum(DeserializerEnumVisitor { de: self })
|
||||
}
|
||||
_ => {
|
||||
@@ -262,7 +261,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
match self.peek_token() {
|
||||
Token::UnitStruct { name: _ } => {
|
||||
Token::UnitStruct { .. } => {
|
||||
assert_next_token!(self, Token::UnitStruct { name: name });
|
||||
visitor.visit_unit()
|
||||
}
|
||||
@@ -275,7 +274,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
match self.peek_token() {
|
||||
Token::NewtypeStruct { name: _ } => {
|
||||
Token::NewtypeStruct { .. } => {
|
||||
assert_next_token!(self, Token::NewtypeStruct { name: name });
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
@@ -289,19 +288,19 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
|
||||
{
|
||||
match self.peek_token() {
|
||||
Token::Unit |
|
||||
Token::UnitStruct { name: _ } => {
|
||||
Token::UnitStruct { .. } => {
|
||||
self.next_token();
|
||||
visitor.visit_unit()
|
||||
}
|
||||
Token::Seq { len: _ } => {
|
||||
Token::Seq { .. } => {
|
||||
self.next_token();
|
||||
self.visit_seq(Some(len), Token::SeqEnd, visitor)
|
||||
}
|
||||
Token::Tuple { len: _ } => {
|
||||
Token::Tuple { .. } => {
|
||||
self.next_token();
|
||||
self.visit_seq(Some(len), Token::TupleEnd, visitor)
|
||||
}
|
||||
Token::TupleStruct { name: _, len: _ } => {
|
||||
Token::TupleStruct { .. } => {
|
||||
self.next_token();
|
||||
self.visit_seq(Some(len), Token::TupleStructEnd, visitor)
|
||||
}
|
||||
@@ -323,19 +322,19 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
|
||||
self.next_token();
|
||||
visitor.visit_unit()
|
||||
}
|
||||
Token::UnitStruct { name: _ } => {
|
||||
Token::UnitStruct { .. } => {
|
||||
assert_next_token!(self, Token::UnitStruct { name: name });
|
||||
visitor.visit_unit()
|
||||
}
|
||||
Token::Seq { len: _ } => {
|
||||
Token::Seq { .. } => {
|
||||
self.next_token();
|
||||
self.visit_seq(Some(len), Token::SeqEnd, visitor)
|
||||
}
|
||||
Token::Tuple { len: _ } => {
|
||||
Token::Tuple { .. } => {
|
||||
self.next_token();
|
||||
self.visit_seq(Some(len), Token::TupleEnd, visitor)
|
||||
}
|
||||
Token::TupleStruct { name: _, len: n } => {
|
||||
Token::TupleStruct { len: n, .. } => {
|
||||
assert_next_token!(self, Token::TupleStruct { name: name, len: n });
|
||||
self.visit_seq(Some(len), Token::TupleStructEnd, visitor)
|
||||
}
|
||||
@@ -353,17 +352,24 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
match self.peek_token() {
|
||||
Token::Struct { name: _, len: n } => {
|
||||
assert_next_token!(self, Token::Struct { name: name, len: n });
|
||||
Token::Struct { .. } => {
|
||||
assert_next_token!(self, Token::Struct { name: name, len: fields.len() });
|
||||
self.visit_map(Some(fields.len()), Token::StructEnd, visitor)
|
||||
}
|
||||
Token::Map { len: _ } => {
|
||||
Token::Map { .. } => {
|
||||
self.next_token();
|
||||
self.visit_map(Some(fields.len()), Token::MapEnd, visitor)
|
||||
}
|
||||
_ => self.deserialize_any(visitor),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_human_readable(&self) -> bool {
|
||||
panic!(
|
||||
"Types which have different human-readable and compact representations \
|
||||
must explicitly mark their test cases with `serde_test::Configure`"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
@@ -442,10 +448,10 @@ impl<'de, 'a> EnumAccess<'de> for DeserializerEnumVisitor<'a, 'de> {
|
||||
V: DeserializeSeed<'de>,
|
||||
{
|
||||
match self.de.peek_token() {
|
||||
Token::UnitVariant { name: _, variant: v } |
|
||||
Token::NewtypeVariant { name: _, variant: v } |
|
||||
Token::TupleVariant { name: _, variant: v, len: _ } |
|
||||
Token::StructVariant { name: _, variant: v, len: _ } => {
|
||||
Token::UnitVariant { variant: v, .. } |
|
||||
Token::NewtypeVariant { variant: v, .. } |
|
||||
Token::TupleVariant { variant: v, .. } |
|
||||
Token::StructVariant { variant: v, .. } => {
|
||||
let de = v.into_deserializer();
|
||||
let value = try!(seed.deserialize(de));
|
||||
Ok((value, self))
|
||||
@@ -463,7 +469,7 @@ impl<'de, 'a> VariantAccess<'de> for DeserializerEnumVisitor<'a, 'de> {
|
||||
|
||||
fn unit_variant(self) -> Result<(), Error> {
|
||||
match self.de.peek_token() {
|
||||
Token::UnitVariant { name: _, variant: _ } => {
|
||||
Token::UnitVariant { .. } => {
|
||||
self.de.next_token();
|
||||
Ok(())
|
||||
}
|
||||
@@ -476,7 +482,7 @@ impl<'de, 'a> VariantAccess<'de> for DeserializerEnumVisitor<'a, 'de> {
|
||||
T: DeserializeSeed<'de>,
|
||||
{
|
||||
match self.de.peek_token() {
|
||||
Token::NewtypeVariant { name: _, variant: _ } => {
|
||||
Token::NewtypeVariant { .. } => {
|
||||
self.de.next_token();
|
||||
seed.deserialize(self.de)
|
||||
}
|
||||
@@ -489,7 +495,7 @@ impl<'de, 'a> VariantAccess<'de> for DeserializerEnumVisitor<'a, 'de> {
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
match self.de.peek_token() {
|
||||
Token::TupleVariant { name: _, variant: _, len: enum_len } => {
|
||||
Token::TupleVariant { len: enum_len, .. } => {
|
||||
let token = self.de.next_token();
|
||||
|
||||
if len == enum_len {
|
||||
@@ -517,7 +523,7 @@ impl<'de, 'a> VariantAccess<'de> for DeserializerEnumVisitor<'a, 'de> {
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
match self.de.peek_token() {
|
||||
Token::StructVariant { name: _, variant: _, len: enum_len } => {
|
||||
Token::StructVariant { len: enum_len, .. } => {
|
||||
let token = self.de.next_token();
|
||||
|
||||
if fields.len() == enum_len {
|
||||
|
||||
@@ -17,13 +17,13 @@ pub struct Error {
|
||||
}
|
||||
|
||||
impl ser::Error for Error {
|
||||
fn custom<T: Display>(msg: T) -> Error {
|
||||
fn custom<T: Display>(msg: T) -> Self {
|
||||
Error { msg: msg.to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Error for Error {
|
||||
fn custom<T: Display>(msg: T) -> Error {
|
||||
fn custom<T: Display>(msg: T) -> Self {
|
||||
Error { msg: msg.to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
+17
-3
@@ -155,7 +155,18 @@
|
||||
//! # }
|
||||
//! ```
|
||||
|
||||
#![doc(html_root_url = "https://docs.rs/serde_test/1.0.1")]
|
||||
#![doc(html_root_url = "https://docs.rs/serde_test/1.0.22")]
|
||||
|
||||
#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))]
|
||||
// Whitelisted clippy lints
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(float_cmp))]
|
||||
// Whitelisted clippy_pedantic lints
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(
|
||||
missing_docs_in_private_items,
|
||||
stutter,
|
||||
use_debug,
|
||||
use_self,
|
||||
))]
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde;
|
||||
@@ -164,12 +175,15 @@ mod ser;
|
||||
mod de;
|
||||
mod error;
|
||||
|
||||
mod configure;
|
||||
mod token;
|
||||
mod assert;
|
||||
|
||||
pub use token::Token;
|
||||
pub use assert::{assert_tokens, assert_ser_tokens, assert_ser_tokens_error, assert_de_tokens,
|
||||
assert_de_tokens_error};
|
||||
pub use assert::{assert_de_tokens, assert_de_tokens_error, assert_ser_tokens,
|
||||
assert_ser_tokens_error, assert_tokens};
|
||||
|
||||
pub use configure::{Compact, Configure, Readable};
|
||||
|
||||
// Not public API.
|
||||
#[doc(hidden)]
|
||||
|
||||
+47
-10
@@ -40,25 +40,43 @@ impl<'a> Serializer<'a> {
|
||||
|
||||
macro_rules! assert_next_token {
|
||||
($ser:expr, $expected:ident) => {
|
||||
assert_next_token!($ser, $expected, Token::$expected, true);
|
||||
assert_next_token!($ser, stringify!($expected), Token::$expected, true);
|
||||
};
|
||||
($ser:expr, $expected:ident($v:expr)) => {
|
||||
assert_next_token!($ser, $expected, Token::$expected(v), v == $v);
|
||||
assert_next_token!(
|
||||
$ser,
|
||||
format_args!("{}({:?})", stringify!($expected), $v),
|
||||
Token::$expected(v),
|
||||
v == $v
|
||||
);
|
||||
};
|
||||
($ser:expr, $expected:ident { $($k:ident),* }) => {
|
||||
let compare = ($($k,)*);
|
||||
assert_next_token!($ser, $expected, Token::$expected { $($k),* }, ($($k,)*) == compare);
|
||||
let field_format = || {
|
||||
use std::fmt::Write;
|
||||
let mut buffer = String::new();
|
||||
$(
|
||||
write!(&mut buffer, "{}: {:?}, ", stringify!($k), $k).unwrap();
|
||||
)*
|
||||
buffer
|
||||
};
|
||||
assert_next_token!(
|
||||
$ser,
|
||||
format_args!("{} {{ {}}}", stringify!($expected), field_format()),
|
||||
Token::$expected { $($k),* },
|
||||
($($k,)*) == compare
|
||||
);
|
||||
};
|
||||
($ser:expr, $expected:ident, $pat:pat, $guard:expr) => {
|
||||
($ser:expr, $expected:expr, $pat:pat, $guard:expr) => {
|
||||
match $ser.next_token() {
|
||||
Some($pat) if $guard => {}
|
||||
Some(other) => {
|
||||
panic!("expected Token::{} but serialized as {}",
|
||||
stringify!($expected), other);
|
||||
$expected, other);
|
||||
}
|
||||
None => {
|
||||
panic!("expected Token::{} after end of serialized tokens",
|
||||
stringify!($expected));
|
||||
$expected);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -247,10 +265,16 @@ impl<'s, 'a> ser::Serializer for &'s mut Serializer<'a> {
|
||||
assert_next_token!(self, Str(variant));
|
||||
let len = Some(len);
|
||||
assert_next_token!(self, Seq { len });
|
||||
Ok(Variant { ser: self, end: Token::SeqEnd })
|
||||
Ok(Variant {
|
||||
ser: self,
|
||||
end: Token::SeqEnd,
|
||||
})
|
||||
} else {
|
||||
assert_next_token!(self, TupleVariant { name, variant, len });
|
||||
Ok(Variant { ser: self, end: Token::TupleVariantEnd })
|
||||
Ok(Variant {
|
||||
ser: self,
|
||||
end: Token::TupleVariantEnd,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,12 +300,25 @@ impl<'s, 'a> ser::Serializer for &'s mut Serializer<'a> {
|
||||
assert_next_token!(self, Str(variant));
|
||||
let len = Some(len);
|
||||
assert_next_token!(self, Map { len });
|
||||
Ok(Variant { ser: self, end: Token::MapEnd })
|
||||
Ok(Variant {
|
||||
ser: self,
|
||||
end: Token::MapEnd,
|
||||
})
|
||||
} else {
|
||||
assert_next_token!(self, StructVariant { name, variant, len });
|
||||
Ok(Variant { ser: self, end: Token::StructVariantEnd })
|
||||
Ok(Variant {
|
||||
ser: self,
|
||||
end: Token::StructVariantEnd,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn is_human_readable(&self) -> bool {
|
||||
panic!(
|
||||
"Types which have different human-readable and compact representations \
|
||||
must explicitly mark their test cases with `serde_test::Configure`"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Variant<'s, 'a: 's> {
|
||||
|
||||
@@ -425,6 +425,10 @@ pub enum Token {
|
||||
|
||||
/// The header of a struct.
|
||||
///
|
||||
/// When testing deserialization, the `len` field must match the number of
|
||||
/// fields that the struct expects to deserialize. This may be different
|
||||
/// from the number of fields contained in the input tokens.
|
||||
///
|
||||
/// After this header are the fields of the struct, followed by `StructEnd`.
|
||||
///
|
||||
/// ```rust
|
||||
@@ -461,6 +465,10 @@ pub enum Token {
|
||||
|
||||
/// The header of a struct variant of an enum.
|
||||
///
|
||||
/// When testing deserialization, the `len` field must match the number of
|
||||
/// fields that the struct variant expects to deserialize. This may be
|
||||
/// different from the number of fields contained in the input tokens.
|
||||
///
|
||||
/// After this header are the fields of the struct variant, followed by
|
||||
/// `StructVariantEnd`.
|
||||
///
|
||||
|
||||
@@ -10,9 +10,9 @@ unstable = ["serde/unstable", "compiletest_rs"]
|
||||
[dev-dependencies]
|
||||
fnv = "1.0"
|
||||
rustc-serialize = "0.3.16"
|
||||
serde = { path = "../serde" }
|
||||
serde = { path = "../serde", features = ["rc"] }
|
||||
serde_derive = { path = "../serde_derive" }
|
||||
serde_test = { path = "../serde_test" }
|
||||
|
||||
[dependencies]
|
||||
compiletest_rs = { version = "0.2", optional = true }
|
||||
compiletest_rs = { version = "0.3", optional = true }
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#![feature(/*=============================================]
|
||||
#![=== Serde test suite requires a nightly compiler. ===]
|
||||
#![====================================================*/)]
|
||||
|
||||
@@ -4,5 +4,8 @@ version = "0.0.0"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
libc = { version = "0.2", default-features = false }
|
||||
serde = { path = "../../serde", default-features = false }
|
||||
serde_derive = { path = "../../serde_derive" }
|
||||
|
||||
[workspace]
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
#![feature(lang_items, start, libc, compiler_builtins_lib)]
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#![feature(lang_items, start, compiler_builtins_lib)]
|
||||
#![no_std]
|
||||
|
||||
extern crate libc;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Str<'a>(&'a str);
|
||||
|
||||
#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
|
||||
enum Test<'a> {
|
||||
#[serde(borrow)] //~^^ HELP: duplicate serde attribute `borrow`
|
||||
S(#[serde(borrow)] Str<'a>)
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Str<'a>(&'a str);
|
||||
|
||||
#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
|
||||
enum Test<'a> {
|
||||
#[serde(borrow)] //~^^ HELP: #[serde(borrow)] may only be used on newtype variants
|
||||
S { s: Str<'a> }
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -16,7 +16,7 @@ mod remote {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)] //~ ERROR: missing field `b` in initializer of `remote::S`
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "remote::S")]
|
||||
struct S {
|
||||
a: u8, //~^^^ ERROR: missing field `b` in initializer of `remote::S`
|
||||
|
||||
@@ -18,7 +18,8 @@ mod remote {
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "remote::S")]
|
||||
struct S {
|
||||
b: u8, //~^^^ ERROR: no field `b` on type `&remote::S`
|
||||
//~^^^ ERROR: struct `remote::S` has no field named `b`
|
||||
b: u8, //~^^^^ ERROR: no field `b` on type `&remote::S`
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
|
||||
//~^ HELP: variant `Newtype` cannot have both #[serde(deserialize_with)] and a field 0 marked with #[serde(skip_deserializing)]
|
||||
enum Enum {
|
||||
#[serde(deserialize_with = "deserialize_some_newtype_variant")]
|
||||
Newtype(#[serde(skip_deserializing)] String),
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
|
||||
//~^ HELP: variant `Struct` cannot have both #[serde(deserialize_with)] and a field `f1` marked with #[serde(skip_deserializing)]
|
||||
enum Enum {
|
||||
#[serde(deserialize_with = "deserialize_some_other_variant")]
|
||||
Struct {
|
||||
#[serde(skip_deserializing)]
|
||||
f1: String,
|
||||
f2: u8,
|
||||
},
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
|
||||
//~^ HELP: variant `Tuple` cannot have both #[serde(deserialize_with)] and a field 0 marked with #[serde(skip_deserializing)]
|
||||
enum Enum {
|
||||
#[serde(deserialize_with = "deserialize_some_other_variant")]
|
||||
Tuple(#[serde(skip_deserializing)] String, u8),
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,20 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
|
||||
//~^ HELP: variant `Unit` cannot have both #[serde(deserialize_with)] and #[serde(skip_deserializing)]
|
||||
enum Enum {
|
||||
#[serde(deserialize_with = "deserialize_some_unit_variant")]
|
||||
#[serde(skip_deserializing)]
|
||||
Unit,
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
//~^ HELP: variant `Newtype` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing)]
|
||||
enum Enum {
|
||||
#[serde(serialize_with = "serialize_some_newtype_variant")]
|
||||
Newtype(#[serde(skip_serializing)] String),
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
//~^ HELP: variant `Newtype` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing_if)]
|
||||
enum Enum {
|
||||
#[serde(serialize_with = "serialize_some_newtype_variant")]
|
||||
Newtype(#[serde(skip_serializing_if = "always")] String),
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
//~^ HELP: variant `Struct` cannot have both #[serde(serialize_with)] and a field `f1` marked with #[serde(skip_serializing)]
|
||||
enum Enum {
|
||||
#[serde(serialize_with = "serialize_some_other_variant")]
|
||||
Struct {
|
||||
#[serde(skip_serializing)]
|
||||
f1: String,
|
||||
f2: u8,
|
||||
},
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
//~^ HELP: variant `Struct` cannot have both #[serde(serialize_with)] and a field `f1` marked with #[serde(skip_serializing_if)]
|
||||
enum Enum {
|
||||
#[serde(serialize_with = "serialize_some_newtype_variant")]
|
||||
Struct {
|
||||
#[serde(skip_serializing_if = "always")]
|
||||
f1: String,
|
||||
f2: u8,
|
||||
},
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
//~^ HELP: variant `Tuple` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing)]
|
||||
enum Enum {
|
||||
#[serde(serialize_with = "serialize_some_other_variant")]
|
||||
Tuple(#[serde(skip_serializing)] String, u8),
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
//~^ HELP: variant `Tuple` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing_if)]
|
||||
enum Enum {
|
||||
#[serde(serialize_with = "serialize_some_other_variant")]
|
||||
Tuple(#[serde(skip_serializing_if = "always")] String, u8),
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -0,0 +1,20 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
|
||||
//~^ HELP: variant `Unit` cannot have both #[serde(serialize_with)] and #[serde(skip_serializing)]
|
||||
enum Enum {
|
||||
#[serde(serialize_with = "serialize_some_unit_variant")]
|
||||
#[serde(skip_serializing)]
|
||||
Unit,
|
||||
}
|
||||
|
||||
fn main() { }
|
||||
@@ -13,7 +13,7 @@ extern crate compiletest_rs as compiletest;
|
||||
use std::env;
|
||||
|
||||
fn run_mode(mode: &'static str) {
|
||||
let mut config = compiletest::default_config();
|
||||
let mut config = compiletest::Config::default();
|
||||
|
||||
config.mode = mode.parse().expect("invalid mode");
|
||||
config.target_rustcflags = Some("-L deps/target/debug/deps".to_owned());
|
||||
|
||||
@@ -73,3 +73,29 @@ macro_rules! hashmap {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! seq_impl {
|
||||
(seq $first:expr,) => {
|
||||
seq_impl!(seq $first)
|
||||
};
|
||||
($first:expr,) => {
|
||||
seq_impl!($first)
|
||||
};
|
||||
(seq $first:expr) => {
|
||||
$first.into_iter()
|
||||
};
|
||||
($first:expr) => {
|
||||
Some($first).into_iter()
|
||||
};
|
||||
(seq $first:expr , $( $elem: tt)*) => {
|
||||
$first.into_iter().chain(seq!( $($elem)* ))
|
||||
};
|
||||
($first:expr , $($elem: tt)*) => {
|
||||
Some($first).into_iter().chain(seq!( $($elem)* ))
|
||||
}
|
||||
}
|
||||
macro_rules! seq {
|
||||
($($tt: tt)*) => {
|
||||
seq_impl!($($tt)*).collect::<Vec<_>>()
|
||||
};
|
||||
}
|
||||
@@ -6,11 +6,14 @@
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(cast_lossless))]
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
extern crate serde;
|
||||
use self::serde::{Serialize, Serializer, Deserialize, Deserializer};
|
||||
use self::serde::de::{self, Unexpected};
|
||||
|
||||
extern crate serde_test;
|
||||
use self::serde_test::{Token, assert_tokens, assert_ser_tokens, assert_de_tokens,
|
||||
@@ -132,7 +135,7 @@ fn test_default_struct() {
|
||||
a5: 123,
|
||||
},
|
||||
&[
|
||||
Token::Struct { name: "DefaultStruct", len: 1 },
|
||||
Token::Struct { name: "DefaultStruct", len: 3 },
|
||||
|
||||
Token::Str("a1"),
|
||||
Token::I32(1),
|
||||
@@ -306,7 +309,7 @@ fn test_elt_not_deserialize() {
|
||||
c: NotDeserializeStruct(123),
|
||||
e: NotDeserializeEnum::Trouble,
|
||||
},
|
||||
&[Token::Struct { name: "ContainsNotDeserialize", len: 3 }, Token::StructEnd],
|
||||
&[Token::Struct { name: "ContainsNotDeserialize", len: 1 }, Token::StructEnd],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -328,7 +331,7 @@ fn test_ignore_unknown() {
|
||||
a5: 123,
|
||||
},
|
||||
&[
|
||||
Token::Struct { name: "DefaultStruct", len: 5 },
|
||||
Token::Struct { name: "DefaultStruct", len: 3 },
|
||||
|
||||
Token::Str("whoops1"),
|
||||
Token::I32(2),
|
||||
@@ -356,7 +359,7 @@ fn test_ignore_unknown() {
|
||||
|
||||
assert_de_tokens_error::<DenyUnknown>(
|
||||
&[
|
||||
Token::Struct { name: "DenyUnknown", len: 2 },
|
||||
Token::Struct { name: "DenyUnknown", len: 1 },
|
||||
|
||||
Token::Str("a1"),
|
||||
Token::I32(1),
|
||||
@@ -580,6 +583,41 @@ fn test_skip_serializing_struct() {
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct SkipStruct<B>
|
||||
{
|
||||
a: i8,
|
||||
#[serde(skip)]
|
||||
b: B,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_skip_struct() {
|
||||
assert_ser_tokens(
|
||||
&SkipStruct { a: 1, b: 2 },
|
||||
&[
|
||||
Token::Struct { name: "SkipStruct", len: 1 },
|
||||
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&SkipStruct { a: 1, b: 0 },
|
||||
&[
|
||||
Token::Struct { name: "SkipStruct", len: 1 },
|
||||
|
||||
Token::Str("a"),
|
||||
Token::I8(1),
|
||||
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
enum SkipSerializingEnum<'a, B, C>
|
||||
where
|
||||
@@ -776,6 +814,145 @@ fn test_serialize_with_enum() {
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
enum WithVariant {
|
||||
#[serde(serialize_with="serialize_unit_variant_as_i8")]
|
||||
#[serde(deserialize_with="deserialize_i8_as_unit_variant")]
|
||||
Unit,
|
||||
|
||||
#[serde(serialize_with="SerializeWith::serialize_with")]
|
||||
#[serde(deserialize_with="DeserializeWith::deserialize_with")]
|
||||
Newtype(i32),
|
||||
|
||||
#[serde(serialize_with="serialize_variant_as_string")]
|
||||
#[serde(deserialize_with="deserialize_string_as_variant")]
|
||||
Tuple(String, u8),
|
||||
|
||||
#[serde(serialize_with="serialize_variant_as_string")]
|
||||
#[serde(deserialize_with="deserialize_string_as_variant")]
|
||||
Struct {
|
||||
f1: String,
|
||||
f2: u8,
|
||||
},
|
||||
}
|
||||
|
||||
fn serialize_unit_variant_as_i8<S>(serializer: S) -> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
serializer.serialize_i8(0)
|
||||
}
|
||||
|
||||
fn deserialize_i8_as_unit_variant<'de, D>(deserializer: D) -> Result<(), D::Error>
|
||||
where D: Deserializer<'de>,
|
||||
{
|
||||
let n = i8::deserialize(deserializer)?;
|
||||
match n {
|
||||
0 => Ok(()),
|
||||
_ => Err(de::Error::invalid_value(Unexpected::Signed(n as i64), &"0")),
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_variant_as_string<S>(f1: &str,
|
||||
f2: &u8,
|
||||
serializer: S)
|
||||
-> Result<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(format!("{};{:?}", f1, f2).as_str())
|
||||
}
|
||||
|
||||
fn deserialize_string_as_variant<'de, D>(deserializer: D) -> Result<(String, u8), D::Error>
|
||||
where D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
let mut pieces = s.split(';');
|
||||
let f1 = match pieces.next() {
|
||||
Some(x) => x,
|
||||
None => return Err(de::Error::invalid_length(0, &"2")),
|
||||
};
|
||||
let f2 = match pieces.next() {
|
||||
Some(x) => x,
|
||||
None => return Err(de::Error::invalid_length(1, &"2")),
|
||||
};
|
||||
let f2 = match f2.parse() {
|
||||
Ok(n) => n,
|
||||
Err(_) => {
|
||||
return Err(de::Error::invalid_value(Unexpected::Str(f2), &"an 8-bit signed integer"));
|
||||
}
|
||||
};
|
||||
Ok((f1.into(), f2))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serialize_with_variant() {
|
||||
assert_ser_tokens(
|
||||
&WithVariant::Unit,
|
||||
&[
|
||||
Token::NewtypeVariant { name: "WithVariant", variant: "Unit" },
|
||||
Token::I8(0),
|
||||
],
|
||||
);
|
||||
|
||||
assert_ser_tokens(
|
||||
&WithVariant::Newtype(123),
|
||||
&[
|
||||
Token::NewtypeVariant { name: "WithVariant", variant: "Newtype" },
|
||||
Token::Bool(true),
|
||||
],
|
||||
);
|
||||
|
||||
assert_ser_tokens(
|
||||
&WithVariant::Tuple("hello".into(), 0),
|
||||
&[
|
||||
Token::NewtypeVariant { name: "WithVariant", variant: "Tuple" },
|
||||
Token::Str("hello;0"),
|
||||
],
|
||||
);
|
||||
|
||||
assert_ser_tokens(
|
||||
&WithVariant::Struct { f1: "world".into(), f2: 1 },
|
||||
&[
|
||||
Token::NewtypeVariant { name: "WithVariant", variant: "Struct" },
|
||||
Token::Str("world;1"),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_with_variant() {
|
||||
assert_de_tokens(
|
||||
&WithVariant::Unit,
|
||||
&[
|
||||
Token::NewtypeVariant { name: "WithVariant", variant: "Unit" },
|
||||
Token::I8(0),
|
||||
],
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&WithVariant::Newtype(123),
|
||||
&[
|
||||
Token::NewtypeVariant { name: "WithVariant", variant: "Newtype" },
|
||||
Token::Bool(true),
|
||||
],
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&WithVariant::Tuple("hello".into(), 0),
|
||||
&[
|
||||
Token::NewtypeVariant { name: "WithVariant", variant: "Tuple" },
|
||||
Token::Str("hello;0"),
|
||||
],
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&WithVariant::Struct { f1: "world".into(), f2: 1 },
|
||||
&[
|
||||
Token::NewtypeVariant { name: "WithVariant", variant: "Struct" },
|
||||
Token::Str("world;1"),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Deserialize)]
|
||||
struct DeserializeWithStruct<B>
|
||||
where
|
||||
|
||||
+221
-62
@@ -6,17 +6,18 @@
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#![cfg_attr(feature = "unstable", feature(into_boxed_c_str))]
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::net;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
use std::default::Default;
|
||||
use std::ffi::{CString, OsString};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::num::Wrapping;
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
use std::ffi::CStr;
|
||||
@@ -28,7 +29,7 @@ extern crate fnv;
|
||||
use self::fnv::FnvHasher;
|
||||
|
||||
extern crate serde_test;
|
||||
use self::serde_test::{Token, assert_de_tokens, assert_de_tokens_error};
|
||||
use self::serde_test::{assert_de_tokens, assert_de_tokens_error, Configure, Token};
|
||||
|
||||
#[macro_use]
|
||||
mod macros;
|
||||
@@ -48,16 +49,14 @@ struct TupleStruct(i32, i32, i32);
|
||||
struct Struct {
|
||||
a: i32,
|
||||
b: i32,
|
||||
#[serde(skip_deserializing)]
|
||||
c: i32,
|
||||
#[serde(skip_deserializing)] c: i32,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct StructDenyUnknown {
|
||||
a: i32,
|
||||
#[serde(skip_deserializing)]
|
||||
b: i32,
|
||||
#[serde(skip_deserializing)] b: i32,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
@@ -78,15 +77,13 @@ impl Default for StructDefault<String> {
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
struct StructSkipAll {
|
||||
#[serde(skip_deserializing)]
|
||||
a: i32,
|
||||
#[serde(skip_deserializing)] a: i32,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct StructSkipAllDenyUnknown {
|
||||
#[serde(skip_deserializing)]
|
||||
a: i32,
|
||||
#[serde(skip_deserializing)] a: i32,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
@@ -109,25 +106,37 @@ enum EnumSkipAll {
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! declare_test {
|
||||
($name:ident { $($value:expr => $tokens:expr,)+ }) => {
|
||||
#[test]
|
||||
fn $name() {
|
||||
$(
|
||||
// Test ser/de roundtripping
|
||||
assert_de_tokens(&$value, $tokens);
|
||||
|
||||
// Test that the tokens are ignorable
|
||||
assert_de_tokens_ignore($tokens);
|
||||
)+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! declare_tests {
|
||||
(
|
||||
$readable:tt
|
||||
$($name:ident { $($value:expr => $tokens:expr,)+ })+
|
||||
) => {
|
||||
$(
|
||||
#[test]
|
||||
fn $name() {
|
||||
$(
|
||||
// Test ser/de roundtripping
|
||||
assert_de_tokens(&$value.$readable(), $tokens);
|
||||
|
||||
// Test that the tokens are ignorable
|
||||
assert_de_tokens_ignore($tokens);
|
||||
)+
|
||||
}
|
||||
)+
|
||||
};
|
||||
|
||||
($($name:ident { $($value:expr => $tokens:expr,)+ })+) => {
|
||||
$(
|
||||
declare_test!($name { $($value => $tokens,)+ });
|
||||
#[test]
|
||||
fn $name() {
|
||||
$(
|
||||
// Test ser/de roundtripping
|
||||
assert_de_tokens(&$value, $tokens);
|
||||
|
||||
// Test that the tokens are ignorable
|
||||
assert_de_tokens_ignore($tokens);
|
||||
)+
|
||||
}
|
||||
)+
|
||||
}
|
||||
}
|
||||
@@ -155,13 +164,11 @@ fn assert_de_tokens_ignore(ignorable_tokens: &[Token]) {
|
||||
Token::Map { len: Some(2) },
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
Token::Str("ignored"),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(ignorable_tokens.to_vec().into_iter())
|
||||
.chain(vec![Token::MapEnd].into_iter())
|
||||
.collect();
|
||||
].into_iter()
|
||||
.chain(ignorable_tokens.to_vec().into_iter())
|
||||
.chain(vec![Token::MapEnd].into_iter())
|
||||
.collect();
|
||||
|
||||
let mut de = serde_test::Deserializer::new(&concated_tokens);
|
||||
let base = IgnoreBase::deserialize(&mut de).unwrap();
|
||||
@@ -522,7 +529,16 @@ declare_tests! {
|
||||
Token::MapEnd,
|
||||
],
|
||||
Struct { a: 1, b: 2, c: 0 } => &[
|
||||
Token::Struct { name: "Struct", len: 3 },
|
||||
Token::Map { len: Some(3) },
|
||||
Token::U32(0),
|
||||
Token::I32(1),
|
||||
|
||||
Token::U32(1),
|
||||
Token::I32(2),
|
||||
Token::MapEnd,
|
||||
],
|
||||
Struct { a: 1, b: 2, c: 0 } => &[
|
||||
Token::Struct { name: "Struct", len: 2 },
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
@@ -554,7 +570,7 @@ declare_tests! {
|
||||
Token::MapEnd,
|
||||
],
|
||||
Struct { a: 1, b: 2, c: 0 } => &[
|
||||
Token::Struct { name: "Struct", len: 3 },
|
||||
Token::Struct { name: "Struct", len: 2 },
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
@@ -575,7 +591,7 @@ declare_tests! {
|
||||
Token::StructEnd,
|
||||
],
|
||||
StructSkipAll { a: 0 } => &[
|
||||
Token::Struct { name: "StructSkipAll", len: 1 },
|
||||
Token::Struct { name: "StructSkipAll", len: 0 },
|
||||
Token::Str("a"),
|
||||
Token::I32(1),
|
||||
|
||||
@@ -592,7 +608,7 @@ declare_tests! {
|
||||
}
|
||||
test_struct_default {
|
||||
StructDefault { a: 50, b: "overwritten".to_string() } => &[
|
||||
Token::Struct { name: "StructDefault", len: 1 },
|
||||
Token::Struct { name: "StructDefault", len: 2 },
|
||||
Token::Str("a"),
|
||||
Token::I32(50),
|
||||
|
||||
@@ -601,7 +617,7 @@ declare_tests! {
|
||||
Token::StructEnd,
|
||||
],
|
||||
StructDefault { a: 100, b: "default".to_string() } => &[
|
||||
Token::Struct { name: "StructDefault", len: 0 },
|
||||
Token::Struct { name: "StructDefault", len: 2 },
|
||||
Token::StructEnd,
|
||||
],
|
||||
}
|
||||
@@ -682,6 +698,23 @@ declare_tests! {
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_system_time {
|
||||
UNIX_EPOCH + Duration::new(1, 2) => &[
|
||||
Token::Struct { name: "SystemTime", len: 2 },
|
||||
Token::Str("secs_since_epoch"),
|
||||
Token::U64(1),
|
||||
|
||||
Token::Str("nanos_since_epoch"),
|
||||
Token::U32(2),
|
||||
Token::StructEnd,
|
||||
],
|
||||
UNIX_EPOCH + Duration::new(1, 2) => &[
|
||||
Token::Seq { len: Some(2) },
|
||||
Token::I64(1),
|
||||
Token::I64(2),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_range {
|
||||
1u32..2u32 => &[
|
||||
Token::Struct { name: "Range", len: 2 },
|
||||
@@ -699,16 +732,10 @@ declare_tests! {
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_net_ipv4addr {
|
||||
"1.2.3.4".parse::<net::Ipv4Addr>().unwrap() => &[Token::Str("1.2.3.4")],
|
||||
}
|
||||
test_net_ipv6addr {
|
||||
"::1".parse::<net::Ipv6Addr>().unwrap() => &[Token::Str("::1")],
|
||||
}
|
||||
test_net_socketaddr {
|
||||
"1.2.3.4:1234".parse::<net::SocketAddr>().unwrap() => &[Token::Str("1.2.3.4:1234")],
|
||||
"1.2.3.4:1234".parse::<net::SocketAddrV4>().unwrap() => &[Token::Str("1.2.3.4:1234")],
|
||||
"[::1]:1234".parse::<net::SocketAddrV6>().unwrap() => &[Token::Str("[::1]:1234")],
|
||||
test_path {
|
||||
Path::new("/usr/local/lib") => &[
|
||||
Token::BorrowedStr("/usr/local/lib"),
|
||||
],
|
||||
}
|
||||
test_path_buf {
|
||||
PathBuf::from("/usr/local/lib") => &[
|
||||
@@ -720,6 +747,141 @@ declare_tests! {
|
||||
Token::Bytes(b"abc"),
|
||||
],
|
||||
}
|
||||
test_rc {
|
||||
Rc::new(true) => &[
|
||||
Token::Bool(true),
|
||||
],
|
||||
}
|
||||
test_arc {
|
||||
Arc::new(true) => &[
|
||||
Token::Bool(true),
|
||||
],
|
||||
}
|
||||
test_wrapping {
|
||||
Wrapping(1usize) => &[
|
||||
Token::U32(1),
|
||||
],
|
||||
Wrapping(1usize) => &[
|
||||
Token::U64(1),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
declare_tests! {
|
||||
readable
|
||||
|
||||
test_net_ipv4addr_readable {
|
||||
"1.2.3.4".parse::<net::Ipv4Addr>().unwrap() => &[Token::Str("1.2.3.4")],
|
||||
}
|
||||
test_net_ipv6addr_readable {
|
||||
"::1".parse::<net::Ipv6Addr>().unwrap() => &[Token::Str("::1")],
|
||||
}
|
||||
test_net_ipaddr_readable {
|
||||
"1.2.3.4".parse::<net::IpAddr>().unwrap() => &[Token::Str("1.2.3.4")],
|
||||
}
|
||||
test_net_socketaddr_readable {
|
||||
"1.2.3.4:1234".parse::<net::SocketAddr>().unwrap() => &[Token::Str("1.2.3.4:1234")],
|
||||
"1.2.3.4:1234".parse::<net::SocketAddrV4>().unwrap() => &[Token::Str("1.2.3.4:1234")],
|
||||
"[::1]:1234".parse::<net::SocketAddrV6>().unwrap() => &[Token::Str("[::1]:1234")],
|
||||
}
|
||||
}
|
||||
|
||||
declare_tests! {
|
||||
compact
|
||||
|
||||
test_net_ipv4addr_compact {
|
||||
net::Ipv4Addr::from(*b"1234") => &seq![
|
||||
Token::Tuple { len: 4 },
|
||||
seq b"1234".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd
|
||||
],
|
||||
}
|
||||
test_net_ipv6addr_compact {
|
||||
net::Ipv6Addr::from(*b"1234567890123456") => &seq![
|
||||
Token::Tuple { len: 4 },
|
||||
seq b"1234567890123456".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd
|
||||
],
|
||||
}
|
||||
test_net_ipaddr_compact {
|
||||
net::IpAddr::from(*b"1234") => &seq![
|
||||
Token::NewtypeVariant { name: "IpAddr", variant: "V4" },
|
||||
|
||||
Token::Tuple { len: 4 },
|
||||
seq b"1234".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd
|
||||
],
|
||||
}
|
||||
test_net_socketaddr_compact {
|
||||
net::SocketAddr::from((*b"1234567890123456", 1234)) => &seq![
|
||||
Token::NewtypeVariant { name: "SocketAddr", variant: "V6" },
|
||||
|
||||
Token::Tuple { len: 2 },
|
||||
|
||||
Token::Tuple { len: 16 },
|
||||
seq b"1234567890123456".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd,
|
||||
|
||||
Token::U16(1234),
|
||||
Token::TupleEnd
|
||||
],
|
||||
net::SocketAddr::from((*b"1234", 1234)) => &seq![
|
||||
Token::NewtypeVariant { name: "SocketAddr", variant: "V4" },
|
||||
|
||||
Token::Tuple { len: 2 },
|
||||
|
||||
Token::Tuple { len: 4 },
|
||||
seq b"1234".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd,
|
||||
|
||||
Token::U16(1234),
|
||||
Token::TupleEnd
|
||||
],
|
||||
net::SocketAddrV4::new(net::Ipv4Addr::from(*b"1234"), 1234) => &seq![
|
||||
Token::Tuple { len: 2 },
|
||||
|
||||
Token::Tuple { len: 4 },
|
||||
seq b"1234".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd,
|
||||
|
||||
Token::U16(1234),
|
||||
Token::TupleEnd
|
||||
],
|
||||
net::SocketAddrV6::new(net::Ipv6Addr::from(*b"1234567890123456"), 1234, 0, 0) => &seq![
|
||||
Token::Tuple { len: 2 },
|
||||
|
||||
Token::Tuple { len: 16 },
|
||||
seq b"1234567890123456".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd,
|
||||
|
||||
Token::U16(1234),
|
||||
Token::TupleEnd
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
declare_tests! {
|
||||
test_rc_dst {
|
||||
Rc::<str>::from("s") => &[
|
||||
Token::Str("s"),
|
||||
],
|
||||
Rc::<[bool]>::from(&[true][..]) => &[
|
||||
Token::Seq { len: Some(1) },
|
||||
Token::Bool(true),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_arc_dst {
|
||||
Arc::<str>::from("s") => &[
|
||||
Token::Str("s"),
|
||||
],
|
||||
Arc::<[bool]>::from(&[true][..]) => &[
|
||||
Token::Seq { len: Some(1) },
|
||||
Token::Bool(true),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -771,15 +933,6 @@ fn test_cstr() {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[test]
|
||||
fn test_net_ipaddr() {
|
||||
assert_de_tokens(
|
||||
&"1.2.3.4".parse::<net::IpAddr>().unwrap(),
|
||||
&[Token::Str("1.2.3.4")],
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[test]
|
||||
fn test_cstr_internal_null() {
|
||||
@@ -801,7 +954,7 @@ fn test_cstr_internal_null_end() {
|
||||
declare_error_tests! {
|
||||
test_unknown_field<StructDenyUnknown> {
|
||||
&[
|
||||
Token::Struct { name: "StructDenyUnknown", len: 2 },
|
||||
Token::Struct { name: "StructDenyUnknown", len: 1 },
|
||||
Token::Str("a"),
|
||||
Token::I32(0),
|
||||
|
||||
@@ -811,14 +964,14 @@ declare_error_tests! {
|
||||
}
|
||||
test_skipped_field_is_unknown<StructDenyUnknown> {
|
||||
&[
|
||||
Token::Struct { name: "StructDenyUnknown", len: 2 },
|
||||
Token::Struct { name: "StructDenyUnknown", len: 1 },
|
||||
Token::Str("b"),
|
||||
],
|
||||
"unknown field `b`, expected `a`",
|
||||
}
|
||||
test_skip_all_deny_unknown<StructSkipAllDenyUnknown> {
|
||||
&[
|
||||
Token::Struct { name: "StructSkipAllDenyUnknown", len: 1 },
|
||||
Token::Struct { name: "StructSkipAllDenyUnknown", len: 0 },
|
||||
Token::Str("a"),
|
||||
],
|
||||
"unknown field `a`, there are no fields",
|
||||
@@ -1021,4 +1174,10 @@ declare_error_tests! {
|
||||
],
|
||||
"invalid type: sequence, expected unit struct UnitStruct",
|
||||
}
|
||||
test_wrapping_overflow<Wrapping<u16>> {
|
||||
&[
|
||||
Token::U32(65_536),
|
||||
],
|
||||
"invalid value: integer `65536`, expected u16",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,11 +10,9 @@
|
||||
// successfully when there are a variety of generics and non-(de)serializable
|
||||
// types involved.
|
||||
|
||||
#![cfg_attr(feature = "unstable", feature(non_ascii_idents))]
|
||||
#![deny(warnings)]
|
||||
|
||||
// Clippy false positive
|
||||
// https://github.com/Manishearth/rust-clippy/issues/292
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
|
||||
#![cfg_attr(feature = "unstable", feature(non_ascii_idents))]
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
@@ -25,6 +23,7 @@ use self::serde::de::{DeserializeOwned, Deserializer};
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::marker::PhantomData;
|
||||
use std::option::Option as StdOption;
|
||||
use std::result::Result as StdResult;
|
||||
|
||||
// Try to trip up the generated code if it fails to use fully qualified paths.
|
||||
@@ -34,6 +33,12 @@ struct Result;
|
||||
struct Ok;
|
||||
#[allow(dead_code)]
|
||||
struct Err;
|
||||
#[allow(dead_code)]
|
||||
struct Option;
|
||||
#[allow(dead_code)]
|
||||
struct Some;
|
||||
#[allow(dead_code)]
|
||||
struct None;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -58,7 +63,7 @@ fn test_gen() {
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct WithRef<'a, T: 'a> {
|
||||
#[serde(skip_deserializing)]
|
||||
t: Option<&'a T>,
|
||||
t: StdOption<&'a T>,
|
||||
#[serde(serialize_with="ser_x", deserialize_with="de_x")]
|
||||
x: X,
|
||||
}
|
||||
@@ -79,9 +84,9 @@ fn test_gen() {
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct NoBounds<T> {
|
||||
t: T,
|
||||
option: Option<T>,
|
||||
option: StdOption<T>,
|
||||
boxed: Box<T>,
|
||||
option_boxed: Option<Box<T>>,
|
||||
option_boxed: StdOption<Box<T>>,
|
||||
}
|
||||
assert::<NoBounds<i32>>();
|
||||
|
||||
@@ -177,8 +182,8 @@ fn test_gen() {
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct OptionStatic<'a> {
|
||||
a: Option<&'a str>,
|
||||
b: Option<&'static str>,
|
||||
a: StdOption<&'a str>,
|
||||
b: StdOption<&'static str>,
|
||||
}
|
||||
assert_ser::<OptionStatic>();
|
||||
|
||||
@@ -330,6 +335,214 @@ fn test_gen() {
|
||||
struct EmptyArray {
|
||||
empty: [X; 0],
|
||||
}
|
||||
|
||||
enum Or<A, B> {
|
||||
A(A),
|
||||
B(B),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(untagged, remote = "Or")]
|
||||
enum OrDef<A, B> {
|
||||
#[allow(dead_code)]
|
||||
A(A),
|
||||
#[allow(dead_code)]
|
||||
B(B),
|
||||
}
|
||||
|
||||
struct Str<'a>(&'a str);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "Str")]
|
||||
struct StrDef<'a>(&'a str);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Remote<'a> {
|
||||
#[serde(with = "OrDef")]
|
||||
or: Or<u8, bool>,
|
||||
#[serde(borrow, with = "StrDef")]
|
||||
s: Str<'a>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BorrowVariant<'a> {
|
||||
#[serde(borrow, with = "StrDef")]
|
||||
S(Str<'a>),
|
||||
}
|
||||
|
||||
mod vis {
|
||||
pub struct S;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "S")]
|
||||
pub struct SDef;
|
||||
}
|
||||
|
||||
// This would not work if SDef::serialize / deserialize are private.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct RemoteVisibility {
|
||||
#[serde(with = "vis::SDef")]
|
||||
s: vis::S,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum ExternallyTaggedVariantWith {
|
||||
#[allow(dead_code)]
|
||||
Normal { f1: String },
|
||||
|
||||
#[serde(serialize_with = "ser_x")]
|
||||
#[serde(deserialize_with = "de_x")]
|
||||
#[allow(dead_code)]
|
||||
Newtype(X),
|
||||
|
||||
#[serde(serialize_with = "serialize_some_other_variant")]
|
||||
#[serde(deserialize_with = "deserialize_some_other_variant")]
|
||||
#[allow(dead_code)]
|
||||
Tuple(String, u8),
|
||||
|
||||
#[serde(serialize_with = "serialize_some_other_variant")]
|
||||
#[serde(deserialize_with = "deserialize_some_other_variant")]
|
||||
#[allow(dead_code)]
|
||||
Struct {
|
||||
f1: String,
|
||||
f2: u8,
|
||||
},
|
||||
|
||||
#[serde(serialize_with = "serialize_some_unit_variant")]
|
||||
#[serde(deserialize_with = "deserialize_some_unit_variant")]
|
||||
#[allow(dead_code)]
|
||||
Unit,
|
||||
}
|
||||
assert_ser::<ExternallyTaggedVariantWith>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(tag = "t")]
|
||||
enum InternallyTaggedVariantWith {
|
||||
#[allow(dead_code)]
|
||||
Normal { f1: String },
|
||||
|
||||
#[serde(serialize_with = "ser_x")]
|
||||
#[serde(deserialize_with = "de_x")]
|
||||
#[allow(dead_code)]
|
||||
Newtype(X),
|
||||
|
||||
#[serde(serialize_with = "serialize_some_other_variant")]
|
||||
#[serde(deserialize_with = "deserialize_some_other_variant")]
|
||||
#[allow(dead_code)]
|
||||
Struct {
|
||||
f1: String,
|
||||
f2: u8,
|
||||
},
|
||||
|
||||
#[serde(serialize_with = "serialize_some_unit_variant")]
|
||||
#[serde(deserialize_with = "deserialize_some_unit_variant")]
|
||||
#[allow(dead_code)]
|
||||
Unit,
|
||||
}
|
||||
assert_ser::<InternallyTaggedVariantWith>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(tag = "t", content = "c")]
|
||||
enum AdjacentlyTaggedVariantWith {
|
||||
#[allow(dead_code)]
|
||||
Normal { f1: String },
|
||||
|
||||
#[serde(serialize_with = "ser_x")]
|
||||
#[serde(deserialize_with = "de_x")]
|
||||
#[allow(dead_code)]
|
||||
Newtype(X),
|
||||
|
||||
#[serde(serialize_with = "serialize_some_other_variant")]
|
||||
#[serde(deserialize_with = "deserialize_some_other_variant")]
|
||||
#[allow(dead_code)]
|
||||
Tuple(String, u8),
|
||||
|
||||
#[serde(serialize_with = "serialize_some_other_variant")]
|
||||
#[serde(deserialize_with = "deserialize_some_other_variant")]
|
||||
#[allow(dead_code)]
|
||||
Struct {
|
||||
f1: String,
|
||||
f2: u8,
|
||||
},
|
||||
|
||||
#[serde(serialize_with = "serialize_some_unit_variant")]
|
||||
#[serde(deserialize_with = "deserialize_some_unit_variant")]
|
||||
#[allow(dead_code)]
|
||||
Unit,
|
||||
}
|
||||
assert_ser::<AdjacentlyTaggedVariantWith>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum UntaggedVariantWith {
|
||||
#[allow(dead_code)]
|
||||
Normal { f1: String },
|
||||
|
||||
#[serde(serialize_with = "ser_x")]
|
||||
#[serde(deserialize_with = "de_x")]
|
||||
#[allow(dead_code)]
|
||||
Newtype(X),
|
||||
|
||||
#[serde(serialize_with = "serialize_some_other_variant")]
|
||||
#[serde(deserialize_with = "deserialize_some_other_variant")]
|
||||
#[allow(dead_code)]
|
||||
Tuple(String, u8),
|
||||
|
||||
#[serde(serialize_with = "serialize_some_other_variant")]
|
||||
#[serde(deserialize_with = "deserialize_some_other_variant")]
|
||||
#[allow(dead_code)]
|
||||
Struct {
|
||||
f1: String,
|
||||
f2: u8,
|
||||
},
|
||||
|
||||
#[serde(serialize_with = "serialize_some_unit_variant")]
|
||||
#[serde(deserialize_with = "deserialize_some_unit_variant")]
|
||||
#[allow(dead_code)]
|
||||
Unit,
|
||||
}
|
||||
assert_ser::<UntaggedVariantWith>();
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct StaticStrStruct<'a> {
|
||||
a: &'a str,
|
||||
b: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct StaticStrTupleStruct<'a>(&'a str, &'static str);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct StaticStrNewtypeStruct(&'static str);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum StaticStrEnum<'a> {
|
||||
Struct {
|
||||
a: &'a str,
|
||||
b: &'static str,
|
||||
},
|
||||
Tuple(&'a str, &'static str),
|
||||
Newtype(&'static str),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct SkippedStaticStr {
|
||||
#[serde(skip_deserializing)]
|
||||
skipped: &'static str,
|
||||
other: isize,
|
||||
}
|
||||
assert::<SkippedStaticStr>();
|
||||
|
||||
macro_rules! T {
|
||||
() => { () }
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypeMacro<T> {
|
||||
mac: T!(),
|
||||
marker: PhantomData<T>,
|
||||
}
|
||||
assert::<TypeMacro<X>>();
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
@@ -371,3 +584,29 @@ impl DeserializeWith for X {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn serialize_some_unit_variant<S>(_: S) -> StdResult<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn deserialize_some_unit_variant<'de, D>(_: D) -> StdResult<(), D::Error>
|
||||
where D: Deserializer<'de>,
|
||||
{
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn serialize_some_other_variant<S>(_: &str, _: &u8, _: S) -> StdResult<S::Ok, S::Error>
|
||||
where S: Serializer,
|
||||
{
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn deserialize_some_other_variant<'de, D>(_: D) -> StdResult<(String, u8), D::Error>
|
||||
where D: Deserializer<'de>,
|
||||
{
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn is_zero(n: &u8) -> bool { *n == 0 }
|
||||
|
||||
@@ -9,10 +9,8 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
extern crate serde;
|
||||
|
||||
extern crate serde_test;
|
||||
use serde_test::{Token, assert_de_tokens};
|
||||
use serde_test::{assert_de_tokens, Token};
|
||||
|
||||
#[test]
|
||||
fn test_variant_identifier() {
|
||||
@@ -23,7 +21,10 @@ fn test_variant_identifier() {
|
||||
Bbb,
|
||||
}
|
||||
|
||||
assert_de_tokens(&V::Aaa, &[Token::U8(0)]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::U16(0)]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::U32(0)]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::U64(0)]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::Str("Aaa")]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::Bytes(b"Aaa")]);
|
||||
}
|
||||
@@ -48,8 +49,7 @@ fn test_unit_fallthrough() {
|
||||
enum F {
|
||||
Aaa,
|
||||
Bbb,
|
||||
#[serde(other)]
|
||||
Other,
|
||||
#[serde(other)] Other,
|
||||
}
|
||||
|
||||
assert_de_tokens(&F::Other, &[Token::Str("x")]);
|
||||
|
||||
+282
-38
@@ -6,6 +6,8 @@
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
#![deny(trivial_numeric_casts)]
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
@@ -589,11 +591,10 @@ fn test_internally_tagged_enum() {
|
||||
#[serde(tag = "type")]
|
||||
enum InternallyTagged {
|
||||
A { a: u8 },
|
||||
B { b: u8 },
|
||||
C,
|
||||
D(BTreeMap<String, String>),
|
||||
E(Newtype),
|
||||
F(Struct),
|
||||
B,
|
||||
C(BTreeMap<String, String>),
|
||||
D(Newtype),
|
||||
E(Struct),
|
||||
}
|
||||
|
||||
assert_tokens(
|
||||
@@ -611,35 +612,62 @@ fn test_internally_tagged_enum() {
|
||||
],
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::B { b: 2 },
|
||||
assert_de_tokens(
|
||||
&InternallyTagged::A { a: 1 },
|
||||
&[
|
||||
Token::Struct { name: "InternallyTagged", len: 2 },
|
||||
|
||||
Token::Str("type"),
|
||||
Token::Str("B"),
|
||||
|
||||
Token::Str("b"),
|
||||
Token::U8(2),
|
||||
|
||||
Token::StructEnd,
|
||||
Token::Seq { len: Some(2) },
|
||||
Token::Str("A"),
|
||||
Token::U8(1),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::C,
|
||||
&InternallyTagged::B,
|
||||
&[
|
||||
Token::Struct { name: "InternallyTagged", len: 1 },
|
||||
|
||||
Token::Str("type"),
|
||||
Token::Str("C"),
|
||||
Token::Str("B"),
|
||||
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&InternallyTagged::B,
|
||||
&[
|
||||
Token::Seq { len: Some(1) },
|
||||
Token::Str("B"),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::D(BTreeMap::new()),
|
||||
&InternallyTagged::C(BTreeMap::new()),
|
||||
&[
|
||||
Token::Map { len: Some(1) },
|
||||
|
||||
Token::Str("type"),
|
||||
Token::Str("C"),
|
||||
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<InternallyTagged>(
|
||||
&[
|
||||
Token::Seq { len: Some(2) },
|
||||
Token::Str("C"),
|
||||
Token::Map { len: Some(0) },
|
||||
Token::MapEnd,
|
||||
Token::SeqEnd,
|
||||
],
|
||||
"invalid type: sequence, expected a map",
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::D(Newtype(BTreeMap::new())),
|
||||
&[
|
||||
Token::Map { len: Some(1) },
|
||||
|
||||
@@ -651,24 +679,12 @@ fn test_internally_tagged_enum() {
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::E(Newtype(BTreeMap::new())),
|
||||
&[
|
||||
Token::Map { len: Some(1) },
|
||||
|
||||
Token::Str("type"),
|
||||
Token::Str("E"),
|
||||
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::F(Struct { f: 6 }),
|
||||
&InternallyTagged::E(Struct { f: 6 }),
|
||||
&[
|
||||
Token::Struct { name: "Struct", len: 2 },
|
||||
|
||||
Token::Str("type"),
|
||||
Token::Str("F"),
|
||||
Token::Str("E"),
|
||||
|
||||
Token::Str("f"),
|
||||
Token::U8(6),
|
||||
@@ -677,6 +693,16 @@ fn test_internally_tagged_enum() {
|
||||
],
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&InternallyTagged::E(Struct { f: 6 }),
|
||||
&[
|
||||
Token::Seq { len: Some(2) },
|
||||
Token::Str("E"),
|
||||
Token::U8(6),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<InternallyTagged>(
|
||||
&[Token::Map { len: Some(0) }, Token::MapEnd],
|
||||
"missing field `type`",
|
||||
@@ -691,7 +717,60 @@ fn test_internally_tagged_enum() {
|
||||
|
||||
Token::MapEnd,
|
||||
],
|
||||
"unknown variant `Z`, expected one of `A`, `B`, `C`, `D`, `E`, `F`",
|
||||
"unknown variant `Z`, expected one of `A`, `B`, `C`, `D`, `E`",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_internally_tagged_struct_variant_containing_unit_variant() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Level {
|
||||
Info,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "action")]
|
||||
pub enum Message {
|
||||
Log { level: Level },
|
||||
}
|
||||
|
||||
assert_de_tokens(
|
||||
&Message::Log { level: Level::Info },
|
||||
&[
|
||||
Token::Struct { name: "Message", len: 2 },
|
||||
|
||||
Token::Str("action"),
|
||||
Token::Str("Log"),
|
||||
|
||||
Token::Str("level"),
|
||||
Token::BorrowedStr("Info"),
|
||||
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_internally_tagged_borrow() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum Input<'a> {
|
||||
Package { name: &'a str },
|
||||
}
|
||||
|
||||
assert_tokens(
|
||||
&Input::Package { name: "borrowed" },
|
||||
&[
|
||||
Token::Struct { name: "Input", len: 2 },
|
||||
|
||||
Token::BorrowedStr("type"),
|
||||
Token::BorrowedStr("Package"),
|
||||
|
||||
Token::BorrowedStr("name"),
|
||||
Token::BorrowedStr("borrowed"),
|
||||
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -707,7 +786,7 @@ fn test_adjacently_tagged_enum() {
|
||||
}
|
||||
|
||||
// unit with no content
|
||||
assert_tokens(
|
||||
assert_ser_tokens(
|
||||
&AdjacentlyTagged::Unit::<u8>,
|
||||
&[
|
||||
Token::Struct { name: "AdjacentlyTagged", len: 1 },
|
||||
@@ -719,11 +798,24 @@ fn test_adjacently_tagged_enum() {
|
||||
],
|
||||
);
|
||||
|
||||
// unit with no content
|
||||
assert_de_tokens(
|
||||
&AdjacentlyTagged::Unit::<u8>,
|
||||
&[
|
||||
Token::Struct { name: "AdjacentlyTagged", len: 2 },
|
||||
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
|
||||
// unit with tag first
|
||||
assert_de_tokens(
|
||||
&AdjacentlyTagged::Unit::<u8>,
|
||||
&[
|
||||
Token::Struct { name: "AdjacentlyTagged", len: 1 },
|
||||
Token::Struct { name: "AdjacentlyTagged", len: 2 },
|
||||
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
@@ -739,7 +831,7 @@ fn test_adjacently_tagged_enum() {
|
||||
assert_de_tokens(
|
||||
&AdjacentlyTagged::Unit::<u8>,
|
||||
&[
|
||||
Token::Struct { name: "AdjacentlyTagged", len: 1 },
|
||||
Token::Struct { name: "AdjacentlyTagged", len: 2 },
|
||||
|
||||
Token::Str("c"),
|
||||
Token::Unit,
|
||||
@@ -751,6 +843,31 @@ fn test_adjacently_tagged_enum() {
|
||||
],
|
||||
);
|
||||
|
||||
// unit with excess content (f, g, h)
|
||||
assert_de_tokens(
|
||||
&AdjacentlyTagged::Unit::<u8>,
|
||||
&[
|
||||
Token::Struct { name: "AdjacentlyTagged", len: 2 },
|
||||
|
||||
Token::Str("f"),
|
||||
Token::Unit,
|
||||
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
|
||||
Token::Str("g"),
|
||||
Token::Unit,
|
||||
|
||||
Token::Str("c"),
|
||||
Token::Unit,
|
||||
|
||||
Token::Str("h"),
|
||||
Token::Unit,
|
||||
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
|
||||
// newtype with tag first
|
||||
assert_tokens(
|
||||
&AdjacentlyTagged::Newtype::<u8>(1),
|
||||
@@ -860,6 +977,66 @@ fn test_adjacently_tagged_enum() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_adjacently_tagged_enum_deny_unknown_fields() {
|
||||
#[derive(Debug, PartialEq, Deserialize)]
|
||||
#[serde(tag = "t", content = "c", deny_unknown_fields)]
|
||||
enum AdjacentlyTagged {
|
||||
Unit,
|
||||
}
|
||||
|
||||
assert_de_tokens(
|
||||
&AdjacentlyTagged::Unit,
|
||||
&[
|
||||
Token::Struct { name: "AdjacentlyTagged", len: 2 },
|
||||
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
|
||||
Token::Str("c"),
|
||||
Token::Unit,
|
||||
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<AdjacentlyTagged>(
|
||||
&[
|
||||
Token::Struct { name: "AdjacentlyTagged", len: 2 },
|
||||
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
|
||||
Token::Str("c"),
|
||||
Token::Unit,
|
||||
|
||||
Token::Str("h"),
|
||||
],
|
||||
r#"invalid value: string "h", expected "t" or "c""#
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<AdjacentlyTagged>(
|
||||
&[
|
||||
Token::Struct { name: "AdjacentlyTagged", len: 2 },
|
||||
|
||||
Token::Str("h"),
|
||||
],
|
||||
r#"invalid value: string "h", expected "t" or "c""#
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<AdjacentlyTagged>(
|
||||
&[
|
||||
Token::Struct { name: "AdjacentlyTagged", len: 2 },
|
||||
|
||||
Token::Str("c"),
|
||||
Token::Unit,
|
||||
|
||||
Token::Str("h"),
|
||||
],
|
||||
r#"invalid value: string "h", expected "t" or "c""#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_enum_in_internally_tagged_enum() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -1011,7 +1188,7 @@ fn test_rename_all() {
|
||||
SerializeMap {
|
||||
serialize: bool,
|
||||
serialize_seq: bool,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, PartialEq)]
|
||||
@@ -1021,6 +1198,13 @@ fn test_rename_all() {
|
||||
serialize_seq: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, PartialEq)]
|
||||
#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
|
||||
struct ScreamingKebab {
|
||||
serialize: bool,
|
||||
serialize_seq: bool,
|
||||
}
|
||||
|
||||
assert_tokens(
|
||||
&E::Serialize {
|
||||
serialize: true,
|
||||
@@ -1080,4 +1264,64 @@ fn test_rename_all() {
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&ScreamingKebab {
|
||||
serialize: true,
|
||||
serialize_seq: true,
|
||||
},
|
||||
&[
|
||||
Token::Struct { name: "ScreamingKebab", len: 2 },
|
||||
Token::Str("SERIALIZE"),
|
||||
Token::Bool(true),
|
||||
Token::Str("SERIALIZE-SEQ"),
|
||||
Token::Bool(true),
|
||||
Token::StructEnd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_untagged_newtype_variant_containing_unit_struct_not_map() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Unit;
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Message {
|
||||
Unit(Unit),
|
||||
Map(BTreeMap<String, String>),
|
||||
}
|
||||
|
||||
assert_tokens(
|
||||
&Message::Map(BTreeMap::new()),
|
||||
&[
|
||||
Token::Map { len: Some(0) },
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_internally_tagged_newtype_variant_containing_unit_struct() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Info;
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "topic")]
|
||||
enum Message {
|
||||
Info(Info),
|
||||
}
|
||||
|
||||
assert_tokens(
|
||||
&Message::Info(Info),
|
||||
&[
|
||||
Token::Map { len: Some(1) },
|
||||
|
||||
Token::Str("topic"),
|
||||
Token::Str("Info"),
|
||||
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,8 +9,6 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
extern crate serde;
|
||||
|
||||
mod remote {
|
||||
pub struct Unit;
|
||||
|
||||
@@ -87,32 +85,23 @@ mod remote {
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Test {
|
||||
#[serde(with = "UnitDef")]
|
||||
unit: remote::Unit,
|
||||
#[serde(with = "UnitDef")] unit: remote::Unit,
|
||||
|
||||
#[serde(with = "PrimitivePrivDef")]
|
||||
primitive_priv: remote::PrimitivePriv,
|
||||
#[serde(with = "PrimitivePrivDef")] primitive_priv: remote::PrimitivePriv,
|
||||
|
||||
#[serde(with = "PrimitivePubDef")]
|
||||
primitive_pub: remote::PrimitivePub,
|
||||
#[serde(with = "PrimitivePubDef")] primitive_pub: remote::PrimitivePub,
|
||||
|
||||
#[serde(with = "NewtypePrivDef")]
|
||||
newtype_priv: remote::NewtypePriv,
|
||||
#[serde(with = "NewtypePrivDef")] newtype_priv: remote::NewtypePriv,
|
||||
|
||||
#[serde(with = "NewtypePubDef")]
|
||||
newtype_pub: remote::NewtypePub,
|
||||
#[serde(with = "NewtypePubDef")] newtype_pub: remote::NewtypePub,
|
||||
|
||||
#[serde(with = "TuplePrivDef")]
|
||||
tuple_priv: remote::TuplePriv,
|
||||
#[serde(with = "TuplePrivDef")] tuple_priv: remote::TuplePriv,
|
||||
|
||||
#[serde(with = "TuplePubDef")]
|
||||
tuple_pub: remote::TuplePub,
|
||||
#[serde(with = "TuplePubDef")] tuple_pub: remote::TuplePub,
|
||||
|
||||
#[serde(with = "StructPrivDef")]
|
||||
struct_priv: remote::StructPriv,
|
||||
#[serde(with = "StructPrivDef")] struct_priv: remote::StructPriv,
|
||||
|
||||
#[serde(with = "StructPubDef")]
|
||||
struct_pub: remote::StructPub,
|
||||
#[serde(with = "StructPubDef")] struct_pub: remote::StructPub,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -121,10 +110,7 @@ struct UnitDef;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "remote::PrimitivePriv")]
|
||||
struct PrimitivePrivDef(
|
||||
#[serde(getter = "remote::PrimitivePriv::get")]
|
||||
u8
|
||||
);
|
||||
struct PrimitivePrivDef(#[serde(getter = "remote::PrimitivePriv::get")] u8);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "remote::PrimitivePub")]
|
||||
@@ -133,53 +119,41 @@ struct PrimitivePubDef(u8);
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "remote::NewtypePriv")]
|
||||
struct NewtypePrivDef(
|
||||
#[serde(getter = "remote::NewtypePriv::get", with = "UnitDef")]
|
||||
remote::Unit
|
||||
#[serde(getter = "remote::NewtypePriv::get", with = "UnitDef")] remote::Unit,
|
||||
);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "remote::NewtypePub")]
|
||||
struct NewtypePubDef(
|
||||
#[serde(with = "UnitDef")]
|
||||
remote::Unit
|
||||
);
|
||||
struct NewtypePubDef(#[serde(with = "UnitDef")] remote::Unit);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "remote::TuplePriv")]
|
||||
struct TuplePrivDef(
|
||||
#[serde(getter = "remote::TuplePriv::first")]
|
||||
u8,
|
||||
#[serde(getter = "remote::TuplePriv::second", with = "UnitDef")]
|
||||
remote::Unit
|
||||
#[serde(getter = "remote::TuplePriv::first")] u8,
|
||||
#[serde(getter = "remote::TuplePriv::second", with = "UnitDef")] remote::Unit,
|
||||
);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "remote::TuplePub")]
|
||||
struct TuplePubDef(
|
||||
u8,
|
||||
#[serde(with = "UnitDef")]
|
||||
remote::Unit
|
||||
);
|
||||
struct TuplePubDef(u8, #[serde(with = "UnitDef")] remote::Unit);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "remote::StructPriv")]
|
||||
struct StructPrivDef {
|
||||
#[serde(getter = "remote::StructPriv::a")]
|
||||
a: u8,
|
||||
#[serde(getter = "remote::StructPriv::a")] a: u8,
|
||||
|
||||
#[serde(getter = "remote::StructPriv::b")]
|
||||
#[serde(with= "UnitDef")]
|
||||
#[serde(with = "UnitDef")]
|
||||
b: remote::Unit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "remote::StructPub")]
|
||||
struct StructPubDef {
|
||||
#[allow(dead_code)]
|
||||
a: u8,
|
||||
#[allow(dead_code)] a: u8,
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[serde(with= "UnitDef")]
|
||||
#[serde(with = "UnitDef")]
|
||||
b: remote::Unit,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// Copyright 2017 Serde Developers
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
extern crate serde_test;
|
||||
use self::serde_test::{assert_tokens, Configure, Token};
|
||||
|
||||
use std::net;
|
||||
|
||||
#[macro_use]
|
||||
#[allow(unused_macros)]
|
||||
mod macros;
|
||||
|
||||
#[test]
|
||||
fn ip_addr_roundtrip() {
|
||||
assert_tokens(
|
||||
&net::IpAddr::from(*b"1234").compact(),
|
||||
&seq![
|
||||
Token::NewtypeVariant { name: "IpAddr", variant: "V4" },
|
||||
|
||||
Token::Tuple { len: 4 },
|
||||
seq b"1234".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn socked_addr_roundtrip() {
|
||||
assert_tokens(
|
||||
&net::SocketAddr::from((*b"1234567890123456", 1234)).compact(),
|
||||
&seq![
|
||||
Token::NewtypeVariant { name: "SocketAddr", variant: "V6" },
|
||||
|
||||
Token::Tuple { len: 2 },
|
||||
|
||||
Token::Tuple { len: 16 },
|
||||
seq b"1234567890123456".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd,
|
||||
|
||||
Token::U16(1234),
|
||||
Token::TupleEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
+165
-35
@@ -9,19 +9,20 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::net;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
use std::ffi::CString;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::num::Wrapping;
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::str;
|
||||
|
||||
extern crate serde;
|
||||
|
||||
extern crate serde_test;
|
||||
use self::serde_test::{Token, assert_ser_tokens, assert_ser_tokens_error};
|
||||
use self::serde_test::{assert_ser_tokens, assert_ser_tokens_error, Configure, Token};
|
||||
|
||||
extern crate fnv;
|
||||
use self::fnv::FnvHasher;
|
||||
@@ -50,19 +51,29 @@ enum Enum {
|
||||
One(i32),
|
||||
Seq(i32, i32),
|
||||
Map { a: i32, b: i32 },
|
||||
#[serde(skip_serializing)]
|
||||
SkippedUnit,
|
||||
#[serde(skip_serializing)]
|
||||
SkippedOne(i32),
|
||||
#[serde(skip_serializing)]
|
||||
SkippedSeq(i32, i32),
|
||||
#[serde(skip_serializing)]
|
||||
SkippedMap { _a: i32, _b: i32 },
|
||||
#[serde(skip_serializing)] SkippedUnit,
|
||||
#[serde(skip_serializing)] SkippedOne(i32),
|
||||
#[serde(skip_serializing)] SkippedSeq(i32, i32),
|
||||
#[serde(skip_serializing)] SkippedMap { _a: i32, _b: i32 },
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! declare_tests {
|
||||
(
|
||||
$readable:tt
|
||||
$($name:ident { $($value:expr => $tokens:expr,)+ })+
|
||||
) => {
|
||||
$(
|
||||
#[test]
|
||||
fn $name() {
|
||||
$(
|
||||
assert_ser_tokens(&$value.$readable(), $tokens);
|
||||
)+
|
||||
}
|
||||
)+
|
||||
};
|
||||
|
||||
($($name:ident { $($value:expr => $tokens:expr,)+ })+) => {
|
||||
$(
|
||||
#[test]
|
||||
@@ -170,6 +181,17 @@ declare_tests! {
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_btreeset {
|
||||
BTreeSet::<isize>::new() => &[
|
||||
Token::Seq { len: Some(0) },
|
||||
Token::SeqEnd,
|
||||
],
|
||||
btreeset![1] => &[
|
||||
Token::Seq { len: Some(1) },
|
||||
Token::I32(1),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_hashset {
|
||||
HashSet::<isize>::new() => &[
|
||||
Token::Seq { len: Some(0) },
|
||||
@@ -319,6 +341,17 @@ declare_tests! {
|
||||
Token::StructEnd,
|
||||
],
|
||||
}
|
||||
test_system_time {
|
||||
UNIX_EPOCH + Duration::new(1, 200) => &[
|
||||
Token::Struct { name: "SystemTime", len: 2 },
|
||||
Token::Str("secs_since_epoch"),
|
||||
Token::U64(1),
|
||||
|
||||
Token::Str("nanos_since_epoch"),
|
||||
Token::U32(200),
|
||||
Token::StructEnd,
|
||||
],
|
||||
}
|
||||
test_range {
|
||||
1u32..2u32 => &[
|
||||
Token::Struct { name: "Range", len: 2 },
|
||||
@@ -330,17 +363,6 @@ declare_tests! {
|
||||
Token::StructEnd,
|
||||
],
|
||||
}
|
||||
test_net_ipv4addr {
|
||||
"1.2.3.4".parse::<net::Ipv4Addr>().unwrap() => &[Token::Str("1.2.3.4")],
|
||||
}
|
||||
test_net_ipv6addr {
|
||||
"::1".parse::<net::Ipv6Addr>().unwrap() => &[Token::Str("::1")],
|
||||
}
|
||||
test_net_socketaddr {
|
||||
"1.2.3.4:1234".parse::<net::SocketAddr>().unwrap() => &[Token::Str("1.2.3.4:1234")],
|
||||
"1.2.3.4:1234".parse::<net::SocketAddrV4>().unwrap() => &[Token::Str("1.2.3.4:1234")],
|
||||
"[::1]:1234".parse::<net::SocketAddrV6>().unwrap() => &[Token::Str("[::1]:1234")],
|
||||
}
|
||||
test_path {
|
||||
Path::new("/usr/local/lib") => &[
|
||||
Token::Str("/usr/local/lib"),
|
||||
@@ -361,15 +383,127 @@ declare_tests! {
|
||||
Token::Bytes(b"abc"),
|
||||
],
|
||||
}
|
||||
test_rc {
|
||||
Rc::new(true) => &[
|
||||
Token::Bool(true),
|
||||
],
|
||||
}
|
||||
test_arc {
|
||||
Arc::new(true) => &[
|
||||
Token::Bool(true),
|
||||
],
|
||||
}
|
||||
test_wrapping {
|
||||
Wrapping(1usize) => &[
|
||||
Token::U64(1),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
declare_tests! {
|
||||
readable
|
||||
|
||||
test_net_ipv4addr_readable {
|
||||
"1.2.3.4".parse::<net::Ipv4Addr>().unwrap() => &[Token::Str("1.2.3.4")],
|
||||
}
|
||||
test_net_ipv6addr_readable {
|
||||
"::1".parse::<net::Ipv6Addr>().unwrap() => &[Token::Str("::1")],
|
||||
}
|
||||
test_net_ipaddr_readable {
|
||||
"1.2.3.4".parse::<net::IpAddr>().unwrap() => &[Token::Str("1.2.3.4")],
|
||||
}
|
||||
test_net_socketaddr_readable {
|
||||
"1.2.3.4:1234".parse::<net::SocketAddr>().unwrap() => &[Token::Str("1.2.3.4:1234")],
|
||||
"1.2.3.4:1234".parse::<net::SocketAddrV4>().unwrap() => &[Token::Str("1.2.3.4:1234")],
|
||||
"[::1]:1234".parse::<net::SocketAddrV6>().unwrap() => &[Token::Str("[::1]:1234")],
|
||||
}
|
||||
}
|
||||
|
||||
declare_tests! {
|
||||
compact
|
||||
|
||||
test_net_ipv4addr_compact {
|
||||
net::Ipv4Addr::from(*b"1234") => &seq![
|
||||
Token::Tuple { len: 4 },
|
||||
seq b"1234".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd,
|
||||
],
|
||||
}
|
||||
test_net_ipv6addr_compact {
|
||||
net::Ipv6Addr::from(*b"1234567890123456") => &seq![
|
||||
Token::Tuple { len: 16 },
|
||||
seq b"1234567890123456".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd,
|
||||
],
|
||||
}
|
||||
test_net_ipaddr_compact {
|
||||
net::IpAddr::from(*b"1234") => &seq![
|
||||
Token::NewtypeVariant { name: "IpAddr", variant: "V4" },
|
||||
|
||||
Token::Tuple { len: 4 },
|
||||
seq b"1234".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd,
|
||||
],
|
||||
}
|
||||
test_net_socketaddr_compact {
|
||||
net::SocketAddr::from((*b"1234567890123456", 1234)) => &seq![
|
||||
Token::NewtypeVariant { name: "SocketAddr", variant: "V6" },
|
||||
|
||||
Token::Tuple { len: 2 },
|
||||
|
||||
Token::Tuple { len: 16 },
|
||||
seq b"1234567890123456".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd,
|
||||
|
||||
Token::U16(1234),
|
||||
Token::TupleEnd,
|
||||
],
|
||||
net::SocketAddrV4::new(net::Ipv4Addr::from(*b"1234"), 1234) => &seq![
|
||||
Token::Tuple { len: 2 },
|
||||
|
||||
Token::Tuple { len: 4 },
|
||||
seq b"1234".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd,
|
||||
|
||||
Token::U16(1234),
|
||||
Token::TupleEnd,
|
||||
],
|
||||
net::SocketAddrV6::new(net::Ipv6Addr::from(*b"1234567890123456"), 1234, 0, 0) => &seq![
|
||||
Token::Tuple { len: 2 },
|
||||
|
||||
Token::Tuple { len: 16 },
|
||||
seq b"1234567890123456".iter().map(|&b| Token::U8(b)),
|
||||
Token::TupleEnd,
|
||||
|
||||
Token::U16(1234),
|
||||
Token::TupleEnd,
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
// Serde's implementation is not unstable, but the constructors are.
|
||||
#[cfg(feature = "unstable")]
|
||||
#[test]
|
||||
fn test_net_ipaddr() {
|
||||
assert_ser_tokens(
|
||||
&"1.2.3.4".parse::<net::IpAddr>().unwrap(),
|
||||
&[Token::Str("1.2.3.4")],
|
||||
);
|
||||
declare_tests! {
|
||||
test_rc_dst {
|
||||
Rc::<str>::from("s") => &[
|
||||
Token::Str("s"),
|
||||
],
|
||||
Rc::<[bool]>::from(&[true][..]) => &[
|
||||
Token::Seq { len: Some(1) },
|
||||
Token::Bool(true),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
test_arc_dst {
|
||||
Arc::<str>::from("s") => &[
|
||||
Token::Str("s"),
|
||||
],
|
||||
Arc::<[bool]>::from(&[true][..]) => &[
|
||||
Token::Seq { len: Some(1) },
|
||||
Token::Bool(true),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -385,11 +519,7 @@ fn test_cannot_serialize_paths() {
|
||||
let mut path_buf = PathBuf::new();
|
||||
path_buf.push(path);
|
||||
|
||||
assert_ser_tokens_error(
|
||||
&path_buf,
|
||||
&[],
|
||||
"path contains invalid UTF-8 characters",
|
||||
);
|
||||
assert_ser_tokens_error(&path_buf, &[], "path contains invalid UTF-8 characters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -34,6 +34,9 @@ if [ -n "${CLIPPY}" ]; then
|
||||
cd "$DIR/serde_derive"
|
||||
cargo clippy -- -Dclippy
|
||||
|
||||
cd "$DIR/serde_test"
|
||||
cargo clippy -- -Dclippy
|
||||
|
||||
cd "$DIR/test_suite"
|
||||
cargo clippy --features unstable -- -Dclippy
|
||||
|
||||
@@ -41,21 +44,24 @@ if [ -n "${CLIPPY}" ]; then
|
||||
cargo clippy -- -Dclippy
|
||||
else
|
||||
CHANNEL=nightly
|
||||
cd "$DIR"
|
||||
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 'rc unstable'
|
||||
cd "$DIR/test_suite/deps"
|
||||
channel build
|
||||
cd "$DIR/test_suite"
|
||||
channel test --features unstable
|
||||
cd "$DIR/test_suite/no_std"
|
||||
channel build
|
||||
if [ -z "${APPVEYOR}" ]; then
|
||||
cd "$DIR/test_suite/no_std"
|
||||
channel build
|
||||
fi
|
||||
|
||||
CHANNEL=beta
|
||||
cd "$DIR"
|
||||
cargo clean
|
||||
cd "$DIR/serde"
|
||||
channel build --features rc
|
||||
@@ -63,6 +69,7 @@ else
|
||||
channel test
|
||||
|
||||
CHANNEL=stable
|
||||
cd "$DIR"
|
||||
cargo clean
|
||||
cd "$DIR/serde"
|
||||
channel build --features rc
|
||||
@@ -72,6 +79,7 @@ else
|
||||
channel test
|
||||
|
||||
CHANNEL=1.13.0
|
||||
cd "$DIR"
|
||||
cargo clean
|
||||
cd "$DIR/serde"
|
||||
channel build --features rc
|
||||
|
||||
Reference in New Issue
Block a user