mirror of
https://github.com/pezkuwichain/serde.git
synced 2026-04-23 03:38:00 +00:00
Compare commits
90 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| eed18ffab2 | |||
| f8e1fa8ebc | |||
| 860241aa88 | |||
| 6f6c60867d | |||
| 77376f39ea | |||
| 302fac91a3 | |||
| 9c659d9d86 | |||
| 21698f264a | |||
| ba002e1119 | |||
| 8b44eb8bfc | |||
| d82a0cc5ff | |||
| 801fd1dc19 | |||
| 222779d46c | |||
| b1c1d964e1 | |||
| b77cfb635d | |||
| c42c08a25b | |||
| 48997cbb5b | |||
| d8ccd8809e | |||
| d2b65e0a5d | |||
| 7c04c98e0e | |||
| a2fa4c2570 | |||
| 42430902e2 | |||
| 23e2e92237 | |||
| 273b2c11c6 | |||
| c1602a4d76 | |||
| c23be3f855 | |||
| 5c9c97c0ce | |||
| e5ed440136 | |||
| d45ca2f5e4 | |||
| d7f9f8209d | |||
| 4a2612ecff | |||
| 05b22a06d7 | |||
| 3145bcc46e | |||
| 2b18b57d84 | |||
| 5520202262 | |||
| 3d647f4063 | |||
| 0fde3c2ee8 | |||
| 27f935f036 | |||
| 99614c7266 | |||
| bb2ecb3bc4 | |||
| 96393bfcc7 | |||
| 1d92569abc | |||
| e4ef087735 | |||
| 695c3eedcb | |||
| 50c636a923 | |||
| 5b884b5bf9 | |||
| 8637dda60f | |||
| abeea89147 | |||
| 6e324e887d | |||
| 7c596c7136 | |||
| f02dbf381b | |||
| 7cf184624a | |||
| c5a3128492 | |||
| 205f606962 | |||
| ad40f976db | |||
| 58d52e784b | |||
| d44f12907b | |||
| 61b167be9a | |||
| f1af2dc5ab | |||
| ebc61baab2 | |||
| ffcde25b6e | |||
| 2f57cecf13 | |||
| bfdcbae9db | |||
| ca41e16e92 | |||
| 352fe7b451 | |||
| 49e302d17d | |||
| b8602a7e43 | |||
| a8c8c2028e | |||
| d1833c5602 | |||
| b4ef7ac323 | |||
| ebf80ac965 | |||
| 112dfd7428 | |||
| b692923321 | |||
| 9e8cda4c37 | |||
| 5457394f5b | |||
| 6627540dd6 | |||
| 5ae06bba49 | |||
| 571bb8caed | |||
| 299cd2dbd0 | |||
| 583c0d8d14 | |||
| 07d07347b3 | |||
| 77b07f3fbf | |||
| 1bd2c6129c | |||
| 39413c8ce7 | |||
| b4dbae250b | |||
| 5a91ac5ba5 | |||
| 7ad836e6a9 | |||
| 72ecb9064c | |||
| f9946ee0ca | |||
| a164f52315 |
@@ -1,9 +1,11 @@
|
||||
# Serde   [![Build Status]][travis] [![Latest Version]][crates.io]
|
||||
# Serde   [![Build Status]][travis] [![Latest Version]][crates.io] [![Rustc Version 1.13+]][rustc]
|
||||
|
||||
[Build Status]: https://api.travis-ci.org/serde-rs/serde.svg?branch=master
|
||||
[travis]: https://travis-ci.org/serde-rs/serde
|
||||
[Latest Version]: https://img.shields.io/crates/v/serde.svg
|
||||
[crates.io]: https://crates.io/crates/serde
|
||||
[Rustc Version 1.13+]: https://img.shields.io/badge/rustc-1.13+-lightgray.svg
|
||||
[rustc]: https://blog.rust-lang.org/2016/11/10/Rust-1.13.html
|
||||
|
||||
**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.**
|
||||
|
||||
|
||||
@@ -1,2 +1 @@
|
||||
error_on_line_overflow = false
|
||||
same_line_attributes = false
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde"
|
||||
version = "1.0.32" # remember to update html_root_url
|
||||
version = "1.0.37" # 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"
|
||||
|
||||
+132
-42
@@ -9,33 +9,33 @@
|
||||
use lib::*;
|
||||
|
||||
macro_rules! int_to_int {
|
||||
($dst:ident, $n:ident) => (
|
||||
($dst:ident, $n:ident) => {
|
||||
if $dst::min_value() as i64 <= $n as i64 && $n as i64 <= $dst::max_value() as i64 {
|
||||
Some($n as $dst)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! int_to_uint {
|
||||
($dst:ident, $n:ident) => (
|
||||
($dst:ident, $n:ident) => {
|
||||
if 0 <= $n && $n as u64 <= $dst::max_value() as u64 {
|
||||
Some($n as $dst)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! uint_to {
|
||||
($dst:ident, $n:ident) => (
|
||||
($dst:ident, $n:ident) => {
|
||||
if $n as u64 <= $dst::max_value() as u64 {
|
||||
Some($n as $dst)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
pub trait FromPrimitive: Sized {
|
||||
@@ -52,54 +52,144 @@ pub trait FromPrimitive: Sized {
|
||||
}
|
||||
|
||||
macro_rules! impl_from_primitive_for_int {
|
||||
($t:ident) => (
|
||||
($t:ident) => {
|
||||
impl FromPrimitive for $t {
|
||||
#[inline] fn from_isize(n: isize) -> Option<Self> { int_to_int!($t, n) }
|
||||
#[inline] fn from_i8(n: i8) -> Option<Self> { int_to_int!($t, n) }
|
||||
#[inline] fn from_i16(n: i16) -> Option<Self> { int_to_int!($t, n) }
|
||||
#[inline] fn from_i32(n: i32) -> Option<Self> { int_to_int!($t, n) }
|
||||
#[inline] fn from_i64(n: i64) -> Option<Self> { int_to_int!($t, n) }
|
||||
#[inline] fn from_usize(n: usize) -> Option<Self> { uint_to!($t, n) }
|
||||
#[inline] fn from_u8(n: u8) -> Option<Self> { uint_to!($t, n) }
|
||||
#[inline] fn from_u16(n: u16) -> Option<Self> { uint_to!($t, n) }
|
||||
#[inline] fn from_u32(n: u32) -> Option<Self> { uint_to!($t, n) }
|
||||
#[inline] fn from_u64(n: u64) -> Option<Self> { uint_to!($t, n) }
|
||||
#[inline]
|
||||
fn from_isize(n: isize) -> Option<Self> {
|
||||
int_to_int!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_i8(n: i8) -> Option<Self> {
|
||||
int_to_int!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_i16(n: i16) -> Option<Self> {
|
||||
int_to_int!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_i32(n: i32) -> Option<Self> {
|
||||
int_to_int!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_i64(n: i64) -> Option<Self> {
|
||||
int_to_int!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_usize(n: usize) -> Option<Self> {
|
||||
uint_to!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_u8(n: u8) -> Option<Self> {
|
||||
uint_to!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_u16(n: u16) -> Option<Self> {
|
||||
uint_to!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_u32(n: u32) -> Option<Self> {
|
||||
uint_to!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_u64(n: u64) -> Option<Self> {
|
||||
uint_to!($t, n)
|
||||
}
|
||||
}
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! impl_from_primitive_for_uint {
|
||||
($t:ident) => (
|
||||
($t:ident) => {
|
||||
impl FromPrimitive for $t {
|
||||
#[inline] fn from_isize(n: isize) -> Option<Self> { int_to_uint!($t, n) }
|
||||
#[inline] fn from_i8(n: i8) -> Option<Self> { int_to_uint!($t, n) }
|
||||
#[inline] fn from_i16(n: i16) -> Option<Self> { int_to_uint!($t, n) }
|
||||
#[inline] fn from_i32(n: i32) -> Option<Self> { int_to_uint!($t, n) }
|
||||
#[inline] fn from_i64(n: i64) -> Option<Self> { int_to_uint!($t, n) }
|
||||
#[inline] fn from_usize(n: usize) -> Option<Self> { uint_to!($t, n) }
|
||||
#[inline] fn from_u8(n: u8) -> Option<Self> { uint_to!($t, n) }
|
||||
#[inline] fn from_u16(n: u16) -> Option<Self> { uint_to!($t, n) }
|
||||
#[inline] fn from_u32(n: u32) -> Option<Self> { uint_to!($t, n) }
|
||||
#[inline] fn from_u64(n: u64) -> Option<Self> { uint_to!($t, n) }
|
||||
#[inline]
|
||||
fn from_isize(n: isize) -> Option<Self> {
|
||||
int_to_uint!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_i8(n: i8) -> Option<Self> {
|
||||
int_to_uint!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_i16(n: i16) -> Option<Self> {
|
||||
int_to_uint!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_i32(n: i32) -> Option<Self> {
|
||||
int_to_uint!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_i64(n: i64) -> Option<Self> {
|
||||
int_to_uint!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_usize(n: usize) -> Option<Self> {
|
||||
uint_to!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_u8(n: u8) -> Option<Self> {
|
||||
uint_to!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_u16(n: u16) -> Option<Self> {
|
||||
uint_to!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_u32(n: u32) -> Option<Self> {
|
||||
uint_to!($t, n)
|
||||
}
|
||||
#[inline]
|
||||
fn from_u64(n: u64) -> Option<Self> {
|
||||
uint_to!($t, n)
|
||||
}
|
||||
}
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! impl_from_primitive_for_float {
|
||||
($t:ident) => (
|
||||
($t:ident) => {
|
||||
impl FromPrimitive for $t {
|
||||
#[inline] fn from_isize(n: isize) -> Option<Self> { Some(n as Self) }
|
||||
#[inline] fn from_i8(n: i8) -> Option<Self> { Some(n as Self) }
|
||||
#[inline] fn from_i16(n: i16) -> Option<Self> { Some(n as Self) }
|
||||
#[inline] fn from_i32(n: i32) -> Option<Self> { Some(n as Self) }
|
||||
#[inline] fn from_i64(n: i64) -> Option<Self> { Some(n as Self) }
|
||||
#[inline] fn from_usize(n: usize) -> Option<Self> { Some(n as Self) }
|
||||
#[inline] fn from_u8(n: u8) -> Option<Self> { Some(n as Self) }
|
||||
#[inline] fn from_u16(n: u16) -> Option<Self> { Some(n as Self) }
|
||||
#[inline] fn from_u32(n: u32) -> Option<Self> { Some(n as Self) }
|
||||
#[inline] fn from_u64(n: u64) -> Option<Self> { Some(n as Self) }
|
||||
#[inline]
|
||||
fn from_isize(n: isize) -> Option<Self> {
|
||||
Some(n as Self)
|
||||
}
|
||||
#[inline]
|
||||
fn from_i8(n: i8) -> Option<Self> {
|
||||
Some(n as Self)
|
||||
}
|
||||
#[inline]
|
||||
fn from_i16(n: i16) -> Option<Self> {
|
||||
Some(n as Self)
|
||||
}
|
||||
#[inline]
|
||||
fn from_i32(n: i32) -> Option<Self> {
|
||||
Some(n as Self)
|
||||
}
|
||||
#[inline]
|
||||
fn from_i64(n: i64) -> Option<Self> {
|
||||
Some(n as Self)
|
||||
}
|
||||
#[inline]
|
||||
fn from_usize(n: usize) -> Option<Self> {
|
||||
Some(n as Self)
|
||||
}
|
||||
#[inline]
|
||||
fn from_u8(n: u8) -> Option<Self> {
|
||||
Some(n as Self)
|
||||
}
|
||||
#[inline]
|
||||
fn from_u16(n: u16) -> Option<Self> {
|
||||
Some(n as Self)
|
||||
}
|
||||
#[inline]
|
||||
fn from_u32(n: u32) -> Option<Self> {
|
||||
Some(n as Self)
|
||||
}
|
||||
#[inline]
|
||||
fn from_u64(n: u64) -> Option<Self> {
|
||||
Some(n as Self)
|
||||
}
|
||||
}
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
impl_from_primitive_for_int!(isize);
|
||||
|
||||
+86
-11
@@ -470,7 +470,11 @@ impl<'de> Deserialize<'de> for CString {
|
||||
}
|
||||
|
||||
macro_rules! forwarded_impl {
|
||||
(( $($id: ident),* ), $ty: ty, $func: expr) => {
|
||||
(
|
||||
$(#[doc = $doc:tt])*
|
||||
( $($id: ident),* ), $ty: ty, $func: expr
|
||||
) => {
|
||||
$(#[doc = $doc])*
|
||||
impl<'de $(, $id : Deserialize<'de>,)*> Deserialize<'de> for $ty {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
@@ -1073,7 +1077,7 @@ map_impl!(
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
macro_rules! parse_ip_impl {
|
||||
($ty:ty; $size: expr) => {
|
||||
($ty:ty; $size:expr) => {
|
||||
impl<'de> Deserialize<'de> for $ty {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
@@ -1087,7 +1091,7 @@ macro_rules! parse_ip_impl {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
@@ -1230,7 +1234,7 @@ parse_ip_impl!(net::Ipv6Addr; 16);
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
macro_rules! parse_socket_impl {
|
||||
($ty:ty, $new: expr) => {
|
||||
($ty:ty, $new:expr) => {
|
||||
impl<'de> Deserialize<'de> for $ty {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
@@ -1244,7 +1248,7 @@ macro_rules! parse_socket_impl {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
@@ -1432,10 +1436,28 @@ forwarded_impl!((T), Box<[T]>, Vec::into_boxed_slice);
|
||||
forwarded_impl!((), Box<str>, String::into_boxed_str);
|
||||
|
||||
#[cfg(all(not(feature = "unstable"), feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
forwarded_impl!((T), Arc<T>, Arc::new);
|
||||
forwarded_impl! {
|
||||
/// This impl requires the [`"rc"`] Cargo feature of Serde.
|
||||
///
|
||||
/// Deserializing a data structure containing `Arc` will not attempt to
|
||||
/// deduplicate `Arc` references to the same data. Every deserialized `Arc`
|
||||
/// will end up with a strong count of 1.
|
||||
///
|
||||
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
|
||||
(T), Arc<T>, Arc::new
|
||||
}
|
||||
|
||||
#[cfg(all(not(feature = "unstable"), feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
forwarded_impl!((T), Rc<T>, Rc::new);
|
||||
forwarded_impl! {
|
||||
/// This impl requires the [`"rc"`] Cargo feature of Serde.
|
||||
///
|
||||
/// Deserializing a data structure containing `Rc` will not attempt to
|
||||
/// deduplicate `Rc` references to the same data. Every deserialized `Rc`
|
||||
/// will end up with a strong count of 1.
|
||||
///
|
||||
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
|
||||
(T), Rc<T>, Rc::new
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'de, 'a, T: ?Sized> Deserialize<'de> for Cow<'a, T>
|
||||
@@ -1456,7 +1478,11 @@ where
|
||||
|
||||
#[cfg(all(feature = "unstable", feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
macro_rules! box_forwarded_impl {
|
||||
($t:ident) => {
|
||||
(
|
||||
$(#[doc = $doc:tt])*
|
||||
$t:ident
|
||||
) => {
|
||||
$(#[doc = $doc])*
|
||||
impl<'de, T: ?Sized> Deserialize<'de> for $t<T>
|
||||
where
|
||||
Box<T>: Deserialize<'de>,
|
||||
@@ -1468,14 +1494,32 @@ macro_rules! box_forwarded_impl {
|
||||
Box::deserialize(deserializer).map(Into::into)
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "unstable", feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
box_forwarded_impl!(Rc);
|
||||
box_forwarded_impl! {
|
||||
/// This impl requires the [`"rc"`] Cargo feature of Serde.
|
||||
///
|
||||
/// Deserializing a data structure containing `Rc` will not attempt to
|
||||
/// deduplicate `Rc` references to the same data. Every deserialized `Rc`
|
||||
/// will end up with a strong count of 1.
|
||||
///
|
||||
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
|
||||
Rc
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "unstable", feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
box_forwarded_impl!(Arc);
|
||||
box_forwarded_impl! {
|
||||
/// This impl requires the [`"rc"`] Cargo feature of Serde.
|
||||
///
|
||||
/// Deserializing a data structure containing `Arc` will not attempt to
|
||||
/// deduplicate `Arc` references to the same data. Every deserialized `Arc`
|
||||
/// will end up with a strong count of 1.
|
||||
///
|
||||
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
|
||||
Arc
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -1918,6 +1962,7 @@ where
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[allow(deprecated)]
|
||||
impl<'de, T> Deserialize<'de> for NonZero<T>
|
||||
where
|
||||
T: Deserialize<'de> + Zeroable,
|
||||
@@ -1934,6 +1979,36 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! nonzero_integers {
|
||||
( $( $T: ty, )+ ) => {
|
||||
$(
|
||||
#[cfg(feature = "unstable")]
|
||||
impl<'de> Deserialize<'de> for $T {
|
||||
fn deserialize<D>(deserializer: D) -> Result<$T, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let value = try!(Deserialize::deserialize(deserializer));
|
||||
match <$T>::new(value) {
|
||||
Some(nonzero) => Ok(nonzero),
|
||||
None => Err(Error::custom("expected a non-zero value")),
|
||||
}
|
||||
}
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
nonzero_integers! {
|
||||
// Not including signed NonZeroI* since they might be removed
|
||||
NonZeroU8,
|
||||
NonZeroU16,
|
||||
NonZeroU32,
|
||||
NonZeroU64,
|
||||
// FIXME: https://github.com/serde-rs/serde/issues/1136 NonZeroU128,
|
||||
NonZeroUsize,
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<'de, T, E> Deserialize<'de> for Result<T, E>
|
||||
|
||||
+2
-1
@@ -98,7 +98,8 @@
|
||||
//! - Path
|
||||
//! - PathBuf
|
||||
//! - Range\<T\>
|
||||
//! - NonZero\<T\> (unstable)
|
||||
//! - NonZero\<T\> (unstable, deprecated)
|
||||
//! - num::NonZero* (unstable)
|
||||
//! - **Net types**:
|
||||
//! - IpAddr
|
||||
//! - Ipv4Addr
|
||||
|
||||
@@ -37,10 +37,10 @@
|
||||
|
||||
use lib::*;
|
||||
|
||||
use self::private::{First, Second};
|
||||
use de::{self, Expected, IntoDeserializer, SeqAccess};
|
||||
use private::de::size_hint;
|
||||
use ser;
|
||||
use self::private::{First, Second};
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
+27
-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.32")]
|
||||
#![doc(html_root_url = "https://docs.rs/serde/1.0.37")]
|
||||
// Support using Serde without the standard library!
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
// Unstable functionality only if the user asks for it. For tracking and
|
||||
@@ -135,16 +135,16 @@ extern crate core;
|
||||
/// module.
|
||||
mod lib {
|
||||
mod core {
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::*;
|
||||
#[cfg(not(feature = "std"))]
|
||||
pub use core::*;
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::*;
|
||||
}
|
||||
|
||||
pub use self::core::{cmp, iter, mem, ops, slice, str};
|
||||
pub use self::core::{f32, f64};
|
||||
pub use self::core::{isize, i16, i32, i64, i8};
|
||||
pub use self::core::{usize, u16, u32, u64, u8};
|
||||
pub use self::core::{f32, f64};
|
||||
|
||||
pub use self::core::cell::{Cell, RefCell};
|
||||
pub use self::core::clone::{self, Clone};
|
||||
@@ -155,40 +155,40 @@ mod lib {
|
||||
pub use self::core::option::{self, Option};
|
||||
pub use self::core::result::{self, Result};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::borrow::{Cow, ToOwned};
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
pub use alloc::borrow::{Cow, ToOwned};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::string::String;
|
||||
pub use std::borrow::{Cow, ToOwned};
|
||||
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
pub use alloc::string::{String, ToString};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::vec::Vec;
|
||||
pub use std::string::String;
|
||||
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
pub use alloc::vec::Vec;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::boxed::Box;
|
||||
pub use std::vec::Vec;
|
||||
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
pub use alloc::boxed::Box;
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::boxed::Box;
|
||||
|
||||
#[cfg(all(feature = "rc", feature = "std"))]
|
||||
pub use std::rc::Rc;
|
||||
#[cfg(all(feature = "rc", feature = "alloc", not(feature = "std")))]
|
||||
pub use alloc::rc::Rc;
|
||||
|
||||
#[cfg(all(feature = "rc", feature = "std"))]
|
||||
pub use std::sync::Arc;
|
||||
pub use std::rc::Rc;
|
||||
|
||||
#[cfg(all(feature = "rc", feature = "alloc", not(feature = "std")))]
|
||||
pub use alloc::arc::Arc;
|
||||
#[cfg(all(feature = "rc", feature = "std"))]
|
||||
pub use std::sync::Arc;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque};
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
pub use alloc::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque};
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::{error, net};
|
||||
@@ -206,12 +206,16 @@ mod lib {
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::path::{Path, PathBuf};
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::sync::{Mutex, RwLock};
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[allow(deprecated)]
|
||||
pub use core::nonzero::{NonZero, Zeroable};
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
pub use core::num::{NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize};
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
@@ -219,13 +223,13 @@ mod lib {
|
||||
#[macro_use]
|
||||
mod macros;
|
||||
|
||||
pub mod ser;
|
||||
pub mod de;
|
||||
pub mod ser;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use ser::{Serialize, Serializer};
|
||||
#[doc(inline)]
|
||||
pub use de::{Deserialize, Deserializer};
|
||||
#[doc(inline)]
|
||||
pub use ser::{Serialize, Serializer};
|
||||
|
||||
// Generated code uses these to support no_std. Not public API.
|
||||
#[doc(hidden)]
|
||||
|
||||
+180
-10
@@ -11,10 +11,10 @@ use lib::*;
|
||||
use de::{Deserialize, DeserializeSeed, Deserializer, Error, IntoDeserializer, Visitor};
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
use de::Unexpected;
|
||||
use de::{MapAccess, Unexpected};
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub use self::content::{Content, ContentDeserializer, ContentRefDeserializer,
|
||||
pub use self::content::{Content, ContentDeserializer, ContentRefDeserializer, EnumDeserializer,
|
||||
InternallyTaggedUnitVisitor, TagContentOtherField,
|
||||
TagContentOtherFieldVisitor, TagOrContentField, TagOrContentFieldVisitor,
|
||||
TaggedContentVisitor, UntaggedUnitVisitor};
|
||||
@@ -228,9 +228,9 @@ mod content {
|
||||
|
||||
use lib::*;
|
||||
|
||||
use super::size_hint;
|
||||
use de::{self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, MapAccess, SeqAccess,
|
||||
Unexpected, Visitor};
|
||||
use super::size_hint;
|
||||
|
||||
/// Used from generated code to buffer the contents of the Deserializer when
|
||||
/// deserializing untagged enums and internally tagged enums.
|
||||
@@ -269,6 +269,14 @@ mod content {
|
||||
}
|
||||
|
||||
impl<'de> Content<'de> {
|
||||
pub fn as_str(&self) -> Option<&str> {
|
||||
match *self {
|
||||
Content::Str(x) => Some(x),
|
||||
Content::String(ref x) => Some(x),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn unexpected(&self) -> Unexpected {
|
||||
match *self {
|
||||
Content::Bool(b) => Unexpected::Bool(b),
|
||||
@@ -1118,11 +1126,7 @@ mod content {
|
||||
}
|
||||
};
|
||||
|
||||
visitor.visit_enum(EnumDeserializer {
|
||||
variant: variant,
|
||||
value: value,
|
||||
err: PhantomData,
|
||||
})
|
||||
visitor.visit_enum(EnumDeserializer::new(variant, value))
|
||||
}
|
||||
|
||||
fn deserialize_unit_struct<V>(
|
||||
@@ -1170,7 +1174,7 @@ mod content {
|
||||
}
|
||||
}
|
||||
|
||||
struct EnumDeserializer<'de, E>
|
||||
pub struct EnumDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
@@ -1179,6 +1183,19 @@ mod content {
|
||||
err: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<'de, E> EnumDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
pub fn new(variant: Content<'de>, value: Option<Content<'de>>) -> EnumDeserializer<'de, E> {
|
||||
EnumDeserializer {
|
||||
variant: variant,
|
||||
value: value,
|
||||
err: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, E> de::EnumAccess<'de> for EnumDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
@@ -1199,7 +1216,7 @@ mod content {
|
||||
}
|
||||
}
|
||||
|
||||
struct VariantDeserializer<'de, E>
|
||||
pub struct VariantDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
@@ -2062,3 +2079,156 @@ where
|
||||
T::deserialize_in_place(deserializer, self.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub struct FlatMapDeserializer<'a, 'de: 'a, E>(
|
||||
pub &'a mut Vec<Option<(Content<'de>, Content<'de>)>>,
|
||||
pub PhantomData<E>,
|
||||
);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, 'de, E> Deserializer<'de> for FlatMapDeserializer<'a, 'de, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn deserialize_any<V>(self, _: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
Err(Error::custom("can only flatten structs and maps"))
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(
|
||||
self,
|
||||
name: &'static str,
|
||||
variants: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
for item in self.0.iter_mut() {
|
||||
// items in the vector are nulled out when used. So we can only use
|
||||
// an item if it's still filled in and if the field is one we care
|
||||
// about.
|
||||
let use_item = match *item {
|
||||
None => false,
|
||||
Some((ref c, _)) => c.as_str().map_or(false, |x| variants.contains(&x)),
|
||||
};
|
||||
|
||||
if use_item {
|
||||
let (key, value) = item.take().unwrap();
|
||||
return visitor.visit_enum(EnumDeserializer::new(key, Some(value)));
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::custom(format_args!(
|
||||
"no variant of enum {} not found in flattened data",
|
||||
name
|
||||
)))
|
||||
}
|
||||
|
||||
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_map(FlatMapAccess::new(self.0.iter_mut(), None))
|
||||
}
|
||||
|
||||
fn deserialize_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_map(FlatMapAccess::new(self.0.iter_mut(), Some(fields)))
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_newtype_struct(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 seq tuple tuple_struct identifier
|
||||
ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub struct FlatMapAccess<'a, 'de: 'a, E> {
|
||||
iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>,
|
||||
pending_content: Option<Content<'de>>,
|
||||
fields: Option<&'static [&'static str]>,
|
||||
_marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, 'de, E> FlatMapAccess<'a, 'de, E> {
|
||||
fn new(
|
||||
iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>,
|
||||
fields: Option<&'static [&'static str]>,
|
||||
) -> FlatMapAccess<'a, 'de, E> {
|
||||
FlatMapAccess {
|
||||
iter: iter,
|
||||
pending_content: None,
|
||||
fields: fields,
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, 'de, E> MapAccess<'de> for FlatMapAccess<'a, 'de, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
|
||||
where
|
||||
T: DeserializeSeed<'de>,
|
||||
{
|
||||
while let Some(item) = self.iter.next() {
|
||||
// items in the vector are nulled out when used. So we can only use
|
||||
// an item if it's still filled in and if the field is one we care
|
||||
// about. In case we do not know which fields we want, we take them all.
|
||||
let use_item = match *item {
|
||||
None => false,
|
||||
Some((ref c, _)) => {
|
||||
c.as_str()
|
||||
.map_or(self.fields.is_none(), |key| match self.fields {
|
||||
None => true,
|
||||
Some(fields) if fields.contains(&key) => true,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
if use_item {
|
||||
let (key, content) = item.take().unwrap();
|
||||
self.pending_content = Some(content);
|
||||
return seed.deserialize(ContentDeserializer::new(key)).map(Some);
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
|
||||
where
|
||||
T: DeserializeSeed<'de>,
|
||||
{
|
||||
match self.pending_content.take() {
|
||||
Some(value) => seed.deserialize(ContentDeserializer::new(value)),
|
||||
None => Err(Error::custom("value is missing")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,5 +8,5 @@
|
||||
|
||||
mod macros;
|
||||
|
||||
pub mod ser;
|
||||
pub mod de;
|
||||
pub mod ser;
|
||||
|
||||
+318
-13
@@ -11,7 +11,8 @@ use lib::*;
|
||||
use ser::{self, Impossible, Serialize, SerializeMap, SerializeStruct, Serializer};
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
use self::content::{SerializeStructVariantAsMapValue, SerializeTupleVariantAsMapValue};
|
||||
use self::content::{Content, ContentSerializer, SerializeStructVariantAsMapValue,
|
||||
SerializeTupleVariantAsMapValue};
|
||||
|
||||
/// Used to check that serde(getter) attributes return the expected type.
|
||||
/// Not public API.
|
||||
@@ -58,10 +59,11 @@ enum Unsupported {
|
||||
ByteArray,
|
||||
Optional,
|
||||
Unit,
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
UnitStruct,
|
||||
Sequence,
|
||||
Tuple,
|
||||
TupleStruct,
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
Enum,
|
||||
}
|
||||
|
||||
@@ -76,10 +78,11 @@ 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"),
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
Unsupported::UnitStruct => formatter.write_str("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 = "alloc")))]
|
||||
Unsupported::Enum => formatter.write_str("an enum"),
|
||||
}
|
||||
}
|
||||
@@ -459,7 +462,7 @@ mod content {
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Content {
|
||||
pub enum Content {
|
||||
Bool(bool),
|
||||
|
||||
U8(u8),
|
||||
@@ -584,12 +587,12 @@ mod content {
|
||||
}
|
||||
}
|
||||
|
||||
struct ContentSerializer<E> {
|
||||
pub struct ContentSerializer<E> {
|
||||
error: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<E> ContentSerializer<E> {
|
||||
fn new() -> Self {
|
||||
pub fn new() -> Self {
|
||||
ContentSerializer { error: PhantomData }
|
||||
}
|
||||
}
|
||||
@@ -804,7 +807,7 @@ mod content {
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeSeq<E> {
|
||||
pub struct SerializeSeq<E> {
|
||||
elements: Vec<Content>,
|
||||
error: PhantomData<E>,
|
||||
}
|
||||
@@ -830,7 +833,7 @@ mod content {
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeTuple<E> {
|
||||
pub struct SerializeTuple<E> {
|
||||
elements: Vec<Content>,
|
||||
error: PhantomData<E>,
|
||||
}
|
||||
@@ -856,7 +859,7 @@ mod content {
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeTupleStruct<E> {
|
||||
pub struct SerializeTupleStruct<E> {
|
||||
name: &'static str,
|
||||
fields: Vec<Content>,
|
||||
error: PhantomData<E>,
|
||||
@@ -883,7 +886,7 @@ mod content {
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeTupleVariant<E> {
|
||||
pub struct SerializeTupleVariant<E> {
|
||||
name: &'static str,
|
||||
variant_index: u32,
|
||||
variant: &'static str,
|
||||
@@ -917,7 +920,7 @@ mod content {
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeMap<E> {
|
||||
pub struct SerializeMap<E> {
|
||||
entries: Vec<(Content, Content)>,
|
||||
key: Option<Content>,
|
||||
error: PhantomData<E>,
|
||||
@@ -967,7 +970,7 @@ mod content {
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeStruct<E> {
|
||||
pub struct SerializeStruct<E> {
|
||||
name: &'static str,
|
||||
fields: Vec<(&'static str, Content)>,
|
||||
error: PhantomData<E>,
|
||||
@@ -994,7 +997,7 @@ mod content {
|
||||
}
|
||||
}
|
||||
|
||||
struct SerializeStructVariant<E> {
|
||||
pub struct SerializeStructVariant<E> {
|
||||
name: &'static str,
|
||||
variant_index: u32,
|
||||
variant: &'static str,
|
||||
@@ -1028,3 +1031,305 @@ mod content {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub struct FlatMapSerializer<'a, M: 'a>(pub &'a mut M);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, M> FlatMapSerializer<'a, M>
|
||||
where
|
||||
M: SerializeMap + 'a,
|
||||
{
|
||||
fn bad_type(self, what: Unsupported) -> M::Error {
|
||||
ser::Error::custom(format_args!(
|
||||
"can only flatten structs and maps (got {})",
|
||||
what
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, M> Serializer for FlatMapSerializer<'a, M>
|
||||
where
|
||||
M: SerializeMap + 'a,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = M::Error;
|
||||
|
||||
type SerializeSeq = Impossible<Self::Ok, M::Error>;
|
||||
type SerializeTuple = Impossible<Self::Ok, M::Error>;
|
||||
type SerializeTupleStruct = Impossible<Self::Ok, M::Error>;
|
||||
type SerializeMap = FlatMapSerializeMap<'a, M>;
|
||||
type SerializeStruct = FlatMapSerializeStruct<'a, M>;
|
||||
type SerializeTupleVariant = Impossible<Self::Ok, M::Error>;
|
||||
type SerializeStructVariant = FlatMapSerializeStructVariantAsMapValue<'a, M>;
|
||||
|
||||
fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Boolean))
|
||||
}
|
||||
|
||||
fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Integer))
|
||||
}
|
||||
|
||||
fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Float))
|
||||
}
|
||||
|
||||
fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Float))
|
||||
}
|
||||
|
||||
fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Char))
|
||||
}
|
||||
|
||||
fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::String))
|
||||
}
|
||||
|
||||
fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::ByteArray))
|
||||
}
|
||||
|
||||
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Optional))
|
||||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
Err(self.bad_type(Unsupported::Optional))
|
||||
}
|
||||
|
||||
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Unit))
|
||||
}
|
||||
|
||||
fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::UnitStruct))
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: u32,
|
||||
_: &'static str,
|
||||
) -> Result<Self::Ok, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Enum))
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized>(
|
||||
self,
|
||||
_: &'static str,
|
||||
value: &T,
|
||||
) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: ?Sized>(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: u32,
|
||||
variant: &'static str,
|
||||
value: &T,
|
||||
) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
try!(self.0.serialize_key(variant));
|
||||
self.0.serialize_value(value)
|
||||
}
|
||||
|
||||
fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Sequence))
|
||||
}
|
||||
|
||||
fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Tuple))
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
) -> Result<Self::SerializeTupleStruct, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::TupleStruct))
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: u32,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
) -> Result<Self::SerializeTupleVariant, Self::Error> {
|
||||
Err(self.bad_type(Unsupported::Enum))
|
||||
}
|
||||
|
||||
fn serialize_map(self, _: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
|
||||
Ok(FlatMapSerializeMap(self.0))
|
||||
}
|
||||
|
||||
fn serialize_struct(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
) -> Result<Self::SerializeStruct, Self::Error> {
|
||||
Ok(FlatMapSerializeStruct(self.0))
|
||||
}
|
||||
|
||||
fn serialize_struct_variant(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: u32,
|
||||
inner_variant: &'static str,
|
||||
_: usize,
|
||||
) -> Result<Self::SerializeStructVariant, Self::Error> {
|
||||
try!(self.0.serialize_key(inner_variant));
|
||||
Ok(FlatMapSerializeStructVariantAsMapValue::new(
|
||||
self.0,
|
||||
inner_variant,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub struct FlatMapSerializeMap<'a, M: 'a>(&'a mut M);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, M> ser::SerializeMap for FlatMapSerializeMap<'a, M>
|
||||
where
|
||||
M: SerializeMap + 'a,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = M::Error;
|
||||
|
||||
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_key(key)
|
||||
}
|
||||
|
||||
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_value(value)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub struct FlatMapSerializeStruct<'a, M: 'a>(&'a mut M);
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, M> ser::SerializeStruct for FlatMapSerializeStruct<'a, M>
|
||||
where
|
||||
M: SerializeMap + 'a,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = M::Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(
|
||||
&mut self,
|
||||
key: &'static str,
|
||||
value: &T,
|
||||
) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_entry(key, value)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub struct FlatMapSerializeStructVariantAsMapValue<'a, M: 'a> {
|
||||
map: &'a mut M,
|
||||
name: &'static str,
|
||||
fields: Vec<(&'static str, Content)>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, M> FlatMapSerializeStructVariantAsMapValue<'a, M>
|
||||
where
|
||||
M: SerializeMap + 'a,
|
||||
{
|
||||
fn new(map: &'a mut M, name: &'static str) -> FlatMapSerializeStructVariantAsMapValue<'a, M> {
|
||||
FlatMapSerializeStructVariantAsMapValue {
|
||||
map: map,
|
||||
name: name,
|
||||
fields: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, M> ser::SerializeStructVariant for FlatMapSerializeStructVariantAsMapValue<'a, M>
|
||||
where
|
||||
M: SerializeMap + 'a,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = M::Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(
|
||||
&mut self,
|
||||
key: &'static str,
|
||||
value: &T,
|
||||
) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
let value = try!(value.serialize(ContentSerializer::<M::Error>::new()));
|
||||
self.fields.push((key, value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Self::Error> {
|
||||
try!(
|
||||
self.map
|
||||
.serialize_value(&Content::Struct(self.name, self.fields))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
+57
-8
@@ -320,8 +320,12 @@ map_impl!(HashMap<K: Eq + Hash, V, H: BuildHasher>);
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! deref_impl {
|
||||
($($desc:tt)+) => {
|
||||
impl $($desc)+ {
|
||||
(
|
||||
$(#[doc = $doc:tt])*
|
||||
<$($desc:tt)+
|
||||
) => {
|
||||
$(#[doc = $doc])*
|
||||
impl <$($desc)+ {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -340,10 +344,30 @@ 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: ?Sized> Serialize for Rc<T> where T: Serialize);
|
||||
deref_impl! {
|
||||
/// This impl requires the [`"rc"`] Cargo feature of Serde.
|
||||
///
|
||||
/// Serializing a data structure containing `Rc` will serialize a copy of
|
||||
/// the contents of the `Rc` each time the `Rc` is referenced within the
|
||||
/// data structure. Serialization will not attempt to deduplicate these
|
||||
/// repeated data.
|
||||
///
|
||||
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
|
||||
<T: ?Sized> Serialize for Rc<T> where T: Serialize
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
deref_impl!(<T: ?Sized> Serialize for Arc<T> where T: Serialize);
|
||||
deref_impl! {
|
||||
/// This impl requires the [`"rc"`] Cargo feature of Serde.
|
||||
///
|
||||
/// Serializing a data structure containing `Arc` will serialize a copy of
|
||||
/// the contents of the `Arc` each time the `Arc` is referenced within the
|
||||
/// data structure. Serialization will not attempt to deduplicate these
|
||||
/// repeated data.
|
||||
///
|
||||
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
|
||||
<T: ?Sized> Serialize for Arc<T> where T: Serialize
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
deref_impl!(<'a, T: ?Sized> Serialize for Cow<'a, T> where T: Serialize + ToOwned);
|
||||
@@ -351,6 +375,7 @@ deref_impl!(<'a, T: ?Sized> Serialize for Cow<'a, T> where T: Serialize + ToOwne
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[allow(deprecated)]
|
||||
impl<T> Serialize for NonZero<T>
|
||||
where
|
||||
T: Serialize + Zeroable + Clone,
|
||||
@@ -363,6 +388,32 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! nonzero_integers {
|
||||
( $( $T: ident, )+ ) => {
|
||||
$(
|
||||
#[cfg(feature = "unstable")]
|
||||
impl Serialize for $T {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
self.get().serialize(serializer)
|
||||
}
|
||||
}
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
nonzero_integers! {
|
||||
// Not including signed NonZeroI* since they might be removed
|
||||
NonZeroU8,
|
||||
NonZeroU16,
|
||||
NonZeroU32,
|
||||
NonZeroU64,
|
||||
// FIXME: https://github.com/serde-rs/serde/issues/1136 NonZeroU128,
|
||||
NonZeroUsize,
|
||||
}
|
||||
|
||||
impl<T> Serialize for Cell<T>
|
||||
where
|
||||
T: Serialize + Copy,
|
||||
@@ -494,11 +545,9 @@ macro_rules! serialize_display_bounded_length {
|
||||
// write! only provides fmt::Formatter to Display implementations, which
|
||||
// has methods write_str and write_char but no method to write arbitrary
|
||||
// bytes. Therefore `written` must be valid UTF-8.
|
||||
let written_str = unsafe {
|
||||
str::from_utf8_unchecked(written)
|
||||
};
|
||||
let written_str = unsafe { str::from_utf8_unchecked(written) };
|
||||
$serializer.serialize_str(written_str)
|
||||
}}
|
||||
}};
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
|
||||
@@ -93,7 +93,8 @@
|
||||
//! - Path
|
||||
//! - PathBuf
|
||||
//! - Range\<T\>
|
||||
//! - NonZero\<T\> (unstable)
|
||||
//! - NonZero\<T\> (unstable, deprecated)
|
||||
//! - num::NonZero* (unstable)
|
||||
//! - **Net types**:
|
||||
//! - IpAddr
|
||||
//! - Ipv4Addr
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde_derive"
|
||||
version = "1.0.32" # remember to update html_root_url
|
||||
version = "1.0.37" # 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)]"
|
||||
@@ -23,10 +23,10 @@ name = "serde_derive"
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
proc-macro2 = "0.2"
|
||||
quote = "0.4"
|
||||
serde_derive_internals = { version = "=0.20.1", default-features = false, path = "../serde_derive_internals" }
|
||||
syn = { version = "0.12", features = ["visit"] }
|
||||
proc-macro2 = "0.3"
|
||||
quote = "0.5"
|
||||
serde_derive_internals = { version = "=0.23.0", default-features = false, path = "../serde_derive_internals" }
|
||||
syn = { version = "0.13", features = ["visit"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde = { version = "1.0", path = "../serde" }
|
||||
|
||||
@@ -14,7 +14,7 @@ use syn::punctuated::Punctuated;
|
||||
use internals::ast::{Data, Container};
|
||||
use internals::attr;
|
||||
|
||||
use proc_macro2::{Span, Term};
|
||||
use proc_macro2::Span;
|
||||
|
||||
// Remove the default from every type parameter because in the generated impls
|
||||
// they look like associated types: "error: associated type bindings are not
|
||||
@@ -44,15 +44,7 @@ pub fn with_where_predicates(
|
||||
predicates: &[syn::WherePredicate],
|
||||
) -> syn::Generics {
|
||||
let mut generics = generics.clone();
|
||||
if generics.where_clause.is_none() {
|
||||
generics.where_clause = Some(syn::WhereClause {
|
||||
where_token: Default::default(),
|
||||
predicates: Punctuated::new(),
|
||||
});
|
||||
}
|
||||
generics.where_clause
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
generics.make_where_clause()
|
||||
.predicates
|
||||
.extend(predicates.into_iter().cloned());
|
||||
generics
|
||||
@@ -72,15 +64,7 @@ where
|
||||
.flat_map(|predicates| predicates.to_vec());
|
||||
|
||||
let mut generics = generics.clone();
|
||||
if generics.where_clause.is_none() {
|
||||
generics.where_clause = Some(syn::WhereClause {
|
||||
where_token: Default::default(),
|
||||
predicates: Punctuated::new(),
|
||||
});
|
||||
}
|
||||
generics.where_clause
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
generics.make_where_clause()
|
||||
.predicates
|
||||
.extend(predicates);
|
||||
generics
|
||||
@@ -192,6 +176,7 @@ where
|
||||
// the bound e.g. Serialize
|
||||
bounds: vec![
|
||||
syn::TypeParamBound::Trait(syn::TraitBound {
|
||||
paren_token: None,
|
||||
modifier: syn::TraitBoundModifier::None,
|
||||
lifetimes: None,
|
||||
path: bound.clone(),
|
||||
@@ -201,15 +186,7 @@ where
|
||||
});
|
||||
|
||||
let mut generics = generics.clone();
|
||||
if generics.where_clause.is_none() {
|
||||
generics.where_clause = Some(syn::WhereClause {
|
||||
where_token: Default::default(),
|
||||
predicates: Punctuated::new(),
|
||||
});
|
||||
}
|
||||
generics.where_clause
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
generics.make_where_clause()
|
||||
.predicates
|
||||
.extend(new_predicates);
|
||||
generics
|
||||
@@ -221,15 +198,7 @@ pub fn with_self_bound(
|
||||
bound: &syn::Path,
|
||||
) -> syn::Generics {
|
||||
let mut generics = generics.clone();
|
||||
if generics.where_clause.is_none() {
|
||||
generics.where_clause = Some(syn::WhereClause {
|
||||
where_token: Default::default(),
|
||||
predicates: Punctuated::new(),
|
||||
});
|
||||
}
|
||||
generics.where_clause
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
generics.make_where_clause()
|
||||
.predicates
|
||||
.push(syn::WherePredicate::Type(syn::PredicateType {
|
||||
lifetimes: None,
|
||||
@@ -239,6 +208,7 @@ pub fn with_self_bound(
|
||||
// the bound e.g. Default
|
||||
bounds: vec![
|
||||
syn::TypeParamBound::Trait(syn::TraitBound {
|
||||
paren_token: None,
|
||||
modifier: syn::TraitBoundModifier::None,
|
||||
lifetimes: None,
|
||||
path: bound.clone(),
|
||||
@@ -249,7 +219,7 @@ pub fn with_self_bound(
|
||||
}
|
||||
|
||||
pub fn with_lifetime_bound(generics: &syn::Generics, lifetime: &str) -> syn::Generics {
|
||||
let bound = syn::Lifetime::new(Term::intern(lifetime), Span::def_site());
|
||||
let bound = syn::Lifetime::new(lifetime, Span::call_site());
|
||||
let def = syn::LifetimeDef {
|
||||
attrs: Vec::new(),
|
||||
lifetime: bound,
|
||||
|
||||
+315
-58
@@ -10,7 +10,7 @@ use syn::{self, Ident, Index, Member};
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::spanned::Spanned;
|
||||
use quote::{ToTokens, Tokens};
|
||||
use proc_macro2::{Literal, Span, Term};
|
||||
use proc_macro2::{Literal, Span};
|
||||
|
||||
use bound;
|
||||
use fragment::{Expr, Fragment, Match, Stmts};
|
||||
@@ -27,7 +27,7 @@ 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), Span::def_site());
|
||||
let dummy_const = Ident::new(&format!("_IMPL_DESERIALIZE_FOR_{}", ident), Span::call_site());
|
||||
let body = Stmts(deserialize_body(&cont, ¶ms));
|
||||
let delife = params.borrowed.de_lifetime();
|
||||
|
||||
@@ -181,8 +181,8 @@ enum BorrowedLifetimes {
|
||||
impl BorrowedLifetimes {
|
||||
fn de_lifetime(&self) -> syn::Lifetime {
|
||||
match *self {
|
||||
BorrowedLifetimes::Borrowed(_) => syn::Lifetime::new(Term::intern("'de"), Span::def_site()),
|
||||
BorrowedLifetimes::Static => syn::Lifetime::new(Term::intern("'static"), Span::def_site()),
|
||||
BorrowedLifetimes::Borrowed(_) => syn::Lifetime::new("'de", Span::call_site()),
|
||||
BorrowedLifetimes::Static => syn::Lifetime::new("'static", Span::call_site()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,7 +190,7 @@ impl BorrowedLifetimes {
|
||||
match *self {
|
||||
BorrowedLifetimes::Borrowed(ref bounds) => Some(syn::LifetimeDef {
|
||||
attrs: Vec::new(),
|
||||
lifetime: syn::Lifetime::new(Term::intern("'de"), Span::def_site()),
|
||||
lifetime: syn::Lifetime::new("'de", Span::call_site()),
|
||||
colon_token: None,
|
||||
bounds: bounds.iter().cloned().collect(),
|
||||
}),
|
||||
@@ -268,7 +268,11 @@ fn deserialize_in_place_body(cont: &Container, params: &Parameters) -> Option<St
|
||||
|
||||
let code = match cont.data {
|
||||
Data::Struct(Style::Struct, ref fields) => {
|
||||
deserialize_struct_in_place(None, params, fields, &cont.attrs, None)
|
||||
if let Some(code) = deserialize_struct_in_place(None, params, fields, &cont.attrs, None) {
|
||||
code
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Data::Struct(Style::Tuple, ref fields) | Data::Struct(Style::Newtype, ref fields) => {
|
||||
deserialize_tuple_in_place(None, params, fields, &cont.attrs, None)
|
||||
@@ -345,6 +349,8 @@ fn deserialize_tuple(
|
||||
split_with_de_lifetime(params);
|
||||
let delife = params.borrowed.de_lifetime();
|
||||
|
||||
assert!(!cattrs.has_flatten());
|
||||
|
||||
// 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
|
||||
// getters then construct the target type directly.
|
||||
@@ -440,6 +446,8 @@ fn deserialize_tuple_in_place(
|
||||
split_with_de_lifetime(params);
|
||||
let delife = params.borrowed.de_lifetime();
|
||||
|
||||
assert!(!cattrs.has_flatten());
|
||||
|
||||
let is_enum = variant_ident.is_some();
|
||||
let expecting = match variant_ident {
|
||||
Some(variant_ident) => format!("tuple variant {}::{}", params.type_name(), variant_ident),
|
||||
@@ -522,6 +530,8 @@ fn deserialize_seq(
|
||||
) -> Fragment {
|
||||
let vars = (0..fields.len()).map(field_i as fn(_) -> _);
|
||||
|
||||
// XXX: do we need an error for flattening here?
|
||||
|
||||
let deserialized_count = fields
|
||||
.iter()
|
||||
.filter(|field| !field.attrs.skip_deserializing())
|
||||
@@ -539,7 +549,7 @@ fn deserialize_seq(
|
||||
let visit = match field.attrs.deserialize_with() {
|
||||
None => {
|
||||
let field_ty = &field.ty;
|
||||
let span = Span::def_site().located_at(field.original.span());
|
||||
let span = field.original.span();
|
||||
let func = quote_spanned!(span=> _serde::de::SeqAccess::next_element::<#field_ty>);
|
||||
quote!(try!(#func(&mut __seq)))
|
||||
}
|
||||
@@ -613,6 +623,8 @@ fn deserialize_seq_in_place(
|
||||
) -> Fragment {
|
||||
let vars = (0..fields.len()).map(field_i as fn(_) -> _);
|
||||
|
||||
// XXX: do we need an error for flattening here?
|
||||
|
||||
let deserialized_count = fields
|
||||
.iter()
|
||||
.filter(|field| !field.attrs.skip_deserializing())
|
||||
@@ -793,10 +805,13 @@ fn deserialize_struct(
|
||||
|
||||
let visit_seq = Stmts(deserialize_seq(&type_path, params, fields, true, cattrs));
|
||||
|
||||
let (field_visitor, fields_stmt, visit_map) =
|
||||
deserialize_struct_visitor(&type_path, params, fields, cattrs);
|
||||
let (field_visitor, fields_stmt, visit_map) = if cattrs.has_flatten() {
|
||||
deserialize_struct_as_map_visitor(&type_path, params, fields, cattrs)
|
||||
} else {
|
||||
deserialize_struct_as_struct_visitor(&type_path, params, fields, cattrs)
|
||||
};
|
||||
let field_visitor = Stmts(field_visitor);
|
||||
let fields_stmt = Stmts(fields_stmt);
|
||||
let fields_stmt = fields_stmt.map(Stmts);
|
||||
let visit_map = Stmts(visit_map);
|
||||
|
||||
let visitor_expr = quote! {
|
||||
@@ -813,6 +828,10 @@ fn deserialize_struct(
|
||||
quote! {
|
||||
_serde::de::VariantAccess::struct_variant(__variant, FIELDS, #visitor_expr)
|
||||
}
|
||||
} else if cattrs.has_flatten() {
|
||||
quote! {
|
||||
_serde::Deserializer::deserialize_map(__deserializer, #visitor_expr)
|
||||
}
|
||||
} else {
|
||||
let type_name = cattrs.name().deserialize_name();
|
||||
quote! {
|
||||
@@ -827,10 +846,10 @@ fn deserialize_struct(
|
||||
quote!(mut __seq)
|
||||
};
|
||||
|
||||
// untagged struct variants do not get a visit_seq method
|
||||
// untagged struct variants do not get a visit_seq method. The same applies to structs that
|
||||
// only have a map representation.
|
||||
let visit_seq = match *untagged {
|
||||
Untagged::Yes => None,
|
||||
Untagged::No => Some(quote! {
|
||||
Untagged::No if !cattrs.has_flatten() => Some(quote! {
|
||||
#[inline]
|
||||
fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error>
|
||||
where __A: _serde::de::SeqAccess<#delife>
|
||||
@@ -838,6 +857,7 @@ fn deserialize_struct(
|
||||
#visit_seq
|
||||
}
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
quote_block! {
|
||||
@@ -878,9 +898,15 @@ fn deserialize_struct_in_place(
|
||||
fields: &[Field],
|
||||
cattrs: &attr::Container,
|
||||
deserializer: Option<Tokens>,
|
||||
) -> Fragment {
|
||||
) -> Option<Fragment> {
|
||||
let is_enum = variant_ident.is_some();
|
||||
|
||||
// for now we do not support in_place deserialization for structs that
|
||||
// are represented as map.
|
||||
if cattrs.has_flatten() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let this = ¶ms.this;
|
||||
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) =
|
||||
split_with_de_lifetime(params);
|
||||
@@ -893,8 +919,9 @@ fn deserialize_struct_in_place(
|
||||
|
||||
let visit_seq = Stmts(deserialize_seq_in_place(params, fields, cattrs));
|
||||
|
||||
let (field_visitor, fields_stmt, visit_map) =
|
||||
deserialize_struct_in_place_visitor(params, fields, cattrs);
|
||||
let (field_visitor, fields_stmt, visit_map) = deserialize_struct_as_struct_in_place_visitor(
|
||||
params, fields, cattrs);
|
||||
|
||||
let field_visitor = Stmts(field_visitor);
|
||||
let fields_stmt = Stmts(fields_stmt);
|
||||
let visit_map = Stmts(visit_map);
|
||||
@@ -940,7 +967,7 @@ fn deserialize_struct_in_place(
|
||||
let in_place_ty_generics = de_ty_generics.in_place();
|
||||
let place_life = place_lifetime();
|
||||
|
||||
quote_block! {
|
||||
Some(quote_block! {
|
||||
#field_visitor
|
||||
|
||||
struct __Visitor #in_place_impl_generics #where_clause {
|
||||
@@ -968,7 +995,7 @@ fn deserialize_struct_in_place(
|
||||
#fields_stmt
|
||||
|
||||
#dispatch
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn deserialize_enum(
|
||||
@@ -1688,12 +1715,16 @@ fn deserialize_untagged_newtype_variant(
|
||||
fn deserialize_generated_identifier(
|
||||
fields: &[(String, Ident)],
|
||||
cattrs: &attr::Container,
|
||||
is_variant: bool,
|
||||
is_variant: bool
|
||||
) -> Fragment {
|
||||
let this = quote!(__Field);
|
||||
let field_idents: &Vec<_> = &fields.iter().map(|&(_, ref ident)| ident).collect();
|
||||
|
||||
let (ignore_variant, fallthrough) = if is_variant || cattrs.deny_unknown_fields() {
|
||||
let (ignore_variant, fallthrough) = if cattrs.has_flatten() {
|
||||
let ignore_variant = quote!(__other(_serde::private::de::Content<'de>),);
|
||||
let fallthrough = quote!(_serde::export::Ok(__Field::__other(__value)));
|
||||
(Some(ignore_variant), Some(fallthrough))
|
||||
} else if is_variant || cattrs.deny_unknown_fields() {
|
||||
(None, None)
|
||||
} else {
|
||||
let ignore_variant = quote!(__ignore,);
|
||||
@@ -1706,11 +1737,18 @@ fn deserialize_generated_identifier(
|
||||
fields,
|
||||
is_variant,
|
||||
fallthrough,
|
||||
cattrs.has_flatten(),
|
||||
));
|
||||
|
||||
let lifetime = if cattrs.has_flatten() {
|
||||
Some(quote!(<'de>))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
quote_block! {
|
||||
#[allow(non_camel_case_types)]
|
||||
enum __Field {
|
||||
enum __Field #lifetime {
|
||||
#(#field_idents,)*
|
||||
#ignore_variant
|
||||
}
|
||||
@@ -1718,12 +1756,12 @@ fn deserialize_generated_identifier(
|
||||
struct __FieldVisitor;
|
||||
|
||||
impl<'de> _serde::de::Visitor<'de> for __FieldVisitor {
|
||||
type Value = __Field;
|
||||
type Value = __Field #lifetime;
|
||||
|
||||
#visitor_impl
|
||||
}
|
||||
|
||||
impl<'de> _serde::Deserialize<'de> for __Field {
|
||||
impl<'de> _serde::Deserialize<'de> for __Field #lifetime {
|
||||
#[inline]
|
||||
fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error>
|
||||
where __D: _serde::Deserializer<'de>
|
||||
@@ -1804,6 +1842,7 @@ fn deserialize_custom_identifier(
|
||||
&names_idents,
|
||||
is_variant,
|
||||
fallthrough,
|
||||
false,
|
||||
));
|
||||
|
||||
quote_block! {
|
||||
@@ -1833,9 +1872,12 @@ fn deserialize_identifier(
|
||||
fields: &[(String, Ident)],
|
||||
is_variant: bool,
|
||||
fallthrough: Option<Tokens>,
|
||||
collect_other_fields: bool
|
||||
) -> Fragment {
|
||||
let field_strs = fields.iter().map(|&(ref name, _)| name);
|
||||
let field_borrowed_strs = fields.iter().map(|&(ref name, _)| name);
|
||||
let field_bytes = fields.iter().map(|&(ref name, _)| Literal::byte_string(name.as_bytes()));
|
||||
let field_borrowed_bytes = fields.iter().map(|&(ref name, _)| Literal::byte_string(name.as_bytes()));
|
||||
|
||||
let constructors: &Vec<_> = &fields
|
||||
.iter()
|
||||
@@ -1852,28 +1894,129 @@ fn deserialize_identifier(
|
||||
|
||||
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 visit_other = if collect_other_fields {
|
||||
Some(quote! {
|
||||
fn visit_bool<__E>(self, __value: bool) -> Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
Ok(__Field::__other(_serde::private::de::Content::Bool(__value)))
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_i8<__E>(self, __value: i8) -> Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
Ok(__Field::__other(_serde::private::de::Content::I8(__value)))
|
||||
}
|
||||
|
||||
fn visit_i16<__E>(self, __value: i16) -> Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
Ok(__Field::__other(_serde::private::de::Content::I16(__value)))
|
||||
}
|
||||
|
||||
fn visit_i32<__E>(self, __value: i32) -> Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
Ok(__Field::__other(_serde::private::de::Content::I32(__value)))
|
||||
}
|
||||
|
||||
fn visit_i64<__E>(self, __value: i64) -> Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
Ok(__Field::__other(_serde::private::de::Content::I64(__value)))
|
||||
}
|
||||
|
||||
fn visit_u8<__E>(self, __value: u8) -> Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
Ok(__Field::__other(_serde::private::de::Content::U8(__value)))
|
||||
}
|
||||
|
||||
fn visit_u16<__E>(self, __value: u16) -> Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
Ok(__Field::__other(_serde::private::de::Content::U16(__value)))
|
||||
}
|
||||
|
||||
fn visit_u32<__E>(self, __value: u32) -> Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
Ok(__Field::__other(_serde::private::de::Content::U32(__value)))
|
||||
}
|
||||
|
||||
fn visit_u64<__E>(self, __value: u64) -> Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
Ok(__Field::__other(_serde::private::de::Content::U64(__value)))
|
||||
}
|
||||
|
||||
fn visit_f32<__E>(self, __value: f32) -> Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
Ok(__Field::__other(_serde::private::de::Content::F32(__value)))
|
||||
}
|
||||
|
||||
fn visit_f64<__E>(self, __value: f64) -> Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
Ok(__Field::__other(_serde::private::de::Content::F64(__value)))
|
||||
}
|
||||
|
||||
fn visit_char<__E>(self, __value: char) -> Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
Ok(__Field::__other(_serde::private::de::Content::Char(__value)))
|
||||
}
|
||||
|
||||
fn visit_unit<__E>(self) -> Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
Ok(__Field::__other(_serde::private::de::Content::Unit))
|
||||
}
|
||||
})
|
||||
} else {
|
||||
Some(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() {
|
||||
let bytes_to_str = if fallthrough.is_some() || collect_other_fields {
|
||||
None
|
||||
} else {
|
||||
let conversion = quote! {
|
||||
Some(quote! {
|
||||
let __value = &_serde::export::from_utf8_lossy(__value);
|
||||
};
|
||||
Some(conversion)
|
||||
})
|
||||
};
|
||||
|
||||
let (value_as_str_content, value_as_borrowed_str_content,
|
||||
value_as_bytes_content, value_as_borrowed_bytes_content) = if !collect_other_fields {
|
||||
(None, None, None, None)
|
||||
} else {
|
||||
(
|
||||
Some(quote! {
|
||||
let __value = _serde::private::de::Content::String(__value.to_string());
|
||||
}),
|
||||
Some(quote! {
|
||||
let __value = _serde::private::de::Content::Str(__value);
|
||||
}),
|
||||
Some(quote! {
|
||||
let __value = _serde::private::de::Content::ByteBuf(__value.to_vec());
|
||||
}),
|
||||
Some(quote! {
|
||||
let __value = _serde::private::de::Content::Bytes(__value);
|
||||
})
|
||||
)
|
||||
};
|
||||
|
||||
let fallthrough_arm = if let Some(fallthrough) = fallthrough {
|
||||
@@ -1893,7 +2036,7 @@ fn deserialize_identifier(
|
||||
_serde::export::Formatter::write_str(formatter, #expecting)
|
||||
}
|
||||
|
||||
#visit_index
|
||||
#visit_other
|
||||
|
||||
fn visit_str<__E>(self, __value: &str) -> _serde::export::Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
@@ -1902,7 +2045,39 @@ fn deserialize_identifier(
|
||||
#(
|
||||
#field_strs => _serde::export::Ok(#constructors),
|
||||
)*
|
||||
_ => #fallthrough_arm
|
||||
_ => {
|
||||
#value_as_str_content
|
||||
#fallthrough_arm
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_borrowed_str<__E>(self, __value: &'de str) -> _serde::export::Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
match __value {
|
||||
#(
|
||||
#field_borrowed_strs => _serde::export::Ok(#constructors),
|
||||
)*
|
||||
_ => {
|
||||
#value_as_borrowed_str_content
|
||||
#fallthrough_arm
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_borrowed_bytes<__E>(self, __value: &'de [u8]) -> _serde::export::Result<Self::Value, __E>
|
||||
where __E: _serde::de::Error
|
||||
{
|
||||
match __value {
|
||||
#(
|
||||
#field_borrowed_bytes => _serde::export::Ok(#constructors),
|
||||
)*
|
||||
_ => {
|
||||
#bytes_to_str
|
||||
#value_as_borrowed_bytes_content
|
||||
#fallthrough_arm
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1915,6 +2090,7 @@ fn deserialize_identifier(
|
||||
)*
|
||||
_ => {
|
||||
#bytes_to_str
|
||||
#value_as_bytes_content
|
||||
#fallthrough_arm
|
||||
}
|
||||
}
|
||||
@@ -1922,12 +2098,14 @@ fn deserialize_identifier(
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_struct_visitor(
|
||||
fn deserialize_struct_as_struct_visitor(
|
||||
struct_path: &Tokens,
|
||||
params: &Parameters,
|
||||
fields: &[Field],
|
||||
cattrs: &attr::Container,
|
||||
) -> (Fragment, Fragment, Fragment) {
|
||||
) -> (Fragment, Option<Fragment>, Fragment) {
|
||||
assert!(!cattrs.has_flatten());
|
||||
|
||||
let field_names_idents: Vec<_> = fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -1946,7 +2124,27 @@ fn deserialize_struct_visitor(
|
||||
|
||||
let visit_map = deserialize_map(struct_path, params, fields, cattrs);
|
||||
|
||||
(field_visitor, fields_stmt, visit_map)
|
||||
(field_visitor, Some(fields_stmt), visit_map)
|
||||
}
|
||||
|
||||
fn deserialize_struct_as_map_visitor(
|
||||
struct_path: &Tokens,
|
||||
params: &Parameters,
|
||||
fields: &[Field],
|
||||
cattrs: &attr::Container,
|
||||
) -> (Fragment, Option<Fragment>, Fragment) {
|
||||
let field_names_idents: Vec<_> = fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|&(_, field)| !field.attrs.skip_deserializing() && !field.attrs.flatten())
|
||||
.map(|(i, field)| (field.attrs.name().deserialize_name(), field_i(i)))
|
||||
.collect();
|
||||
|
||||
let field_visitor = deserialize_generated_identifier(&field_names_idents, cattrs, false);
|
||||
|
||||
let visit_map = deserialize_map(struct_path, params, fields, cattrs);
|
||||
|
||||
(field_visitor, None, visit_map)
|
||||
}
|
||||
|
||||
fn deserialize_map(
|
||||
@@ -1965,7 +2163,7 @@ fn deserialize_map(
|
||||
// Declare each field that will be deserialized.
|
||||
let let_values = fields_names
|
||||
.iter()
|
||||
.filter(|&&(field, _)| !field.attrs.skip_deserializing())
|
||||
.filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten())
|
||||
.map(|&(field, ref name)| {
|
||||
let field_ty = &field.ty;
|
||||
quote! {
|
||||
@@ -1973,17 +2171,29 @@ fn deserialize_map(
|
||||
}
|
||||
});
|
||||
|
||||
// Collect contents for flatten fields into a buffer
|
||||
let let_collect = if cattrs.has_flatten() {
|
||||
Some(quote! {
|
||||
let mut __collect = Vec::<Option<(
|
||||
_serde::private::de::Content,
|
||||
_serde::private::de::Content
|
||||
)>>::new();
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Match arms to extract a value for a field.
|
||||
let value_arms = fields_names
|
||||
.iter()
|
||||
.filter(|&&(field, _)| !field.attrs.skip_deserializing())
|
||||
.filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten())
|
||||
.map(|&(field, ref name)| {
|
||||
let deser_name = field.attrs.name().deserialize_name();
|
||||
|
||||
let visit = match field.attrs.deserialize_with() {
|
||||
None => {
|
||||
let field_ty = &field.ty;
|
||||
let span = Span::def_site().located_at(field.original.span());
|
||||
let span = field.original.span();
|
||||
let func = quote_spanned!(span=> _serde::de::MapAccess::next_value::<#field_ty>);
|
||||
quote! {
|
||||
try!(#func(&mut __map))
|
||||
@@ -2008,7 +2218,15 @@ fn deserialize_map(
|
||||
});
|
||||
|
||||
// Visit ignored values to consume them
|
||||
let ignored_arm = if cattrs.deny_unknown_fields() {
|
||||
let ignored_arm = if cattrs.has_flatten() {
|
||||
Some(quote! {
|
||||
__Field::__other(__name) => {
|
||||
__collect.push(Some((
|
||||
__name,
|
||||
try!(_serde::de::MapAccess::next_value(&mut __map)))));
|
||||
}
|
||||
})
|
||||
} else if cattrs.deny_unknown_fields() {
|
||||
None
|
||||
} else {
|
||||
Some(quote! {
|
||||
@@ -2038,7 +2256,7 @@ fn deserialize_map(
|
||||
|
||||
let extract_values = fields_names
|
||||
.iter()
|
||||
.filter(|&&(field, _)| !field.attrs.skip_deserializing())
|
||||
.filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten())
|
||||
.map(|&(field, ref name)| {
|
||||
let missing_expr = Match(expr_is_missing(field, cattrs));
|
||||
|
||||
@@ -2050,6 +2268,35 @@ fn deserialize_map(
|
||||
}
|
||||
});
|
||||
|
||||
let extract_collected = fields_names
|
||||
.iter()
|
||||
.filter(|&&(field, _)| field.attrs.flatten())
|
||||
.map(|&(field, ref name)| {
|
||||
let field_ty = field.ty;
|
||||
quote! {
|
||||
let #name: #field_ty = try!(_serde::de::Deserialize::deserialize(
|
||||
_serde::private::de::FlatMapDeserializer(
|
||||
&mut __collect,
|
||||
_serde::export::PhantomData)));
|
||||
}
|
||||
});
|
||||
|
||||
let collected_deny_unknown_fields = if cattrs.has_flatten() && cattrs.deny_unknown_fields() {
|
||||
Some(quote! {
|
||||
if let Some(Some((__key, _))) = __collect.into_iter().filter(|x| x.is_some()).next() {
|
||||
if let Some(__key) = __key.as_str() {
|
||||
return _serde::export::Err(
|
||||
_serde::de::Error::custom(format_args!("unknown field `{}`", &__key)));
|
||||
} else {
|
||||
return _serde::export::Err(
|
||||
_serde::de::Error::custom(format_args!("unexpected map key")));
|
||||
}
|
||||
}
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let result = fields_names.iter().map(|&(field, ref name)| {
|
||||
let ident = field.ident.expect("struct contains unnamed fields");
|
||||
if field.attrs.skip_deserializing() {
|
||||
@@ -2085,22 +2332,30 @@ fn deserialize_map(
|
||||
quote_block! {
|
||||
#(#let_values)*
|
||||
|
||||
#let_collect
|
||||
|
||||
#match_keys
|
||||
|
||||
#let_default
|
||||
|
||||
#(#extract_values)*
|
||||
|
||||
#(#extract_collected)*
|
||||
|
||||
#collected_deny_unknown_fields
|
||||
|
||||
_serde::export::Ok(#result)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "deserialize_in_place")]
|
||||
fn deserialize_struct_in_place_visitor(
|
||||
fn deserialize_struct_as_struct_in_place_visitor(
|
||||
params: &Parameters,
|
||||
fields: &[Field],
|
||||
cattrs: &attr::Container,
|
||||
) -> (Fragment, Fragment, Fragment) {
|
||||
assert!(!cattrs.has_flatten());
|
||||
|
||||
let field_names_idents: Vec<_> = fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -2128,6 +2383,8 @@ fn deserialize_map_in_place(
|
||||
fields: &[Field],
|
||||
cattrs: &attr::Container,
|
||||
) -> Fragment {
|
||||
assert!(!cattrs.has_flatten());
|
||||
|
||||
// Create the field names for the fields.
|
||||
let fields_names: Vec<_> = fields
|
||||
.iter()
|
||||
@@ -2265,7 +2522,7 @@ fn deserialize_map_in_place(
|
||||
}
|
||||
|
||||
fn field_i(i: usize) -> Ident {
|
||||
Ident::new(&format!("__field{}", i), Span::def_site())
|
||||
Ident::new(&format!("__field{}", i), Span::call_site())
|
||||
}
|
||||
|
||||
/// This function wraps the expression in `#[serde(deserialize_with = "...")]`
|
||||
@@ -2273,7 +2530,7 @@ fn field_i(i: usize) -> Ident {
|
||||
fn wrap_deserialize_with(
|
||||
params: &Parameters,
|
||||
value_ty: &Tokens,
|
||||
deserialize_with: &syn::Path,
|
||||
deserialize_with: &syn::ExprPath,
|
||||
) -> (Tokens, Tokens) {
|
||||
let this = ¶ms.this;
|
||||
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) =
|
||||
@@ -2308,7 +2565,7 @@ fn wrap_deserialize_with(
|
||||
fn wrap_deserialize_field_with(
|
||||
params: &Parameters,
|
||||
field_ty: &syn::Type,
|
||||
deserialize_with: &syn::Path,
|
||||
deserialize_with: &syn::ExprPath,
|
||||
) -> (Tokens, Tokens) {
|
||||
wrap_deserialize_with(params, "e!(#field_ty), deserialize_with)
|
||||
}
|
||||
@@ -2316,7 +2573,7 @@ fn wrap_deserialize_field_with(
|
||||
fn wrap_deserialize_variant_with(
|
||||
params: &Parameters,
|
||||
variant: &Variant,
|
||||
deserialize_with: &syn::Path,
|
||||
deserialize_with: &syn::ExprPath,
|
||||
) -> (Tokens, Tokens, Tokens) {
|
||||
let this = ¶ms.this;
|
||||
let variant_ident = &variant.ident;
|
||||
@@ -2381,7 +2638,7 @@ fn expr_is_missing(field: &Field, cattrs: &attr::Container) -> Fragment {
|
||||
let name = field.attrs.name().deserialize_name();
|
||||
match field.attrs.deserialize_with() {
|
||||
None => {
|
||||
let span = Span::def_site().located_at(field.original.span());
|
||||
let span = field.original.span();
|
||||
let func = quote_spanned!(span=> _serde::private::de::missing_field);
|
||||
quote_expr! {
|
||||
try!(#func(#name))
|
||||
@@ -2464,7 +2721,7 @@ impl<'a> ToTokens for DeTypeGenerics<'a> {
|
||||
if self.0.borrowed.de_lifetime_def().is_some() {
|
||||
let def = syn::LifetimeDef {
|
||||
attrs: Vec::new(),
|
||||
lifetime: syn::Lifetime::new(Term::intern("'de"), Span::def_site()),
|
||||
lifetime: syn::Lifetime::new("'de", Span::call_site()),
|
||||
colon_token: None,
|
||||
bounds: Punctuated::new(),
|
||||
};
|
||||
@@ -2490,7 +2747,7 @@ impl<'a> ToTokens for InPlaceTypeGenerics<'a> {
|
||||
if self.0.borrowed.de_lifetime_def().is_some() {
|
||||
let def = syn::LifetimeDef {
|
||||
attrs: Vec::new(),
|
||||
lifetime: syn::Lifetime::new(Term::intern("'de"), Span::def_site()),
|
||||
lifetime: syn::Lifetime::new("'de", Span::call_site()),
|
||||
colon_token: None,
|
||||
bounds: Punctuated::new(),
|
||||
};
|
||||
@@ -2515,7 +2772,7 @@ impl<'a> DeTypeGenerics<'a> {
|
||||
fn place_lifetime() -> syn::LifetimeDef {
|
||||
syn::LifetimeDef {
|
||||
attrs: Vec::new(),
|
||||
lifetime: syn::Lifetime::new(Term::intern("'place"), Span::def_site()),
|
||||
lifetime: syn::Lifetime::new("'place", Span::call_site()),
|
||||
colon_token: None,
|
||||
bounds: Punctuated::new(),
|
||||
}
|
||||
|
||||
+10
-2
@@ -22,11 +22,11 @@
|
||||
//!
|
||||
//! [https://serde.rs/derive.html]: https://serde.rs/derive.html
|
||||
|
||||
#![doc(html_root_url = "https://docs.rs/serde_derive/1.0.32")]
|
||||
#![doc(html_root_url = "https://docs.rs/serde_derive/1.0.37")]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(enum_variant_names, redundant_field_names,
|
||||
too_many_arguments, used_underscore_binding))]
|
||||
// The `quote!` macro requires deep recursion.
|
||||
#![recursion_limit = "256"]
|
||||
#![recursion_limit = "512"]
|
||||
|
||||
#[macro_use]
|
||||
extern crate quote;
|
||||
@@ -41,6 +41,14 @@ extern crate proc_macro2;
|
||||
use proc_macro::TokenStream;
|
||||
use syn::DeriveInput;
|
||||
|
||||
// Quote's default is def_site but it appears call_site is likely to stabilize
|
||||
// before def_site. Thus we try to use only call_site.
|
||||
macro_rules! quote {
|
||||
($($tt:tt)*) => {
|
||||
quote_spanned!($crate::proc_macro2::Span::call_site()=> $($tt)*)
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_use]
|
||||
mod bound;
|
||||
#[macro_use]
|
||||
|
||||
+93
-28
@@ -27,7 +27,7 @@ pub fn expand_derive_serialize(input: &syn::DeriveInput) -> Result<Tokens, Strin
|
||||
let ident = &cont.ident;
|
||||
let params = Parameters::new(&cont);
|
||||
let (impl_generics, ty_generics, where_clause) = params.generics.split_for_impl();
|
||||
let dummy_const = Ident::new(&format!("_IMPL_SERIALIZE_FOR_{}", ident), Span::def_site());
|
||||
let dummy_const = Ident::new(&format!("_IMPL_SERIALIZE_FOR_{}", ident), Span::call_site());
|
||||
let body = Stmts(serialize_body(&cont, ¶ms));
|
||||
|
||||
let impl_block = if let Some(remote) = cont.attrs.remote() {
|
||||
@@ -98,9 +98,9 @@ impl Parameters {
|
||||
fn new(cont: &Container) -> Self {
|
||||
let is_remote = cont.attrs.remote().is_some();
|
||||
let self_var = if is_remote {
|
||||
Ident::new("__self", Span::def_site())
|
||||
Ident::new("__self", Span::call_site())
|
||||
} else {
|
||||
Ident::new("self", Span::def_site())
|
||||
Ident::new("self", Span::call_site())
|
||||
};
|
||||
|
||||
let this = match cont.attrs.remote() {
|
||||
@@ -212,7 +212,7 @@ fn serialize_newtype_struct(
|
||||
field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr);
|
||||
}
|
||||
|
||||
let span = Span::def_site().located_at(field.original.span());
|
||||
let span = field.original.span();
|
||||
let func = quote_spanned!(span=> _serde::Serializer::serialize_newtype_struct);
|
||||
quote_expr! {
|
||||
#func(__serializer, #type_name, #field_expr)
|
||||
@@ -245,6 +245,14 @@ fn serialize_tuple_struct(
|
||||
fn serialize_struct(params: &Parameters, fields: &[Field], cattrs: &attr::Container) -> Fragment {
|
||||
assert!(fields.len() as u64 <= u64::from(u32::MAX));
|
||||
|
||||
if cattrs.has_flatten() {
|
||||
serialize_struct_as_map(params, fields, cattrs)
|
||||
} else {
|
||||
serialize_struct_as_struct(params, fields, cattrs)
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_struct_as_struct(params: &Parameters, fields: &[Field], cattrs: &attr::Container) -> Fragment {
|
||||
let serialize_fields = serialize_struct_visitor(
|
||||
fields,
|
||||
params,
|
||||
@@ -279,6 +287,44 @@ fn serialize_struct(params: &Parameters, fields: &[Field], cattrs: &attr::Contai
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_struct_as_map(params: &Parameters, fields: &[Field], cattrs: &attr::Container) -> Fragment {
|
||||
let serialize_fields = serialize_struct_visitor(
|
||||
fields,
|
||||
params,
|
||||
false,
|
||||
&StructTrait::SerializeMap,
|
||||
);
|
||||
|
||||
let mut serialized_fields = fields
|
||||
.iter()
|
||||
.filter(|&field| !field.attrs.skip_serializing())
|
||||
.peekable();
|
||||
|
||||
let let_mut = mut_if(serialized_fields.peek().is_some());
|
||||
|
||||
let len = if cattrs.has_flatten() {
|
||||
quote!(_serde::export::None)
|
||||
} else {
|
||||
let len = serialized_fields
|
||||
.map(|field| match field.attrs.skip_serializing_if() {
|
||||
None => quote!(1),
|
||||
Some(path) => {
|
||||
let ident = field.ident.expect("struct has unnamed fields");
|
||||
let field_expr = get_member(params, field, &Member::Named(ident));
|
||||
quote!(if #path(#field_expr) { 0 } else { 1 })
|
||||
}
|
||||
})
|
||||
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
|
||||
quote!(_serde::export::Some(#len))
|
||||
};
|
||||
|
||||
quote_block! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_map(__serializer, #len));
|
||||
#(#serialize_fields)*
|
||||
_serde::ser::SerializeMap::end(__serde_state)
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_enum(params: &Parameters, variants: &[Variant], cattrs: &attr::Container) -> Fragment {
|
||||
assert!(variants.len() as u64 <= u64::from(u32::MAX));
|
||||
|
||||
@@ -340,7 +386,7 @@ fn serialize_variant(
|
||||
}
|
||||
Style::Tuple => {
|
||||
let field_names =
|
||||
(0..variant.fields.len()).map(|i| Ident::new(&format!("__field{}", i), Span::def_site()));
|
||||
(0..variant.fields.len()).map(|i| Ident::new(&format!("__field{}", i), Span::call_site()));
|
||||
quote! {
|
||||
#this::#variant_ident(#(ref #field_names),*)
|
||||
}
|
||||
@@ -573,9 +619,9 @@ fn serialize_adjacently_tagged_variant(
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
Style::Newtype => vec![Ident::new("__field0", Span::def_site())],
|
||||
Style::Newtype => vec![Ident::new("__field0", Span::call_site())],
|
||||
Style::Tuple => (0..variant.fields.len())
|
||||
.map(|i| Ident::new(&format!("__field{}", i), Span::def_site()))
|
||||
.map(|i| Ident::new(&format!("__field{}", i), Span::call_site()))
|
||||
.collect(),
|
||||
Style::Struct => variant
|
||||
.fields
|
||||
@@ -816,7 +862,7 @@ fn serialize_tuple_struct_visitor(
|
||||
.enumerate()
|
||||
.map(|(i, field)| {
|
||||
let mut field_expr = if is_enum {
|
||||
let id = Ident::new(&format!("__field{}", i), Span::def_site());
|
||||
let id = Ident::new(&format!("__field{}", i), Span::call_site());
|
||||
quote!(#id)
|
||||
} else {
|
||||
get_member(params, field, &Member::Unnamed(Index {
|
||||
@@ -834,7 +880,7 @@ fn serialize_tuple_struct_visitor(
|
||||
field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr);
|
||||
}
|
||||
|
||||
let span = Span::def_site().located_at(field.original.span());
|
||||
let span = field.original.span();
|
||||
let func = tuple_trait.serialize_element(span);
|
||||
let ser = quote! {
|
||||
try!(#func(&mut __serde_state, #field_expr));
|
||||
@@ -859,6 +905,7 @@ fn serialize_struct_visitor(
|
||||
.filter(|&field| !field.attrs.skip_serializing())
|
||||
.map(|field| {
|
||||
let field_ident = field.ident.expect("struct has unnamed field");
|
||||
|
||||
let mut field_expr = if is_enum {
|
||||
quote!(#field_ident)
|
||||
} else {
|
||||
@@ -876,21 +923,34 @@ fn serialize_struct_visitor(
|
||||
field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr);
|
||||
}
|
||||
|
||||
let span = Span::def_site().located_at(field.original.span());
|
||||
let func = struct_trait.serialize_field(span);
|
||||
let ser = quote! {
|
||||
try!(#func(&mut __serde_state, #key_expr, #field_expr));
|
||||
let span = field.original.span();
|
||||
let ser = if field.attrs.flatten() {
|
||||
quote! {
|
||||
try!(_serde::Serialize::serialize(&#field_expr, _serde::private::ser::FlatMapSerializer(&mut __serde_state)));
|
||||
}
|
||||
} else {
|
||||
let func = struct_trait.serialize_field(span);
|
||||
quote! {
|
||||
try!(#func(&mut __serde_state, #key_expr, #field_expr));
|
||||
}
|
||||
};
|
||||
|
||||
match skip {
|
||||
None => ser,
|
||||
Some(skip) => {
|
||||
let skip_func = struct_trait.skip_field(span);
|
||||
quote! {
|
||||
if !#skip {
|
||||
#ser
|
||||
} else {
|
||||
try!(#skip_func(&mut __serde_state, #key_expr));
|
||||
if let Some(skip_func) = struct_trait.skip_field(span) {
|
||||
quote! {
|
||||
if !#skip {
|
||||
#ser
|
||||
} else {
|
||||
try!(#skip_func(&mut __serde_state, #key_expr));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
if !#skip {
|
||||
#ser
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -902,7 +962,7 @@ fn serialize_struct_visitor(
|
||||
fn wrap_serialize_field_with(
|
||||
params: &Parameters,
|
||||
field_ty: &syn::Type,
|
||||
serialize_with: &syn::Path,
|
||||
serialize_with: &syn::ExprPath,
|
||||
field_expr: &Tokens,
|
||||
) -> Tokens {
|
||||
wrap_serialize_with(params, serialize_with, &[field_ty], &[quote!(#field_expr)])
|
||||
@@ -910,7 +970,7 @@ fn wrap_serialize_field_with(
|
||||
|
||||
fn wrap_serialize_variant_with(
|
||||
params: &Parameters,
|
||||
serialize_with: &syn::Path,
|
||||
serialize_with: &syn::ExprPath,
|
||||
variant: &Variant,
|
||||
) -> Tokens {
|
||||
let field_tys: Vec<_> = variant.fields.iter().map(|field| field.ty).collect();
|
||||
@@ -921,7 +981,7 @@ fn wrap_serialize_variant_with(
|
||||
.map(|(i, field)| {
|
||||
let id = field
|
||||
.ident
|
||||
.unwrap_or_else(|| Ident::new(&format!("__field{}", i), Span::def_site()));
|
||||
.unwrap_or_else(|| Ident::new(&format!("__field{}", i), Span::call_site()));
|
||||
quote!(#id)
|
||||
})
|
||||
.collect();
|
||||
@@ -935,7 +995,7 @@ fn wrap_serialize_variant_with(
|
||||
|
||||
fn wrap_serialize_with(
|
||||
params: &Parameters,
|
||||
serialize_with: &syn::Path,
|
||||
serialize_with: &syn::ExprPath,
|
||||
field_tys: &[&syn::Type],
|
||||
field_exprs: &[Tokens],
|
||||
) -> Tokens {
|
||||
@@ -1011,6 +1071,7 @@ fn get_member(params: &Parameters, field: &Field, member: &Member) -> Tokens {
|
||||
}
|
||||
|
||||
enum StructTrait {
|
||||
SerializeMap,
|
||||
SerializeStruct,
|
||||
SerializeStructVariant,
|
||||
}
|
||||
@@ -1018,6 +1079,9 @@ enum StructTrait {
|
||||
impl StructTrait {
|
||||
fn serialize_field(&self, span: Span) -> Tokens {
|
||||
match *self {
|
||||
StructTrait::SerializeMap => {
|
||||
quote_spanned!(span=> _serde::ser::SerializeMap::serialize_entry)
|
||||
}
|
||||
StructTrait::SerializeStruct => {
|
||||
quote_spanned!(span=> _serde::ser::SerializeStruct::serialize_field)
|
||||
}
|
||||
@@ -1027,14 +1091,15 @@ impl StructTrait {
|
||||
}
|
||||
}
|
||||
|
||||
fn skip_field(&self, span: Span) -> Tokens {
|
||||
fn skip_field(&self, span: Span) -> Option<Tokens> {
|
||||
match *self {
|
||||
StructTrait::SerializeStruct => {
|
||||
StructTrait::SerializeMap => None,
|
||||
StructTrait::SerializeStruct => Some({
|
||||
quote_spanned!(span=> _serde::ser::SerializeStruct::skip_field)
|
||||
}
|
||||
StructTrait::SerializeStructVariant => {
|
||||
}),
|
||||
StructTrait::SerializeStructVariant => Some({
|
||||
quote_spanned!(span=> _serde::ser::SerializeStructVariant::skip_field)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde_derive_internals"
|
||||
version = "0.20.1" # remember to update html_root_url
|
||||
version = "0.23.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."
|
||||
@@ -12,8 +12,8 @@ readme = "README.md"
|
||||
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
|
||||
[dependencies]
|
||||
proc-macro2 = "0.2"
|
||||
syn = { version = "0.12", default-features = false, features = ["derive", "parsing", "clone-impls"] }
|
||||
proc-macro2 = "0.3"
|
||||
syn = { version = "0.13", default-features = false, features = ["derive", "parsing", "clone-impls"] }
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "serde-rs/serde" }
|
||||
|
||||
@@ -48,7 +48,7 @@ pub enum Style {
|
||||
|
||||
impl<'a> Container<'a> {
|
||||
pub fn from_ast(cx: &Ctxt, item: &'a syn::DeriveInput) -> Container<'a> {
|
||||
let attrs = attr::Container::from_ast(cx, item);
|
||||
let mut attrs = attr::Container::from_ast(cx, item);
|
||||
|
||||
let mut data = match item.data {
|
||||
syn::Data::Enum(ref data) => {
|
||||
@@ -63,18 +63,29 @@ impl<'a> Container<'a> {
|
||||
}
|
||||
};
|
||||
|
||||
let mut has_flatten = false;
|
||||
match data {
|
||||
Data::Enum(ref mut variants) => for variant in variants {
|
||||
variant.attrs.rename_by_rule(attrs.rename_all());
|
||||
for field in &mut variant.fields {
|
||||
if field.attrs.flatten() {
|
||||
has_flatten = true;
|
||||
}
|
||||
field.attrs.rename_by_rule(variant.attrs.rename_all());
|
||||
}
|
||||
},
|
||||
Data::Struct(_, ref mut fields) => for field in fields {
|
||||
if field.attrs.flatten() {
|
||||
has_flatten = true;
|
||||
}
|
||||
field.attrs.rename_by_rule(attrs.rename_all());
|
||||
},
|
||||
}
|
||||
|
||||
if has_flatten {
|
||||
attrs.mark_has_flatten();
|
||||
}
|
||||
|
||||
let item = Container {
|
||||
ident: item.ident,
|
||||
attrs: attrs,
|
||||
|
||||
@@ -15,7 +15,7 @@ use syn::punctuated::Punctuated;
|
||||
use syn::synom::{Synom, ParseError};
|
||||
use std::collections::BTreeSet;
|
||||
use std::str::FromStr;
|
||||
use proc_macro2::{Span, TokenStream, TokenNode, TokenTree};
|
||||
use proc_macro2::{Span, TokenStream, TokenTree, Group};
|
||||
|
||||
// This module handles parsing of `#[serde(...)]` attributes. The entrypoints
|
||||
// are `attr::Container::from_ast`, `attr::Variant::from_ast`, and
|
||||
@@ -27,6 +27,7 @@ use proc_macro2::{Span, TokenStream, TokenNode, TokenTree};
|
||||
|
||||
pub use case::RenameRule;
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
struct Attr<'c, T> {
|
||||
cx: &'c Ctxt,
|
||||
name: &'static str,
|
||||
@@ -114,6 +115,7 @@ pub struct Container {
|
||||
type_into: Option<syn::Type>,
|
||||
remote: Option<syn::Path>,
|
||||
identifier: Identifier,
|
||||
has_flatten: bool,
|
||||
}
|
||||
|
||||
/// Styles of representing an enum.
|
||||
@@ -243,7 +245,7 @@ impl Container {
|
||||
|
||||
// Parse `#[serde(default = "...")]`
|
||||
Meta(NameValue(ref m)) if m.ident == "default" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
match item.data {
|
||||
syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(_), .. }) => {
|
||||
default.set(Default::Path(path));
|
||||
@@ -330,7 +332,11 @@ impl Container {
|
||||
// Parse `#[serde(remote = "...")]`
|
||||
Meta(NameValue(ref m)) if m.ident == "remote" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
remote.set(path);
|
||||
if is_primitive_path(&path, "Self") {
|
||||
remote.set(item.ident.into());
|
||||
} else {
|
||||
remote.set(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -373,6 +379,7 @@ impl Container {
|
||||
type_into: type_into.get(),
|
||||
remote: remote.get(),
|
||||
identifier: decide_identifier(cx, item, &field_identifier, &variant_identifier),
|
||||
has_flatten: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -419,6 +426,14 @@ impl Container {
|
||||
pub fn identifier(&self) -> Identifier {
|
||||
self.identifier
|
||||
}
|
||||
|
||||
pub fn has_flatten(&self) -> bool {
|
||||
self.has_flatten
|
||||
}
|
||||
|
||||
pub fn mark_has_flatten(&mut self) {
|
||||
self.has_flatten = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn decide_tag(
|
||||
@@ -510,8 +525,8 @@ pub struct Variant {
|
||||
skip_deserializing: bool,
|
||||
skip_serializing: bool,
|
||||
other: bool,
|
||||
serialize_with: Option<syn::Path>,
|
||||
deserialize_with: Option<syn::Path>,
|
||||
serialize_with: Option<syn::ExprPath>,
|
||||
deserialize_with: Option<syn::ExprPath>,
|
||||
borrow: Option<syn::Meta>,
|
||||
}
|
||||
|
||||
@@ -577,26 +592,26 @@ impl Variant {
|
||||
|
||||
// Parse `#[serde(with = "...")]`
|
||||
Meta(NameValue(ref m)) if m.ident == "with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
let mut ser_path = path.clone();
|
||||
ser_path.segments.push(Ident::new("serialize", Span::call_site()).into());
|
||||
ser_path.path.segments.push(Ident::new("serialize", Span::call_site()).into());
|
||||
serialize_with.set(ser_path);
|
||||
let mut de_path = path;
|
||||
de_path.segments.push(Ident::new("deserialize", Span::call_site()).into());
|
||||
de_path.path.segments.push(Ident::new("deserialize", Span::call_site()).into());
|
||||
deserialize_with.set(de_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(serialize_with = "...")]`
|
||||
Meta(NameValue(ref m)) if m.ident == "serialize_with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
serialize_with.set(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(deserialize_with = "...")]`
|
||||
Meta(NameValue(ref m)) if m.ident == "deserialize_with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
deserialize_with.set(path);
|
||||
}
|
||||
}
|
||||
@@ -675,11 +690,11 @@ impl Variant {
|
||||
self.other
|
||||
}
|
||||
|
||||
pub fn serialize_with(&self) -> Option<&syn::Path> {
|
||||
pub fn serialize_with(&self) -> Option<&syn::ExprPath> {
|
||||
self.serialize_with.as_ref()
|
||||
}
|
||||
|
||||
pub fn deserialize_with(&self) -> Option<&syn::Path> {
|
||||
pub fn deserialize_with(&self) -> Option<&syn::ExprPath> {
|
||||
self.deserialize_with.as_ref()
|
||||
}
|
||||
}
|
||||
@@ -691,14 +706,15 @@ pub struct Field {
|
||||
de_renamed: bool,
|
||||
skip_serializing: bool,
|
||||
skip_deserializing: bool,
|
||||
skip_serializing_if: Option<syn::Path>,
|
||||
skip_serializing_if: Option<syn::ExprPath>,
|
||||
default: Default,
|
||||
serialize_with: Option<syn::Path>,
|
||||
deserialize_with: Option<syn::Path>,
|
||||
serialize_with: Option<syn::ExprPath>,
|
||||
deserialize_with: Option<syn::ExprPath>,
|
||||
ser_bound: Option<Vec<syn::WherePredicate>>,
|
||||
de_bound: Option<Vec<syn::WherePredicate>>,
|
||||
borrowed_lifetimes: BTreeSet<syn::Lifetime>,
|
||||
getter: Option<syn::Path>,
|
||||
getter: Option<syn::ExprPath>,
|
||||
flatten: bool,
|
||||
}
|
||||
|
||||
/// Represents the default to use for a field when deserializing.
|
||||
@@ -708,7 +724,7 @@ pub enum Default {
|
||||
/// The default is given by `std::default::Default::default()`.
|
||||
Default,
|
||||
/// The default is given by this function.
|
||||
Path(syn::Path),
|
||||
Path(syn::ExprPath),
|
||||
}
|
||||
|
||||
impl Field {
|
||||
@@ -732,6 +748,7 @@ impl Field {
|
||||
let mut de_bound = Attr::none(cx, "bound");
|
||||
let mut borrowed_lifetimes = Attr::none(cx, "borrow");
|
||||
let mut getter = Attr::none(cx, "getter");
|
||||
let mut flatten = BoolAttr::none(cx, "flatten");
|
||||
|
||||
let ident = match field.ident {
|
||||
Some(ref ident) => ident.to_string(),
|
||||
@@ -775,7 +792,7 @@ impl Field {
|
||||
|
||||
// Parse `#[serde(default = "...")]`
|
||||
Meta(NameValue(ref m)) if m.ident == "default" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
default.set(Default::Path(path));
|
||||
}
|
||||
}
|
||||
@@ -798,33 +815,33 @@ impl Field {
|
||||
|
||||
// Parse `#[serde(skip_serializing_if = "...")]`
|
||||
Meta(NameValue(ref m)) if m.ident == "skip_serializing_if" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
skip_serializing_if.set(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(serialize_with = "...")]`
|
||||
Meta(NameValue(ref m)) if m.ident == "serialize_with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
serialize_with.set(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(deserialize_with = "...")]`
|
||||
Meta(NameValue(ref m)) if m.ident == "deserialize_with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
deserialize_with.set(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(with = "...")]`
|
||||
Meta(NameValue(ref m)) if m.ident == "with" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
let mut ser_path = path.clone();
|
||||
ser_path.segments.push(Ident::new("serialize", Span::call_site()).into());
|
||||
ser_path.path.segments.push(Ident::new("serialize", Span::call_site()).into());
|
||||
serialize_with.set(ser_path);
|
||||
let mut de_path = path;
|
||||
de_path.segments.push(Ident::new("deserialize", Span::call_site()).into());
|
||||
de_path.path.segments.push(Ident::new("deserialize", Span::call_site()).into());
|
||||
deserialize_with.set(de_path);
|
||||
}
|
||||
}
|
||||
@@ -873,11 +890,16 @@ impl Field {
|
||||
|
||||
// Parse `#[serde(getter = "...")]`
|
||||
Meta(NameValue(ref m)) if m.ident == "getter" => {
|
||||
if let Ok(path) = parse_lit_into_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) {
|
||||
getter.set(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `#[serde(flatten)]`
|
||||
Meta(Word(word)) if word == "flatten" => {
|
||||
flatten.set_true();
|
||||
}
|
||||
|
||||
Meta(ref meta_item) => {
|
||||
cx.error(format!(
|
||||
"unknown serde field attribute `{}`",
|
||||
@@ -917,21 +939,31 @@ impl Field {
|
||||
leading_colon: None,
|
||||
segments: Punctuated::new(),
|
||||
};
|
||||
path.segments.push(Ident::new("_serde", Span::def_site()).into());
|
||||
path.segments.push(Ident::new("private", Span::def_site()).into());
|
||||
path.segments.push(Ident::new("de", Span::def_site()).into());
|
||||
path.segments.push(Ident::new("borrow_cow_str", Span::def_site()).into());
|
||||
deserialize_with.set_if_none(path);
|
||||
path.segments.push(Ident::new("_serde", Span::call_site()).into());
|
||||
path.segments.push(Ident::new("private", Span::call_site()).into());
|
||||
path.segments.push(Ident::new("de", Span::call_site()).into());
|
||||
path.segments.push(Ident::new("borrow_cow_str", Span::call_site()).into());
|
||||
let expr = syn::ExprPath {
|
||||
attrs: Vec::new(),
|
||||
qself: None,
|
||||
path: path,
|
||||
};
|
||||
deserialize_with.set_if_none(expr);
|
||||
} else if is_cow(&field.ty, is_slice_u8) {
|
||||
let mut path = syn::Path {
|
||||
leading_colon: None,
|
||||
segments: Punctuated::new(),
|
||||
};
|
||||
path.segments.push(Ident::new("_serde", Span::def_site()).into());
|
||||
path.segments.push(Ident::new("private", Span::def_site()).into());
|
||||
path.segments.push(Ident::new("de", Span::def_site()).into());
|
||||
path.segments.push(Ident::new("borrow_cow_bytes", Span::def_site()).into());
|
||||
deserialize_with.set_if_none(path);
|
||||
path.segments.push(Ident::new("_serde", Span::call_site()).into());
|
||||
path.segments.push(Ident::new("private", Span::call_site()).into());
|
||||
path.segments.push(Ident::new("de", Span::call_site()).into());
|
||||
path.segments.push(Ident::new("borrow_cow_bytes", Span::call_site()).into());
|
||||
let expr = syn::ExprPath {
|
||||
attrs: Vec::new(),
|
||||
qself: None,
|
||||
path: path,
|
||||
};
|
||||
deserialize_with.set_if_none(expr);
|
||||
}
|
||||
} else if is_rptr(&field.ty, is_str) || is_rptr(&field.ty, is_slice_u8) {
|
||||
// Types &str and &[u8] are always implicitly borrowed. No need for
|
||||
@@ -960,6 +992,7 @@ impl Field {
|
||||
de_bound: de_bound.get(),
|
||||
borrowed_lifetimes: borrowed_lifetimes,
|
||||
getter: getter.get(),
|
||||
flatten: flatten.get(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -984,7 +1017,7 @@ impl Field {
|
||||
self.skip_deserializing
|
||||
}
|
||||
|
||||
pub fn skip_serializing_if(&self) -> Option<&syn::Path> {
|
||||
pub fn skip_serializing_if(&self) -> Option<&syn::ExprPath> {
|
||||
self.skip_serializing_if.as_ref()
|
||||
}
|
||||
|
||||
@@ -992,11 +1025,11 @@ impl Field {
|
||||
&self.default
|
||||
}
|
||||
|
||||
pub fn serialize_with(&self) -> Option<&syn::Path> {
|
||||
pub fn serialize_with(&self) -> Option<&syn::ExprPath> {
|
||||
self.serialize_with.as_ref()
|
||||
}
|
||||
|
||||
pub fn deserialize_with(&self) -> Option<&syn::Path> {
|
||||
pub fn deserialize_with(&self) -> Option<&syn::ExprPath> {
|
||||
self.deserialize_with.as_ref()
|
||||
}
|
||||
|
||||
@@ -1012,9 +1045,13 @@ impl Field {
|
||||
&self.borrowed_lifetimes
|
||||
}
|
||||
|
||||
pub fn getter(&self) -> Option<&syn::Path> {
|
||||
pub fn getter(&self) -> Option<&syn::ExprPath> {
|
||||
self.getter.as_ref()
|
||||
}
|
||||
|
||||
pub fn flatten(&self) -> bool {
|
||||
self.flatten
|
||||
}
|
||||
}
|
||||
|
||||
type SerAndDe<T> = (Option<T>, Option<T>);
|
||||
@@ -1107,6 +1144,11 @@ fn parse_lit_into_path(cx: &Ctxt, attr_name: &str, lit: &syn::Lit) -> Result<syn
|
||||
parse_lit_str(string).map_err(|_| cx.error(format!("failed to parse path: {:?}", string.value())))
|
||||
}
|
||||
|
||||
fn parse_lit_into_expr_path(cx: &Ctxt, attr_name: &str, lit: &syn::Lit) -> Result<syn::ExprPath, ()> {
|
||||
let string = try!(get_lit_str(cx, attr_name, attr_name, lit));
|
||||
parse_lit_str(string).map_err(|_| cx.error(format!("failed to parse path: {:?}", string.value())))
|
||||
}
|
||||
|
||||
fn parse_lit_into_where(
|
||||
cx: &Ctxt,
|
||||
attr_name: &str,
|
||||
@@ -1118,7 +1160,7 @@ fn parse_lit_into_where(
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let where_string = syn::LitStr::new(&format!("where {}", string.value()), string.span);
|
||||
let where_string = syn::LitStr::new(&format!("where {}", string.value()), string.span());
|
||||
|
||||
parse_lit_str::<syn::WhereClause>(&where_string)
|
||||
.map(|wh| wh.predicates.into_iter().collect())
|
||||
@@ -1253,29 +1295,32 @@ fn is_rptr(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool {
|
||||
}
|
||||
|
||||
fn is_str(ty: &syn::Type) -> bool {
|
||||
is_primitive_path(ty, "str")
|
||||
is_primitive_type(ty, "str")
|
||||
}
|
||||
|
||||
fn is_slice_u8(ty: &syn::Type) -> bool {
|
||||
match *ty {
|
||||
syn::Type::Slice(ref ty) => is_primitive_path(&ty.elem, "u8"),
|
||||
syn::Type::Slice(ref ty) => is_primitive_type(&ty.elem, "u8"),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_primitive_path(ty: &syn::Type, primitive: &str) -> bool {
|
||||
fn is_primitive_type(ty: &syn::Type, primitive: &str) -> bool {
|
||||
match *ty {
|
||||
syn::Type::Path(ref ty) => {
|
||||
ty.qself.is_none()
|
||||
&& ty.path.leading_colon.is_none()
|
||||
&& ty.path.segments.len() == 1
|
||||
&& ty.path.segments[0].ident == primitive
|
||||
&& ty.path.segments[0].arguments.is_empty()
|
||||
ty.qself.is_none() && is_primitive_path(&ty.path, primitive)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_primitive_path(path: &syn::Path, primitive: &str) -> bool {
|
||||
path.leading_colon.is_none()
|
||||
&& path.segments.len() == 1
|
||||
&& path.segments[0].ident == primitive
|
||||
&& path.segments[0].arguments.is_empty()
|
||||
}
|
||||
|
||||
// All lifetimes that this type could borrow from a Deserializer.
|
||||
//
|
||||
// For example a type `S<'a, 'b>` could borrow `'a` and `'b`. On the other hand
|
||||
@@ -1365,21 +1410,17 @@ where
|
||||
|
||||
fn spanned_tokens(s: &syn::LitStr) -> Result<TokenStream, ParseError> {
|
||||
let stream = try!(syn::parse_str(&s.value()));
|
||||
Ok(respan_token_stream(stream, s.span))
|
||||
Ok(respan_token_stream(stream, s.span()))
|
||||
}
|
||||
|
||||
fn respan_token_stream(stream: TokenStream, span: Span) -> TokenStream {
|
||||
stream.into_iter().map(|token| respan_token_tree(token, span)).collect()
|
||||
}
|
||||
|
||||
fn respan_token_tree(token: TokenTree, span: Span) -> TokenTree {
|
||||
TokenTree {
|
||||
span: span,
|
||||
kind: match token.kind {
|
||||
TokenNode::Group(delimiter, nested) => {
|
||||
TokenNode::Group(delimiter, respan_token_stream(nested, span))
|
||||
}
|
||||
other => other,
|
||||
},
|
||||
fn respan_token_tree(mut token: TokenTree, span: Span) -> TokenTree {
|
||||
if let TokenTree::Group(ref mut g) = token {
|
||||
*g = Group::new(g.delimiter(), respan_token_stream(g.stream().clone(), span));
|
||||
}
|
||||
token.set_span(span);
|
||||
token
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
// 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)]
|
||||
#[allow(deprecated, unused_imports)]
|
||||
use std::ascii::AsciiExt;
|
||||
|
||||
use std::str::FromStr;
|
||||
|
||||
@@ -14,6 +14,7 @@ use Ctxt;
|
||||
/// object. Simpler checks should happen when parsing and building the attrs.
|
||||
pub fn check(cx: &Ctxt, cont: &Container) {
|
||||
check_getter(cx, cont);
|
||||
check_flatten(cx, cont);
|
||||
check_identifier(cx, cont);
|
||||
check_variant_skip_attrs(cx, cont);
|
||||
check_internal_tag_field_name_conflict(cx, cont);
|
||||
@@ -40,6 +41,49 @@ fn check_getter(cx: &Ctxt, cont: &Container) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Flattening has some restrictions we can test.
|
||||
fn check_flatten(cx: &Ctxt, cont: &Container) {
|
||||
match cont.data {
|
||||
Data::Enum(_) => {
|
||||
if cont.attrs.has_flatten() {
|
||||
cx.error("#[serde(flatten)] cannot be used within enums");
|
||||
}
|
||||
}
|
||||
Data::Struct(style, _) => {
|
||||
for field in cont.data.all_fields() {
|
||||
if !field.attrs.flatten() {
|
||||
continue;
|
||||
}
|
||||
match style {
|
||||
Style::Tuple => {
|
||||
cx.error("#[serde(flatten)] cannot be used on tuple structs");
|
||||
}
|
||||
Style::Newtype => {
|
||||
cx.error("#[serde(flatten)] cannot be used on newtype structs");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if field.attrs.skip_serializing() {
|
||||
cx.error(
|
||||
"#[serde(flatten] can not be combined with \
|
||||
#[serde(skip_serializing)]"
|
||||
);
|
||||
} else if field.attrs.skip_serializing_if().is_some() {
|
||||
cx.error(
|
||||
"#[serde(flatten] can not be combined with \
|
||||
#[serde(skip_serializing_if = \"...\")]"
|
||||
);
|
||||
} else if field.attrs.skip_deserializing() {
|
||||
cx.error(
|
||||
"#[serde(flatten] can not be combined with \
|
||||
#[serde(skip_deserializing)]"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `other` attribute must be used at most once and it must be the last
|
||||
/// variant of an enum that has the `field_identifier` attribute.
|
||||
///
|
||||
|
||||
@@ -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.20.1")]
|
||||
#![doc(html_root_url = "https://docs.rs/serde_derive_internals/0.23.0")]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(cyclomatic_complexity, doc_markdown, match_same_arms,
|
||||
redundant_field_names))]
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "serde_test"
|
||||
version = "1.0.32" # remember to update html_root_url
|
||||
version = "1.0.37" # 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"
|
||||
|
||||
@@ -155,7 +155,7 @@
|
||||
//! # }
|
||||
//! ```
|
||||
|
||||
#![doc(html_root_url = "https://docs.rs/serde_test/1.0.32")]
|
||||
#![doc(html_root_url = "https://docs.rs/serde_test/1.0.37")]
|
||||
#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))]
|
||||
// Whitelisted clippy lints
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(float_cmp))]
|
||||
|
||||
@@ -9,7 +9,7 @@ unstable = ["serde/unstable", "compiletest_rs"]
|
||||
|
||||
[dev-dependencies]
|
||||
fnv = "1.0"
|
||||
proc-macro2 = "0.2"
|
||||
proc-macro2 = "0.3"
|
||||
rustc-serialize = "0.3.16"
|
||||
serde = { path = "../serde", features = ["rc"] }
|
||||
serde_derive = { path = "../serde_derive", features = ["deserialize_in_place"] }
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// Copyright 2018 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: #[serde(flatten)] cannot be used on newtype structs
|
||||
struct Foo(#[serde(flatten)] HashMap<String, String>);
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Copyright 2018 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: #[serde(flatten] can not be combined with #[serde(skip_deserializing)]
|
||||
struct Foo {
|
||||
#[serde(flatten, skip_deserializing)]
|
||||
other: Other,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Other {
|
||||
x: u32
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Copyright 2018 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: #[serde(flatten] can not be combined with #[serde(skip_serializing_if = "...")]
|
||||
struct Foo {
|
||||
#[serde(flatten, skip_serializing_if="Option::is_none")]
|
||||
other: Option<Other>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Other {
|
||||
x: u32
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Copyright 2018 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: #[serde(flatten] can not be combined with #[serde(skip_serializing)]
|
||||
struct Foo {
|
||||
#[serde(flatten, skip_serializing)]
|
||||
other: Other,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Other {
|
||||
x: u32
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Copyright 2018 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: #[serde(flatten)] cannot be used on tuple structs
|
||||
struct Foo(u32, #[serde(flatten)] HashMap<String, String>);
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright 2018 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: #[serde(flatten)] cannot be used within enums
|
||||
enum Foo {
|
||||
A {
|
||||
#[serde(flatten)]
|
||||
fields: HashMap<String, String>,
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -12,12 +12,13 @@
|
||||
extern crate serde_derive;
|
||||
|
||||
extern crate serde;
|
||||
use std::collections::HashMap;
|
||||
use self::serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use self::serde::de::{self, Unexpected};
|
||||
|
||||
extern crate serde_test;
|
||||
use self::serde_test::{assert_de_tokens, assert_de_tokens_error, assert_ser_tokens, assert_tokens,
|
||||
Token};
|
||||
use self::serde_test::{assert_de_tokens, assert_de_tokens_error, assert_ser_tokens,
|
||||
assert_ser_tokens_error, assert_tokens, Token};
|
||||
|
||||
trait MyDefault: Sized {
|
||||
fn my_default() -> Self;
|
||||
@@ -94,6 +95,56 @@ where
|
||||
a5: E,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct CollectOther {
|
||||
a: u32,
|
||||
b: u32,
|
||||
#[serde(flatten)]
|
||||
extra: HashMap<String, u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct FlattenStructEnumWrapper {
|
||||
#[serde(flatten)]
|
||||
data: FlattenStructEnum,
|
||||
#[serde(flatten)]
|
||||
extra: HashMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum FlattenStructEnum {
|
||||
InsertInteger {
|
||||
index: u32,
|
||||
value: u32
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct FlattenStructTagContentEnumWrapper {
|
||||
outer: u32,
|
||||
#[serde(flatten)]
|
||||
data: FlattenStructTagContentEnumNewtype,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct FlattenStructTagContentEnumNewtype(pub FlattenStructTagContentEnum);
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case", tag = "type", content = "value")]
|
||||
enum FlattenStructTagContentEnum {
|
||||
InsertInteger {
|
||||
index: u32,
|
||||
value: u32
|
||||
},
|
||||
NewtypeVariant(FlattenStructTagContentEnumNewtypeVariant),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct FlattenStructTagContentEnumNewtypeVariant {
|
||||
value: u32,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_struct() {
|
||||
assert_de_tokens(
|
||||
@@ -1267,3 +1318,482 @@ fn test_from_into_traits() {
|
||||
assert_ser_tokens::<StructFromEnum>(&StructFromEnum(None), &[Token::None]);
|
||||
assert_de_tokens::<StructFromEnum>(&StructFromEnum(Some(2)), &[Token::Some, Token::U32(2)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_collect_other() {
|
||||
let mut extra = HashMap::new();
|
||||
extra.insert("c".into(), 3);
|
||||
assert_tokens(
|
||||
&CollectOther { a: 1, b: 2, extra },
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Str("a"),
|
||||
Token::U32(1),
|
||||
Token::Str("b"),
|
||||
Token::U32(2),
|
||||
Token::Str("c"),
|
||||
Token::U32(3),
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_flatten_struct_enum() {
|
||||
let mut extra = HashMap::new();
|
||||
extra.insert("extra_key".into(), "extra value".into());
|
||||
let change_request = FlattenStructEnumWrapper {
|
||||
data: FlattenStructEnum::InsertInteger {
|
||||
index: 0,
|
||||
value: 42
|
||||
},
|
||||
extra,
|
||||
};
|
||||
assert_de_tokens(
|
||||
&change_request,
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Str("insert_integer"),
|
||||
Token::Map { len: None },
|
||||
Token::Str("index"),
|
||||
Token::U32(0),
|
||||
Token::Str("value"),
|
||||
Token::U32(42),
|
||||
Token::MapEnd,
|
||||
Token::Str("extra_key"),
|
||||
Token::Str("extra value"),
|
||||
Token::MapEnd
|
||||
],
|
||||
);
|
||||
assert_ser_tokens(
|
||||
&change_request,
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Str("insert_integer"),
|
||||
Token::Struct { len: 2, name: "insert_integer" },
|
||||
Token::Str("index"),
|
||||
Token::U32(0),
|
||||
Token::Str("value"),
|
||||
Token::U32(42),
|
||||
Token::StructEnd,
|
||||
Token::Str("extra_key"),
|
||||
Token::Str("extra value"),
|
||||
Token::MapEnd
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_flatten_struct_tag_content_enum() {
|
||||
let change_request = FlattenStructTagContentEnumWrapper {
|
||||
outer: 42,
|
||||
data: FlattenStructTagContentEnumNewtype(
|
||||
FlattenStructTagContentEnum::InsertInteger {
|
||||
index: 0,
|
||||
value: 42
|
||||
}
|
||||
),
|
||||
};
|
||||
assert_de_tokens(
|
||||
&change_request,
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Str("outer"),
|
||||
Token::U32(42),
|
||||
Token::Str("type"),
|
||||
Token::Str("insert_integer"),
|
||||
Token::Str("value"),
|
||||
Token::Map { len: None },
|
||||
Token::Str("index"),
|
||||
Token::U32(0),
|
||||
Token::Str("value"),
|
||||
Token::U32(42),
|
||||
Token::MapEnd,
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
assert_ser_tokens(
|
||||
&change_request,
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Str("outer"),
|
||||
Token::U32(42),
|
||||
Token::Str("type"),
|
||||
Token::Str("insert_integer"),
|
||||
Token::Str("value"),
|
||||
Token::Struct { len: 2, name: "insert_integer" },
|
||||
Token::Str("index"),
|
||||
Token::U32(0),
|
||||
Token::Str("value"),
|
||||
Token::U32(42),
|
||||
Token::StructEnd,
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_flatten_struct_tag_content_enum_newtype() {
|
||||
let change_request = FlattenStructTagContentEnumWrapper {
|
||||
outer: 42,
|
||||
data: FlattenStructTagContentEnumNewtype(
|
||||
FlattenStructTagContentEnum::NewtypeVariant(
|
||||
FlattenStructTagContentEnumNewtypeVariant {
|
||||
value: 23
|
||||
}
|
||||
)
|
||||
),
|
||||
};
|
||||
assert_de_tokens(
|
||||
&change_request,
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Str("outer"),
|
||||
Token::U32(42),
|
||||
Token::Str("type"),
|
||||
Token::Str("newtype_variant"),
|
||||
Token::Str("value"),
|
||||
Token::Map { len: None },
|
||||
Token::Str("value"),
|
||||
Token::U32(23),
|
||||
Token::MapEnd,
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
assert_ser_tokens(
|
||||
&change_request,
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Str("outer"),
|
||||
Token::U32(42),
|
||||
Token::Str("type"),
|
||||
Token::Str("newtype_variant"),
|
||||
Token::Str("value"),
|
||||
Token::Struct { len: 1, name: "FlattenStructTagContentEnumNewtypeVariant" },
|
||||
Token::Str("value"),
|
||||
Token::U32(23),
|
||||
Token::StructEnd,
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unknown_field_in_flatten() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Outer {
|
||||
dummy: String,
|
||||
#[serde(flatten)]
|
||||
inner: Inner,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Inner {
|
||||
foo: HashMap<String, u32>,
|
||||
}
|
||||
|
||||
assert_de_tokens_error::<Outer>(
|
||||
&[
|
||||
Token::Struct {
|
||||
name: "Outer",
|
||||
len: 1,
|
||||
},
|
||||
Token::Str("dummy"),
|
||||
Token::Str("23"),
|
||||
Token::Str("foo"),
|
||||
Token::Map { len: None },
|
||||
Token::Str("a"),
|
||||
Token::U32(1),
|
||||
Token::Str("b"),
|
||||
Token::U32(2),
|
||||
Token::MapEnd,
|
||||
Token::Str("bar"),
|
||||
Token::U32(23),
|
||||
Token::StructEnd,
|
||||
],
|
||||
"unknown field `bar`",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_complex_flatten() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Outer {
|
||||
y: u32,
|
||||
#[serde(flatten)]
|
||||
first: First,
|
||||
#[serde(flatten)]
|
||||
second: Second,
|
||||
z: u32
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct First {
|
||||
a: u32,
|
||||
b: bool,
|
||||
c: Vec<String>,
|
||||
d: String,
|
||||
e: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Second {
|
||||
f: u32,
|
||||
}
|
||||
|
||||
assert_de_tokens(
|
||||
&Outer {
|
||||
y: 0,
|
||||
first: First {
|
||||
a: 1,
|
||||
b: true,
|
||||
c: vec!["a".into(), "b".into()],
|
||||
d: "c".into(),
|
||||
e: Some(2),
|
||||
},
|
||||
second: Second {
|
||||
f: 3
|
||||
},
|
||||
z: 4
|
||||
},
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Str("y"),
|
||||
Token::U32(0),
|
||||
Token::Str("a"),
|
||||
Token::U32(1),
|
||||
Token::Str("b"),
|
||||
Token::Bool(true),
|
||||
Token::Str("c"),
|
||||
Token::Seq { len: Some(2) },
|
||||
Token::Str("a"),
|
||||
Token::Str("b"),
|
||||
Token::SeqEnd,
|
||||
Token::Str("d"),
|
||||
Token::Str("c"),
|
||||
Token::Str("e"),
|
||||
Token::U64(2),
|
||||
Token::Str("f"),
|
||||
Token::U32(3),
|
||||
Token::Str("z"),
|
||||
Token::U32(4),
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_ser_tokens(
|
||||
&Outer {
|
||||
y: 0,
|
||||
first: First {
|
||||
a: 1,
|
||||
b: true,
|
||||
c: vec!["a".into(), "b".into()],
|
||||
d: "c".into(),
|
||||
e: Some(2),
|
||||
},
|
||||
second: Second {
|
||||
f: 3
|
||||
},
|
||||
z: 4
|
||||
},
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Str("y"),
|
||||
Token::U32(0),
|
||||
Token::Str("a"),
|
||||
Token::U32(1),
|
||||
Token::Str("b"),
|
||||
Token::Bool(true),
|
||||
Token::Str("c"),
|
||||
Token::Seq { len: Some(2) },
|
||||
Token::Str("a"),
|
||||
Token::Str("b"),
|
||||
Token::SeqEnd,
|
||||
Token::Str("d"),
|
||||
Token::Str("c"),
|
||||
Token::Str("e"),
|
||||
Token::Some,
|
||||
Token::U64(2),
|
||||
Token::Str("f"),
|
||||
Token::U32(3),
|
||||
Token::Str("z"),
|
||||
Token::U32(4),
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_flatten_unsupported_type() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Outer {
|
||||
outer: String,
|
||||
#[serde(flatten)]
|
||||
inner: String,
|
||||
}
|
||||
|
||||
assert_ser_tokens_error(
|
||||
&Outer {
|
||||
outer: "foo".into(),
|
||||
inner: "bar".into(),
|
||||
},
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Str("outer"),
|
||||
Token::Str("foo"),
|
||||
],
|
||||
"can only flatten structs and maps (got a string)",
|
||||
);
|
||||
assert_de_tokens_error::<Outer>(
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Str("outer"),
|
||||
Token::Str("foo"),
|
||||
Token::Str("a"),
|
||||
Token::Str("b"),
|
||||
Token::MapEnd
|
||||
],
|
||||
"can only flatten structs and maps",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_non_string_keys() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct TestStruct {
|
||||
name: String,
|
||||
age: u32,
|
||||
#[serde(flatten)]
|
||||
mapping: HashMap<u32, u32>,
|
||||
}
|
||||
|
||||
let mut mapping = HashMap::new();
|
||||
mapping.insert(0, 42);
|
||||
assert_tokens(
|
||||
&TestStruct { name: "peter".into(), age: 3, mapping },
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Str("name"),
|
||||
Token::Str("peter"),
|
||||
Token::Str("age"),
|
||||
Token::U32(3),
|
||||
Token::U32(0),
|
||||
Token::U32(42),
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lifetime_propagation_for_flatten() {
|
||||
#[derive(Deserialize, Serialize, Debug, PartialEq)]
|
||||
struct A<T> {
|
||||
#[serde(flatten)]
|
||||
t: T,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, PartialEq)]
|
||||
struct B<'a> {
|
||||
#[serde(flatten, borrow)]
|
||||
t: HashMap<&'a str, u32>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, PartialEq)]
|
||||
struct C<'a> {
|
||||
#[serde(flatten, borrow)]
|
||||
t: HashMap<&'a [u8], u32>,
|
||||
}
|
||||
|
||||
let mut owned_map = HashMap::new();
|
||||
owned_map.insert("x".to_string(), 42u32);
|
||||
assert_tokens(
|
||||
&A { t: owned_map },
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Str("x"),
|
||||
Token::U32(42),
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
|
||||
let mut borrowed_map = HashMap::new();
|
||||
borrowed_map.insert("x", 42u32);
|
||||
assert_ser_tokens(
|
||||
&B { t: borrowed_map.clone() },
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::BorrowedStr("x"),
|
||||
Token::U32(42),
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&B { t: borrowed_map },
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::BorrowedStr("x"),
|
||||
Token::U32(42),
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
|
||||
let mut borrowed_map = HashMap::new();
|
||||
borrowed_map.insert(&b"x"[..], 42u32);
|
||||
assert_ser_tokens(
|
||||
&C { t: borrowed_map.clone() },
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Seq { len: Some(1) },
|
||||
Token::U8(120),
|
||||
Token::SeqEnd,
|
||||
Token::U32(42),
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&C { t: borrowed_map },
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::BorrowedBytes(b"x"),
|
||||
Token::U32(42),
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_flatten_enum_newtype() {
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
struct S {
|
||||
#[serde(flatten)]
|
||||
flat: E,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
enum E {
|
||||
Q(HashMap<String, String>),
|
||||
}
|
||||
|
||||
let e = E::Q({
|
||||
let mut map = HashMap::new();
|
||||
map.insert("k".to_owned(), "v".to_owned());
|
||||
map
|
||||
});
|
||||
let s = S { flat: e };
|
||||
|
||||
assert_tokens(
|
||||
&s,
|
||||
&[
|
||||
Token::Map { len: None },
|
||||
Token::Str("Q"),
|
||||
Token::Map { len: Some(1) },
|
||||
Token::Str("k"),
|
||||
Token::Str("v"),
|
||||
Token::MapEnd,
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -385,6 +385,10 @@ fn test_gen() {
|
||||
s: vis::S,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "Self")]
|
||||
struct RemoteSelf;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum ExternallyTaggedVariantWith {
|
||||
#[allow(dead_code)]
|
||||
@@ -528,6 +532,13 @@ fn test_gen() {
|
||||
marker: PhantomData<T>,
|
||||
}
|
||||
assert::<TypeMacro<X>>();
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct BigArray {
|
||||
#[serde(serialize_with = "<[_]>::serialize")]
|
||||
array: [u8; 256],
|
||||
}
|
||||
assert_ser::<BigArray>();
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
Reference in New Issue
Block a user