pull_number int64 64 2.85k | test_patch stringlengths 303 98.3k | issue_numbers listlengths 1 2 | instance_id stringlengths 18 20 | problem_statement stringlengths 24 6.49k | version stringclasses 19 values | base_commit stringlengths 40 40 | patch stringlengths 372 188k | repo stringclasses 1 value | created_at stringlengths 20 20 | hints_text stringlengths 0 6.32k | environment_setup_commit stringclasses 20 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
1,363 | diff --git a/test_suite/tests/test_unstable.rs b/test_suite/tests/test_unstable.rs
new file mode 100644
index 000000000..ccc68c822
--- /dev/null
+++ b/test_suite/tests/test_unstable.rs
@@ -0,0 +1,27 @@
+// 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.
+
+#![deny(warnings)]
+#![cfg_attr(feature = "unstable", feature(raw_identifiers))]
+
+#[cfg(feature = "unstable")]
+#[macro_use]
+extern crate serde_derive;
+
+#[cfg(feature = "unstable")]
+extern crate serde;
+#[cfg(feature = "unstable")]
+extern crate serde_test;
+
+// This test target is convoluted with the actual #[test] in a separate file to
+// get it so that the stable compiler does not need to parse the code of the
+// test. If the test were written with #[cfg(feature = "unstable")] #[test]
+// right here, the stable compiler would fail to parse those raw identifiers
+// even if the cfg were not enabled.
+#[cfg(feature = "unstable")]
+mod unstable;
diff --git a/test_suite/tests/unstable/mod.rs b/test_suite/tests/unstable/mod.rs
new file mode 100644
index 000000000..0a8a3330f
--- /dev/null
+++ b/test_suite/tests/unstable/mod.rs
@@ -0,0 +1,30 @@
+// 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.
+
+use serde_test::{assert_tokens, Token};
+
+#[test]
+fn test_raw_identifiers() {
+ #[derive(Debug, PartialEq, Serialize, Deserialize)]
+ #[allow(non_camel_case_types)]
+ enum r#type {
+ r#type {
+ r#type: (),
+ }
+ }
+
+ assert_tokens(
+ &r#type::r#type { r#type: () },
+ &[
+ Token::StructVariant { name: "type", variant: "type", len: 1 },
+ Token::Str("type"),
+ Token::Unit,
+ Token::StructVariantEnd,
+ ],
+ );
+}
| [
"1362"
] | serde-rs__serde-1363 | Raw identifier keywords
Right now, `serde_derive` passes through the `r#` on [raw identifiers](https://rust-lang-nursery.github.io/edition-guide/rust-2018/module-system/raw-identifiers.html) when the identifier is a keyword.
For example ([playground link](https://play.rust-lang.org/?gist=0492ec75839fb4634b7a9ee6e9a1094f&version=nightly&mode=debug&edition=2018))
```rust
#[derive(Serialize)]
struct Foo {
r#type: i32,
r#bar: i32
}
fn main() {
let foo = Foo{ r#type: 3, r#bar: 12 };
println!("{}", serde_json::to_string_pretty(&foo).unwrap());
}
```
prints
```
{
"r#type": 3,
"bar": 12
}
```
That `r#` on the `r#type` seems like it shouldn't be exposed downstream of serde, since the current-list-of-keywords-in-Rust is an implementation detail that serialization probably shouldn't care about. Currently, a bunch of the data format libraries that work with serde (e.g. [ron](https://github.com/ron-rs/ron)) emit invalid data when provided with these raw identifiers, since they assume that field identifiers have a limited set of characters (that doesn't include `#`).
Unfortunately, the root of this issue is probably upstream of serde, and even writing a test case for this in this repo is tricky (since the test code has to be Rust 2018).
| 1.0 | c69a3e083fa865b7801a80db498e4fdc87435aad | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index e2ddfee1e..af5d5b0ca 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -30,8 +30,9 @@ pub fn expand_derive_deserialize(input: &syn::DeriveInput) -> Result<TokenStream
let ident = &cont.ident;
let params = Parameters::new(&cont);
let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(¶ms);
+ let suffix = ident.to_string().trim_left_matches("r#").to_owned();
let dummy_const = Ident::new(
- &format!("_IMPL_DESERIALIZE_FOR_{}", ident),
+ &format!("_IMPL_DESERIALIZE_FOR_{}", suffix),
Span::call_site(),
);
let body = Stmts(deserialize_body(&cont, ¶ms));
diff --git a/serde_derive/src/internals/attr.rs b/serde_derive/src/internals/attr.rs
index ede409db1..3f399ded9 100644
--- a/serde_derive/src/internals/attr.rs
+++ b/serde_derive/src/internals/attr.rs
@@ -90,6 +90,10 @@ pub struct Name {
deserialize: String,
}
+fn unraw(ident: &Ident) -> String {
+ ident.to_string().trim_left_matches("r#").to_owned()
+}
+
impl Name {
/// Return the container name for the container when serializing.
pub fn serialize_name(&self) -> String {
@@ -380,8 +384,8 @@ impl Container {
Container {
name: Name {
- serialize: ser_name.get().unwrap_or_else(|| item.ident.to_string()),
- deserialize: de_name.get().unwrap_or_else(|| item.ident.to_string()),
+ serialize: ser_name.get().unwrap_or_else(|| unraw(&item.ident)),
+ deserialize: de_name.get().unwrap_or_else(|| unraw(&item.ident)),
},
transparent: transparent.get(),
deny_unknown_fields: deny_unknown_fields.get(),
@@ -697,8 +701,8 @@ impl Variant {
let de_renamed = de_name.is_some();
Variant {
name: Name {
- serialize: ser_name.unwrap_or_else(|| variant.ident.to_string()),
- deserialize: de_name.unwrap_or_else(|| variant.ident.to_string()),
+ serialize: ser_name.unwrap_or_else(|| unraw(&variant.ident)),
+ deserialize: de_name.unwrap_or_else(|| unraw(&variant.ident)),
},
ser_renamed: ser_renamed,
de_renamed: de_renamed,
@@ -822,7 +826,7 @@ impl Field {
let mut flatten = BoolAttr::none(cx, "flatten");
let ident = match field.ident {
- Some(ref ident) => ident.to_string(),
+ Some(ref ident) => unraw(ident),
None => index.to_string(),
};
diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index 30c326d99..d5ae14019 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -26,7 +26,8 @@ pub fn expand_derive_serialize(input: &syn::DeriveInput) -> Result<TokenStream,
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::call_site());
+ let suffix = ident.to_string().trim_left_matches("r#").to_owned();
+ let dummy_const = Ident::new(&format!("_IMPL_SERIALIZE_FOR_{}", suffix), Span::call_site());
let body = Stmts(serialize_body(&cont, ¶ms));
let impl_block = if let Some(remote) = cont.attrs.remote() {
| serde-rs/serde | 2018-08-23T01:10:37Z | Interesting! This is a bug. That program should be printing `"type": 3` instead of `"r#type": 3`.
Would you be interested in tracking down where this is going wrong and sending a PR? Otherwise I should be able to take a look later this week.
As a workaround, at least `serde(rename = "...")` seems to work but this shouldn't be necessary.
```rust
#[derive(Serialize)]
struct Foo {
#[serde(rename = "type")]
r#type: i32,
r#bar: i32
}
``` | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,323 | diff --git a/test_suite/tests/test_ser.rs b/test_suite/tests/test_ser.rs
index cd4ce6bf4..eff19069c 100644
--- a/test_suite/tests/test_ser.rs
+++ b/test_suite/tests/test_ser.rs
@@ -462,6 +462,11 @@ declare_tests! {
Token::SeqEnd,
],
}
+ test_fmt_arguments {
+ format_args!("{}{}", 1, 'a') => &[
+ Token::Str("1a"),
+ ],
+ }
}
declare_tests! {
| [
"1319"
] | serde-rs__serde-1323 | impl<'a> Serialize for fmt::Arguments<'a>
Would it make sense to impl<'a> Serialize for fmt::Arguments<'a> ?
It's a very handy type, and available in `core` library. Though I guess for best support, the `Serializer` would have to get a `serialize_fmt` method, so it is possible to write it out without allocating temporary strings, etc. That would probably be a breaking change, though maybe an implementation that serializes into temporary, and calls `serialize_str` or something would do.
| 1.0 | d827b101d9a5896071013bc70f88be172cf0a550 | diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index 0b21e5414..cb2739820 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -69,6 +69,15 @@ impl Serialize for String {
}
}
+impl<'a> Serialize for fmt::Arguments<'a> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.collect_str(self)
+ }
+}
+
////////////////////////////////////////////////////////////////////////////////
#[cfg(feature = "std")]
| serde-rs/serde | 2018-06-27T06:31:00Z | Well... We could add an impl of [`std::fmt::Write`](https://doc.rust-lang.org/std/fmt/trait.Write.html) for all `Serializer`s. I guess the `write_str` method could just forward to `serialize_str`:
DISCLAIMER: all the code below is entirely untested and probably will not compile without some adjustments
```rust
impl<S: Serializer> std::fmt::Write for S {
#[inline]
fn write_str(&mut self, s: &str) -> std::fmt::Result {
self.serialize_str(s).map_err(|_| std::fmt::Error)
}
}
```
Although that would be a breaking change, because someone might have implemented `Write` for their serializer already.
We can still do this by adding a wrapper type for `Serializer`s that we then use inside the `Serialize` impl of `fmt::Arguments`
```rust
impl<'a> Serialize for fmt::Arguments<'a> {
fn serialize<S: Serializer>(&self, s: &mut S) -> Result<(), S::Error> {
struct Wrapper<'b, S: Serializer>(&'b mut S, Option<S::Error>);
impl<'b, S: Serializer> std::fmt::Write for Wrapper<'b, S> {
#[inline]
fn write_str(&mut self, s: &str) -> std::fmt::Result {
self.0.serialize_str(s).map_err(|err| {
assert!(self.1.is_none());
self.1 = Some(err);
std::fmt::Error
})
}
}
let mut wrapper = Wrapper(s);
match wrapper.write_fmt(*self) {
Ok(()) => Ok(()),
Err(std::fmt::Error) => Ok(wrapper.1.unwrap()),
}
}
}
```
Unfortunately this means you get a bunch of strings in the output, not sure how useful that is. What's the expected output format? A sequence of strings?
Thanks for response. I don't think serializaing this value to series of `serialize_str` is going to work, but I might be wrong.
> What's the expected output format? A sequence of strings?
In my use-case (`slog` and logging in general) `fmt::Arguments` is just a string that wasn't yet "put together" (lazy-evalution-sort-of). When logging, it's useful to take `&fmt::Arguments` because it's fast, and only if a given logging statement/value reaches logging output make a string out of it/write it out to output. So from my perspective `fmt::Arguments` == lazily evaluated `String`.
I'm toying with some API re-designs where publicly accepted types would be `&dyn serde::Serailize`, and I'm loosing `fmt::Arguments` support because `serde` doesn't support it. I need to be able to do things like `impl<T> Something for T where T : serde:Serialize`, but without `serde` having `impl Serialize for fmt::Arguments`, this can't be done due to coherency conflicts. Well, I could just do impl for each single type that serde supports, but it's not perfect.
In ideal case `Serializer` would get a `serialize_fmt` that would be much like *one* call to `serialize_str`, but serializer would be responsible for either writing it directly to its output, or to temporary string. I am not sure if this is possible, especially without breaking backward compat. Maybe adding a method like that with default impl that writes it out to `String` and calls `write_str` would be OK for non-`no_std`, and in `no_std` it could just return error/do nothing.
| 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,302 | diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index 6c1f3d82f..b4ca2e198 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -7,6 +7,7 @@
// except according to those terms.
#![cfg_attr(feature = "cargo-clippy", allow(decimal_literal_representation))]
+#![cfg_attr(feature = "unstable", feature(never_type))]
#[macro_use]
extern crate serde_derive;
@@ -984,6 +985,16 @@ declare_tests! {
}
}
+#[cfg(feature = "unstable")]
+declare_tests! {
+ test_never_result {
+ Ok::<u8, !>(0) => &[
+ Token::NewtypeVariant { name: "Result", variant: "Ok" },
+ Token::U8(0),
+ ],
+ }
+}
+
#[cfg(unix)]
#[test]
fn test_osstring() {
@@ -1051,6 +1062,20 @@ fn test_cstr_internal_null_end() {
);
}
+#[cfg(feature = "unstable")]
+#[test]
+fn test_never_type() {
+ assert_de_tokens_error::<!>(&[], "cannot deserialize `!`");
+
+ assert_de_tokens_error::<Result<u8, !>>(
+ &[Token::NewtypeVariant {
+ name: "Result",
+ variant: "Err",
+ }],
+ "cannot deserialize `!`",
+ );
+}
+
declare_error_tests! {
test_unknown_field<StructDenyUnknown> {
&[
diff --git a/test_suite/tests/test_ser.rs b/test_suite/tests/test_ser.rs
index 21c641a7a..0d4a35de1 100644
--- a/test_suite/tests/test_ser.rs
+++ b/test_suite/tests/test_ser.rs
@@ -6,6 +6,8 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![cfg_attr(feature = "unstable", feature(never_type))]
+
#[macro_use]
extern crate serde_derive;
@@ -548,6 +550,16 @@ declare_tests! {
}
}
+#[cfg(feature = "unstable")]
+declare_tests! {
+ test_never_result {
+ Ok::<u8, !>(0) => &[
+ Token::NewtypeVariant { name: "Result", variant: "Ok" },
+ Token::U8(0),
+ ],
+ }
+}
+
#[test]
#[cfg(unix)]
fn test_cannot_serialize_paths() {
| [
"544"
] | serde-rs__serde-1302 | Impl Serialize/Deserialize for !
`Serialize` is straightforward. As for `Deserialize`, I guess it would just panic? This is useful for me when serializing and deserializing types like `Result<T, !>`.
| 1.0 | 0a71fe329c8898a28d03ddfb746707cf958c21e8 | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 342ca3bea..579ee594e 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -49,6 +49,16 @@ impl<'de> Deserialize<'de> for () {
}
}
+#[cfg(feature = "unstable")]
+impl<'de> Deserialize<'de> for ! {
+ fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ Err(Error::custom("cannot deserialize `!`"))
+ }
+}
+
////////////////////////////////////////////////////////////////////////////////
struct BoolVisitor;
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index 104271568..ec1ed5e86 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -98,6 +98,7 @@
//! - PathBuf
//! - Range\<T\>
//! - num::NonZero*
+//! - `!` *(unstable)*
//! - **Net types**:
//! - IpAddr
//! - Ipv4Addr
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 56ed7c57f..fe097042b 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -176,6 +176,48 @@ where
////////////////////////////////////////////////////////////////////////////////
+/// A deserializer that cannot be instantiated.
+#[cfg(feature = "unstable")]
+pub struct NeverDeserializer<E> {
+ never: !,
+ marker: PhantomData<E>,
+}
+
+#[cfg(feature = "unstable")]
+impl<'de, E> IntoDeserializer<'de, E> for !
+where
+ E: de::Error,
+{
+ type Deserializer = NeverDeserializer<E>;
+
+ fn into_deserializer(self) -> Self::Deserializer {
+ self
+ }
+}
+
+#[cfg(feature = "unstable")]
+impl<'de, E> de::Deserializer<'de> for NeverDeserializer<E>
+where
+ E: de::Error,
+{
+ type Error = E;
+
+ fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
+ where
+ V: de::Visitor<'de>,
+ {
+ self.never
+ }
+
+ forward_to_deserialize_any! {
+ bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
+ bytes byte_buf option unit unit_struct newtype_struct seq tuple
+ tuple_struct map struct enum identifier ignored_any
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
macro_rules! primitive_deserializer {
($ty:ty, $doc:tt, $name:ident, $method:ident $($cast:tt)*) => {
#[doc = "A deserializer holding"]
diff --git a/serde/src/lib.rs b/serde/src/lib.rs
index 9c1535a31..148e1ac44 100644
--- a/serde/src/lib.rs
+++ b/serde/src/lib.rs
@@ -89,7 +89,7 @@
// discussion of these features please refer to this issue:
//
// https://github.com/serde-rs/serde/issues/812
-#![cfg_attr(feature = "unstable", feature(specialization))]
+#![cfg_attr(feature = "unstable", feature(specialization, never_type))]
#![cfg_attr(feature = "alloc", feature(alloc))]
#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))]
// Whitelisted clippy lints
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index be07d061c..3a4a4efee 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -247,6 +247,16 @@ impl Serialize for () {
}
}
+#[cfg(feature = "unstable")]
+impl Serialize for ! {
+ fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ *self
+ }
+}
+
////////////////////////////////////////////////////////////////////////////////
macro_rules! tuple_impls {
diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs
index c5c9c423c..d1d4bd7fb 100644
--- a/serde/src/ser/mod.rs
+++ b/serde/src/ser/mod.rs
@@ -93,6 +93,7 @@
//! - PathBuf
//! - Range\<T\>
//! - num::NonZero*
+//! - `!` *(unstable)*
//! - **Net types**:
//! - IpAddr
//! - Ipv4Addr
| serde-rs/serde | 2018-06-03T07:23:07Z | If we do `Deserialize for !` it should error, not panic.
Is `Result<T, !>` the only instance where you need this? Would it make more sense to specialize De/Serialize for `Result<T, !>` instead of implementing them for `!`? `Result<T, !>` is equivalent to T so we might as well serialize it the same way.
The `Result<T, !>` was actually a simplified example. My actual use case involves an error type where one variant is generic: the actual type being deserialized is `Result<T, Error<!>>`. Basically, if a user implements a service that can never return an application error, the application error is `!`, and the framework error is `Error<!>`.
That being said, it could definitely make sense to specialize the `Result<T, !>` case as well!
| 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,297 | diff --git a/test_suite/tests/compile-fail/borrow/bad_lifetimes.rs b/test_suite/tests/compile-fail/borrow/bad_lifetimes.rs
index a33968f37..f2ab9de07 100644
--- a/test_suite/tests/compile-fail/borrow/bad_lifetimes.rs
+++ b/test_suite/tests/compile-fail/borrow/bad_lifetimes.rs
@@ -9,9 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: failed to parse borrowed lifetimes: "zzz"
struct Test<'a> {
- #[serde(borrow = "zzz")] //~^^ HELP: failed to parse borrowed lifetimes: "zzz"
+ #[serde(borrow = "zzz")]
s: &'a str,
}
diff --git a/test_suite/tests/compile-fail/borrow/duplicate_lifetime.rs b/test_suite/tests/compile-fail/borrow/duplicate_lifetime.rs
index 482a84118..e575e0703 100644
--- a/test_suite/tests/compile-fail/borrow/duplicate_lifetime.rs
+++ b/test_suite/tests/compile-fail/borrow/duplicate_lifetime.rs
@@ -9,9 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: duplicate borrowed lifetime `'a`
struct Test<'a> {
- #[serde(borrow = "'a + 'a")] //~^^ HELP: duplicate borrowed lifetime `'a`
+ #[serde(borrow = "'a + 'a")]
s: &'a str,
}
diff --git a/test_suite/tests/compile-fail/borrow/duplicate_variant.rs b/test_suite/tests/compile-fail/borrow/duplicate_variant.rs
index 5cc3ad3b3..07e286679 100644
--- a/test_suite/tests/compile-fail/borrow/duplicate_variant.rs
+++ b/test_suite/tests/compile-fail/borrow/duplicate_variant.rs
@@ -12,9 +12,9 @@ extern crate serde_derive;
#[derive(Deserialize)]
struct Str<'a>(&'a str);
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 15:10: 15:21: duplicate serde attribute `borrow`
enum Test<'a> {
- #[serde(borrow)] //~^^ HELP: duplicate serde attribute `borrow`
+ #[serde(borrow)]
S(#[serde(borrow)] Str<'a>)
}
diff --git a/test_suite/tests/compile-fail/borrow/empty_lifetimes.rs b/test_suite/tests/compile-fail/borrow/empty_lifetimes.rs
index 0aec052ba..a18c51770 100644
--- a/test_suite/tests/compile-fail/borrow/empty_lifetimes.rs
+++ b/test_suite/tests/compile-fail/borrow/empty_lifetimes.rs
@@ -9,9 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: at least one lifetime must be borrowed
struct Test<'a> {
- #[serde(borrow = "")] //~^^ HELP: at least one lifetime must be borrowed
+ #[serde(borrow = "")]
s: &'a str,
}
diff --git a/test_suite/tests/compile-fail/borrow/no_lifetimes.rs b/test_suite/tests/compile-fail/borrow/no_lifetimes.rs
index ca0f0409b..ee9d5fcd9 100644
--- a/test_suite/tests/compile-fail/borrow/no_lifetimes.rs
+++ b/test_suite/tests/compile-fail/borrow/no_lifetimes.rs
@@ -9,9 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: field `s` has no lifetimes to borrow
struct Test {
- #[serde(borrow)] //~^^ HELP: field `s` has no lifetimes to borrow
+ #[serde(borrow)]
s: String,
}
diff --git a/test_suite/tests/compile-fail/borrow/struct_variant.rs b/test_suite/tests/compile-fail/borrow/struct_variant.rs
index 5bab07171..b4827dec4 100644
--- a/test_suite/tests/compile-fail/borrow/struct_variant.rs
+++ b/test_suite/tests/compile-fail/borrow/struct_variant.rs
@@ -12,9 +12,9 @@ extern crate serde_derive;
#[derive(Deserialize)]
struct Str<'a>(&'a str);
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 15:10: 15:21: #[serde(borrow)] may only be used on newtype variants
enum Test<'a> {
- #[serde(borrow)] //~^^ HELP: #[serde(borrow)] may only be used on newtype variants
+ #[serde(borrow)]
S { s: Str<'a> }
}
diff --git a/test_suite/tests/compile-fail/borrow/wrong_lifetime.rs b/test_suite/tests/compile-fail/borrow/wrong_lifetime.rs
index 707cd1183..a42e90c4a 100644
--- a/test_suite/tests/compile-fail/borrow/wrong_lifetime.rs
+++ b/test_suite/tests/compile-fail/borrow/wrong_lifetime.rs
@@ -9,9 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: field `s` does not have lifetime 'b
struct Test<'a> {
- #[serde(borrow = "'b")] //~^^ HELP: field `s` does not have lifetime 'b
+ #[serde(borrow = "'b")]
s: &'a str,
}
diff --git a/test_suite/tests/compile-fail/conflict/adjacent-tag.rs b/test_suite/tests/compile-fail/conflict/adjacent-tag.rs
index 419afa4c7..c8c6fea1d 100644
--- a/test_suite/tests/compile-fail/conflict/adjacent-tag.rs
+++ b/test_suite/tests/compile-fail/conflict/adjacent-tag.rs
@@ -9,9 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: enum tags `conflict` for type and content conflict with each other
#[serde(tag = "conflict", content = "conflict")]
-//~^^ HELP: enum tags `conflict` for type and content conflict with each other
enum E {
A,
B,
diff --git a/test_suite/tests/compile-fail/conflict/flatten-newtype-struct.rs b/test_suite/tests/compile-fail/conflict/flatten-newtype-struct.rs
index 07566f8c7..bd5089abb 100644
--- a/test_suite/tests/compile-fail/conflict/flatten-newtype-struct.rs
+++ b/test_suite/tests/compile-fail/conflict/flatten-newtype-struct.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: #[serde(flatten)] cannot be used on newtype structs
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: #[serde(flatten)] cannot be used on newtype structs
struct Foo(#[serde(flatten)] HashMap<String, String>);
fn main() {}
diff --git a/test_suite/tests/compile-fail/conflict/flatten-skip-deserializing.rs b/test_suite/tests/compile-fail/conflict/flatten-skip-deserializing.rs
index 3ef4d38f4..0b10ea53b 100644
--- a/test_suite/tests/compile-fail/conflict/flatten-skip-deserializing.rs
+++ b/test_suite/tests/compile-fail/conflict/flatten-skip-deserializing.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: #[serde(flatten] can not be combined with #[serde(skip_deserializing)]
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: #[serde(flatten] can not be combined with #[serde(skip_deserializing)]
struct Foo {
#[serde(flatten, skip_deserializing)]
other: Other,
diff --git a/test_suite/tests/compile-fail/conflict/flatten-skip-serializing-if.rs b/test_suite/tests/compile-fail/conflict/flatten-skip-serializing-if.rs
index 6a5fa9d62..273902e4e 100644
--- a/test_suite/tests/compile-fail/conflict/flatten-skip-serializing-if.rs
+++ b/test_suite/tests/compile-fail/conflict/flatten-skip-serializing-if.rs
@@ -9,8 +9,7 @@
#[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 = "...")]
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: #[serde(flatten] can not be combined with #[serde(skip_serializing_if = "...")]
struct Foo {
#[serde(flatten, skip_serializing_if="Option::is_none")]
other: Option<Other>,
diff --git a/test_suite/tests/compile-fail/conflict/flatten-skip-serializing.rs b/test_suite/tests/compile-fail/conflict/flatten-skip-serializing.rs
index 204f9bf31..ba6ae7a77 100644
--- a/test_suite/tests/compile-fail/conflict/flatten-skip-serializing.rs
+++ b/test_suite/tests/compile-fail/conflict/flatten-skip-serializing.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: #[serde(flatten] can not be combined with #[serde(skip_serializing)]
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: #[serde(flatten] can not be combined with #[serde(skip_serializing)]
struct Foo {
#[serde(flatten, skip_serializing)]
other: Other,
diff --git a/test_suite/tests/compile-fail/conflict/flatten-tuple-struct.rs b/test_suite/tests/compile-fail/conflict/flatten-tuple-struct.rs
index 167bdbdac..311ea37d3 100644
--- a/test_suite/tests/compile-fail/conflict/flatten-tuple-struct.rs
+++ b/test_suite/tests/compile-fail/conflict/flatten-tuple-struct.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: #[serde(flatten)] cannot be used on tuple structs
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: #[serde(flatten)] cannot be used on tuple structs
struct Foo(u32, #[serde(flatten)] HashMap<String, String>);
fn main() {}
diff --git a/test_suite/tests/compile-fail/conflict/internal-tag.rs b/test_suite/tests/compile-fail/conflict/internal-tag.rs
index 777718bc7..75941922f 100644
--- a/test_suite/tests/compile-fail/conflict/internal-tag.rs
+++ b/test_suite/tests/compile-fail/conflict/internal-tag.rs
@@ -9,9 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: variant field name `conflict` conflicts with internal tag
#[serde(tag = "conflict")]
-//~^^ HELP: variant field name `conflict` conflicts with internal tag
enum E {
A {
#[serde(rename = "conflict")]
diff --git a/test_suite/tests/compile-fail/default-attribute/enum.rs b/test_suite/tests/compile-fail/default-attribute/enum.rs
index 7b0649bbc..989519a0e 100644
--- a/test_suite/tests/compile-fail/default-attribute/enum.rs
+++ b/test_suite/tests/compile-fail/default-attribute/enum.rs
@@ -9,8 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
-#[serde(default)] //~^ HELP: #[serde(default)] can only be used on structs
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: #[serde(default)] can only be used on structs with named fields
+#[serde(default)]
enum E {
S { f: u8 },
}
diff --git a/test_suite/tests/compile-fail/default-attribute/nameless_struct_fields.rs b/test_suite/tests/compile-fail/default-attribute/nameless_struct_fields.rs
index 83aec668a..cff48b5c6 100644
--- a/test_suite/tests/compile-fail/default-attribute/nameless_struct_fields.rs
+++ b/test_suite/tests/compile-fail/default-attribute/nameless_struct_fields.rs
@@ -9,8 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
-#[serde(default)] //~^ HELP: #[serde(default)] can only be used on structs
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: #[serde(default)] can only be used on structs with named fields
+#[serde(default)]
struct T(u8, u8);
fn main() { }
diff --git a/test_suite/tests/compile-fail/duplicate-attribute/rename-and-ser.rs b/test_suite/tests/compile-fail/duplicate-attribute/rename-and-ser.rs
index cc94685c8..ac34d5cbd 100644
--- a/test_suite/tests/compile-fail/duplicate-attribute/rename-and-ser.rs
+++ b/test_suite/tests/compile-fail/duplicate-attribute/rename-and-ser.rs
@@ -9,9 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: unknown serde field attribute `serialize`
struct S {
- #[serde(rename="x", serialize="y")] //~^^ HELP: unknown serde field attribute `serialize`
+ #[serde(rename="x", serialize="y")]
x: (),
}
diff --git a/test_suite/tests/compile-fail/duplicate-attribute/rename-rename-de.rs b/test_suite/tests/compile-fail/duplicate-attribute/rename-rename-de.rs
index 9b02357ab..039b46ca3 100644
--- a/test_suite/tests/compile-fail/duplicate-attribute/rename-rename-de.rs
+++ b/test_suite/tests/compile-fail/duplicate-attribute/rename-rename-de.rs
@@ -9,10 +9,10 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: duplicate serde attribute `rename`
struct S {
#[serde(rename="x")]
- #[serde(rename(deserialize="y"))] //~^^^ HELP: duplicate serde attribute `rename`
+ #[serde(rename(deserialize="y"))]
x: (),
}
diff --git a/test_suite/tests/compile-fail/duplicate-attribute/rename-ser-rename-ser.rs b/test_suite/tests/compile-fail/duplicate-attribute/rename-ser-rename-ser.rs
index b84344138..08efbe5fd 100644
--- a/test_suite/tests/compile-fail/duplicate-attribute/rename-ser-rename-ser.rs
+++ b/test_suite/tests/compile-fail/duplicate-attribute/rename-ser-rename-ser.rs
@@ -9,9 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: duplicate serde attribute `rename`
struct S {
- #[serde(rename(serialize="x"), rename(serialize="y"))] //~^^ HELP: duplicate serde attribute `rename`
+ #[serde(rename(serialize="x"), rename(serialize="y"))]
x: (),
}
diff --git a/test_suite/tests/compile-fail/duplicate-attribute/rename-ser-rename.rs b/test_suite/tests/compile-fail/duplicate-attribute/rename-ser-rename.rs
index 8aee51312..9e4b32d73 100644
--- a/test_suite/tests/compile-fail/duplicate-attribute/rename-ser-rename.rs
+++ b/test_suite/tests/compile-fail/duplicate-attribute/rename-ser-rename.rs
@@ -9,10 +9,10 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: duplicate serde attribute `rename`
struct S {
#[serde(rename(serialize="x"))]
- #[serde(rename="y")] //~^^^ HELP: duplicate serde attribute `rename`
+ #[serde(rename="y")]
x: (),
}
diff --git a/test_suite/tests/compile-fail/duplicate-attribute/rename-ser-ser.rs b/test_suite/tests/compile-fail/duplicate-attribute/rename-ser-ser.rs
index 25c50fa2a..57d595d17 100644
--- a/test_suite/tests/compile-fail/duplicate-attribute/rename-ser-ser.rs
+++ b/test_suite/tests/compile-fail/duplicate-attribute/rename-ser-ser.rs
@@ -9,9 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: duplicate serde attribute `rename`
struct S {
- #[serde(rename(serialize="x", serialize="y"))] //~^^ HELP: duplicate serde attribute `rename`
+ #[serde(rename(serialize="x", serialize="y"))]
x: (),
}
diff --git a/test_suite/tests/compile-fail/duplicate-attribute/two-rename-ser.rs b/test_suite/tests/compile-fail/duplicate-attribute/two-rename-ser.rs
index 96a657323..313877b39 100644
--- a/test_suite/tests/compile-fail/duplicate-attribute/two-rename-ser.rs
+++ b/test_suite/tests/compile-fail/duplicate-attribute/two-rename-ser.rs
@@ -9,10 +9,10 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: duplicate serde attribute `rename`
struct S {
#[serde(rename(serialize="x"))]
- #[serde(rename(serialize="y"))] //~^^^ HELP: duplicate serde attribute `rename`
+ #[serde(rename(serialize="y"))]
x: (),
}
diff --git a/test_suite/tests/compile-fail/duplicate-attribute/with-and-serialize-with.rs b/test_suite/tests/compile-fail/duplicate-attribute/with-and-serialize-with.rs
index 9ca989954..a6fe4f649 100644
--- a/test_suite/tests/compile-fail/duplicate-attribute/with-and-serialize-with.rs
+++ b/test_suite/tests/compile-fail/duplicate-attribute/with-and-serialize-with.rs
@@ -9,9 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: duplicate serde attribute `serialize_with`
struct S {
- #[serde(with = "w", serialize_with = "s")] //~^^ HELP: duplicate serde attribute `serialize_with`
+ #[serde(with = "w", serialize_with = "s")]
x: (),
}
diff --git a/test_suite/tests/compile-fail/enum-representation/internal-tuple-variant.rs b/test_suite/tests/compile-fail/enum-representation/internal-tuple-variant.rs
index 6b02bfd04..45b4f3d5b 100644
--- a/test_suite/tests/compile-fail/enum-representation/internal-tuple-variant.rs
+++ b/test_suite/tests/compile-fail/enum-representation/internal-tuple-variant.rs
@@ -9,8 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-#[serde(tag = "type")] //~^ HELP: #[serde(tag = "...")] cannot be used with tuple variants
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: #[serde(tag = "...")] cannot be used with tuple variants
+#[serde(tag = "type")]
enum E {
Tuple(u8, u8),
}
diff --git a/test_suite/tests/compile-fail/enum-representation/internally-tagged-struct.rs b/test_suite/tests/compile-fail/enum-representation/internally-tagged-struct.rs
index 31615ff6a..f88a46830 100644
--- a/test_suite/tests/compile-fail/enum-representation/internally-tagged-struct.rs
+++ b/test_suite/tests/compile-fail/enum-representation/internally-tagged-struct.rs
@@ -9,8 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-#[serde(tag = "type")] //~^ HELP: #[serde(tag = "...")] can only be used on enums
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: #[serde(tag = "...")] can only be used on enums
+#[serde(tag = "type")]
struct S;
fn main() {}
diff --git a/test_suite/tests/compile-fail/enum-representation/untagged-and-internal.rs b/test_suite/tests/compile-fail/enum-representation/untagged-and-internal.rs
index 4edbf0043..c7d419923 100644
--- a/test_suite/tests/compile-fail/enum-representation/untagged-and-internal.rs
+++ b/test_suite/tests/compile-fail/enum-representation/untagged-and-internal.rs
@@ -9,9 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: enum cannot be both untagged and internally tagged
#[serde(untagged)]
-#[serde(tag = "type")] //~^^ HELP: enum cannot be both untagged and internally tagged
+#[serde(tag = "type")]
enum E {
A(u8),
B(String),
diff --git a/test_suite/tests/compile-fail/enum-representation/untagged-struct.rs b/test_suite/tests/compile-fail/enum-representation/untagged-struct.rs
index 3546748e2..784d0691a 100644
--- a/test_suite/tests/compile-fail/enum-representation/untagged-struct.rs
+++ b/test_suite/tests/compile-fail/enum-representation/untagged-struct.rs
@@ -9,8 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-#[serde(untagged)] //~^ HELP: #[serde(untagged)] can only be used on enums
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: #[serde(untagged)] can only be used on enums
+#[serde(untagged)]
struct S;
fn main() {}
diff --git a/test_suite/tests/compile-fail/identifier/both.rs b/test_suite/tests/compile-fail/identifier/both.rs
index 13a8d9175..c7b75f84d 100644
--- a/test_suite/tests/compile-fail/identifier/both.rs
+++ b/test_suite/tests/compile-fail/identifier/both.rs
@@ -9,8 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
-#[serde(field_identifier, variant_identifier)] //~^ HELP: `field_identifier` and `variant_identifier` cannot both be set
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: `field_identifier` and `variant_identifier` cannot both be set
+#[serde(field_identifier, variant_identifier)]
enum F {
A,
B,
diff --git a/test_suite/tests/compile-fail/identifier/field_struct.rs b/test_suite/tests/compile-fail/identifier/field_struct.rs
index 79b380d94..dddcf1706 100644
--- a/test_suite/tests/compile-fail/identifier/field_struct.rs
+++ b/test_suite/tests/compile-fail/identifier/field_struct.rs
@@ -9,8 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: `field_identifier` can only be used on an enum
#[serde(field_identifier)]
-struct S; //~^^ HELP: `field_identifier` can only be used on an enum
+struct S;
fn main() {}
diff --git a/test_suite/tests/compile-fail/identifier/field_tuple.rs b/test_suite/tests/compile-fail/identifier/field_tuple.rs
index 7b26885d2..b55925a78 100644
--- a/test_suite/tests/compile-fail/identifier/field_tuple.rs
+++ b/test_suite/tests/compile-fail/identifier/field_tuple.rs
@@ -9,11 +9,11 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: field_identifier may only contain unit variants
#[serde(field_identifier)]
enum F {
A,
- B(u8, u8), //~^^^^ HELP: field_identifier may only contain unit variants
+ B(u8, u8),
}
fn main() {}
diff --git a/test_suite/tests/compile-fail/identifier/newtype_not_last.rs b/test_suite/tests/compile-fail/identifier/newtype_not_last.rs
index f601be3e8..71d8ac3e8 100644
--- a/test_suite/tests/compile-fail/identifier/newtype_not_last.rs
+++ b/test_suite/tests/compile-fail/identifier/newtype_not_last.rs
@@ -9,11 +9,11 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: `Other` must be the last variant
#[serde(field_identifier)]
enum F {
A,
- Other(String), //~^^^^ HELP: `Other` must be the last variant
+ Other(String),
B,
}
diff --git a/test_suite/tests/compile-fail/identifier/not_identifier.rs b/test_suite/tests/compile-fail/identifier/not_identifier.rs
index 3dd6d65f9..3bc961750 100644
--- a/test_suite/tests/compile-fail/identifier/not_identifier.rs
+++ b/test_suite/tests/compile-fail/identifier/not_identifier.rs
@@ -9,10 +9,10 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: #[serde(other)] may only be used inside a field_identifier
enum F {
A,
- #[serde(other)] //~^^^ HELP: #[serde(other)] may only be used inside a field_identifier
+ #[serde(other)]
B,
}
diff --git a/test_suite/tests/compile-fail/identifier/not_unit.rs b/test_suite/tests/compile-fail/identifier/not_unit.rs
index dfc65df2a..e94a05921 100644
--- a/test_suite/tests/compile-fail/identifier/not_unit.rs
+++ b/test_suite/tests/compile-fail/identifier/not_unit.rs
@@ -9,11 +9,11 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: #[serde(other)] must be on a unit variant
#[serde(field_identifier)]
enum F {
A,
- #[serde(other)] //~^^^^ HELP: #[serde(other)] must be on a unit variant
+ #[serde(other)]
Other(u8, u8),
}
diff --git a/test_suite/tests/compile-fail/identifier/other_not_last.rs b/test_suite/tests/compile-fail/identifier/other_not_last.rs
index 481f47645..31e2675bf 100644
--- a/test_suite/tests/compile-fail/identifier/other_not_last.rs
+++ b/test_suite/tests/compile-fail/identifier/other_not_last.rs
@@ -9,11 +9,11 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: #[serde(other)] must be the last variant
#[serde(field_identifier)]
enum F {
A,
- #[serde(other)] //~^^^^ HELP: #[serde(other)] must be the last variant
+ #[serde(other)]
Other,
B,
}
diff --git a/test_suite/tests/compile-fail/identifier/serialize.rs b/test_suite/tests/compile-fail/identifier/serialize.rs
index 1c928b3f8..33e7eb759 100644
--- a/test_suite/tests/compile-fail/identifier/serialize.rs
+++ b/test_suite/tests/compile-fail/identifier/serialize.rs
@@ -9,8 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-#[serde(field_identifier)] //~^ HELP: field identifiers cannot be serialized
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: field identifiers cannot be serialized
+#[serde(field_identifier)]
enum F {
A,
B,
diff --git a/test_suite/tests/compile-fail/identifier/variant_struct.rs b/test_suite/tests/compile-fail/identifier/variant_struct.rs
index aeb37f9a5..b14edebd7 100644
--- a/test_suite/tests/compile-fail/identifier/variant_struct.rs
+++ b/test_suite/tests/compile-fail/identifier/variant_struct.rs
@@ -9,8 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: `variant_identifier` can only be used on an enum
#[serde(variant_identifier)]
-struct S; //~^^ HELP: `variant_identifier` can only be used on an enum
+struct S;
fn main() {}
diff --git a/test_suite/tests/compile-fail/identifier/variant_tuple.rs b/test_suite/tests/compile-fail/identifier/variant_tuple.rs
index 9ea2ee2ec..597df1720 100644
--- a/test_suite/tests/compile-fail/identifier/variant_tuple.rs
+++ b/test_suite/tests/compile-fail/identifier/variant_tuple.rs
@@ -9,11 +9,11 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: variant_identifier may only contain unit variants
#[serde(variant_identifier)]
enum F {
A,
- B(u8, u8), //~^^^^ HELP: variant_identifier may only contain unit variants
+ B(u8, u8),
}
fn main() {}
diff --git a/test_suite/tests/compile-fail/precondition/deserialize_de_lifetime.rs b/test_suite/tests/compile-fail/precondition/deserialize_de_lifetime.rs
index 4ab2f6a3b..19ecdbaad 100644
--- a/test_suite/tests/compile-fail/precondition/deserialize_de_lifetime.rs
+++ b/test_suite/tests/compile-fail/precondition/deserialize_de_lifetime.rs
@@ -9,7 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: cannot deserialize when there is a lifetime parameter called 'de
struct S<'de> {
- s: &'de str, //~^^ HELP: cannot deserialize when there is a lifetime parameter called 'de
+ s: &'de str,
}
diff --git a/test_suite/tests/compile-fail/precondition/deserialize_dst.rs b/test_suite/tests/compile-fail/precondition/deserialize_dst.rs
index 243b998d7..ed12a0012 100644
--- a/test_suite/tests/compile-fail/precondition/deserialize_dst.rs
+++ b/test_suite/tests/compile-fail/precondition/deserialize_dst.rs
@@ -9,8 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: cannot deserialize a dynamically sized struct
struct S {
string: String,
- slice: [u8], //~^^^ HELP: cannot deserialize a dynamically sized struct
+ slice: [u8],
}
diff --git a/test_suite/tests/compile-fail/remote/bad_getter.rs b/test_suite/tests/compile-fail/remote/bad_getter.rs
index 7b01c9cfa..3d62d4b4e 100644
--- a/test_suite/tests/compile-fail/remote/bad_getter.rs
+++ b/test_suite/tests/compile-fail/remote/bad_getter.rs
@@ -15,10 +15,10 @@ mod remote {
}
}
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 18:10: 18:19: failed to parse path: "~~~"
#[serde(remote = "remote::S")]
struct S {
- #[serde(getter = "~~~")] //~^^^ HELP: failed to parse path: "~~~"
+ #[serde(getter = "~~~")]
a: u8,
}
diff --git a/test_suite/tests/compile-fail/remote/bad_remote.rs b/test_suite/tests/compile-fail/remote/bad_remote.rs
index a81627dbe..6fca32f85 100644
--- a/test_suite/tests/compile-fail/remote/bad_remote.rs
+++ b/test_suite/tests/compile-fail/remote/bad_remote.rs
@@ -15,8 +15,8 @@ mod remote {
}
}
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-#[serde(remote = "~~~")] //~^ HELP: failed to parse path: "~~~"
+#[derive(Serialize)] //~ ERROR: 18:10: 18:19: failed to parse path: "~~~"
+#[serde(remote = "~~~")]
struct S {
a: u8,
}
diff --git a/test_suite/tests/compile-fail/remote/enum_getter.rs b/test_suite/tests/compile-fail/remote/enum_getter.rs
index 016cfc031..603badce3 100644
--- a/test_suite/tests/compile-fail/remote/enum_getter.rs
+++ b/test_suite/tests/compile-fail/remote/enum_getter.rs
@@ -15,11 +15,11 @@ mod remote {
}
}
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 18:10: 18:19: #[serde(getter = "...")] is not allowed in an enum
#[serde(remote = "remote::E")]
pub enum E {
A {
- #[serde(getter = "get_a")] //~^^^^ HELP: #[serde(getter = "...")] is not allowed in an enum
+ #[serde(getter = "get_a")]
a: u8,
}
}
diff --git a/test_suite/tests/compile-fail/remote/nonremote_getter.rs b/test_suite/tests/compile-fail/remote/nonremote_getter.rs
index ce7539bef..fbd26ad6a 100644
--- a/test_suite/tests/compile-fail/remote/nonremote_getter.rs
+++ b/test_suite/tests/compile-fail/remote/nonremote_getter.rs
@@ -9,9 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: #[serde(getter = "...")] can only be used in structs that have #[serde(remote = "...")]
struct S {
- #[serde(getter = "S::get")] //~^^ HELP: #[serde(getter = "...")] can only be used in structs that have #[serde(remote = "...")]
+ #[serde(getter = "S::get")]
a: u8,
}
diff --git a/test_suite/tests/compile-fail/transparent/at_most_one.rs b/test_suite/tests/compile-fail/transparent/at_most_one.rs
index d5b7dae89..bade8ce8f 100644
--- a/test_suite/tests/compile-fail/transparent/at_most_one.rs
+++ b/test_suite/tests/compile-fail/transparent/at_most_one.rs
@@ -9,10 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: #[serde(transparent)] requires struct to have at most one transparent field
#[serde(transparent)]
struct S {
- //~^^^ HELP: #[serde(transparent)] requires struct to have at most one transparent field
a: u8,
b: u8,
}
diff --git a/test_suite/tests/compile-fail/transparent/de_at_least_one.rs b/test_suite/tests/compile-fail/transparent/de_at_least_one.rs
index a1abe4746..3de299249 100644
--- a/test_suite/tests/compile-fail/transparent/de_at_least_one.rs
+++ b/test_suite/tests/compile-fail/transparent/de_at_least_one.rs
@@ -9,10 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: #[serde(transparent)] requires at least one field that is neither skipped nor has a default
#[serde(transparent)]
struct S {
- //~^^^ HELP: #[serde(transparent)] requires at least one field that is neither skipped nor has a default
#[serde(skip)]
a: u8,
#[serde(default)]
diff --git a/test_suite/tests/compile-fail/transparent/ser_at_least_one.rs b/test_suite/tests/compile-fail/transparent/ser_at_least_one.rs
index 19dd59c17..b13b1ee43 100644
--- a/test_suite/tests/compile-fail/transparent/ser_at_least_one.rs
+++ b/test_suite/tests/compile-fail/transparent/ser_at_least_one.rs
@@ -9,10 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: #[serde(transparent)] requires at least one field that is not skipped
#[serde(transparent)]
struct S {
- //~^^^ HELP: #[serde(transparent)] requires at least one field that is not skipped
#[serde(skip)]
a: u8,
}
diff --git a/test_suite/tests/compile-fail/type-attribute/from.rs b/test_suite/tests/compile-fail/type-attribute/from.rs
index 72e0f1de3..550d0973b 100644
--- a/test_suite/tests/compile-fail/type-attribute/from.rs
+++ b/test_suite/tests/compile-fail/type-attribute/from.rs
@@ -9,8 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
-#[serde(from = "Option<T")] //~^ HELP: failed to parse type: from = "Option<T"
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: failed to parse type: from = "Option<T"
+#[serde(from = "Option<T")]
enum TestOne {
Testing,
One,
diff --git a/test_suite/tests/compile-fail/type-attribute/into.rs b/test_suite/tests/compile-fail/type-attribute/into.rs
index 8f6de4d42..f1b2ae577 100644
--- a/test_suite/tests/compile-fail/type-attribute/into.rs
+++ b/test_suite/tests/compile-fail/type-attribute/into.rs
@@ -9,8 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-#[serde(into = "Option<T")] //~^ HELP: failed to parse type: into = "Option<T"
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: failed to parse type: into = "Option<T"
+#[serde(into = "Option<T")]
enum TestOne {
Testing,
One,
diff --git a/test_suite/tests/compile-fail/unknown-attribute/container.rs b/test_suite/tests/compile-fail/unknown-attribute/container.rs
index c60c99c1f..dfce43aab 100644
--- a/test_suite/tests/compile-fail/unknown-attribute/container.rs
+++ b/test_suite/tests/compile-fail/unknown-attribute/container.rs
@@ -9,8 +9,8 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-#[serde(abc="xyz")] //~^ HELP: unknown serde container attribute `abc`
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: unknown serde container attribute `abc`
+#[serde(abc="xyz")]
struct A {
x: u32,
}
diff --git a/test_suite/tests/compile-fail/unknown-attribute/field.rs b/test_suite/tests/compile-fail/unknown-attribute/field.rs
index 66c3a0a80..e4e96cbc8 100644
--- a/test_suite/tests/compile-fail/unknown-attribute/field.rs
+++ b/test_suite/tests/compile-fail/unknown-attribute/field.rs
@@ -9,9 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: unknown serde field attribute `abc`
struct C {
- #[serde(abc="xyz")] //~^^ HELP: unknown serde field attribute `abc`
+ #[serde(abc="xyz")]
x: u32,
}
diff --git a/test_suite/tests/compile-fail/unknown-attribute/variant.rs b/test_suite/tests/compile-fail/unknown-attribute/variant.rs
index 0cfac6275..9d179b205 100644
--- a/test_suite/tests/compile-fail/unknown-attribute/variant.rs
+++ b/test_suite/tests/compile-fail/unknown-attribute/variant.rs
@@ -9,9 +9,9 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: unknown serde variant attribute `abc`
enum E {
- #[serde(abc="xyz")] //~^^ HELP: unknown serde variant attribute `abc`
+ #[serde(abc="xyz")]
V,
}
diff --git a/test_suite/tests/compile-fail/with-variant/skip_de_newtype_field.rs b/test_suite/tests/compile-fail/with-variant/skip_de_newtype_field.rs
index b198f9af3..f783ca8bc 100644
--- a/test_suite/tests/compile-fail/with-variant/skip_de_newtype_field.rs
+++ b/test_suite/tests/compile-fail/with-variant/skip_de_newtype_field.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: variant `Newtype` cannot have both #[serde(deserialize_with)] and a field 0 marked with #[serde(skip_deserializing)]
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: variant `Newtype` cannot have both #[serde(deserialize_with)] and a field 0 marked with #[serde(skip_deserializing)]
enum Enum {
#[serde(deserialize_with = "deserialize_some_newtype_variant")]
Newtype(#[serde(skip_deserializing)] String),
diff --git a/test_suite/tests/compile-fail/with-variant/skip_de_struct_field.rs b/test_suite/tests/compile-fail/with-variant/skip_de_struct_field.rs
index 248389c94..eb96456f4 100644
--- a/test_suite/tests/compile-fail/with-variant/skip_de_struct_field.rs
+++ b/test_suite/tests/compile-fail/with-variant/skip_de_struct_field.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: variant `Struct` cannot have both #[serde(deserialize_with)] and a field `f1` marked with #[serde(skip_deserializing)]
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: variant `Struct` cannot have both #[serde(deserialize_with)] and a field `f1` marked with #[serde(skip_deserializing)]
enum Enum {
#[serde(deserialize_with = "deserialize_some_other_variant")]
Struct {
diff --git a/test_suite/tests/compile-fail/with-variant/skip_de_tuple_field.rs b/test_suite/tests/compile-fail/with-variant/skip_de_tuple_field.rs
index 7bdeddc45..5b5408d58 100644
--- a/test_suite/tests/compile-fail/with-variant/skip_de_tuple_field.rs
+++ b/test_suite/tests/compile-fail/with-variant/skip_de_tuple_field.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: variant `Tuple` cannot have both #[serde(deserialize_with)] and a field 0 marked with #[serde(skip_deserializing)]
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: variant `Tuple` cannot have both #[serde(deserialize_with)] and a field 0 marked with #[serde(skip_deserializing)]
enum Enum {
#[serde(deserialize_with = "deserialize_some_other_variant")]
Tuple(#[serde(skip_deserializing)] String, u8),
diff --git a/test_suite/tests/compile-fail/with-variant/skip_de_whole_variant.rs b/test_suite/tests/compile-fail/with-variant/skip_de_whole_variant.rs
index 2bf2b016c..d70b36a86 100644
--- a/test_suite/tests/compile-fail/with-variant/skip_de_whole_variant.rs
+++ b/test_suite/tests/compile-fail/with-variant/skip_de_whole_variant.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: variant `Unit` cannot have both #[serde(deserialize_with)] and #[serde(skip_deserializing)]
+#[derive(Deserialize)] //~ ERROR: 12:10: 12:21: variant `Unit` cannot have both #[serde(deserialize_with)] and #[serde(skip_deserializing)]
enum Enum {
#[serde(deserialize_with = "deserialize_some_unit_variant")]
#[serde(skip_deserializing)]
diff --git a/test_suite/tests/compile-fail/with-variant/skip_ser_newtype_field.rs b/test_suite/tests/compile-fail/with-variant/skip_ser_newtype_field.rs
index 58e4b1b10..fbebcc842 100644
--- a/test_suite/tests/compile-fail/with-variant/skip_ser_newtype_field.rs
+++ b/test_suite/tests/compile-fail/with-variant/skip_ser_newtype_field.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: variant `Newtype` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing)]
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: variant `Newtype` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing)]
enum Enum {
#[serde(serialize_with = "serialize_some_newtype_variant")]
Newtype(#[serde(skip_serializing)] String),
diff --git a/test_suite/tests/compile-fail/with-variant/skip_ser_newtype_field_if.rs b/test_suite/tests/compile-fail/with-variant/skip_ser_newtype_field_if.rs
index 61c3112f7..d46d2ccda 100644
--- a/test_suite/tests/compile-fail/with-variant/skip_ser_newtype_field_if.rs
+++ b/test_suite/tests/compile-fail/with-variant/skip_ser_newtype_field_if.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: variant `Newtype` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing_if)]
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: variant `Newtype` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing_if)]
enum Enum {
#[serde(serialize_with = "serialize_some_newtype_variant")]
Newtype(#[serde(skip_serializing_if = "always")] String),
diff --git a/test_suite/tests/compile-fail/with-variant/skip_ser_struct_field.rs b/test_suite/tests/compile-fail/with-variant/skip_ser_struct_field.rs
index 0149553cf..29997d052 100644
--- a/test_suite/tests/compile-fail/with-variant/skip_ser_struct_field.rs
+++ b/test_suite/tests/compile-fail/with-variant/skip_ser_struct_field.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: variant `Struct` cannot have both #[serde(serialize_with)] and a field `f1` marked with #[serde(skip_serializing)]
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: variant `Struct` cannot have both #[serde(serialize_with)] and a field `f1` marked with #[serde(skip_serializing)]
enum Enum {
#[serde(serialize_with = "serialize_some_other_variant")]
Struct {
diff --git a/test_suite/tests/compile-fail/with-variant/skip_ser_struct_field_if.rs b/test_suite/tests/compile-fail/with-variant/skip_ser_struct_field_if.rs
index 5f94ff83d..6a2a58bce 100644
--- a/test_suite/tests/compile-fail/with-variant/skip_ser_struct_field_if.rs
+++ b/test_suite/tests/compile-fail/with-variant/skip_ser_struct_field_if.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: variant `Struct` cannot have both #[serde(serialize_with)] and a field `f1` marked with #[serde(skip_serializing_if)]
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: variant `Struct` cannot have both #[serde(serialize_with)] and a field `f1` marked with #[serde(skip_serializing_if)]
enum Enum {
#[serde(serialize_with = "serialize_some_newtype_variant")]
Struct {
diff --git a/test_suite/tests/compile-fail/with-variant/skip_ser_tuple_field.rs b/test_suite/tests/compile-fail/with-variant/skip_ser_tuple_field.rs
index 51e2ce87e..eaf318ac0 100644
--- a/test_suite/tests/compile-fail/with-variant/skip_ser_tuple_field.rs
+++ b/test_suite/tests/compile-fail/with-variant/skip_ser_tuple_field.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: variant `Tuple` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing)]
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: variant `Tuple` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing)]
enum Enum {
#[serde(serialize_with = "serialize_some_other_variant")]
Tuple(#[serde(skip_serializing)] String, u8),
diff --git a/test_suite/tests/compile-fail/with-variant/skip_ser_tuple_field_if.rs b/test_suite/tests/compile-fail/with-variant/skip_ser_tuple_field_if.rs
index efd2e11e7..cae191a58 100644
--- a/test_suite/tests/compile-fail/with-variant/skip_ser_tuple_field_if.rs
+++ b/test_suite/tests/compile-fail/with-variant/skip_ser_tuple_field_if.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: variant `Tuple` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing_if)]
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: variant `Tuple` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing_if)]
enum Enum {
#[serde(serialize_with = "serialize_some_other_variant")]
Tuple(#[serde(skip_serializing_if = "always")] String, u8),
diff --git a/test_suite/tests/compile-fail/with-variant/skip_ser_whole_variant.rs b/test_suite/tests/compile-fail/with-variant/skip_ser_whole_variant.rs
index 0446770e8..55c5d27dc 100644
--- a/test_suite/tests/compile-fail/with-variant/skip_ser_whole_variant.rs
+++ b/test_suite/tests/compile-fail/with-variant/skip_ser_whole_variant.rs
@@ -9,8 +9,7 @@
#[macro_use]
extern crate serde_derive;
-#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
-//~^ HELP: variant `Unit` cannot have both #[serde(serialize_with)] and #[serde(skip_serializing)]
+#[derive(Serialize)] //~ ERROR: 12:10: 12:19: variant `Unit` cannot have both #[serde(serialize_with)] and #[serde(skip_serializing)]
enum Enum {
#[serde(serialize_with = "serialize_some_unit_variant")]
#[serde(skip_serializing)]
| [
"1168"
] | serde-rs__serde-1297 | Use compile_error macro to report invalid attribute errors
Currently we use [`Ctxt`](https://github.com/serde-rs/serde/blob/v1.0.27/serde_derive_internals/src/ctxt.rs) in `serde_derive_internals` to batch up errors detected during the attribute parsing step of `serde_derive`, then panic with the resulting message in [`derive_serialize` and `derive_deserialize`](https://github.com/serde-rs/serde/blob/v1.0.27/serde_derive/src/lib.rs).
```rust
#[derive(Serialize)]
struct S {
#[serde(typo, with = 1)]
field: String,
}
```
```
error: proc-macro derive panicked
--> src/main.rs:4:10
|
4 | #[derive(Serialize)]
| ^^^^^^^^^
|
= help: message: 2 errors:
# unknown serde field attribute `typo`
# expected serde with attribute to be a string: `with = "..."`
```
It would be better to use [`std::compile_error!`](https://doc.rust-lang.org/std/macro.compile_error.html) instead of a panic. The resulting user-visible error message can be rendered more nicely.
The `compile_error!` macro was stabilized in Rust 1.20 and we currently support older Rust versions than that, but it would not be a breaking change to begin using `compile_error!` and I am comfortable doing so. In the worst case somebody's code failed to compile before the change and then fails to compile a slightly different way after the change.
| 1.0 | dbaf2893e32a72f9564757b0f95bf9f7869bd900 | diff --git a/serde_derive/src/lib.rs b/serde_derive/src/lib.rs
index 708f3bf46..65886bf1e 100644
--- a/serde_derive/src/lib.rs
+++ b/serde_derive/src/lib.rs
@@ -53,6 +53,7 @@ extern crate proc_macro2;
mod internals;
+use std::str::FromStr;
use proc_macro::TokenStream;
use syn::DeriveInput;
@@ -71,7 +72,7 @@ pub fn derive_serialize(input: TokenStream) -> TokenStream {
let input: DeriveInput = syn::parse(input).unwrap();
match ser::expand_derive_serialize(&input) {
Ok(expanded) => expanded.into(),
- Err(msg) => panic!(msg),
+ Err(msg) => quote! {compile_error!(#msg);}.into(),
}
}
@@ -80,6 +81,6 @@ pub fn derive_deserialize(input: TokenStream) -> TokenStream {
let input: DeriveInput = syn::parse(input).unwrap();
match de::expand_derive_deserialize(&input) {
Ok(expanded) => expanded.into(),
- Err(msg) => panic!(msg),
+ Err(msg) => quote! {compile_error!(#msg);}.into(),
}
}
| serde-rs/serde | 2018-06-01T03:19:31Z | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 | |
1,288 | diff --git a/test_suite/tests/test_value.rs b/test_suite/tests/test_value.rs
index 80554663c..d2d9e67c0 100644
--- a/test_suite/tests/test_value.rs
+++ b/test_suite/tests/test_value.rs
@@ -32,14 +32,14 @@ fn test_integer128() {
let de_i128 = IntoDeserializer::<value::Error>::into_deserializer(1i128);
// u128 to u128
- assert_eq!(1u128, u128::deserialize(de_u128.clone()).unwrap());
+ assert_eq!(1u128, u128::deserialize(de_u128).unwrap());
// u128 to i128
- assert_eq!(1i128, i128::deserialize(de_u128.clone()).unwrap());
+ assert_eq!(1i128, i128::deserialize(de_u128).unwrap());
// i128 to u128
- assert_eq!(1u128, u128::deserialize(de_i128.clone()).unwrap());
+ assert_eq!(1u128, u128::deserialize(de_i128).unwrap());
// i128 to i128
- assert_eq!(1i128, i128::deserialize(de_i128.clone()).unwrap());
+ assert_eq!(1i128, i128::deserialize(de_i128).unwrap());
}
| [
"1287"
] | serde-rs__serde-1288 | Implement Copy for the primitive value deserializers
https://docs.serde.rs/serde/de/value/index.html
The primitive deserializers (I8Deserializer, I16Deserializer, etc) only wrap only wrap a value of their primitive type and a phantom data for the error type, so it should be fine to allow copying.
| 1.0 | cd0b2d312c00dd9763aa62062180e3fba2a74b9d | diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index d08bae3b2..56ed7c57f 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -44,6 +44,22 @@ use ser;
////////////////////////////////////////////////////////////////////////////////
+// For structs that contain a PhantomData. We do not want the trait
+// bound `E: Clone` inferred by derive(Clone).
+macro_rules! impl_copy_clone {
+ ($ty:ident $(<$lifetime:tt>)*) => {
+ impl<$($lifetime,)* E> Copy for $ty<$($lifetime,)* E> {}
+
+ impl<$($lifetime,)* E> Clone for $ty<$($lifetime,)* E> {
+ fn clone(&self) -> Self {
+ *self
+ }
+ }
+ };
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
/// A minimal representation of all possible errors that can occur using the
/// `IntoDeserializer` trait.
#[derive(Clone, Debug, PartialEq)]
@@ -124,11 +140,13 @@ where
}
/// A deserializer holding a `()`.
-#[derive(Clone, Debug)]
+#[derive(Debug)]
pub struct UnitDeserializer<E> {
marker: PhantomData<E>,
}
+impl_copy_clone!(UnitDeserializer);
+
impl<'de, E> de::Deserializer<'de> for UnitDeserializer<E>
where
E: de::Error,
@@ -162,12 +180,14 @@ macro_rules! primitive_deserializer {
($ty:ty, $doc:tt, $name:ident, $method:ident $($cast:tt)*) => {
#[doc = "A deserializer holding"]
#[doc = $doc]
- #[derive(Clone, Debug)]
+ #[derive(Debug)]
pub struct $name<E> {
value: $ty,
marker: PhantomData<E>
}
+ impl_copy_clone!($name);
+
impl<'de, E> IntoDeserializer<'de, E> for $ty
where
E: de::Error,
@@ -224,12 +244,14 @@ serde_if_integer128! {
}
/// A deserializer holding a `u32`.
-#[derive(Clone, Debug)]
+#[derive(Debug)]
pub struct U32Deserializer<E> {
value: u32,
marker: PhantomData<E>,
}
+impl_copy_clone!(U32Deserializer);
+
impl<'de, E> IntoDeserializer<'de, E> for u32
where
E: de::Error,
@@ -296,12 +318,14 @@ where
////////////////////////////////////////////////////////////////////////////////
/// A deserializer holding a `&str`.
-#[derive(Clone, Debug)]
+#[derive(Debug)]
pub struct StrDeserializer<'a, E> {
value: &'a str,
marker: PhantomData<E>,
}
+impl_copy_clone!(StrDeserializer<'de>);
+
impl<'de, 'a, E> IntoDeserializer<'de, E> for &'a str
where
E: de::Error,
@@ -369,12 +393,14 @@ where
/// A deserializer holding a `&str` with a lifetime tied to another
/// deserializer.
-#[derive(Clone, Debug)]
+#[derive(Debug)]
pub struct BorrowedStrDeserializer<'de, E> {
value: &'de str,
marker: PhantomData<E>,
}
+impl_copy_clone!(BorrowedStrDeserializer<'de>);
+
impl<'de, E> BorrowedStrDeserializer<'de, E> {
/// Create a new borrowed deserializer from the given string.
pub fn new(value: &'de str) -> BorrowedStrDeserializer<'de, E> {
@@ -438,12 +464,22 @@ where
/// A deserializer holding a `String`.
#[cfg(any(feature = "std", feature = "alloc"))]
-#[derive(Clone, Debug)]
+#[derive(Debug)]
pub struct StringDeserializer<E> {
value: String,
marker: PhantomData<E>,
}
+#[cfg(any(feature = "std", feature = "alloc"))]
+impl<E> Clone for StringDeserializer<E> {
+ fn clone(&self) -> Self {
+ StringDeserializer {
+ value: self.value.clone(),
+ marker: PhantomData,
+ }
+ }
+}
+
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'de, E> IntoDeserializer<'de, E> for String
where
@@ -514,12 +550,22 @@ where
/// A deserializer holding a `Cow<str>`.
#[cfg(any(feature = "std", feature = "alloc"))]
-#[derive(Clone, Debug)]
+#[derive(Debug)]
pub struct CowStrDeserializer<'a, E> {
value: Cow<'a, str>,
marker: PhantomData<E>,
}
+#[cfg(any(feature = "std", feature = "alloc"))]
+impl<'a, E> Clone for CowStrDeserializer<'a, E> {
+ fn clone(&self) -> Self {
+ CowStrDeserializer {
+ value: self.value.clone(),
+ marker: PhantomData,
+ }
+ }
+}
+
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'de, 'a, E> IntoDeserializer<'de, E> for Cow<'a, str>
where
@@ -593,12 +639,14 @@ where
/// A deserializer holding a `&[u8]` with a lifetime tied to another
/// deserializer.
-#[derive(Clone, Debug)]
+#[derive(Debug)]
pub struct BorrowedBytesDeserializer<'de, E> {
value: &'de [u8],
marker: PhantomData<E>,
}
+impl_copy_clone!(BorrowedBytesDeserializer<'de>);
+
impl<'de, E> BorrowedBytesDeserializer<'de, E> {
/// Create a new borrowed deserializer from the given byte slice.
pub fn new(value: &'de [u8]) -> BorrowedBytesDeserializer<'de, E> {
| serde-rs/serde | 2018-05-26T22:49:24Z | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 | |
1,286 | diff --git a/test_suite/tests/test_value.rs b/test_suite/tests/test_value.rs
index acd3ddd6c..80554663c 100644
--- a/test_suite/tests/test_value.rs
+++ b/test_suite/tests/test_value.rs
@@ -25,3 +25,21 @@ fn test_u32_to_enum() {
let e: E = E::deserialize(deserializer).unwrap();
assert_eq!(E::B, e);
}
+
+#[test]
+fn test_integer128() {
+ let de_u128 = IntoDeserializer::<value::Error>::into_deserializer(1u128);
+ let de_i128 = IntoDeserializer::<value::Error>::into_deserializer(1i128);
+
+ // u128 to u128
+ assert_eq!(1u128, u128::deserialize(de_u128.clone()).unwrap());
+
+ // u128 to i128
+ assert_eq!(1i128, i128::deserialize(de_u128.clone()).unwrap());
+
+ // i128 to u128
+ assert_eq!(1u128, u128::deserialize(de_i128.clone()).unwrap());
+
+ // i128 to i128
+ assert_eq!(1i128, i128::deserialize(de_i128.clone()).unwrap());
+}
| [
"1280"
] | serde-rs__serde-1286 | Implement IntoDeserializer for i128 and u128
| 1.0 | 7407d71417bc7a72c0a61f2c2f595db517457de9 | diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 101531b3d..d08bae3b2 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -218,6 +218,11 @@ primitive_deserializer!(f32, "an `f32`.", F32Deserializer, visit_f32);
primitive_deserializer!(f64, "an `f64`.", F64Deserializer, visit_f64);
primitive_deserializer!(char, "a `char`.", CharDeserializer, visit_char);
+serde_if_integer128! {
+ primitive_deserializer!(i128, "an `i128`.", I128Deserializer, visit_i128);
+ primitive_deserializer!(u128, "a `u128`.", U128Deserializer, visit_u128);
+}
+
/// A deserializer holding a `u32`.
#[derive(Clone, Debug)]
pub struct U32Deserializer<E> {
| serde-rs/serde | 2018-05-26T22:22:38Z | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 | |
1,270 | diff --git a/test_suite/tests/compile-fail/transparent/at_most_one.rs b/test_suite/tests/compile-fail/transparent/at_most_one.rs
new file mode 100644
index 000000000..d5b7dae89
--- /dev/null
+++ b/test_suite/tests/compile-fail/transparent/at_most_one.rs
@@ -0,0 +1,20 @@
+// 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
+#[serde(transparent)]
+struct S {
+ //~^^^ HELP: #[serde(transparent)] requires struct to have at most one transparent field
+ a: u8,
+ b: u8,
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/transparent/de_at_least_one.rs b/test_suite/tests/compile-fail/transparent/de_at_least_one.rs
new file mode 100644
index 000000000..a1abe4746
--- /dev/null
+++ b/test_suite/tests/compile-fail/transparent/de_at_least_one.rs
@@ -0,0 +1,22 @@
+// 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
+#[serde(transparent)]
+struct S {
+ //~^^^ HELP: #[serde(transparent)] requires at least one field that is neither skipped nor has a default
+ #[serde(skip)]
+ a: u8,
+ #[serde(default)]
+ b: u8,
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/transparent/ser_at_least_one.rs b/test_suite/tests/compile-fail/transparent/ser_at_least_one.rs
new file mode 100644
index 000000000..19dd59c17
--- /dev/null
+++ b/test_suite/tests/compile-fail/transparent/ser_at_least_one.rs
@@ -0,0 +1,20 @@
+// 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
+#[serde(transparent)]
+struct S {
+ //~^^^ HELP: #[serde(transparent)] requires at least one field that is not skipped
+ #[serde(skip)]
+ a: u8,
+}
+
+fn main() {}
diff --git a/test_suite/tests/test_annotations.rs b/test_suite/tests/test_annotations.rs
index 5b82ad88d..aea692cba 100644
--- a/test_suite/tests/test_annotations.rs
+++ b/test_suite/tests/test_annotations.rs
@@ -15,6 +15,7 @@ extern crate serde;
use self::serde::de::{self, Unexpected};
use self::serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;
+use std::marker::PhantomData;
extern crate serde_test;
use self::serde_test::{
@@ -2161,3 +2162,41 @@ fn test_flatten_option() {
&[Token::Map { len: None }, Token::MapEnd],
);
}
+
+#[test]
+fn test_transparent_struct() {
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
+ #[serde(transparent)]
+ struct Transparent {
+ #[serde(skip)]
+ a: bool,
+ b: u32,
+ #[serde(skip)]
+ c: bool,
+ d: PhantomData<()>,
+ }
+
+ assert_tokens(
+ &Transparent {
+ a: false,
+ b: 1,
+ c: false,
+ d: PhantomData,
+ },
+ &[Token::U32(1)],
+ );
+}
+
+#[test]
+fn test_transparent_tuple_struct() {
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
+ #[serde(transparent)]
+ struct Transparent(
+ #[serde(skip)] bool,
+ u32,
+ #[serde(skip)] bool,
+ PhantomData<()>,
+ );
+
+ assert_tokens(&Transparent(false, 1, false, PhantomData), &[Token::U32(1)]);
+}
diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index ffb73210a..ef301b590 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -653,6 +653,14 @@ fn test_gen() {
X,
),
}
+
+ #[derive(Serialize, Deserialize)]
+ #[serde(transparent)]
+ struct TransparentWith {
+ #[serde(serialize_with = "ser_x")]
+ #[serde(deserialize_with = "de_x")]
+ x: X,
+ }
}
//////////////////////////////////////////////////////////////////////////
| [
"1054"
] | serde-rs__serde-1270 | Attribute to specify that type representation is the same as its only field
By analogy with [`#[repr(transparent)]`](https://github.com/rust-lang/rfcs/blob/master/text/1758-repr-transparent.md).
```rust
// This should serialize and deserialize directly as String, rather than as newtype.
#[derive(Serialize, Deserialize)]
#[serde(transparent)]
struct Transparent(String);
// Generated code.
impl Serialize for Transparent {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
self.0.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Transparent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
Deserialize::deserialize(deserializer).map(Transparent)
}
}
```
Should also work for structs with one field, and structs and tuple structs with all but one skipped field.
@bluss
| 1.0 | 320897679b3bff07d2e54aa96525422237b6e832 | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 875c941a7..ad105398d 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -15,7 +15,7 @@ use syn::{self, Ident, Index, Member};
use bound;
use fragment::{Expr, Fragment, Match, Stmts};
use internals::ast::{Container, Data, Field, Style, Variant};
-use internals::{attr, Ctxt};
+use internals::{attr, Ctxt, Derive};
use pretend;
use try;
@@ -23,7 +23,7 @@ use std::collections::BTreeSet;
pub fn expand_derive_deserialize(input: &syn::DeriveInput) -> Result<TokenStream, String> {
let ctxt = Ctxt::new();
- let cont = Container::from_ast(&ctxt, input);
+ let cont = Container::from_ast(&ctxt, input, Derive::Deserialize);
precondition(&ctxt, &cont);
try!(ctxt.check());
@@ -269,7 +269,9 @@ fn borrowed_lifetimes(cont: &Container) -> BorrowedLifetimes {
}
fn deserialize_body(cont: &Container, params: &Parameters) -> Fragment {
- if let Some(type_from) = cont.attrs.type_from() {
+ if cont.attrs.transparent() {
+ deserialize_transparent(cont, params)
+ } else if let Some(type_from) = cont.attrs.type_from() {
deserialize_from(type_from)
} else if let attr::Identifier::No = cont.attrs.identifier() {
match cont.data {
@@ -298,7 +300,9 @@ fn deserialize_in_place_body(cont: &Container, params: &Parameters) -> Option<St
// deserialize_in_place for remote derives.
assert!(!params.has_getter);
- if cont.attrs.type_from().is_some() || cont.attrs.identifier().is_some()
+ if cont.attrs.transparent()
+ || cont.attrs.type_from().is_some()
+ || cont.attrs.identifier().is_some()
|| cont
.data
.all_fields()
@@ -344,6 +348,41 @@ fn deserialize_in_place_body(_cont: &Container, _params: &Parameters) -> Option<
None
}
+fn deserialize_transparent(cont: &Container, params: &Parameters) -> Fragment {
+ let fields = match cont.data {
+ Data::Struct(_, ref fields) => fields,
+ Data::Enum(_) => unreachable!(),
+ };
+
+ let this = ¶ms.this;
+ let transparent_field = fields.iter().find(|f| f.attrs.transparent()).unwrap();
+
+ let path = match transparent_field.attrs.deserialize_with() {
+ Some(path) => quote!(#path),
+ None => quote!(_serde::Deserialize::deserialize),
+ };
+
+ let assign = fields.iter().map(|field| {
+ let member = &field.member;
+ if field as *const Field == transparent_field as *const Field {
+ quote!(#member: __transparent)
+ } else {
+ let value = match *field.attrs.default() {
+ attr::Default::Default => quote!(_serde::export::Default::default()),
+ attr::Default::Path(ref path) => quote!(#path()),
+ attr::Default::None => quote!(_serde::export::PhantomData),
+ };
+ quote!(#member: #value)
+ }
+ });
+
+ quote_block! {
+ _serde::export::Result::map(
+ #path(__deserializer),
+ |__transparent| #this { #(#assign),* })
+ }
+}
+
fn deserialize_from(type_from: &syn::Type) -> Fragment {
quote_block! {
_serde::export::Result::map(
diff --git a/serde_derive/src/internals/ast.rs b/serde_derive/src/internals/ast.rs
index 093910d77..ce1d3197f 100644
--- a/serde_derive/src/internals/ast.rs
+++ b/serde_derive/src/internals/ast.rs
@@ -8,7 +8,7 @@
use internals::attr;
use internals::check;
-use internals::Ctxt;
+use internals::{Ctxt, Derive};
use syn;
use syn::punctuated::Punctuated;
@@ -47,7 +47,7 @@ pub enum Style {
}
impl<'a> Container<'a> {
- pub fn from_ast(cx: &Ctxt, item: &'a syn::DeriveInput) -> Container<'a> {
+ pub fn from_ast(cx: &Ctxt, item: &'a syn::DeriveInput, derive: Derive) -> Container<'a> {
let mut attrs = attr::Container::from_ast(cx, item);
let mut data = match item.data {
@@ -86,13 +86,13 @@ impl<'a> Container<'a> {
attrs.mark_has_flatten();
}
- let item = Container {
+ let mut item = Container {
ident: item.ident.clone(),
attrs: attrs,
data: data,
generics: &item.generics,
};
- check::check(cx, &item);
+ check::check(cx, &mut item, derive);
item
}
}
diff --git a/serde_derive/src/internals/attr.rs b/serde_derive/src/internals/attr.rs
index 43c689a0a..abfb005b5 100644
--- a/serde_derive/src/internals/attr.rs
+++ b/serde_derive/src/internals/attr.rs
@@ -105,6 +105,7 @@ impl Name {
/// Represents container (e.g. struct) attribute information
pub struct Container {
name: Name,
+ transparent: bool,
deny_unknown_fields: bool,
default: Default,
rename_all: RenameRule,
@@ -181,6 +182,7 @@ impl Container {
pub fn from_ast(cx: &Ctxt, item: &syn::DeriveInput) -> Self {
let mut ser_name = Attr::none(cx, "rename");
let mut de_name = Attr::none(cx, "rename");
+ let mut transparent = BoolAttr::none(cx, "transparent");
let mut deny_unknown_fields = BoolAttr::none(cx, "deny_unknown_fields");
let mut default = Attr::none(cx, "default");
let mut rename_all = Attr::none(cx, "rename_all");
@@ -228,6 +230,11 @@ impl Container {
}
}
+ // Parse `#[serde(transparent)]`
+ Meta(Word(ref word)) if word == "transparent" => {
+ transparent.set_true();
+ }
+
// Parse `#[serde(deny_unknown_fields)]`
Meta(Word(ref word)) if word == "deny_unknown_fields" => {
deny_unknown_fields.set_true();
@@ -376,6 +383,7 @@ impl Container {
serialize: ser_name.get().unwrap_or_else(|| item.ident.to_string()),
deserialize: de_name.get().unwrap_or_else(|| item.ident.to_string()),
},
+ transparent: transparent.get(),
deny_unknown_fields: deny_unknown_fields.get(),
default: default.get().unwrap_or(Default::None),
rename_all: rename_all.get().unwrap_or(RenameRule::None),
@@ -398,6 +406,10 @@ impl Container {
&self.rename_all
}
+ pub fn transparent(&self) -> bool {
+ self.transparent
+ }
+
pub fn deny_unknown_fields(&self) -> bool {
self.deny_unknown_fields
}
@@ -764,6 +776,7 @@ pub struct Field {
borrowed_lifetimes: BTreeSet<syn::Lifetime>,
getter: Option<syn::ExprPath>,
flatten: bool,
+ transparent: bool,
}
/// Represents the default to use for a field when deserializing.
@@ -777,7 +790,6 @@ pub enum Default {
}
impl Default {
- #[cfg(feature = "deserialize_in_place")]
pub fn is_none(&self) -> bool {
match *self {
Default::None => true,
@@ -1066,6 +1078,7 @@ impl Field {
borrowed_lifetimes: borrowed_lifetimes,
getter: getter.get(),
flatten: flatten.get(),
+ transparent: false,
}
}
@@ -1125,6 +1138,14 @@ impl Field {
pub fn flatten(&self) -> bool {
self.flatten
}
+
+ pub fn transparent(&self) -> bool {
+ self.transparent
+ }
+
+ pub fn mark_transparent(&mut self) {
+ self.transparent = true;
+ }
}
type SerAndDe<T> = (Option<T>, Option<T>);
diff --git a/serde_derive/src/internals/check.rs b/serde_derive/src/internals/check.rs
index eac1c2293..0caa4b502 100644
--- a/serde_derive/src/internals/check.rs
+++ b/serde_derive/src/internals/check.rs
@@ -8,18 +8,19 @@
use internals::ast::{Container, Data, Field, Style};
use internals::attr::{EnumTag, Identifier};
-use internals::Ctxt;
-use syn::Member;
+use internals::{Ctxt, Derive};
+use syn::{Member, Type};
/// Cross-cutting checks that require looking at more than a single attrs
/// object. Simpler checks should happen when parsing and building the attrs.
-pub fn check(cx: &Ctxt, cont: &Container) {
+pub fn check(cx: &Ctxt, cont: &mut Container, derive: Derive) {
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);
check_adjacent_tag_conflict(cx, cont);
+ check_transparent(cx, cont, derive);
}
/// Getters are only allowed inside structs (not enums) with the `remote`
@@ -278,9 +279,75 @@ fn check_adjacent_tag_conflict(cx: &Ctxt, cont: &Container) {
}
}
+/// Enums and unit structs cannot be transparent.
+fn check_transparent(cx: &Ctxt, cont: &mut Container, derive: Derive) {
+ if !cont.attrs.transparent() {
+ return;
+ }
+
+ if cont.attrs.type_from().is_some() {
+ cx.error("#[serde(transparent)] is not allowed with #[serde(from = \"...\")]");
+ }
+
+ if cont.attrs.type_into().is_some() {
+ cx.error("#[serde(transparent)] is not allowed with #[serde(into = \"...\")]");
+ }
+
+ let fields = match cont.data {
+ Data::Enum(_) => {
+ cx.error("#[serde(transparent)] is not allowed on an enum");
+ return;
+ }
+ Data::Struct(Style::Unit, _) => {
+ cx.error("#[serde(transparent)] is not allowed on a unit struct");
+ return;
+ }
+ Data::Struct(_, ref mut fields) => fields,
+ };
+
+ let mut transparent_field = None;
+
+ for field in fields {
+ if allow_transparent(field, derive) {
+ if transparent_field.is_some() {
+ cx.error("#[serde(transparent)] requires struct to have at most one transparent field");
+ return;
+ }
+ transparent_field = Some(field);
+ }
+ }
+
+ match transparent_field {
+ Some(transparent_field) => transparent_field.attrs.mark_transparent(),
+ None => match derive {
+ Derive::Serialize => {
+ cx.error("#[serde(transparent)] requires at least one field that is not skipped");
+ }
+ Derive::Deserialize => {
+ cx.error("#[serde(transparent)] requires at least one field that is neither skipped nor has a default");
+ }
+ }
+ }
+}
+
fn member_message(member: &Member) -> String {
match *member {
Member::Named(ref ident) => format!("`{}`", ident),
Member::Unnamed(ref i) => i.index.to_string(),
}
}
+
+fn allow_transparent(field: &Field, derive: Derive) -> bool {
+ if let Type::Path(ref ty) = *field.ty {
+ if let Some(seg) = ty.path.segments.last() {
+ if seg.into_value().ident == "PhantomData" {
+ return false;
+ }
+ }
+ }
+
+ match derive {
+ Derive::Serialize => !field.attrs.skip_serializing(),
+ Derive::Deserialize => !field.attrs.skip_deserializing() && field.attrs.default().is_none(),
+ }
+}
diff --git a/serde_derive/src/internals/mod.rs b/serde_derive/src/internals/mod.rs
index f68462c9e..7a39688da 100644
--- a/serde_derive/src/internals/mod.rs
+++ b/serde_derive/src/internals/mod.rs
@@ -14,3 +14,9 @@ pub use self::ctxt::Ctxt;
mod case;
mod check;
+
+#[derive(Copy, Clone)]
+pub enum Derive {
+ Serialize,
+ Deserialize,
+}
diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index 11e5b4835..c78237bf9 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -13,13 +13,13 @@ use syn::{self, Ident, Index, Member};
use bound;
use fragment::{Fragment, Match, Stmts};
use internals::ast::{Container, Data, Field, Style, Variant};
-use internals::{attr, Ctxt};
+use internals::{attr, Ctxt, Derive};
use pretend;
use try;
pub fn expand_derive_serialize(input: &syn::DeriveInput) -> Result<TokenStream, String> {
let ctxt = Ctxt::new();
- let cont = Container::from_ast(&ctxt, input);
+ let cont = Container::from_ast(&ctxt, input, Derive::Serialize);
precondition(&ctxt, &cont);
try!(ctxt.check());
@@ -166,7 +166,9 @@ fn needs_serialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -
}
fn serialize_body(cont: &Container, params: &Parameters) -> Fragment {
- if let Some(type_into) = cont.attrs.type_into() {
+ if cont.attrs.transparent() {
+ serialize_transparent(cont, params)
+ } else if let Some(type_into) = cont.attrs.type_into() {
serialize_into(params, type_into)
} else {
match cont.data {
@@ -185,6 +187,26 @@ fn serialize_body(cont: &Container, params: &Parameters) -> Fragment {
}
}
+fn serialize_transparent(cont: &Container, params: &Parameters) -> Fragment {
+ let fields = match cont.data {
+ Data::Struct(_, ref fields) => fields,
+ Data::Enum(_) => unreachable!(),
+ };
+
+ let self_var = ¶ms.self_var;
+ let transparent_field = fields.iter().find(|f| f.attrs.transparent()).unwrap();
+ let member = &transparent_field.member;
+
+ let path = match transparent_field.attrs.serialize_with() {
+ Some(path) => quote!(#path),
+ None => quote!(_serde::Serialize::serialize),
+ };
+
+ quote_block! {
+ #path(&#self_var.#member, __serializer)
+ }
+}
+
fn serialize_into(params: &Parameters, type_into: &syn::Type) -> Fragment {
let self_var = ¶ms.self_var;
quote_block! {
| serde-rs/serde | 2018-05-20T20:54:37Z | Can this attribute also be used to inline the fields of a struct member type into the parent struct for the purpose of (de)serialization?
Like this:
```rust
#[derive(Serialize, Deserialize)]
struct Common {
a: i32,
}
#[derive(Serialize, Deserialize)]
struct Foo {
#[serde(transparent)]
common: Common,
foo: u8,
}
#[derive(Serialize, Deserialize)]
struct Bar {
#[serde(transparent)]
common: Common,
bar: u64,
}
```
Ah, nvm, I found out that it's `#[serde(flatten)]`.. | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,269 | diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index 7888f2d82..ffb73210a 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -643,6 +643,16 @@ fn test_gen() {
struct ImpliciltyBorrowedOption<'a> {
option: std::option::Option<&'a str>,
}
+
+ #[derive(Serialize, Deserialize)]
+ #[serde(untagged)]
+ enum UntaggedNewtypeVariantWith {
+ Newtype(
+ #[serde(serialize_with = "ser_x")]
+ #[serde(deserialize_with = "de_x")]
+ X,
+ ),
+ }
}
//////////////////////////////////////////////////////////////////////////
| [
"1268"
] | serde-rs__serde-1269 | serde_derive deserialize_with untagged enum regression
I still need to create a simple reproduction for the issue, and not sure if this is covered by another issue report, but effectively...
```rust
#[derive(Deserialize)]
#[serde(untagged)]
enum E {
Variant(
#[serde(deserialize_with="...")]
Ty
),
}
```
Now fails to compile with a type mismatch error where it used to work properly. Moving the attribute outside of the variant (`#[serde(deserialize_with="...")] Variant(Ty)`) seems to work on both and I believe should be equivalent and a valid workaround for now? Tested with serde_derive v1.0.29 (worked) and v1.0.57 (broken).
| 1.0 | f09320b2932972e55317bf2899f69cab038f4377 | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 40a5d1050..3cce5f071 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -1802,10 +1802,8 @@ fn deserialize_untagged_newtype_variant(
}
Some(path) => {
quote_block! {
- let __value: #field_ty = _serde::export::Result::map(
- #path(#deserializer),
- #this::#variant_ident);
- __value
+ let __value: _serde::export::Result<#field_ty, _> = #path(#deserializer);
+ _serde::export::Result::map(__value, #this::#variant_ident)
}
}
}
| serde-rs/serde | 2018-05-20T00:21:09Z | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 | |
1,256 | diff --git a/test_suite/tests/test_annotations.rs b/test_suite/tests/test_annotations.rs
index 248e42118..7aaa97d5b 100644
--- a/test_suite/tests/test_annotations.rs
+++ b/test_suite/tests/test_annotations.rs
@@ -2095,3 +2095,84 @@ fn test_flatten_untagged_enum() {
],
);
}
+
+#[test]
+fn test_flatten_option() {
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
+ struct Outer {
+ #[serde(flatten)]
+ inner1: Option<Inner1>,
+ #[serde(flatten)]
+ inner2: Option<Inner2>,
+ }
+
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
+ struct Inner1 {
+ inner1: i32,
+ }
+
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
+ struct Inner2 {
+ inner2: i32,
+ }
+
+ assert_tokens(
+ &Outer {
+ inner1: Some(Inner1 {
+ inner1: 1,
+ }),
+ inner2: Some(Inner2 {
+ inner2: 2,
+ }),
+ },
+ &[
+ Token::Map { len: None },
+ Token::Str("inner1"),
+ Token::I32(1),
+ Token::Str("inner2"),
+ Token::I32(2),
+ Token::MapEnd,
+ ],
+ );
+
+ assert_tokens(
+ &Outer {
+ inner1: Some(Inner1 {
+ inner1: 1,
+ }),
+ inner2: None,
+ },
+ &[
+ Token::Map { len: None },
+ Token::Str("inner1"),
+ Token::I32(1),
+ Token::MapEnd,
+ ],
+ );
+
+ assert_tokens(
+ &Outer {
+ inner1: None,
+ inner2: Some(Inner2 {
+ inner2: 2,
+ }),
+ },
+ &[
+ Token::Map { len: None },
+ Token::Str("inner2"),
+ Token::I32(2),
+ Token::MapEnd,
+ ],
+ );
+
+ assert_tokens(
+ &Outer {
+ inner1: None,
+ inner2: None,
+ },
+ &[
+ Token::Map { len: None },
+ Token::MapEnd,
+ ],
+ );
+}
| [
"1255"
] | serde-rs__serde-1256 | Allow flattened untagged Options in struct fields
I have a small use case for `#[serde(flatten)]` that did not work as I expected due to the intermediary presence of an `Option` type. Here's what I mean:
```
#[derive(Serialize, Deserialize)]
enum Quux {
A,
B,
C,
}
#[derive(Serialize, Deserialize)]
struct Bar {
quux: Quux,
}
#[derive(Serialize, Deserialize)]
struct Foo {
baz: i32,
#[serde(flatten)]
bar: Option<Bar>,
}
fn main() {
let f : Foo = serde_json::from_str(r#"{
"baz": 10,
"quux": "A"
}"#).unwrap(); // panics unwrapping 'Error("can only flatten structs and maps", line: 4, column: 5)'
}
```
I'm able to get around this problem by using my own untagged `Option` type.
```
#[derive(Serialize, Deserialize)]
enum Quux {
A,
B,
C,
}
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum OptBar {
Some(Bar),
None,
}
#[derive(Serialize, Deserialize)]
struct Bar {
quux: Quux,
}
#[derive(Serialize, Deserialize)]
struct Foo {
baz: i32,
#[serde(flatten)]
bar: OptBar,
}
fn main() {
let f : Foo = serde_json::from_str(r#"{
"n": 10,
"quux": "A"
}"#).unwrap(); // returns a 'Foo { n: 10, bar: Some(Bar { quux: A }) }'
}
```
Is there any way to get around this otherwise? Continuing to use the standard `Option` type allows some more straightforward checking of `Foo.bar`, which is quite useful. Worst case scenario I can change my data representation.
| 1.0 | 35aae92b5609dc0707bea73a890ed0beb5c8cac0 | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index b13800dca..59f667ed7 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -529,6 +529,14 @@ where
{
T::deserialize(deserializer).map(Some)
}
+
+ #[doc(hidden)]
+ fn __private_visit_untagged_option<D>(self, deserializer: D) -> Result<Self::Value, ()>
+ where
+ D: Deserializer<'de>,
+ {
+ Ok(T::deserialize(deserializer).ok())
+ }
}
impl<'de, T> Deserialize<'de> for Option<T>
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index 826662dfa..fbc24016e 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -1529,6 +1529,15 @@ pub trait Visitor<'de>: Sized {
let _ = data;
Err(Error::invalid_type(Unexpected::Enum, &self))
}
+
+ // Used when deserializing a flattened Option field. Not public API.
+ #[doc(hidden)]
+ fn __private_visit_untagged_option<D>(self, _: D) -> Result<Self::Value, ()>
+ where
+ D: Deserializer<'de>,
+ {
+ Err(())
+ }
}
////////////////////////////////////////////////////////////////////////////////
diff --git a/serde/src/private/de.rs b/serde/src/private/de.rs
index dcf5008f5..fab85534c 100644
--- a/serde/src/private/de.rs
+++ b/serde/src/private/de.rs
@@ -2645,10 +2645,7 @@ impl<'a, 'de, E> FlatMapDeserializer<'a, 'de, E>
where
E: Error,
{
- fn deserialize_other<V>(self, _: V) -> Result<V::Value, E>
- where
- V: Visitor<'de>,
- {
+ fn deserialize_other<V>() -> Result<V, E> {
Err(Error::custom("can only flatten structs and maps"))
}
}
@@ -2657,11 +2654,11 @@ where
macro_rules! forward_to_deserialize_other {
($($func:ident ( $($arg:ty),* ))*) => {
$(
- fn $func<V>(self, $(_: $arg,)* visitor: V) -> Result<V::Value, Self::Error>
+ fn $func<V>(self, $(_: $arg,)* _visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
- self.deserialize_other(visitor)
+ Self::deserialize_other()
}
)*
}
@@ -2741,6 +2738,16 @@ where
visitor.visit_newtype_struct(self)
}
+ fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ where
+ V: Visitor<'de>,
+ {
+ match visitor.__private_visit_untagged_option(self) {
+ Ok(value) => Ok(value),
+ Err(()) => Self::deserialize_other(),
+ }
+ }
+
forward_to_deserialize_other! {
deserialize_bool()
deserialize_i8()
@@ -2758,7 +2765,6 @@ where
deserialize_string()
deserialize_bytes()
deserialize_byte_buf()
- deserialize_option()
deserialize_unit()
deserialize_unit_struct(&'static str)
deserialize_seq()
diff --git a/serde/src/private/ser.rs b/serde/src/private/ser.rs
index 54bb4ce02..c21de1635 100644
--- a/serde/src/private/ser.rs
+++ b/serde/src/private/ser.rs
@@ -1122,14 +1122,14 @@ where
}
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
- Err(self.bad_type(Unsupported::Optional))
+ Ok(())
}
- fn serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error>
+ fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: Serialize,
{
- Err(self.bad_type(Unsupported::Optional))
+ value.serialize(self)
}
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
| serde-rs/serde | 2018-05-12T05:14:42Z | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 | |
1,252 | diff --git a/test_suite/tests/compile-fail/precondition/deserialize_dst.rs b/test_suite/tests/compile-fail/precondition/deserialize_dst.rs
new file mode 100644
index 000000000..243b998d7
--- /dev/null
+++ b/test_suite/tests/compile-fail/precondition/deserialize_dst.rs
@@ -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(Deserialize)] //~ ERROR: proc-macro derive panicked
+struct S {
+ string: String,
+ slice: [u8], //~^^^ HELP: cannot deserialize a dynamically sized struct
+}
| [
"830"
] | serde-rs__serde-1252 | Deserialize for dynamically sized struct generates invalid code
```rust
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[derive(Deserialize)]
struct S {
last: [u8],
}
```
```
error[E0277]: the trait bound `[u8]: std::marker::Sized` is not satisfied in `S`
--> src/main.rs:6:10
|
6 | #[derive(Deserialize)]
| ^^^^^^^^^^^ within `S`, the trait `std::marker::Sized` is not implemented for `[u8]`
|
= note: `[u8]` does not have a constant size known at compile-time
= note: required because it appears within the type `S`
= note: required by `serde::Deserialize`
```
| 1.0 | 536bdd77a0725fff5ae4e55e1c4905d957c5eb94 | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 42dbe3860..b0953450b 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -15,15 +15,16 @@ use syn::{self, Ident, Index, Member};
use bound;
use fragment::{Expr, Fragment, Match, Stmts};
use internals::ast::{Container, Data, Field, Style, Variant};
-use internals::{self, attr};
+use internals::{attr, Ctxt};
use pretend;
use try;
use std::collections::BTreeSet;
pub fn expand_derive_deserialize(input: &syn::DeriveInput) -> Result<Tokens, String> {
- let ctxt = internals::Ctxt::new();
+ let ctxt = Ctxt::new();
let cont = Container::from_ast(&ctxt, input);
+ precondition(&ctxt, &cont);
try!(ctxt.check());
let ident = cont.ident;
@@ -80,6 +81,16 @@ pub fn expand_derive_deserialize(input: &syn::DeriveInput) -> Result<Tokens, Str
Ok(generated)
}
+fn precondition(cx: &Ctxt, cont: &Container) {
+ if let Data::Struct(_, ref fields) = cont.data {
+ if let Some(last) = fields.last() {
+ if let syn::Type::Slice(_) = *last.ty {
+ cx.error("cannot deserialize a dynamically sized struct");
+ }
+ }
+ }
+}
+
struct Parameters {
/// Name of the type the `derive` is on.
local: syn::Ident,
| serde-rs/serde | 2018-05-07T18:28:17Z | There is no way to implement a working Deserialize for this type because Deserialize requires Self: Sized, but it would be nice to at least detect the case of dynamically sized slice as the last field and fail with a message rather than generating broken code. | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,961 | diff --git a/test_suite/tests/ui/rename/container_unknown_rename_rule.stderr b/test_suite/tests/ui/rename/container_unknown_rename_rule.stderr
index 728d71ca2..3fd68f3f3 100644
--- a/test_suite/tests/ui/rename/container_unknown_rename_rule.stderr
+++ b/test_suite/tests/ui/rename/container_unknown_rename_rule.stderr
@@ -1,4 +1,4 @@
-error: unknown rename rule for #[serde(rename_all = "abc")]
+error: unknown rename rule `rename_all = "abc"`, expected one of "lowercase", "UPPERCASE", "PascalCase", "camelCase", "snake_case", "SCREAMING_SNAKE_CASE", "kebab-case", "SCREAMING-KEBAB-CASE"
--> $DIR/container_unknown_rename_rule.rs:4:22
|
4 | #[serde(rename_all = "abc")]
diff --git a/test_suite/tests/ui/rename/variant_unknown_rename_rule.stderr b/test_suite/tests/ui/rename/variant_unknown_rename_rule.stderr
index 7a52f37a8..48f53f893 100644
--- a/test_suite/tests/ui/rename/variant_unknown_rename_rule.stderr
+++ b/test_suite/tests/ui/rename/variant_unknown_rename_rule.stderr
@@ -1,4 +1,4 @@
-error: unknown rename rule for #[serde(rename_all = "abc")]
+error: unknown rename rule `rename_all = "abc"`, expected one of "lowercase", "UPPERCASE", "PascalCase", "camelCase", "snake_case", "SCREAMING_SNAKE_CASE", "kebab-case", "SCREAMING-KEBAB-CASE"
--> $DIR/variant_unknown_rename_rule.rs:5:26
|
5 | #[serde(rename_all = "abc")]
| [
"1928"
] | serde-rs__serde-1961 | add a list of possible rename rules upon an error
An implementation of https://github.com/serde-rs/serde/issues/1923
| 1.12 | eaccae2c464eb096c115be38a1930539f5698ce3 | diff --git a/serde_derive/src/internals/case.rs b/serde_derive/src/internals/case.rs
index 199fd4bcb..554505160 100644
--- a/serde_derive/src/internals/case.rs
+++ b/serde_derive/src/internals/case.rs
@@ -5,7 +5,7 @@
#[allow(deprecated, unused_imports)]
use std::ascii::AsciiExt;
-use std::fmt::{self, Display};
+use std::fmt::{self, Debug, Display};
use self::RenameRule::*;
@@ -120,11 +120,16 @@ pub struct ParseError<'a> {
impl<'a> Display for ParseError<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(
- f,
- "unknown rename rule for #[serde(rename_all = {:?})]",
- self.unknown,
- )
+ f.write_str("unknown rename rule `rename_all = ")?;
+ Debug::fmt(self.unknown, f)?;
+ f.write_str("`, expected one of ")?;
+ for (i, (name, _rule)) in RENAME_RULES.iter().enumerate() {
+ if i > 0 {
+ f.write_str(", ")?;
+ }
+ Debug::fmt(name, f)?;
+ }
+ Ok(())
}
}
| serde-rs/serde | 2021-01-23T22:42:17Z | 55fdbea20bbcb0f0fa7e9545ec0ea10c87a6643d | |
1,958 | diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index 025d87b09..a0261bd35 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -1452,4 +1452,25 @@ declare_error_tests! {
],
"invalid value: integer `65536`, expected u16",
}
+ test_duration_overflow_seq<Duration> {
+ &[
+ Token::Seq { len: Some(2) },
+ Token::U64(u64::max_value()),
+ Token::U32(1_000_000_000),
+ Token::SeqEnd,
+ ],
+ "overflow deserializing Duration",
+ }
+ test_duration_overflow_struct<Duration> {
+ &[
+ Token::Struct { name: "Duration", len: 2 },
+ Token::Str("secs"),
+ Token::U64(u64::max_value()),
+
+ Token::Str("nanos"),
+ Token::U32(1_000_000_000),
+ Token::StructEnd,
+ ],
+ "overflow deserializing Duration",
+ }
}
| [
"1933"
] | serde-rs__serde-1958 | Serde panics when deserializing malformed Duration
The documentation for `std::time::Duration::new` states that it panics if `nanos` overflows and causes `secs` to overflow.
This should cause a deserialization error instead of causing the application to panic.
| 1.12 | 398fba9b1ee6d27a2e556f8d6cd6d1a82315ee9a | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index fd77ddf1f..7f0b5d907 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -1849,6 +1849,17 @@ impl<'de> Deserialize<'de> for Duration {
}
}
+ fn check_overflow<E>(secs: u64, nanos: u32) -> Result<(), E>
+ where
+ E: Error,
+ {
+ static NANOS_PER_SEC: u32 = 1_000_000_000;
+ match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
+ Some(_) => Ok(()),
+ None => Err(E::custom("overflow deserializing Duration")),
+ }
+ }
+
struct DurationVisitor;
impl<'de> Visitor<'de> for DurationVisitor {
@@ -1874,6 +1885,7 @@ impl<'de> Deserialize<'de> for Duration {
return Err(Error::invalid_length(1, &self));
}
};
+ try!(check_overflow(secs, nanos));
Ok(Duration::new(secs, nanos))
}
@@ -1907,6 +1919,7 @@ impl<'de> Deserialize<'de> for Duration {
Some(nanos) => nanos,
None => return Err(<A::Error as Error>::missing_field("nanos")),
};
+ try!(check_overflow(secs, nanos));
Ok(Duration::new(secs, nanos))
}
}
| serde-rs/serde | 2021-01-20T19:48:24Z | 55fdbea20bbcb0f0fa7e9545ec0ea10c87a6643d | |
1,916 | diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index c9bcee5b3..a1d62758e 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -250,9 +250,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
{
visitor.visit_enum(DeserializerEnumVisitor { de: self })
}
- _ => {
- unexpected!(self.next_token());
- }
+ _ => self.deserialize_any(visitor)
}
}
diff --git a/test_suite/tests/test_annotations.rs b/test_suite/tests/test_annotations.rs
index 7604fe031..10d81ad4b 100644
--- a/test_suite/tests/test_annotations.rs
+++ b/test_suite/tests/test_annotations.rs
@@ -2633,3 +2633,200 @@ fn test_flatten_any_after_flatten_struct() {
],
);
}
+
+/// https://github.com/serde-rs/serde/issues/1883
+#[test]
+fn test_expecting_message() {
+ #[derive(Deserialize, PartialEq, Debug)]
+ #[serde(expecting = "something strange...")]
+ struct Unit;
+
+ #[derive(Deserialize)]
+ #[serde(expecting = "something strange...")]
+ struct Newtype(bool);
+
+ #[derive(Deserialize)]
+ #[serde(expecting = "something strange...")]
+ struct Tuple(u32, bool);
+
+ #[derive(Deserialize)]
+ #[serde(expecting = "something strange...")]
+ struct Struct {
+ question: String,
+ answer: u32,
+ }
+
+ assert_de_tokens_error::<Unit>(
+ &[Token::Str("Unit")],
+ r#"invalid type: string "Unit", expected something strange..."#
+ );
+
+ assert_de_tokens_error::<Newtype>(
+ &[Token::Str("Newtype")],
+ r#"invalid type: string "Newtype", expected something strange..."#
+ );
+
+ assert_de_tokens_error::<Tuple>(
+ &[Token::Str("Tuple")],
+ r#"invalid type: string "Tuple", expected something strange..."#
+ );
+
+ assert_de_tokens_error::<Struct>(
+ &[Token::Str("Struct")],
+ r#"invalid type: string "Struct", expected something strange..."#
+ );
+}
+
+#[test]
+fn test_expecting_message_externally_tagged_enum() {
+ #[derive(Deserialize)]
+ #[serde(expecting = "something strange...")]
+ enum Enum {
+ ExternallyTagged,
+ }
+
+ assert_de_tokens_error::<Enum>(
+ &[
+ Token::Str("ExternallyTagged"),
+ ],
+ r#"invalid type: string "ExternallyTagged", expected something strange..."#
+ );
+
+ // Check that #[serde(expecting = "...")] doesn't affect variant identifier error message
+ assert_de_tokens_error::<Enum>(
+ &[
+ Token::Enum { name: "Enum" },
+ Token::Unit,
+ ],
+ r#"invalid type: unit value, expected variant identifier"#
+ );
+}
+
+#[test]
+fn test_expecting_message_internally_tagged_enum() {
+ #[derive(Deserialize)]
+ #[serde(tag = "tag")]
+ #[serde(expecting = "something strange...")]
+ enum Enum {
+ InternallyTagged,
+ }
+
+ assert_de_tokens_error::<Enum>(
+ &[
+ Token::Str("InternallyTagged"),
+ ],
+ r#"invalid type: string "InternallyTagged", expected something strange..."#
+ );
+
+ // Check that #[serde(expecting = "...")] doesn't affect variant identifier error message
+ assert_de_tokens_error::<Enum>(
+ &[
+ Token::Map { len: None },
+ Token::Str("tag"),
+ Token::Unit,
+ ],
+ r#"invalid type: unit value, expected variant identifier"#
+ );
+}
+
+#[test]
+fn test_expecting_message_adjacently_tagged_enum() {
+ #[derive(Deserialize)]
+ #[serde(tag = "tag", content = "content")]
+ #[serde(expecting = "something strange...")]
+ enum Enum {
+ AdjacentlyTagged,
+ }
+
+ assert_de_tokens_error::<Enum>(
+ &[
+ Token::Str("AdjacentlyTagged"),
+ ],
+ r#"invalid type: string "AdjacentlyTagged", expected something strange..."#
+ );
+
+ assert_de_tokens_error::<Enum>(
+ &[
+ Token::Map { len: None },
+ Token::Unit,
+ ],
+ r#"invalid type: unit value, expected "tag", "content", or other ignored fields"#
+ );
+
+ // Check that #[serde(expecting = "...")] doesn't affect variant identifier error message
+ assert_de_tokens_error::<Enum>(
+ &[
+ Token::Map { len: None },
+ Token::Str("tag"),
+ Token::Unit,
+ ],
+ r#"invalid type: unit value, expected variant identifier"#
+ );
+}
+
+#[test]
+fn test_expecting_message_untagged_tagged_enum() {
+ #[derive(Deserialize)]
+ #[serde(untagged)]
+ #[serde(expecting = "something strange...")]
+ enum Enum {
+ Untagged,
+ }
+
+ assert_de_tokens_error::<Enum>(
+ &[
+ Token::Str("Untagged"),
+ ],
+ r#"something strange..."#
+ );
+}
+
+#[test]
+fn test_expecting_message_identifier_enum() {
+ #[derive(Deserialize)]
+ #[serde(field_identifier)]
+ #[serde(expecting = "something strange...")]
+ enum FieldEnum {
+ Field,
+ }
+
+ #[derive(Deserialize)]
+ #[serde(variant_identifier)]
+ #[serde(expecting = "something strange...")]
+ enum VariantEnum {
+ Variant,
+ }
+
+ assert_de_tokens_error::<FieldEnum>(
+ &[
+ Token::Unit,
+ ],
+ r#"invalid type: unit value, expected something strange..."#
+ );
+
+ assert_de_tokens_error::<FieldEnum>(
+ &[
+ Token::Enum { name: "FieldEnum" },
+ Token::Str("Unknown"),
+ Token::None,
+ ],
+ r#"invalid type: map, expected something strange..."#
+ );
+
+
+ assert_de_tokens_error::<VariantEnum>(
+ &[
+ Token::Unit,
+ ],
+ r#"invalid type: unit value, expected something strange..."#
+ );
+
+ assert_de_tokens_error::<VariantEnum>(
+ &[
+ Token::Enum { name: "VariantEnum" },
+ Token::Str("Unknown"),
+ Token::None,
+ ],
+ r#"invalid type: map, expected something strange..."#
+ );
+}
diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index d8def742b..b5c12d606 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -723,6 +723,55 @@ fn test_gen() {
}
deriving!(&'a str);
+
+ // https://github.com/serde-rs/serde/issues/1883
+ #[derive(Deserialize)]
+ #[serde(expecting = "a message")]
+ struct CustomMessageUnit;
+
+ #[derive(Deserialize)]
+ #[serde(expecting = "a message")]
+ struct CustomMessageNewtype(bool);
+
+ #[derive(Deserialize)]
+ #[serde(expecting = "a message")]
+ struct CustomMessageTuple(u32, bool);
+
+ #[derive(Deserialize)]
+ #[serde(expecting = "a message")]
+ struct CustomMessageStruct {
+ question: String,
+ answer: u32,
+ }
+
+ #[derive(Deserialize)]
+ #[serde(expecting = "a message")]
+ enum CustomMessageExternallyTaggedEnum {}
+
+ #[derive(Deserialize)]
+ #[serde(tag = "tag")]
+ #[serde(expecting = "a message")]
+ enum CustomMessageInternallyTaggedEnum {}
+
+ #[derive(Deserialize)]
+ #[serde(tag = "tag", content = "content")]
+ #[serde(expecting = "a message")]
+ enum CustomMessageAdjacentlyTaggedEnum {}
+
+ #[derive(Deserialize)]
+ #[serde(untagged)]
+ #[serde(expecting = "a message")]
+ enum CustomMessageUntaggedEnum {}
+
+ #[derive(Deserialize)]
+ #[serde(field_identifier)]
+ #[serde(expecting = "a message")]
+ enum CustomMessageFieldIdentifierEnum {}
+
+ #[derive(Deserialize)]
+ #[serde(variant_identifier)]
+ #[serde(expecting = "a message")]
+ enum CustomMessageVariantIdentifierEnum {}
}
//////////////////////////////////////////////////////////////////////////
| [
"1883"
] | serde-rs__serde-1916 | Provide an easy way to customize only the error message
**EDIT** After thinking about it some more, I feel it would be better to improve this error message rather than add API surface area. #1544 gets close, but I believe those errors are still too opaque for Cargo's purposes, and it's hidden behind a flag. Anyway, my original post:
-----------------
I have an untagged union:
```rust
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum MyEnum {
Foo(Vec<String>),
Bar(usize)
}
```
If all variants fail, you get this error message:
https://github.com/serde-rs/serde/blob/9f331cc25753edd71ad7ab0ea08a430fefaa90e1/serde_derive/src/de.rs#L1648
Is there a good way to customize the error message but keep the default `#[derive(Deserialize)]` implementation? Perhaps a new attribute?:
```rust
#[serde(untagged, expecting = "a number or a list of strings")]
enum MyEnum {
...
}
```
## Advantages:
- You don't have to reimplement `Deserialize`
- Concise
## Disadvantages
- How common is this use-case? We have to do this a couple of times [within Cargo](https://github.com/rust-lang/cargo/commit/cb53e1b2056a02bd1eb83d926e1cc37e56180368).
- Is there a better solution I am overlooking?
| 1.11 | 8084258a3edc1dc4007e8df7f24b022d015b5fb0 | diff --git a/serde/src/private/de.rs b/serde/src/private/de.rs
index bcb964a9c..e3b685e88 100644
--- a/serde/src/private/de.rs
+++ b/serde/src/private/de.rs
@@ -824,15 +824,17 @@ mod content {
/// Not public API.
pub struct TaggedContentVisitor<'de, T> {
tag_name: &'static str,
+ expecting: &'static str,
value: PhantomData<TaggedContent<'de, T>>,
}
impl<'de, T> TaggedContentVisitor<'de, T> {
/// Visitor for the content of an internally tagged enum with the given
/// tag name.
- pub fn new(name: &'static str) -> Self {
+ pub fn new(name: &'static str, expecting: &'static str) -> Self {
TaggedContentVisitor {
tag_name: name,
+ expecting: expecting,
value: PhantomData,
}
}
@@ -861,7 +863,7 @@ mod content {
type Value = TaggedContent<'de, T>;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.write_str("internally tagged enum")
+ fmt.write_str(self.expecting)
}
fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 1f5733a6d..071db57bc 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -399,6 +399,7 @@ fn deserialize_unit_struct(params: &Parameters, cattrs: &attr::Container) -> Fra
let type_name = cattrs.name().deserialize_name();
let expecting = format!("unit struct {}", params.type_name());
+ let expecting = cattrs.expecting().unwrap_or(&expecting);
quote_block! {
struct __Visitor;
@@ -456,6 +457,7 @@ fn deserialize_tuple(
Some(variant_ident) => format!("tuple variant {}::{}", params.type_name(), variant_ident),
None => format!("tuple struct {}", params.type_name()),
};
+ let expecting = cattrs.expecting().unwrap_or(&expecting);
let nfields = fields.len();
@@ -542,6 +544,7 @@ fn deserialize_tuple_in_place(
Some(variant_ident) => format!("tuple variant {}::{}", params.type_name(), variant_ident),
None => format!("tuple struct {}", params.type_name()),
};
+ let expecting = cattrs.expecting().unwrap_or(&expecting);
let nfields = fields.len();
@@ -630,6 +633,7 @@ fn deserialize_seq(
} else {
format!("{} with {} elements", expecting, deserialized_count)
};
+ let expecting = cattrs.expecting().unwrap_or(&expecting);
let mut index_in_seq = 0_usize;
let let_values = vars.clone().zip(fields).map(|(var, field)| {
@@ -732,6 +736,7 @@ fn deserialize_seq_in_place(
} else {
format!("{} with {} elements", expecting, deserialized_count)
};
+ let expecting = cattrs.expecting().unwrap_or(&expecting);
let mut index_in_seq = 0usize;
let write_values = fields.iter().map(|field| {
@@ -907,6 +912,7 @@ fn deserialize_struct(
Some(variant_ident) => format!("struct variant {}::{}", params.type_name(), variant_ident),
None => format!("struct {}", params.type_name()),
};
+ let expecting = cattrs.expecting().unwrap_or(&expecting);
let visit_seq = Stmts(deserialize_seq(
&type_path, params, fields, true, cattrs, &expecting,
@@ -1048,6 +1054,7 @@ fn deserialize_struct_in_place(
Some(variant_ident) => format!("struct variant {}::{}", params.type_name(), variant_ident),
None => format!("struct {}", params.type_name()),
};
+ let expecting = cattrs.expecting().unwrap_or(&expecting);
let visit_seq = Stmts(deserialize_seq_in_place(params, fields, cattrs, &expecting));
@@ -1200,6 +1207,7 @@ fn deserialize_externally_tagged_enum(
let type_name = cattrs.name().deserialize_name();
let expecting = format!("enum {}", params.type_name());
+ let expecting = cattrs.expecting().unwrap_or(&expecting);
let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants, cattrs);
@@ -1309,6 +1317,9 @@ fn deserialize_internally_tagged_enum(
}
});
+ let expecting = format!("internally tagged enum {}", params.type_name());
+ let expecting = cattrs.expecting().unwrap_or(&expecting);
+
quote_block! {
#variant_visitor
@@ -1316,7 +1327,7 @@ fn deserialize_internally_tagged_enum(
let __tagged = try!(_serde::Deserializer::deserialize_any(
__deserializer,
- _serde::private::de::TaggedContentVisitor::<__Field>::new(#tag)));
+ _serde::private::de::TaggedContentVisitor::<__Field>::new(#tag, #expecting)));
match __tagged.tag {
#(#variant_arms)*
@@ -1359,6 +1370,7 @@ fn deserialize_adjacently_tagged_enum(
.collect();
let expecting = format!("adjacently tagged enum {}", params.type_name());
+ let expecting = cattrs.expecting().unwrap_or(&expecting);
let type_name = cattrs.name().deserialize_name();
let deny_unknown_fields = cattrs.deny_unknown_fields();
@@ -1648,6 +1660,7 @@ fn deserialize_untagged_enum(
"data did not match any variant of untagged enum {}",
params.type_name()
);
+ let fallthrough_msg = cattrs.expecting().unwrap_or(&fallthrough_msg);
quote_block! {
let __content = try!(<_serde::private::de::Content as _serde::Deserialize>::deserialize(__deserializer));
@@ -1905,6 +1918,7 @@ fn deserialize_generated_identifier(
is_variant,
fallthrough,
!is_variant && cattrs.has_flatten(),
+ None,
));
let lifetime = if !is_variant && cattrs.has_flatten() {
@@ -2012,6 +2026,7 @@ fn deserialize_custom_identifier(
is_variant,
fallthrough,
false,
+ cattrs.expecting(),
));
quote_block! {
@@ -2042,6 +2057,7 @@ fn deserialize_identifier(
is_variant: bool,
fallthrough: Option<TokenStream>,
collect_other_fields: bool,
+ expecting: Option<&str>,
) -> Fragment {
let mut flat_fields = Vec::new();
for (_, ident, aliases) in fields {
@@ -2066,11 +2082,11 @@ fn deserialize_identifier(
.map(|(_, ident, _)| quote!(#this::#ident))
.collect();
- let expecting = if is_variant {
+ let expecting = expecting.unwrap_or(if is_variant {
"variant identifier"
} else {
"field identifier"
- };
+ });
let index_expecting = if is_variant { "variant" } else { "field" };
diff --git a/serde_derive/src/internals/attr.rs b/serde_derive/src/internals/attr.rs
index e6f72dfe7..fc523d16d 100644
--- a/serde_derive/src/internals/attr.rs
+++ b/serde_derive/src/internals/attr.rs
@@ -223,6 +223,8 @@ pub struct Container {
has_flatten: bool,
serde_path: Option<syn::Path>,
is_packed: bool,
+ /// Error message generated when type can't be deserialized
+ expecting: Option<String>,
}
/// Styles of representing an enum.
@@ -305,6 +307,7 @@ impl Container {
let mut field_identifier = BoolAttr::none(cx, FIELD_IDENTIFIER);
let mut variant_identifier = BoolAttr::none(cx, VARIANT_IDENTIFIER);
let mut serde_path = Attr::none(cx, CRATE);
+ let mut expecting = Attr::none(cx, EXPECTING);
for meta_item in item
.attrs
@@ -575,6 +578,13 @@ impl Container {
}
}
+ // Parse `#[serde(expecting = "a message")]`
+ Meta(NameValue(m)) if m.path == EXPECTING => {
+ if let Ok(s) = get_lit_str(cx, EXPECTING, &m.lit) {
+ expecting.set(&m.path, s.value());
+ }
+ }
+
Meta(meta_item) => {
let path = meta_item
.path()
@@ -627,6 +637,7 @@ impl Container {
has_flatten: false,
serde_path: serde_path.get(),
is_packed,
+ expecting: expecting.get(),
}
}
@@ -702,6 +713,12 @@ impl Container {
self.custom_serde_path()
.map_or_else(|| Cow::Owned(parse_quote!(_serde)), Cow::Borrowed)
}
+
+ /// Error message generated when type can't be deserialized.
+ /// If `None`, default message will be used
+ pub fn expecting(&self) -> Option<&str> {
+ self.expecting.as_ref().map(String::as_ref)
+ }
}
fn decide_tag(
diff --git a/serde_derive/src/internals/symbol.rs b/serde_derive/src/internals/symbol.rs
index 318b81bbb..1fedd2754 100644
--- a/serde_derive/src/internals/symbol.rs
+++ b/serde_derive/src/internals/symbol.rs
@@ -35,6 +35,7 @@ pub const TRY_FROM: Symbol = Symbol("try_from");
pub const UNTAGGED: Symbol = Symbol("untagged");
pub const VARIANT_IDENTIFIER: Symbol = Symbol("variant_identifier");
pub const WITH: Symbol = Symbol("with");
+pub const EXPECTING: Symbol = Symbol("expecting");
impl PartialEq<Symbol> for Ident {
fn eq(&self, word: &Symbol) -> bool {
| serde-rs/serde | 2020-10-22T20:11:56Z | 8084258a3edc1dc4007e8df7f24b022d015b5fb0 | |
1,874 | diff --git a/test_suite/tests/test_annotations.rs b/test_suite/tests/test_annotations.rs
index 06c485dff..7604fe031 100644
--- a/test_suite/tests/test_annotations.rs
+++ b/test_suite/tests/test_annotations.rs
@@ -1967,6 +1967,29 @@ fn test_flatten_map_twice() {
);
}
+#[test]
+fn test_flatten_unit() {
+ #[derive(Debug, PartialEq, Serialize, Deserialize)]
+ struct Response<T> {
+ #[serde(flatten)]
+ data: T,
+ status: usize,
+ }
+
+ assert_tokens(
+ &Response {
+ data: (),
+ status: 0,
+ },
+ &[
+ Token::Map { len: None },
+ Token::Str("status"),
+ Token::U64(0),
+ Token::MapEnd,
+ ],
+ );
+}
+
#[test]
fn test_flatten_unsupported_type() {
#[derive(Debug, PartialEq, Serialize, Deserialize)]
| [
"1873"
] | serde-rs__serde-1874 | Flattening a Unit aka () should produce no extra fields
I'm designing an http api where every response is json and has diffferent fields depending on the api call, but always has a status and code field. I am acomplishing this through the Response struct:
```rust
#[derive(Debug, Serialize)]
pub struct Response<T> {
#[serde(flatten)]
data: T,
status: Status,
}
```
In situations where I just want to return a status, I intended on constructing a `Response<()>`, but that gives me this error:
```thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("can only flatten structs and maps (got unit)", line: 0, column: 0)', src/libcore/result.rs:1189:5```
I expected that flattening a Unit would just add no fields. I could make a struct with no fields and make a `Response<NoFields>`, but that seems unidiomatic and requires adding an extra type that doesn't do anything. Is there a reason that you can't flatten a Unit?
| 1.11 | 53b9871b172c1c29a16e66138f108bf4155444fe | diff --git a/serde/src/private/de.rs b/serde/src/private/de.rs
index eb5424cc8..bcb964a9c 100644
--- a/serde/src/private/de.rs
+++ b/serde/src/private/de.rs
@@ -2763,6 +2763,13 @@ where
}
}
+ fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_unit()
+ }
+
forward_to_deserialize_other! {
deserialize_bool()
deserialize_i8()
@@ -2780,7 +2787,6 @@ where
deserialize_string()
deserialize_bytes()
deserialize_byte_buf()
- deserialize_unit()
deserialize_unit_struct(&'static str)
deserialize_seq()
deserialize_tuple(usize)
diff --git a/serde/src/private/ser.rs b/serde/src/private/ser.rs
index 70f338181..eb8cfc988 100644
--- a/serde/src/private/ser.rs
+++ b/serde/src/private/ser.rs
@@ -1124,7 +1124,7 @@ where
}
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
- Err(Self::bad_type(Unsupported::Unit))
+ Ok(())
}
fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
| serde-rs/serde | 2020-08-10T22:07:47Z | 8084258a3edc1dc4007e8df7f24b022d015b5fb0 | |
1,831 | diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index d8def742b..73f7fa50f 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -723,6 +723,18 @@ fn test_gen() {
}
deriving!(&'a str);
+
+ macro_rules! mac {
+ ($($tt:tt)*) => {
+ $($tt)*
+ };
+ }
+
+ #[derive(Deserialize)]
+ struct BorrowLifetimeInsideMacro<'a> {
+ #[serde(borrow = "'a")]
+ f: mac!(Cow<'a, str>),
+ }
}
//////////////////////////////////////////////////////////////////////////
| [
"1562"
] | serde-rs__serde-1831 | Error: "field has no lifetimes to borrow" if type is behind a macro
```Rust
use serde::Deserialize;
use std::borrow::Cow;
macro_rules! t {
($t:ty) => { $t }
}
#[derive(Deserialize)]
struct B<'a> {
#[serde(borrow="'a")]
f: t!(Cow<'a , str>)
}
```
This generates error:
```
error: field `f` has no lifetimes to borrow
--> src\main.rs:10:5
|
10 | / #[serde(borrow="'a")]
11 | | f: t!(Cow<'a , str>)
| |________________________^
```
but If I manually substitute type that macro expands to then everything works fine.
| 1.11 | 8084258a3edc1dc4007e8df7f24b022d015b5fb0 | diff --git a/serde_derive/src/internals/attr.rs b/serde_derive/src/internals/attr.rs
index e6f72dfe7..d59e681a0 100644
--- a/serde_derive/src/internals/attr.rs
+++ b/serde_derive/src/internals/attr.rs
@@ -1,6 +1,6 @@
use internals::symbol::*;
use internals::{ungroup, Ctxt};
-use proc_macro2::{Group, Span, TokenStream, TokenTree};
+use proc_macro2::{Group, Spacing, Span, TokenStream, TokenTree};
use quote::ToTokens;
use std::borrow::Cow;
use std::collections::BTreeSet;
@@ -1921,17 +1921,40 @@ fn collect_lifetimes(ty: &syn::Type, out: &mut BTreeSet<syn::Lifetime>) {
syn::Type::Group(ty) => {
collect_lifetimes(&ty.elem, out);
}
+ syn::Type::Macro(ty) => {
+ collect_lifetimes_from_tokens(ty.mac.tokens.clone(), out);
+ }
syn::Type::BareFn(_)
| syn::Type::Never(_)
| syn::Type::TraitObject(_)
| syn::Type::ImplTrait(_)
| syn::Type::Infer(_)
- | syn::Type::Macro(_)
| syn::Type::Verbatim(_)
| _ => {}
}
}
+fn collect_lifetimes_from_tokens(tokens: TokenStream, out: &mut BTreeSet<syn::Lifetime>) {
+ let mut iter = tokens.into_iter();
+ while let Some(tt) = iter.next() {
+ match &tt {
+ TokenTree::Punct(op) if op.as_char() == '\'' && op.spacing() == Spacing::Joint => {
+ if let Some(TokenTree::Ident(ident)) = iter.next() {
+ out.insert(syn::Lifetime {
+ apostrophe: op.span(),
+ ident,
+ });
+ }
+ }
+ TokenTree::Group(group) => {
+ let tokens = group.stream();
+ collect_lifetimes_from_tokens(tokens, out);
+ }
+ _ => {}
+ }
+ }
+}
+
fn parse_lit_str<T>(s: &syn::LitStr) -> parse::Result<T>
where
T: Parse,
| serde-rs/serde | 2020-06-07T11:15:57Z | Thanks! I would accept a PR to fix this. | 8084258a3edc1dc4007e8df7f24b022d015b5fb0 |
1,830 | diff --git a/test_suite/tests/test_self.rs b/test_suite/tests/test_self.rs
new file mode 100644
index 000000000..d2241749c
--- /dev/null
+++ b/test_suite/tests/test_self.rs
@@ -0,0 +1,101 @@
+use serde::{Deserialize, Serialize};
+
+#[test]
+fn test_self() {
+ macro_rules! mac {
+ ($($tt:tt)*) => {
+ $($tt)*
+ };
+ }
+
+ pub trait Trait {
+ type Assoc;
+ }
+
+ #[derive(Deserialize, Serialize)]
+ pub struct Generics<T: Trait<Assoc = Self>>
+ where
+ Self: Trait<Assoc = Self>,
+ <Self as Trait>::Assoc: Sized,
+ mac!(Self): Trait<Assoc = mac!(Self)>,
+ {
+ _f: T,
+ }
+
+ impl<T: Trait<Assoc = Self>> Trait for Generics<T> {
+ type Assoc = Self;
+ }
+
+ #[derive(Deserialize, Serialize)]
+ pub struct Struct {
+ _f1: Box<Self>,
+ _f2: Box<<Self as Trait>::Assoc>,
+ _f3: Box<mac!(Self)>,
+ _f4: [(); Self::ASSOC],
+ _f5: [(); Self::assoc()],
+ _f6: [(); mac!(Self::assoc())],
+ }
+
+ impl Struct {
+ const ASSOC: usize = 1;
+ const fn assoc() -> usize {
+ 0
+ }
+ }
+
+ impl Trait for Struct {
+ type Assoc = Self;
+ }
+
+ #[derive(Deserialize, Serialize)]
+ struct Tuple(
+ Box<Self>,
+ Box<<Self as Trait>::Assoc>,
+ Box<mac!(Self)>,
+ [(); Self::ASSOC],
+ [(); Self::assoc()],
+ [(); mac!(Self::assoc())],
+ );
+
+ impl Tuple {
+ const ASSOC: usize = 1;
+ const fn assoc() -> usize {
+ 0
+ }
+ }
+
+ impl Trait for Tuple {
+ type Assoc = Self;
+ }
+
+ #[derive(Deserialize, Serialize)]
+ enum Enum {
+ Struct {
+ _f1: Box<Self>,
+ _f2: Box<<Self as Trait>::Assoc>,
+ _f3: Box<mac!(Self)>,
+ _f4: [(); Self::ASSOC],
+ _f5: [(); Self::assoc()],
+ _f6: [(); mac!(Self::assoc())],
+ },
+ Tuple(
+ Box<Self>,
+ Box<<Self as Trait>::Assoc>,
+ Box<mac!(Self)>,
+ [(); Self::ASSOC],
+ [(); Self::assoc()],
+ [(); mac!(Self::assoc())],
+ ),
+ }
+
+ impl Enum {
+ const ASSOC: usize = 1;
+ const fn assoc() -> usize {
+ 0
+ }
+ }
+
+ impl Trait for Enum {
+ type Assoc = Self;
+ }
+}
| [
"1565"
] | serde-rs__serde-1830 | Derive Deserialize: Self in recursive type is not supported
As the code and errors below show, deriving `Deserialize` on a recursive enum with a `Self` reference does not work.
Note: `Serialize` works fine.
```rust
// Works fine:
#[derive(serde_derive::Deserialize)]
enum E {
Nested(Vec<E>),
}
// Fails with ERROR:
#[derive(serde_derive::Deserialize)]
enum E {
Nested(Vec<Self>),
}
```
```
Compiling playground v0.0.1 (/playground)
error[E0277]: the trait bound `_IMPL_DESERIALIZE_FOR_E::<impl _IMPL_DESERIALIZE_FOR_E::_serde::Deserialize<'de> for E>::deserialize::__Visitor<'de>: _IMPL_DESERIALIZE_FOR_E::_serde::Deserialize<'_>` is not satisfied
--> src/lib.rs:5:12
|
5 | Nested(Vec<Self>),
| ^^^ the trait `_IMPL_DESERIALIZE_FOR_E::_serde::Deserialize<'_>` is not implemented for `_IMPL_DESERIALIZE_FOR_E::<impl _IMPL_DESERIALIZE_FOR_E::_serde::Deserialize<'de> for E>::deserialize::__Visitor<'de>`
|
= note: required because of the requirements on the impl of `_IMPL_DESERIALIZE_FOR_E::_serde::Deserialize<'_>` for `std::vec::Vec<_IMPL_DESERIALIZE_FOR_E::<impl _IMPL_DESERIALIZE_FOR_E::_serde::Deserialize<'de> for E>::deserialize::__Visitor<'de>>`
= note: required by `_IMPL_DESERIALIZE_FOR_E::_serde::de::VariantAccess::newtype_variant`
error[E0631]: type mismatch in function arguments
--> src/lib.rs:3:10
|
3 | #[derive(serde_derive::Deserialize)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^ expected signature of `fn(std::vec::Vec<_IMPL_DESERIALIZE_FOR_E::<impl _IMPL_DESERIALIZE_FOR_E::_serde::Deserialize<'de> for E>::deserialize::__Visitor<'_>>) -> _`
4 | enum E {
5 | Nested(Vec<Self>),
| ----------------- found signature of `fn(std::vec::Vec<E>) -> _`
|
= note: required by `std::result::Result::<T, E>::map`
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0277`.
error: Could not compile `playground`.
```
| 1.12 | f6e7366b46f767c427ca0423ae4cc69531213498 | diff --git a/serde_derive/Cargo.toml b/serde_derive/Cargo.toml
index 185fe9787..5b6fa4344 100644
--- a/serde_derive/Cargo.toml
+++ b/serde_derive/Cargo.toml
@@ -22,7 +22,7 @@ proc-macro = true
[dependencies]
proc-macro2 = "1.0"
quote = "1.0"
-syn = { version = "1.0.58", features = ["visit"] }
+syn = { version = "1.0.58", features = ["visit", "visit-mut"] }
[dev-dependencies]
serde = { version = "1.0", path = "../serde" }
diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 90d0ab7c1..3daa9d1e6 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -8,13 +8,17 @@ use bound;
use dummy;
use fragment::{Expr, Fragment, Match, Stmts};
use internals::ast::{Container, Data, Field, Style, Variant};
-use internals::{attr, ungroup, Ctxt, Derive};
+use internals::{attr, replace_receiver, ungroup, Ctxt, Derive};
use pretend;
use std::collections::BTreeSet;
use std::ptr;
-pub fn expand_derive_deserialize(input: &syn::DeriveInput) -> Result<TokenStream, Vec<syn::Error>> {
+pub fn expand_derive_deserialize(
+ input: &mut syn::DeriveInput,
+) -> Result<TokenStream, Vec<syn::Error>> {
+ replace_receiver(input);
+
let ctxt = Ctxt::new();
let cont = match Container::from_ast(&ctxt, input, Derive::Deserialize) {
Some(cont) => cont,
diff --git a/serde_derive/src/internals/mod.rs b/serde_derive/src/internals/mod.rs
index d36b6e45c..5e9f416c4 100644
--- a/serde_derive/src/internals/mod.rs
+++ b/serde_derive/src/internals/mod.rs
@@ -4,8 +4,12 @@ pub mod attr;
mod ctxt;
pub use self::ctxt::Ctxt;
+mod receiver;
+pub use self::receiver::replace_receiver;
+
mod case;
mod check;
+mod respan;
mod symbol;
use syn::Type;
diff --git a/serde_derive/src/internals/receiver.rs b/serde_derive/src/internals/receiver.rs
new file mode 100644
index 000000000..1aaddb8bd
--- /dev/null
+++ b/serde_derive/src/internals/receiver.rs
@@ -0,0 +1,190 @@
+use super::respan::respan;
+use proc_macro2::{Group, Spacing, Span, TokenStream, TokenTree};
+use quote::{quote, quote_spanned};
+use std::{iter::FromIterator, mem};
+use syn::{
+ parse_quote,
+ punctuated::Punctuated,
+ visit_mut::{self, VisitMut},
+ DeriveInput, ExprPath, Macro, Path, PathArguments, QSelf, Type, TypePath,
+};
+
+pub fn replace_receiver(input: &mut DeriveInput) {
+ let self_ty = {
+ let ident = &input.ident;
+ let ty_generics = input.generics.split_for_impl().1;
+ parse_quote!(#ident #ty_generics)
+ };
+ let mut visitor = ReplaceReceiver(&self_ty);
+ visitor.visit_generics_mut(&mut input.generics);
+ visitor.visit_data_mut(&mut input.data);
+}
+
+struct ReplaceReceiver<'a>(&'a TypePath);
+
+impl ReplaceReceiver<'_> {
+ fn self_ty(&self, span: Span) -> TypePath {
+ respan(self.0, span)
+ }
+
+ fn self_to_qself(&self, qself: &mut Option<QSelf>, path: &mut Path) {
+ if path.leading_colon.is_some() {
+ return;
+ }
+
+ // Make borrow checker happy
+ {
+ let first = &path.segments[0];
+ if first.ident != "Self" || !first.arguments.is_empty() {
+ return;
+ }
+ }
+
+ if path.segments.len() == 1 {
+ self.self_to_expr_path(path);
+ return;
+ }
+
+ let span = path.segments[0].ident.span();
+ *qself = Some(QSelf {
+ lt_token: Token,
+ ty: Box::new(self.self_ty(span).into()),
+ position: 0,
+ as_token: None,
+ gt_token: Token,
+ });
+
+ path.leading_colon = Some(**path.segments.pairs().next().unwrap().punct().unwrap());
+
+ let segments = mem::replace(&mut path.segments, Punctuated::new());
+ path.segments = segments.into_pairs().skip(1).collect();
+ }
+
+ fn self_to_expr_path(&self, path: &mut Path) {
+ if path.leading_colon.is_some() {
+ return;
+ }
+
+ // Make borrow checker happy
+ {
+ let first = &path.segments[0];
+ if first.ident != "Self" || !first.arguments.is_empty() {
+ return;
+ }
+ }
+
+ let self_ty = self.self_ty(path.segments[0].ident.span());
+ let variant = mem::replace(path, self_ty.path);
+ for segment in &mut path.segments {
+ if let PathArguments::AngleBracketed(bracketed) = &mut segment.arguments {
+ if bracketed.colon2_token.is_none() && !bracketed.args.is_empty() {
+ bracketed.colon2_token = Some(<Token![::]>::default());
+ }
+ }
+ }
+ if variant.segments.len() > 1 {
+ path.segments.push_punct(<Token![::]>::default());
+ path.segments.extend(variant.segments.into_pairs().skip(1));
+ }
+ }
+
+ fn visit_token_stream(&self, tokens: &mut TokenStream) -> bool {
+ let mut out = Vec::new();
+ let mut modified = false;
+ let mut iter = tokens.clone().into_iter().peekable();
+ while let Some(tt) = iter.next() {
+ match tt {
+ TokenTree::Ident(ident) => {
+ if ident == "Self" {
+ modified = true;
+ let self_ty = self.self_ty(ident.span());
+ match iter.peek() {
+ Some(TokenTree::Punct(p))
+ if p.as_char() == ':' && p.spacing() == Spacing::Joint => {}
+ _ => {
+ out.extend(quote!(#self_ty));
+ continue;
+ }
+ }
+ let next = iter.next().unwrap();
+ match iter.peek() {
+ Some(TokenTree::Punct(p)) if p.as_char() == ':' => {
+ let span = ident.span();
+ out.extend(quote_spanned!(span=> <#self_ty>));
+ }
+ _ => out.extend(quote!(#self_ty)),
+ }
+ out.push(next);
+ } else {
+ out.push(TokenTree::Ident(ident));
+ }
+ }
+ TokenTree::Group(group) => {
+ let mut content = group.stream();
+ modified |= self.visit_token_stream(&mut content);
+ let mut new = Group::new(group.delimiter(), content);
+ new.set_span(group.span());
+ out.push(TokenTree::Group(new));
+ }
+ other => out.push(other),
+ }
+ }
+ if modified {
+ *tokens = TokenStream::from_iter(out);
+ }
+ modified
+ }
+}
+
+impl VisitMut for ReplaceReceiver<'_> {
+ // `Self` -> `Receiver`
+ fn visit_type_mut(&mut self, ty: &mut Type) {
+ let span = if let Type::Path(node) = ty {
+ if node.qself.is_none() && node.path.is_ident("Self") {
+ node.path.segments[0].ident.span()
+ } else {
+ self.visit_type_path_mut(node);
+ return;
+ }
+ } else {
+ visit_mut::visit_type_mut(self, ty);
+ return;
+ };
+ *ty = self.self_ty(span).into();
+ }
+
+ // `Self::Assoc` -> `<Receiver>::Assoc`
+ fn visit_type_path_mut(&mut self, ty: &mut TypePath) {
+ if ty.qself.is_none() {
+ self.self_to_qself(&mut ty.qself, &mut ty.path);
+ }
+ visit_mut::visit_type_path_mut(self, ty);
+ }
+
+ // `Self::method` -> `<Receiver>::method`
+ fn visit_expr_path_mut(&mut self, expr: &mut ExprPath) {
+ if expr.qself.is_none() {
+ self.self_to_qself(&mut expr.qself, &mut expr.path);
+ }
+ visit_mut::visit_expr_path_mut(self, expr);
+ }
+
+ fn visit_macro_mut(&mut self, mac: &mut Macro) {
+ // We can't tell in general whether `self` inside a macro invocation
+ // refers to the self in the argument list or a different self
+ // introduced within the macro. Heuristic: if the macro input contains
+ // `fn`, then `self` is more likely to refer to something other than the
+ // outer function's self argument.
+ if !contains_fn(mac.tokens.clone()) {
+ self.visit_token_stream(&mut mac.tokens);
+ }
+ }
+}
+
+fn contains_fn(tokens: TokenStream) -> bool {
+ tokens.into_iter().any(|tt| match tt {
+ TokenTree::Ident(ident) => ident == "fn",
+ TokenTree::Group(group) => contains_fn(group.stream()),
+ _ => false,
+ })
+}
diff --git a/serde_derive/src/internals/respan.rs b/serde_derive/src/internals/respan.rs
new file mode 100644
index 000000000..38f6612c4
--- /dev/null
+++ b/serde_derive/src/internals/respan.rs
@@ -0,0 +1,22 @@
+use proc_macro2::{Span, TokenStream};
+use quote::ToTokens;
+use syn::parse::Parse;
+
+pub(crate) fn respan<T>(node: &T, span: Span) -> T
+where
+ T: ToTokens + Parse,
+{
+ let tokens = node.to_token_stream();
+ let respanned = respan_tokens(tokens, span);
+ syn::parse2(respanned).unwrap()
+}
+
+fn respan_tokens(tokens: TokenStream, span: Span) -> TokenStream {
+ tokens
+ .into_iter()
+ .map(|mut token| {
+ token.set_span(span);
+ token
+ })
+ .collect()
+}
diff --git a/serde_derive/src/lib.rs b/serde_derive/src/lib.rs
index 3b4f28817..c34f00722 100644
--- a/serde_derive/src/lib.rs
+++ b/serde_derive/src/lib.rs
@@ -86,8 +86,8 @@ pub fn derive_serialize(input: TokenStream) -> TokenStream {
#[proc_macro_derive(Deserialize, attributes(serde))]
pub fn derive_deserialize(input: TokenStream) -> TokenStream {
- let input = parse_macro_input!(input as DeriveInput);
- de::expand_derive_deserialize(&input)
+ let mut input = parse_macro_input!(input as DeriveInput);
+ de::expand_derive_deserialize(&mut input)
.unwrap_or_else(to_compile_errors)
.into()
}
diff --git a/serde_derive_internals/Cargo.toml b/serde_derive_internals/Cargo.toml
index 64ee1c629..6e9214558 100644
--- a/serde_derive_internals/Cargo.toml
+++ b/serde_derive_internals/Cargo.toml
@@ -16,7 +16,7 @@ path = "lib.rs"
[dependencies]
proc-macro2 = "1.0"
quote = "1.0"
-syn = { version = "1.0.33", default-features = false, features = ["derive", "parsing", "printing", "clone-impls"] }
+syn = { version = "1.0.33", default-features = false, features = ["derive", "parsing", "printing", "clone-impls", "visit-mut"] }
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
| serde-rs/serde | 2020-06-07T09:37:23Z | Thanks! This is a bug. I would accept a PR to fix this.
I assume this just boils down to special casing `Self` in the derive code?
I'll take a look.
Yeah, I imagine what happens is that the field type is referred to from somewhere outside of the Deserialize impl itself, such as from a Visitor impl where Self would refer to the visitor struct and not the output type. Check `cargo expand` to identify where that happens. In that code, we will need to replace `Self` with either the type name (`E` in this case, but making sure to fill in generic parameters if there are any) or a convenient associated type like `Self::Value` if there is already one available that means the right thing. I believe there already is some code for recursively replacing `Self` in types, but if not, the easiest way would be with a syn Fold or VisitMut impl that walks the type and performs the replacement. | 55fdbea20bbcb0f0fa7e9545ec0ea10c87a6643d |
1,827 | diff --git a/test_suite/tests/expand/de_enum.expanded.rs b/test_suite/tests/expand/de_enum.expanded.rs
index 58d40459b..a4ba24911 100644
--- a/test_suite/tests/expand/de_enum.expanded.rs
+++ b/test_suite/tests/expand/de_enum.expanded.rs
@@ -9,7 +9,7 @@ enum DeEnum<B, C, D> {
}
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_SERIALIZE_FOR_DeEnum: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
@@ -261,7 +261,7 @@ const _IMPL_SERIALIZE_FOR_DeEnum: () = {
};
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_DESERIALIZE_FOR_DeEnum: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
diff --git a/test_suite/tests/expand/default_ty_param.expanded.rs b/test_suite/tests/expand/default_ty_param.expanded.rs
index 23c243bc0..8aaa3ab43 100644
--- a/test_suite/tests/expand/default_ty_param.expanded.rs
+++ b/test_suite/tests/expand/default_ty_param.expanded.rs
@@ -10,7 +10,7 @@ struct DefaultTyParam<T: AssociatedType<X = i32> = i32> {
}
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_SERIALIZE_FOR_DefaultTyParam: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
@@ -45,7 +45,7 @@ const _IMPL_SERIALIZE_FOR_DefaultTyParam: () = {
};
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_DESERIALIZE_FOR_DefaultTyParam: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
diff --git a/test_suite/tests/expand/generic_enum.expanded.rs b/test_suite/tests/expand/generic_enum.expanded.rs
index 899e4fea2..add7c510d 100644
--- a/test_suite/tests/expand/generic_enum.expanded.rs
+++ b/test_suite/tests/expand/generic_enum.expanded.rs
@@ -7,7 +7,7 @@ pub enum GenericEnum<T, U> {
}
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_SERIALIZE_FOR_GenericEnum: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
@@ -110,7 +110,7 @@ const _IMPL_SERIALIZE_FOR_GenericEnum: () = {
};
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_DESERIALIZE_FOR_GenericEnum: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
diff --git a/test_suite/tests/expand/generic_struct.expanded.rs b/test_suite/tests/expand/generic_struct.expanded.rs
index 1331e7e96..59d2e51d7 100644
--- a/test_suite/tests/expand/generic_struct.expanded.rs
+++ b/test_suite/tests/expand/generic_struct.expanded.rs
@@ -4,7 +4,7 @@ pub struct GenericStruct<T> {
}
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_SERIALIZE_FOR_GenericStruct: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
@@ -38,7 +38,7 @@ const _IMPL_SERIALIZE_FOR_GenericStruct: () = {
};
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_DESERIALIZE_FOR_GenericStruct: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
@@ -400,7 +400,7 @@ const _IMPL_DESERIALIZE_FOR_GenericStruct: () = {
pub struct GenericNewTypeStruct<T>(T);
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_SERIALIZE_FOR_GenericNewTypeStruct: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
@@ -422,7 +422,7 @@ const _IMPL_SERIALIZE_FOR_GenericNewTypeStruct: () = {
};
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_DESERIALIZE_FOR_GenericNewTypeStruct: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
diff --git a/test_suite/tests/expand/generic_tuple_struct.expanded.rs b/test_suite/tests/expand/generic_tuple_struct.expanded.rs
index 508667387..8eaf0e7ef 100644
--- a/test_suite/tests/expand/generic_tuple_struct.expanded.rs
+++ b/test_suite/tests/expand/generic_tuple_struct.expanded.rs
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
pub struct GenericTupleStruct<T, U>(T, U);
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_DESERIALIZE_FOR_GenericTupleStruct: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
diff --git a/test_suite/tests/expand/lifetimes.expanded.rs b/test_suite/tests/expand/lifetimes.expanded.rs
index 6916ac905..9840d4401 100644
--- a/test_suite/tests/expand/lifetimes.expanded.rs
+++ b/test_suite/tests/expand/lifetimes.expanded.rs
@@ -7,7 +7,7 @@ enum Lifetimes<'a> {
}
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_SERIALIZE_FOR_Lifetimes: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
@@ -91,7 +91,7 @@ const _IMPL_SERIALIZE_FOR_Lifetimes: () = {
};
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_DESERIALIZE_FOR_Lifetimes: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
diff --git a/test_suite/tests/expand/named_map.expanded.rs b/test_suite/tests/expand/named_map.expanded.rs
index 5283993ec..ce43b6634 100644
--- a/test_suite/tests/expand/named_map.expanded.rs
+++ b/test_suite/tests/expand/named_map.expanded.rs
@@ -6,7 +6,7 @@ struct SerNamedMap<'a, 'b, A: 'a, B: 'b, C> {
}
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_SERIALIZE_FOR_SerNamedMap: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
@@ -59,7 +59,7 @@ struct DeNamedMap<A, B, C> {
}
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_DESERIALIZE_FOR_DeNamedMap: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
diff --git a/test_suite/tests/expand/named_tuple.expanded.rs b/test_suite/tests/expand/named_tuple.expanded.rs
index 2966c295e..8b5e4eee0 100644
--- a/test_suite/tests/expand/named_tuple.expanded.rs
+++ b/test_suite/tests/expand/named_tuple.expanded.rs
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
struct SerNamedTuple<'a, 'b, A: 'a, B: 'b, C>(&'a A, &'b mut B, C);
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_SERIALIZE_FOR_SerNamedTuple: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
@@ -51,7 +51,7 @@ const _IMPL_SERIALIZE_FOR_SerNamedTuple: () = {
struct DeNamedTuple<A, B, C>(A, B, C);
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_DESERIALIZE_FOR_DeNamedTuple: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
diff --git a/test_suite/tests/expand/named_unit.expanded.rs b/test_suite/tests/expand/named_unit.expanded.rs
index f100688a2..dfe44ddd0 100644
--- a/test_suite/tests/expand/named_unit.expanded.rs
+++ b/test_suite/tests/expand/named_unit.expanded.rs
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
struct NamedUnit;
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_SERIALIZE_FOR_NamedUnit: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
@@ -17,7 +17,7 @@ const _IMPL_SERIALIZE_FOR_NamedUnit: () = {
};
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_DESERIALIZE_FOR_NamedUnit: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
diff --git a/test_suite/tests/expand/ser_enum.expanded.rs b/test_suite/tests/expand/ser_enum.expanded.rs
index cd2723fae..3f4db97d9 100644
--- a/test_suite/tests/expand/ser_enum.expanded.rs
+++ b/test_suite/tests/expand/ser_enum.expanded.rs
@@ -12,7 +12,7 @@ where
}
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_SERIALIZE_FOR_SerEnum: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
diff --git a/test_suite/tests/expand/void.expanded.rs b/test_suite/tests/expand/void.expanded.rs
index e7db4ac2f..fb98c321a 100644
--- a/test_suite/tests/expand/void.expanded.rs
+++ b/test_suite/tests/expand/void.expanded.rs
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
enum Void {}
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_SERIALIZE_FOR_Void: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
@@ -17,7 +17,7 @@ const _IMPL_SERIALIZE_FOR_Void: () = {
};
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
-const _IMPL_DESERIALIZE_FOR_Void: () = {
+const _: () = {
#[allow(rust_2018_idioms, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
| [
"1683"
] | serde-rs__serde-1827 | Use underscore consts on rustc 1.37+
https://blog.rust-lang.org/2019/08/15/Rust-1.37.0.html#using-unnamed-const-items-for-macros
This would tend to produce more readable error messages, because the paths currently emitted by rustc in error messages are silly (https://github.com/rust-lang/rust/issues/46991).
It will require adding a build.rs script to serde_derive similar to the one that exists in serde.
| 1.11 | 6980727d74e1b4fd0f2bff85e824e2c47ca08ba3 | diff --git a/serde_derive/Cargo.toml b/serde_derive/Cargo.toml
index 879a65199..2e90c0b91 100644
--- a/serde_derive/Cargo.toml
+++ b/serde_derive/Cargo.toml
@@ -9,7 +9,7 @@ repository = "https://github.com/serde-rs/serde"
documentation = "https://serde.rs/derive.html"
keywords = ["serde", "serialization", "no_std"]
readme = "crates-io.md"
-include = ["src/**/*.rs", "crates-io.md", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
+include = ["build.rs", "src/**/*.rs", "crates-io.md", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
[features]
default = []
diff --git a/serde_derive/build.rs b/serde_derive/build.rs
new file mode 100644
index 000000000..a2c481a4a
--- /dev/null
+++ b/serde_derive/build.rs
@@ -0,0 +1,30 @@
+use std::env;
+use std::process::Command;
+use std::str;
+
+// The rustc-cfg strings below are *not* public API. Please let us know by
+// opening a GitHub issue if your build environment requires some way to enable
+// these cfgs other than by executing our build script.
+fn main() {
+ let minor = match rustc_minor_version() {
+ Some(minor) => minor,
+ None => return,
+ };
+
+ // Underscore const names stabilized in Rust 1.37:
+ // https://github.com/rust-lang/rust/pull/61347
+ if minor >= 37 {
+ println!("cargo:rustc-cfg=underscore_consts");
+ }
+}
+
+fn rustc_minor_version() -> Option<u32> {
+ let rustc = env::var_os("RUSTC")?;
+ let output = Command::new(rustc).arg("--version").output().ok()?;
+ let version = str::from_utf8(&output.stdout).ok()?;
+ let mut pieces = version.split('.');
+ if pieces.next() != Some("rustc 1") {
+ return None;
+ }
+ pieces.next()?.parse().ok()
+}
diff --git a/serde_derive/src/dummy.rs b/serde_derive/src/dummy.rs
index d55baf29c..9a4e5f085 100644
--- a/serde_derive/src/dummy.rs
+++ b/serde_derive/src/dummy.rs
@@ -1,4 +1,5 @@
-use proc_macro2::{Ident, Span, TokenStream};
+use proc_macro2::{Ident, TokenStream};
+use quote::format_ident;
use syn;
use try;
@@ -11,10 +12,11 @@ pub fn wrap_in_const(
) -> TokenStream {
let try_replacement = try::replacement();
- let dummy_const = Ident::new(
- &format!("_IMPL_{}_FOR_{}", trait_, unraw(ty)),
- Span::call_site(),
- );
+ let dummy_const = if cfg!(underscore_consts) {
+ format_ident!("_")
+ } else {
+ format_ident!("_IMPL_{}_FOR_{}", trait_, unraw(ty))
+ };
let use_serde = match serde_path {
Some(path) => quote! {
| serde-rs/serde | 2020-06-07T00:17:10Z | 8084258a3edc1dc4007e8df7f24b022d015b5fb0 | |
1,805 | diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index 92bb0ae1f..c429500c1 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -691,6 +691,16 @@ fn test_gen() {
#[serde(flatten, skip_deserializing)]
flat: T,
}
+
+ // https://github.com/serde-rs/serde/issues/1804
+ #[derive(Serialize, Deserialize)]
+ enum Message {
+ #[serde(skip)]
+ #[allow(dead_code)]
+ String(String),
+ #[serde(other)]
+ Unknown,
+ }
}
//////////////////////////////////////////////////////////////////////////
| [
"1804"
] | serde-rs__serde-1805 | derive(Deserialize) panics with index out of bounds for `#[serde(skip)]`
Observed in this commit
https://github.com/matklad/cargo_metadata/commit/0b1c8d85c860fe9fb3488fea5990d659780065fc
```
Compiling cargo_metadata v0.9.1 (/home/matklad/projects/cargo_metadata)
error: proc-macro derive panicked
--> src/messages.rs:99:35
|
99 | #[derive(Debug, Clone, Serialize, Deserialize)]
| ^^^^^^^^^^^
|
= help: message: index out of bounds: the len is 5 but the index is 5
error: aborting due to previous error
error: could not compile `cargo_metadata`.
```
I think I am doing something very stupid with this skip, which is a bug in my code, *but* I think serde still should not panic, but rather explain me that I am holding it wrong?
serde_derive version = "1.0.106"
| 1.10 | 099fa25b86524f07d86852ea2de071e8dd2a653f | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 5ccd38a8f..74df11df7 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -1153,10 +1153,13 @@ fn prepare_enum_variant_enum(
variants: &[Variant],
cattrs: &attr::Container,
) -> (TokenStream, Stmts) {
- let variant_names_idents: Vec<_> = variants
+ let mut deserialized_variants = variants
.iter()
.enumerate()
- .filter(|&(_, variant)| !variant.attrs.skip_deserializing())
+ .filter(|&(_, variant)| !variant.attrs.skip_deserializing());
+
+ let variant_names_idents: Vec<_> = deserialized_variants
+ .clone()
.map(|(i, variant)| {
(
variant.attrs.name().deserialize_name(),
@@ -1166,7 +1169,7 @@ fn prepare_enum_variant_enum(
})
.collect();
- let other_idx = variants.iter().position(|variant| variant.attrs.other());
+ let other_idx = deserialized_variants.position(|(_, variant)| variant.attrs.other());
let variants_stmt = {
let variant_names = variant_names_idents.iter().map(|(name, _, _)| name);
| serde-rs/serde | 2020-05-08T22:40:13Z | 099fa25b86524f07d86852ea2de071e8dd2a653f | |
1,706 | diff --git a/test_suite/tests/test_macros.rs b/test_suite/tests/test_macros.rs
index d4456bed7..c0c807ec7 100644
--- a/test_suite/tests/test_macros.rs
+++ b/test_suite/tests/test_macros.rs
@@ -1145,6 +1145,20 @@ fn test_adjacently_tagged_enum() {
],
);
+ // optional newtype with no content field
+ assert_de_tokens(
+ &AdjacentlyTagged::Newtype::<Option<u8>>(None),
+ &[
+ Token::Struct {
+ name: "AdjacentlyTagged",
+ len: 1,
+ },
+ Token::Str("t"),
+ Token::Str("Newtype"),
+ Token::StructEnd,
+ ],
+ );
+
// tuple with tag first
assert_tokens(
&AdjacentlyTagged::Tuple::<u8>(1, 1),
| [
"1553"
] | serde-rs__serde-1706 | Optional content for enum variants?
Hi!
I need to de/serialize JSON messages such as the following:
```javascript
{ ..., "command": "cmd1", "arguments": { <command-dependent> } }
```
So far so good, this fits the adjacently tagged enum representation.
The wrinkle is that for some commands the `arguments` field may be optional. I tried modelling this as
```rust
#[serde(tag = "command", content = "arguments")]
enum Command {
cmd1(Option<Cmd1Arguments>)
...
}
```
but Serde is not liking it and complains about "missing field \`arguments\`".
Any suggestions? (besides custom serialization)
| 1.10 | a81968af3caea9528e8e935a9a19ccad19a16778 | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 64113a603..c3b779bf9 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -1379,42 +1379,37 @@ fn deserialize_adjacently_tagged_enum(
}
};
- fn is_unit(variant: &Variant) -> bool {
- match variant.style {
- Style::Unit => true,
- Style::Struct | Style::Tuple | Style::Newtype => false,
- }
- }
+ let arms = variants
+ .iter()
+ .enumerate()
+ .filter(|&(_, variant)| !variant.attrs.skip_deserializing())
+ .filter_map(|(i, variant)| {
+ let variant_index = field_i(i);
+ let variant_ident = &variant.ident;
- let mut missing_content = quote! {
- _serde::export::Err(<__A::Error as _serde::de::Error>::missing_field(#content))
- };
- if variants.iter().any(is_unit) {
- let fallthrough = if variants.iter().all(is_unit) {
- None
- } else {
+ let arm = match variant.style {
+ Style::Unit => quote! {
+ _serde::export::Ok(#this::#variant_ident)
+ },
+ Style::Newtype if variant.attrs.deserialize_with().is_none() => {
+ let span = variant.original.span();
+ let func = quote_spanned!(span=> _serde::private::de::missing_field);
+ quote! {
+ #func(#content).map(#this::#variant_ident)
+ }
+ }
+ _ => return None,
+ };
Some(quote! {
- _ => #missing_content
+ __Field::#variant_index => #arm,
})
- };
- let arms = variants
- .iter()
- .enumerate()
- .filter(|&(_, variant)| !variant.attrs.skip_deserializing() && is_unit(variant))
- .map(|(i, variant)| {
- let variant_index = field_i(i);
- let variant_ident = &variant.ident;
- quote! {
- __Field::#variant_index => _serde::export::Ok(#this::#variant_ident),
- }
- });
- missing_content = quote! {
- match __field {
- #(#arms)*
- #fallthrough
- }
- };
- }
+ });
+ let missing_content = quote! {
+ match __field {
+ #(#arms)*
+ _ => _serde::export::Err(<__A::Error as _serde::de::Error>::missing_field(#content))
+ }
+ };
// Advance the map by one key, returning early in case of error.
let next_key = quote! {
| serde-rs/serde | 2020-01-06T21:07:44Z | 099fa25b86524f07d86852ea2de071e8dd2a653f | |
1,695 | diff --git a/test_suite/tests/test_macros.rs b/test_suite/tests/test_macros.rs
index 0594d8d45..d95fa928f 100644
--- a/test_suite/tests/test_macros.rs
+++ b/test_suite/tests/test_macros.rs
@@ -1924,6 +1924,62 @@ fn test_rename_all() {
);
}
+#[test]
+fn test_rename_all_fields() {
+ #[derive(Serialize, Deserialize, Debug, PartialEq)]
+ #[serde(rename_all_fields = "kebab-case")]
+ enum E {
+ V1,
+ V2(bool),
+ V3 {
+ a_field: bool,
+ another_field: bool,
+ #[serde(rename = "last-field")]
+ yet_another_field: bool,
+ },
+ #[serde(rename_all = "snake_case")]
+ V4 {
+ a_field: bool,
+ },
+ }
+
+ assert_tokens(
+ &E::V3 {
+ a_field: true,
+ another_field: true,
+ yet_another_field: true,
+ },
+ &[
+ Token::StructVariant {
+ name: "E",
+ variant: "V3",
+ len: 3,
+ },
+ Token::Str("a-field"),
+ Token::Bool(true),
+ Token::Str("another-field"),
+ Token::Bool(true),
+ Token::Str("last-field"),
+ Token::Bool(true),
+ Token::StructVariantEnd,
+ ],
+ );
+
+ assert_tokens(
+ &E::V4 { a_field: true },
+ &[
+ Token::StructVariant {
+ name: "E",
+ variant: "V4",
+ len: 1,
+ },
+ Token::Str("a_field"),
+ Token::Bool(true),
+ Token::StructVariantEnd,
+ ],
+ );
+}
+
#[test]
fn test_untagged_newtype_variant_containing_unit_struct_not_map() {
#[derive(Debug, PartialEq, Serialize, Deserialize)]
| [
"1061"
] | serde-rs__serde-1695 | Apply rename_all to enum member "fields"
When using enums with struct-like members it would be useful if `rename_all` on the enclosing enum could apply to the members, too. For example:
```rust
#[serde(untagged, rename_all = "camelCase" )]
pub enum Value {
Null { null_value: () },
String { string_value: String },
Boolean { boolean_value: bool },
}
```
could do
```json
Value::String("foo".to_string())
=>
{ "stringValue": "foo" }
------^-----
|
This here is what I want
```
Currently the annotation has to be placed on the fields in addition:
```rust
#[serde(untagged)]
pub enum Value {
Null {
#[serde(rename = "nullValue")]
null_value: ()
},
String {
#[serde(rename = "stringValue")]
string_value: String
},
/* etc. */
}
```
(If you're wondering what is going on with this type, it's [Google Datastore](https://cloud.google.com/datastore/docs/reference/rest/v1/projects/runQuery#Value)).
| 1.17 | ad94aed75398d43d174368aa8c4869332bb94e33 | diff --git a/serde_derive/src/internals/ast.rs b/serde_derive/src/internals/ast.rs
index 8bcb0ecd1..75b28c969 100644
--- a/serde_derive/src/internals/ast.rs
+++ b/serde_derive/src/internals/ast.rs
@@ -88,9 +88,12 @@ impl<'a> Container<'a> {
if field.attrs.flatten() {
has_flatten = true;
}
- field
- .attrs
- .rename_by_rules(variant.attrs.rename_all_rules());
+ field.attrs.rename_by_rules(
+ variant
+ .attrs
+ .rename_all_rules()
+ .or(attrs.rename_all_fields_rules()),
+ );
}
}
}
diff --git a/serde_derive/src/internals/attr.rs b/serde_derive/src/internals/attr.rs
index 42212a64d..133299564 100644
--- a/serde_derive/src/internals/attr.rs
+++ b/serde_derive/src/internals/attr.rs
@@ -193,11 +193,23 @@ impl Name {
}
}
+#[derive(Copy, Clone)]
pub struct RenameAllRules {
serialize: RenameRule,
deserialize: RenameRule,
}
+impl RenameAllRules {
+ /// Returns a new `RenameAllRules` with the individual rules of `self` and
+ /// `other_rules` joined by `RenameRules::or`.
+ pub fn or(self, other_rules: Self) -> Self {
+ Self {
+ serialize: self.serialize.or(other_rules.serialize),
+ deserialize: self.deserialize.or(other_rules.deserialize),
+ }
+ }
+}
+
/// Represents struct or enum attribute information.
pub struct Container {
name: Name,
@@ -205,6 +217,7 @@ pub struct Container {
deny_unknown_fields: bool,
default: Default,
rename_all_rules: RenameAllRules,
+ rename_all_fields_rules: RenameAllRules,
ser_bound: Option<Vec<syn::WherePredicate>>,
de_bound: Option<Vec<syn::WherePredicate>>,
tag: TagType,
@@ -288,6 +301,8 @@ impl Container {
let mut default = Attr::none(cx, DEFAULT);
let mut rename_all_ser_rule = Attr::none(cx, RENAME_ALL);
let mut rename_all_de_rule = Attr::none(cx, RENAME_ALL);
+ let mut rename_all_fields_ser_rule = Attr::none(cx, RENAME_ALL_FIELDS);
+ let mut rename_all_fields_de_rule = Attr::none(cx, RENAME_ALL_FIELDS);
let mut ser_bound = Attr::none(cx, BOUND);
let mut de_bound = Attr::none(cx, BOUND);
let mut untagged = BoolAttr::none(cx, UNTAGGED);
@@ -341,6 +356,44 @@ impl Container {
}
}
}
+ } else if meta.path == RENAME_ALL_FIELDS {
+ // #[serde(rename_all_fields = "foo")]
+ // #[serde(rename_all_fields(serialize = "foo", deserialize = "bar"))]
+ let one_name = meta.input.peek(Token![=]);
+ let (ser, de) = get_renames(cx, RENAME_ALL_FIELDS, &meta)?;
+
+ match item.data {
+ syn::Data::Enum(_) => {
+ if let Some(ser) = ser {
+ match RenameRule::from_str(&ser.value()) {
+ Ok(rename_rule) => {
+ rename_all_fields_ser_rule.set(&meta.path, rename_rule);
+ }
+ Err(err) => cx.error_spanned_by(ser, err),
+ }
+ }
+ if let Some(de) = de {
+ match RenameRule::from_str(&de.value()) {
+ Ok(rename_rule) => {
+ rename_all_fields_de_rule.set(&meta.path, rename_rule);
+ }
+ Err(err) => {
+ if !one_name {
+ cx.error_spanned_by(de, err);
+ }
+ }
+ }
+ }
+ }
+ syn::Data::Struct(_) => {
+ let msg = "#[serde(rename_all_fields)] can only be used on enums";
+ cx.error_spanned_by(&meta.path, msg);
+ }
+ syn::Data::Union(_) => {
+ let msg = "#[serde(rename_all_fields)] can only be used on enums";
+ cx.error_spanned_by(&meta.path, msg);
+ }
+ }
} else if meta.path == TRANSPARENT {
// #[serde(transparent)]
transparent.set_true(meta.path);
@@ -528,6 +581,10 @@ impl Container {
serialize: rename_all_ser_rule.get().unwrap_or(RenameRule::None),
deserialize: rename_all_de_rule.get().unwrap_or(RenameRule::None),
},
+ rename_all_fields_rules: RenameAllRules {
+ serialize: rename_all_fields_ser_rule.get().unwrap_or(RenameRule::None),
+ deserialize: rename_all_fields_de_rule.get().unwrap_or(RenameRule::None),
+ },
ser_bound: ser_bound.get(),
de_bound: de_bound.get(),
tag: decide_tag(cx, item, untagged, internal_tag, content),
@@ -547,8 +604,12 @@ impl Container {
&self.name
}
- pub fn rename_all_rules(&self) -> &RenameAllRules {
- &self.rename_all_rules
+ pub fn rename_all_rules(&self) -> RenameAllRules {
+ self.rename_all_rules
+ }
+
+ pub fn rename_all_fields_rules(&self) -> RenameAllRules {
+ self.rename_all_fields_rules
}
pub fn transparent(&self) -> bool {
@@ -921,7 +982,7 @@ impl Variant {
self.name.deserialize_aliases()
}
- pub fn rename_by_rules(&mut self, rules: &RenameAllRules) {
+ pub fn rename_by_rules(&mut self, rules: RenameAllRules) {
if !self.name.serialize_renamed {
self.name.serialize = rules.serialize.apply_to_variant(&self.name.serialize);
}
@@ -930,8 +991,8 @@ impl Variant {
}
}
- pub fn rename_all_rules(&self) -> &RenameAllRules {
- &self.rename_all_rules
+ pub fn rename_all_rules(&self) -> RenameAllRules {
+ self.rename_all_rules
}
pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> {
@@ -1260,7 +1321,7 @@ impl Field {
self.name.deserialize_aliases()
}
- pub fn rename_by_rules(&mut self, rules: &RenameAllRules) {
+ pub fn rename_by_rules(&mut self, rules: RenameAllRules) {
if !self.name.serialize_renamed {
self.name.serialize = rules.serialize.apply_to_field(&self.name.serialize);
}
diff --git a/serde_derive/src/internals/case.rs b/serde_derive/src/internals/case.rs
index 554505160..e769462cd 100644
--- a/serde_derive/src/internals/case.rs
+++ b/serde_derive/src/internals/case.rs
@@ -59,8 +59,8 @@ impl RenameRule {
}
/// Apply a renaming rule to an enum variant, returning the version expected in the source.
- pub fn apply_to_variant(&self, variant: &str) -> String {
- match *self {
+ pub fn apply_to_variant(self, variant: &str) -> String {
+ match self {
None | PascalCase => variant.to_owned(),
LowerCase => variant.to_ascii_lowercase(),
UpperCase => variant.to_ascii_uppercase(),
@@ -84,8 +84,8 @@ impl RenameRule {
}
/// Apply a renaming rule to a struct field, returning the version expected in the source.
- pub fn apply_to_field(&self, field: &str) -> String {
- match *self {
+ pub fn apply_to_field(self, field: &str) -> String {
+ match self {
None | LowerCase | SnakeCase => field.to_owned(),
UpperCase => field.to_ascii_uppercase(),
PascalCase => {
@@ -112,6 +112,14 @@ impl RenameRule {
ScreamingKebabCase => ScreamingSnakeCase.apply_to_field(field).replace('_', "-"),
}
}
+
+ /// Returns the `RenameRule` if it is not `None`, `rule_b` otherwise.
+ pub fn or(self, rule_b: Self) -> Self {
+ match self {
+ None => rule_b,
+ _ => self,
+ }
+ }
}
pub struct ParseError<'a> {
diff --git a/serde_derive/src/internals/symbol.rs b/serde_derive/src/internals/symbol.rs
index 9606edb5f..68091fb85 100644
--- a/serde_derive/src/internals/symbol.rs
+++ b/serde_derive/src/internals/symbol.rs
@@ -23,6 +23,7 @@ pub const OTHER: Symbol = Symbol("other");
pub const REMOTE: Symbol = Symbol("remote");
pub const RENAME: Symbol = Symbol("rename");
pub const RENAME_ALL: Symbol = Symbol("rename_all");
+pub const RENAME_ALL_FIELDS: Symbol = Symbol("rename_all_fields");
pub const REPR: Symbol = Symbol("repr");
pub const SERDE: Symbol = Symbol("serde");
pub const SERIALIZE: Symbol = Symbol("serialize");
| serde-rs/serde | 2019-12-15T18:14:14Z | Seems reasonable. Do you have a suggestion for how this should work? Simplify changing the meaning of `rename_all` would be a breaking change.
Side note: representing the datastore value the following way may be more convenient. This avoids restating the type twice in Rust code -- <code>Value::<b>Boolean</b>(true)</code> instead of <code>Value::<b>Boolean</b> { <b>boolean</b>_value: true }</code>.
```rust
#[derive(Serialize, Deserialize)]
enum Value {
#[serde(rename = "nullValue", with = "null")]
Null,
#[serde(rename = "stringValue")]
String(String),
#[serde(rename = "booleanValue")]
Boolean(bool),
}
// Serialize the unit variant `Value::Null` as `{"nullValue":null}` rather
// than the default `"nullValue"`.
mod null {
use serde::{Serialize, Serializer, Deserialize, Deserializer};
pub fn serialize<S>(serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
().serialize(serializer)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<(), D::Error>
where D: Deserializer<'de>
{
<()>::deserialize(deserializer)
}
}
```
Thanks for a quick reply! I'm really enjoying `serde` btw, easily the most pleasant serialisation lib I've worked with so far :-)
----------------
> Do you have a suggestion for how this should work? Simplify changing the meaning of rename_all would be a breaking change.
Agreed, maybe it's sensible to have a separate `rename_fields` for this that would both apply to `struct` and `enum`-member fields?
---------------
> Side note: representing the datastore value the following way may be more convenient
The problem is that the enum is "key-tagged", i.e. it's adjacent to other keys inside of a different struct and the *key* that contains the `Value` determines its type.
I haven't found a better way than the current `untagged` solution, but I also really need to stop thinking about this for today and find a nearby bed! ;-)
Maybe instead of `rename_all` we should have had distinct `rename_fields` and `rename_variants` attributes, so that you can write both to get the desired effect.
It may be confusing to add those now and *not* have `rename_all` mean rename both fields and variants.
I would be willing to consider a pull request that adds a `serde(rename_all_fields = "...")` attribute for enums that applies a rename rule to every field of every variant. | ad94aed75398d43d174368aa8c4869332bb94e33 |
884 | diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index 9b5fc85a0..bb2010738 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -132,7 +132,6 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
Token::UnitStruct(_name) => visitor.visit_unit(),
Token::NewtypeStruct(_name) => visitor.visit_newtype_struct(self),
Token::Seq(len) => self.visit_seq(len, Token::SeqEnd, visitor),
- Token::SeqFixedSize(len) => self.visit_seq(Some(len), Token::SeqEnd, visitor),
Token::Tuple(len) => self.visit_seq(Some(len), Token::TupleEnd, visitor),
Token::TupleStruct(_, len) => self.visit_seq(Some(len), Token::TupleStructEnd, visitor),
Token::Map(len) => self.visit_map(len, Token::MapEnd, visitor),
@@ -262,20 +261,6 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
}
}
- fn deserialize_seq_fixed_size<V>(self, len: usize, visitor: V) -> Result<V::Value, Error>
- where
- V: Visitor<'de>,
- {
- match self.tokens.first() {
- Some(&Token::SeqFixedSize(_)) => {
- self.next_token();
- self.visit_seq(Some(len), Token::SeqEnd, visitor)
- }
- Some(_) => self.deserialize_any(visitor),
- None => Err(Error::EndOfTokens),
- }
- }
-
fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Error>
where
V: Visitor<'de>,
@@ -290,10 +275,6 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
self.next_token();
self.visit_seq(Some(len), Token::SeqEnd, visitor)
}
- Some(&Token::SeqFixedSize(_)) => {
- self.next_token();
- self.visit_seq(Some(len), Token::SeqEnd, visitor)
- }
Some(&Token::Tuple(_)) => {
self.next_token();
self.visit_seq(Some(len), Token::TupleEnd, visitor)
@@ -333,10 +314,6 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
self.next_token();
self.visit_seq(Some(len), Token::SeqEnd, visitor)
}
- Some(&Token::SeqFixedSize(_)) => {
- self.next_token();
- self.visit_seq(Some(len), Token::SeqEnd, visitor)
- }
Some(&Token::Tuple(_)) => {
self.next_token();
self.visit_seq(Some(len), Token::TupleEnd, visitor)
@@ -656,7 +633,7 @@ impl<'de> de::Deserializer<'de> for BytesDeserializer {
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct enum identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
+ map struct enum identifier ignored_any
}
}
diff --git a/serde_test/src/ser.rs b/serde_test/src/ser.rs
index b7b80d3be..5c90fee4e 100644
--- a/serde_test/src/ser.rs
+++ b/serde_test/src/ser.rs
@@ -212,11 +212,6 @@ impl<'s, 'a> ser::Serializer for &'s mut Serializer<'a> {
Ok(self)
}
- fn serialize_seq_fixed_size(self, len: usize) -> Result<Self, Error> {
- assert_next_token!(self, SeqFixedSize(len));
- Ok(self)
- }
-
fn serialize_tuple(self, len: usize) -> Result<Self, Error> {
assert_next_token!(self, Tuple(len));
Ok(self)
diff --git a/serde_test/src/token.rs b/serde_test/src/token.rs
index c640e48f1..07bbc0b99 100644
--- a/serde_test/src/token.rs
+++ b/serde_test/src/token.rs
@@ -103,12 +103,6 @@ pub enum Token {
/// header is a list of elements, followed by `SeqEnd`.
Seq(Option<usize>),
- /// The header to an array of the given length.
- ///
- /// These are serialized via `serialize_seq_fized_size`, which requires a length. After this
- /// header is a list of elements, followed by `SeqEnd`.
- SeqFixedSize(usize),
-
/// An indicator of the end of a sequence.
SeqEnd,
diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index 4a0ebb10e..e76fc6a95 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -360,8 +360,8 @@ declare_tests! {
Token::SeqEnd,
],
[0; 0] => &[
- Token::SeqFixedSize(0),
- Token::SeqEnd,
+ Token::Tuple(0),
+ Token::TupleEnd,
],
([0; 0], [1], [2, 3]) => &[
Token::Seq(Some(3)),
@@ -379,19 +379,19 @@ declare_tests! {
Token::SeqEnd,
],
([0; 0], [1], [2, 3]) => &[
- Token::SeqFixedSize(3),
- Token::SeqFixedSize(0),
- Token::SeqEnd,
+ Token::Tuple(3),
+ Token::Tuple(0),
+ Token::TupleEnd,
- Token::SeqFixedSize(1),
+ Token::Tuple(1),
Token::I32(1),
- Token::SeqEnd,
+ Token::TupleEnd,
- Token::SeqFixedSize(2),
+ Token::Tuple(2),
Token::I32(2),
Token::I32(3),
- Token::SeqEnd,
- Token::SeqEnd,
+ Token::TupleEnd,
+ Token::TupleEnd,
],
[0; 0] => &[
Token::TupleStruct("Anything", 0),
diff --git a/test_suite/tests/test_ser.rs b/test_suite/tests/test_ser.rs
index 28472ce37..2de5db147 100644
--- a/test_suite/tests/test_ser.rs
+++ b/test_suite/tests/test_ser.rs
@@ -138,15 +138,15 @@ declare_tests! {
}
test_array {
[0; 0] => &[
- Token::SeqFixedSize(0),
- Token::SeqEnd,
+ Token::Tuple(0),
+ Token::TupleEnd,
],
[1, 2, 3] => &[
- Token::SeqFixedSize(3),
+ Token::Tuple(3),
Token::I32(1),
Token::I32(2),
Token::I32(3),
- Token::SeqEnd,
+ Token::TupleEnd,
],
}
test_vec {
@@ -301,11 +301,11 @@ declare_tests! {
}
test_boxed_slice {
Box::new([0, 1, 2]) => &[
- Token::SeqFixedSize(3),
+ Token::Tuple(3),
Token::I32(0),
Token::I32(1),
Token::I32(2),
- Token::SeqEnd,
+ Token::TupleEnd,
],
}
test_duration {
| [
"883"
] | serde-rs__serde-884 | Remove seq_fixed_size in favor of tuple
Currently the data model uses different types for tuples like `(A, B, C)` and seq_fixed_size like `[u64; 3]`. I don't think there are any formats that treat these differently. The defining characteristic in both cases is they are heterogeneous sequences in which the length is known during deserialization without looking at the serialized data.
Let's remove seq_fixed_size and serialize fixed size arrays as tuples instead.
| 0.9 | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 6e4c65021..d7e6b7f83 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -634,7 +634,7 @@ impl<'de, T> Deserialize<'de> for [T; 0] {
where
D: Deserializer<'de>,
{
- deserializer.deserialize_seq_fixed_size(0, ArrayVisitor::<[T; 0]>::new())
+ deserializer.deserialize_tuple(0, ArrayVisitor::<[T; 0]>::new())
}
}
@@ -675,7 +675,7 @@ macro_rules! array_impls {
where
D: Deserializer<'de>,
{
- deserializer.deserialize_seq_fixed_size($len, ArrayVisitor::<[T; $len]>::new())
+ deserializer.deserialize_tuple($len, ArrayVisitor::<[T; $len]>::new())
}
}
)+
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index 245aa6ea0..3c9afa6f9 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -704,7 +704,7 @@ where
/// Serde.
///
/// The role of this trait is to define the deserialization half of the Serde
-/// data model, which is a way to categorize every Rust data type into one of 28
+/// data model, which is a way to categorize every Rust data type into one of 27
/// possible types. Each method of the `Serializer` trait corresponds to one of
/// the types of the data model.
///
@@ -714,47 +714,54 @@ where
///
/// The types that make up the Serde data model are:
///
-/// - 12 primitive types:
+/// - **12 primitive types**
/// - bool
/// - i8, i16, i32, i64
/// - u8, u16, u32, u64
/// - f32, f64
/// - char
-/// - string
-/// - byte array - [u8]
-/// - option
-/// - either none or some value
-/// - unit
-/// - unit is the type of () in Rust
-/// - unit_struct
-/// - for example `struct Unit` or `PhantomData<T>`
-/// - unit_variant
-/// - the `E::A` and `E::B` in `enum E { A, B }`
-/// - newtype_struct
-/// - for example `struct Millimeters(u8)`
-/// - newtype_variant
-/// - the `E::N` in `enum E { N(u8) }`
-/// - seq
-/// - a variably sized sequence of values, for example `Vec<T>` or
-/// `HashSet<T>`
-/// - seq_fixed_size
-/// - a statically sized sequence of values for which the size will be known
-/// at deserialization time without looking at the serialized data, for
-/// example `[u64; 10]`
-/// - tuple
-/// - for example `(u8,)` or `(String, u64, Vec<T>)`
-/// - tuple_struct
-/// - for example `struct Rgb(u8, u8, u8)`
-/// - tuple_variant
-/// - the `E::T` in `enum E { T(u8, u8) }`
-/// - map
-/// - for example `BTreeMap<K, V>`
-/// - struct
-/// - a key-value pairing in which the keys will be known at deserialization
-/// time without looking at the serialized data, for example `struct S { r:
-/// u8, g: u8, b: u8 }`
-/// - struct_variant
-/// - the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`
+/// - **string**
+/// - UTF-8 bytes with a length and no null terminator.
+/// - When serializing, all strings are handled equally. When deserializing,
+/// there are three flavors of strings: transient, owned, and borrowed.
+/// - **byte array** - [u8]
+/// - Similar to strings, during deserialization byte arrays can be transient,
+/// owned, or borrowed.
+/// - **option**
+/// - Either none or some value.
+/// - **unit**
+/// - The type of `()` in Rust. It represents an anonymous value containing no
+/// data.
+/// - **unit_struct**
+/// - For example `struct Unit` or `PhantomData<T>`. It represents a named value
+/// containing no data.
+/// - **unit_variant**
+/// - For example the `E::A` and `E::B` in `enum E { A, B }`.
+/// - **newtype_struct**
+/// - For example `struct Millimeters(u8)`.
+/// - **newtype_variant**
+/// - For example the `E::N` in `enum E { N(u8) }`.
+/// - **seq**
+/// - A variably sized heterogeneous sequence of values, for example `Vec<T>` or
+/// `HashSet<T>`. When serializing, the length may or may not be known before
+/// iterating through all the data. When deserializing, the length is determined
+/// by looking at the serialized data.
+/// - **tuple**
+/// - A statically sized heterogeneous sequence of values for which the length
+/// will be known at deserialization time without looking at the serialized
+/// data, for example `(u8,)` or `(String, u64, Vec<T>)` or `[u64; 10]`.
+/// - **tuple_struct**
+/// - A named tuple, for example `struct Rgb(u8, u8, u8)`.
+/// - **tuple_variant**
+/// - For example the `E::T` in `enum E { T(u8, u8) }`.
+/// - **map**
+/// - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`.
+/// - **struct**
+/// - A heterogeneous key-value pairing in which the keys are strings and will be
+/// known at deserialization time without looking at the serialized data, for
+/// example `struct S { r: u8, g: u8, b: u8 }`.
+/// - **struct_variant**
+/// - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`.
///
/// The `Deserializer` trait supports two entry point styles which enables
/// different kinds of deserialization.
@@ -944,16 +951,6 @@ pub trait Deserializer<'de>: Sized {
/// Hint that the `Deserialize` type is expecting a sequence of values and
/// knows how many values there are without looking at the serialized data.
- fn deserialize_seq_fixed_size<V>(
- self,
- len: usize,
- visitor: V,
- ) -> Result<V::Value, Self::Error>
- where
- V: Visitor<'de>;
-
- /// Hint that the `Deserialize` type is expecting a tuple value with a
- /// particular number of elements.
fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>;
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 97c558816..d8b0b434a 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -130,8 +130,8 @@ where
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf unit unit_struct newtype_struct seq seq_fixed_size tuple
- tuple_struct map struct enum identifier ignored_any
+ byte_buf unit unit_struct newtype_struct seq tuple tuple_struct map
+ struct enum identifier ignored_any
}
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
@@ -183,8 +183,8 @@ macro_rules! primitive_deserializer {
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct enum identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple
+ tuple_struct map struct enum identifier ignored_any
}
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
@@ -240,8 +240,8 @@ where
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
+ map struct identifier ignored_any
}
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
@@ -333,8 +333,8 @@ where
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
+ map struct identifier ignored_any
}
}
@@ -408,8 +408,8 @@ where
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
+ map struct identifier ignored_any
}
}
@@ -487,8 +487,8 @@ where
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
+ map struct identifier ignored_any
}
}
@@ -573,8 +573,8 @@ where
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct enum identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
+ map struct enum identifier ignored_any
}
}
@@ -687,8 +687,8 @@ where
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct enum identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
+ map struct enum identifier ignored_any
}
}
@@ -791,7 +791,7 @@ where
Ok(value)
}
- fn deserialize_seq_fixed_size<V>(
+ fn deserialize_tuple<V>(
self,
len: usize,
visitor: V,
@@ -805,8 +805,8 @@ where
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct tuple tuple_struct
- map struct enum identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct tuple_struct map struct
+ enum identifier ignored_any
}
}
@@ -946,8 +946,8 @@ where
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct tuple tuple_struct
- map struct enum identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct tuple_struct map struct
+ enum identifier ignored_any
}
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
@@ -973,7 +973,7 @@ where
}
}
- fn deserialize_seq_fixed_size<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
@@ -1093,8 +1093,8 @@ where
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct enum identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
+ map struct enum identifier ignored_any
}
}
diff --git a/serde/src/macros.rs b/serde/src/macros.rs
index 0d6545839..2a3d08724 100644
--- a/serde/src/macros.rs
+++ b/serde/src/macros.rs
@@ -44,9 +44,9 @@
/// }
/// #
/// # forward_to_deserialize_any! {
-/// # u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
-/// # seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
-/// # tuple_struct struct identifier tuple enum ignored_any
+/// # i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
+/// # byte_buf option unit unit_struct newtype_struct seq tuple
+/// # tuple_struct map struct enum identifier ignored_any
/// # }
/// # }
/// #
@@ -78,8 +78,8 @@
///
/// forward_to_deserialize_any! {
/// bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
-/// byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
-/// tuple tuple_struct map struct enum identifier ignored_any
+/// byte_buf option unit unit_struct newtype_struct seq tuple
+/// tuple_struct map struct enum identifier ignored_any
/// }
/// }
/// #
@@ -113,8 +113,8 @@
/// forward_to_deserialize_any! {
/// <W: Visitor<'q>>
/// bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
-/// byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
-/// tuple tuple_struct map struct enum identifier ignored_any
+/// byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
+/// map struct enum identifier ignored_any
/// }
/// # }
/// #
@@ -218,9 +218,6 @@ macro_rules! forward_to_deserialize_any_helper {
(seq<$l:tt, $v:ident>) => {
forward_to_deserialize_any_method!{deserialize_seq<$l, $v>()}
};
- (seq_fixed_size<$l:tt, $v:ident>) => {
- forward_to_deserialize_any_method!{deserialize_seq_fixed_size<$l, $v>(len: usize)}
- };
(tuple<$l:tt, $v:ident>) => {
forward_to_deserialize_any_method!{deserialize_tuple<$l, $v>(len: usize)}
};
diff --git a/serde/src/private/de.rs b/serde/src/private/de.rs
index 751113211..6666ada2d 100644
--- a/serde/src/private/de.rs
+++ b/serde/src/private/de.rs
@@ -49,8 +49,8 @@ where
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf unit unit_struct newtype_struct seq seq_fixed_size tuple
- tuple_struct map struct enum identifier ignored_any
+ byte_buf unit unit_struct newtype_struct seq tuple tuple_struct map
+ struct enum identifier ignored_any
}
}
@@ -995,8 +995,8 @@ mod content {
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf unit unit_struct seq seq_fixed_size tuple tuple_struct map
- struct identifier ignored_any
+ byte_buf unit unit_struct seq tuple tuple_struct map struct
+ identifier ignored_any
}
}
@@ -1153,8 +1153,8 @@ mod content {
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct enum identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple
+ tuple_struct map struct enum identifier ignored_any
}
}
@@ -1254,8 +1254,8 @@ mod content {
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct enum identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple
+ tuple_struct map struct enum identifier ignored_any
}
}
@@ -1390,8 +1390,8 @@ mod content {
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf unit unit_struct seq seq_fixed_size tuple tuple_struct map
- struct identifier ignored_any
+ byte_buf unit unit_struct seq tuple tuple_struct map struct
+ identifier ignored_any
}
}
@@ -1545,8 +1545,8 @@ mod content {
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct enum identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple
+ tuple_struct map struct enum identifier ignored_any
}
}
@@ -1647,8 +1647,8 @@ mod content {
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct enum identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple
+ tuple_struct map struct enum identifier ignored_any
}
}
@@ -1804,8 +1804,8 @@ where
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct enum identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
+ map struct enum identifier ignored_any
}
}
@@ -1843,7 +1843,7 @@ where
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
- byte_buf option unit unit_struct newtype_struct seq seq_fixed_size
- tuple tuple_struct map struct enum identifier ignored_any
+ byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
+ map struct enum identifier ignored_any
}
}
diff --git a/serde/src/private/macros.rs b/serde/src/private/macros.rs
index 0253e6e09..046761385 100644
--- a/serde/src/private/macros.rs
+++ b/serde/src/private/macros.rs
@@ -121,9 +121,6 @@ macro_rules! __serialize_unimplemented_helper {
type SerializeSeq = $crate::ser::Impossible<Self::Ok, Self::Error>;
__serialize_unimplemented_method!(serialize_seq(Option<usize>) -> SerializeSeq);
};
- (seq_fixed_size) => {
- __serialize_unimplemented_method!(serialize_seq_fixed_size(usize) -> SerializeSeq);
- };
(tuple) => {
type SerializeTuple = $crate::ser::Impossible<Self::Ok, Self::Error>;
__serialize_unimplemented_method!(serialize_tuple(usize) -> SerializeTuple);
diff --git a/serde/src/private/ser.rs b/serde/src/private/ser.rs
index 994875d44..8cb26d955 100644
--- a/serde/src/private/ser.rs
+++ b/serde/src/private/ser.rs
@@ -245,10 +245,6 @@ where
Err(self.bad_type(Unsupported::Sequence))
}
- fn serialize_seq_fixed_size(self, _: usize) -> Result<Self::SerializeSeq, Self::Error> {
- Err(self.bad_type(Unsupported::Sequence))
- }
-
fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
Err(self.bad_type(Unsupported::Tuple))
}
@@ -484,7 +480,6 @@ mod content {
NewtypeVariant(&'static str, u32, &'static str, Box<Content>),
Seq(Vec<Content>),
- SeqFixedSize(Vec<Content>),
Tuple(Vec<Content>),
TupleStruct(&'static str, Vec<Content>),
TupleVariant(&'static str, u32, &'static str, Vec<Content>),
@@ -523,14 +518,6 @@ mod content {
serializer.serialize_newtype_variant(n, i, v, &**c)
}
Content::Seq(ref elements) => elements.serialize(serializer),
- Content::SeqFixedSize(ref elements) => {
- use ser::SerializeSeq;
- let mut seq = try!(serializer.serialize_seq_fixed_size(elements.len()));
- for e in elements {
- try!(seq.serialize_element(e));
- }
- seq.end()
- }
Content::Tuple(ref elements) => {
use ser::SerializeTuple;
let mut tuple = try!(serializer.serialize_tuple(elements.len()));
@@ -726,23 +713,12 @@ mod content {
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, E> {
Ok(
SerializeSeq {
- fixed_size: false,
elements: Vec::with_capacity(len.unwrap_or(0)),
error: PhantomData,
},
)
}
- fn serialize_seq_fixed_size(self, size: usize) -> Result<Self::SerializeSeq, E> {
- Ok(
- SerializeSeq {
- fixed_size: true,
- elements: Vec::with_capacity(size),
- error: PhantomData,
- },
- )
- }
-
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, E> {
Ok(
SerializeTuple {
@@ -828,7 +804,6 @@ mod content {
}
struct SerializeSeq<E> {
- fixed_size: bool,
elements: Vec<Content>,
error: PhantomData<E>,
}
@@ -850,13 +825,7 @@ mod content {
}
fn end(self) -> Result<Content, E> {
- Ok(
- if self.fixed_size {
- Content::SeqFixedSize(self.elements)
- } else {
- Content::Seq(self.elements)
- },
- )
+ Ok(Content::Seq(self.elements))
}
}
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index b127773e7..dad456f15 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -8,7 +8,7 @@
use lib::*;
-use ser::{Serialize, SerializeSeq, SerializeTuple, Serializer};
+use ser::{Serialize, SerializeTuple, Serializer};
#[cfg(feature = "std")]
use ser::Error;
@@ -130,7 +130,7 @@ impl<T> Serialize for [T; 0] {
where
S: Serializer,
{
- try!(serializer.serialize_seq_fixed_size(0)).end()
+ try!(serializer.serialize_tuple(0)).end()
}
}
@@ -146,7 +146,7 @@ macro_rules! array_impls {
where
S: Serializer,
{
- let mut seq = try!(serializer.serialize_seq_fixed_size($len));
+ let mut seq = try!(serializer.serialize_tuple($len));
for e in self {
try!(seq.serialize_element(e));
}
diff --git a/serde/src/ser/impossible.rs b/serde/src/ser/impossible.rs
index 592047f4f..f72748f69 100644
--- a/serde/src/ser/impossible.rs
+++ b/serde/src/ser/impossible.rs
@@ -53,8 +53,7 @@ use ser::{self, Serialize, SerializeSeq, SerializeTuple, SerializeTupleStruct,
/// # __serialize_unimplemented! {
/// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str bytes none some
/// # unit unit_struct unit_variant newtype_struct newtype_variant
-/// # seq_fixed_size tuple tuple_struct tuple_variant map struct
-/// # struct_variant
+/// # tuple tuple_struct tuple_variant map struct struct_variant
/// # }
/// }
/// #
diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs
index 0aa3c9a7c..67b60fcc7 100644
--- a/serde/src/ser/mod.rs
+++ b/serde/src/ser/mod.rs
@@ -239,7 +239,7 @@ pub trait Serialize {
/// A **data format** that can serialize any data structure supported by Serde.
///
/// The role of this trait is to define the serialization half of the Serde data
-/// model, which is a way to categorize every Rust data structure into one of 28
+/// model, which is a way to categorize every Rust data structure into one of 27
/// possible types. Each method of the `Serializer` trait corresponds to one of
/// the types of the data model.
///
@@ -248,47 +248,54 @@ pub trait Serialize {
///
/// The types that make up the Serde data model are:
///
-/// - 12 primitive types:
+/// - **12 primitive types**
/// - bool
/// - i8, i16, i32, i64
/// - u8, u16, u32, u64
/// - f32, f64
/// - char
-/// - string
-/// - byte array - [u8]
-/// - option
-/// - either none or some value
-/// - unit
-/// - unit is the type of () in Rust
-/// - unit_struct
-/// - for example `struct Unit` or `PhantomData<T>`
-/// - unit_variant
-/// - the `E::A` and `E::B` in `enum E { A, B }`
-/// - newtype_struct
-/// - for example `struct Millimeters(u8)`
-/// - newtype_variant
-/// - the `E::N` in `enum E { N(u8) }`
-/// - seq
-/// - a variably sized sequence of values, for example `Vec<T>` or
-/// `HashSet<T>`
-/// - seq_fixed_size
-/// - a statically sized sequence of values for which the size will be known
-/// at deserialization time without looking at the serialized data, for
-/// example `[u64; 10]`
-/// - tuple
-/// - for example `(u8,)` or `(String, u64, Vec<T>)`
-/// - tuple_struct
-/// - for example `struct Rgb(u8, u8, u8)`
-/// - tuple_variant
-/// - the `E::T` in `enum E { T(u8, u8) }`
-/// - map
-/// - for example `BTreeMap<K, V>`
-/// - struct
-/// - a key-value pairing in which the keys will be known at deserialization
-/// time without looking at the serialized data, for example `struct S { r:
-/// u8, g: u8, b: u8 }`
-/// - struct_variant
-/// - the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`
+/// - **string**
+/// - UTF-8 bytes with a length and no null terminator.
+/// - When serializing, all strings are handled equally. When deserializing,
+/// there are three flavors of strings: transient, owned, and borrowed.
+/// - **byte array** - [u8]
+/// - Similar to strings, during deserialization byte arrays can be transient,
+/// owned, or borrowed.
+/// - **option**
+/// - Either none or some value.
+/// - **unit**
+/// - The type of `()` in Rust. It represents an anonymous value containing no
+/// data.
+/// - **unit_struct**
+/// - For example `struct Unit` or `PhantomData<T>`. It represents a named value
+/// containing no data.
+/// - **unit_variant**
+/// - For example the `E::A` and `E::B` in `enum E { A, B }`.
+/// - **newtype_struct**
+/// - For example `struct Millimeters(u8)`.
+/// - **newtype_variant**
+/// - For example the `E::N` in `enum E { N(u8) }`.
+/// - **seq**
+/// - A variably sized heterogeneous sequence of values, for example `Vec<T>` or
+/// `HashSet<T>`. When serializing, the length may or may not be known before
+/// iterating through all the data. When deserializing, the length is determined
+/// by looking at the serialized data.
+/// - **tuple**
+/// - A statically sized heterogeneous sequence of values for which the length
+/// will be known at deserialization time without looking at the serialized
+/// data, for example `(u8,)` or `(String, u64, Vec<T>)` or `[u64; 10]`.
+/// - **tuple_struct**
+/// - A named tuple, for example `struct Rgb(u8, u8, u8)`.
+/// - **tuple_variant**
+/// - For example the `E::T` in `enum E { T(u8, u8) }`.
+/// - **map**
+/// - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`.
+/// - **struct**
+/// - A heterogeneous key-value pairing in which the keys are strings and will be
+/// known at deserialization time without looking at the serialized data, for
+/// example `struct S { r: u8, g: u8, b: u8 }`.
+/// - **struct_variant**
+/// - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`.
///
/// Many Serde serializers produce text or binary data as output, for example
/// JSON or Bincode. This is not a requirement of the `Serializer` trait, and
@@ -310,11 +317,10 @@ pub trait Serializer: Sized {
/// The error type when some error occurs during serialization.
type Error: Error;
- /// Type returned from [`serialize_seq`] and [`serialize_seq_fixed_size`]
- /// for serializing the content of the sequence.
+ /// Type returned from [`serialize_seq`] for serializing the content of the
+ /// sequence.
///
/// [`serialize_seq`]: #tymethod.serialize_seq
- /// [`serialize_seq_fixed_size`]: #tymethod.serialize_seq_fixed_size
type SerializeSeq: SerializeSeq<Ok = Self::Ok, Error = Self::Error>;
/// Type returned from [`serialize_tuple`] for serializing the content of
@@ -702,8 +708,7 @@ pub trait Serializer: Sized {
/// # __serialize_unimplemented! {
/// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str none some
/// # unit unit_struct unit_variant newtype_struct newtype_variant
- /// # seq seq_fixed_size tuple tuple_struct tuple_variant map struct
- /// # struct_variant
+ /// # seq tuple tuple_struct tuple_variant map struct struct_variant
/// # }
/// # }
/// #
@@ -966,29 +971,6 @@ pub trait Serializer: Sized {
/// then a call to `end`.
///
/// ```rust
- /// use serde::ser::{Serialize, Serializer, SerializeSeq};
- ///
- /// const VRAM_SIZE: usize = 386;
- /// struct Vram([u16; VRAM_SIZE]);
- ///
- /// impl Serialize for Vram {
- /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- /// where S: Serializer
- /// {
- /// let mut seq = serializer.serialize_seq_fixed_size(VRAM_SIZE)?;
- /// for element in &self.0[..] {
- /// seq.serialize_element(element)?;
- /// }
- /// seq.end()
- /// }
- /// }
- /// ```
- fn serialize_seq_fixed_size(self, size: usize) -> Result<Self::SerializeSeq, Self::Error>;
-
- /// Begin to serialize a tuple. This call must be followed by zero or more
- /// calls to `serialize_element`, then a call to `end`.
- ///
- /// ```rust
/// use serde::ser::{Serialize, Serializer, SerializeTuple};
///
/// # mod fool {
@@ -1015,6 +997,25 @@ pub trait Serializer: Sized {
/// }
/// }
/// ```
+ ///
+ /// ```rust
+ /// use serde::ser::{Serialize, Serializer, SerializeTuple};
+ ///
+ /// const VRAM_SIZE: usize = 386;
+ /// struct Vram([u16; VRAM_SIZE]);
+ ///
+ /// impl Serialize for Vram {
+ /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ /// where S: Serializer
+ /// {
+ /// let mut seq = serializer.serialize_tuple(VRAM_SIZE)?;
+ /// for element in &self.0[..] {
+ /// seq.serialize_element(element)?;
+ /// }
+ /// seq.end()
+ /// }
+ /// }
+ /// ```
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error>;
/// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This
@@ -1359,34 +1360,26 @@ pub trait Serializer: Sized {
T: Display;
}
-/// Returned from `Serializer::serialize_seq` and
-/// `Serializer::serialize_seq_fixed_size`.
+/// Returned from `Serializer::serialize_seq`.
///
/// ```rust
/// # use std::marker::PhantomData;
/// #
-/// # macro_rules! unimplemented_vec {
-/// # ($name:ident) => {
-/// # struct $name<T>(PhantomData<T>);
-/// #
-/// # impl<T> $name<T> {
-/// # fn len(&self) -> usize {
-/// # unimplemented!()
-/// # }
-/// # }
+/// # struct Vec<T>(PhantomData<T>);
/// #
-/// # impl<'a, T> IntoIterator for &'a $name<T> {
-/// # type Item = &'a T;
-/// # type IntoIter = Box<Iterator<Item = &'a T>>;
-/// # fn into_iter(self) -> Self::IntoIter {
-/// # unimplemented!()
-/// # }
-/// # }
+/// # impl<T> Vec<T> {
+/// # fn len(&self) -> usize {
+/// # unimplemented!()
/// # }
/// # }
/// #
-/// # unimplemented_vec!(Vec);
-/// # unimplemented_vec!(Array);
+/// # impl<'a, T> IntoIterator for &'a Vec<T> {
+/// # type Item = &'a T;
+/// # type IntoIter = Box<Iterator<Item = &'a T>>;
+/// # fn into_iter(self) -> Self::IntoIter {
+/// # unimplemented!()
+/// # }
+/// # }
/// #
/// use serde::ser::{Serialize, Serializer, SerializeSeq};
///
@@ -1403,26 +1396,6 @@ pub trait Serializer: Sized {
/// seq.end()
/// }
/// }
-///
-/// # mod fool {
-/// # trait Serialize {}
-/// impl<T> Serialize for [T; 16]
-/// # {}
-/// # }
-/// #
-/// # impl<T> Serialize for Array<T>
-/// where T: Serialize
-/// {
-/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
-/// where S: Serializer
-/// {
-/// let mut seq = serializer.serialize_seq_fixed_size(16)?;
-/// for element in self {
-/// seq.serialize_element(element)?;
-/// }
-/// seq.end()
-/// }
-/// }
/// ```
pub trait SerializeSeq {
/// Must match the `Ok` type of our `Serializer`.
@@ -1469,6 +1442,48 @@ pub trait SerializeSeq {
/// }
/// }
/// ```
+///
+/// ```rust
+/// # use std::marker::PhantomData;
+/// #
+/// # struct Array<T>(PhantomData<T>);
+/// #
+/// # impl<T> Array<T> {
+/// # fn len(&self) -> usize {
+/// # unimplemented!()
+/// # }
+/// # }
+/// #
+/// # impl<'a, T> IntoIterator for &'a Array<T> {
+/// # type Item = &'a T;
+/// # type IntoIter = Box<Iterator<Item = &'a T>>;
+/// # fn into_iter(self) -> Self::IntoIter {
+/// # unimplemented!()
+/// # }
+/// # }
+/// #
+/// use serde::ser::{Serialize, Serializer, SerializeTuple};
+///
+/// # mod fool {
+/// # trait Serialize {}
+/// impl<T> Serialize for [T; 16]
+/// # {}
+/// # }
+/// #
+/// # impl<T> Serialize for Array<T>
+/// where T: Serialize
+/// {
+/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+/// where S: Serializer
+/// {
+/// let mut seq = serializer.serialize_tuple(16)?;
+/// for element in self {
+/// seq.serialize_element(element)?;
+/// }
+/// seq.end()
+/// }
+/// }
+/// ```
pub trait SerializeTuple {
/// Must match the `Ok` type of our `Serializer`.
type Ok;
| serde-rs/serde | 2017-04-17T19:08:34Z | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 | |
879 | diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index cef4bcaed..c826ee865 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -404,9 +404,8 @@ impl<'de, 'a> SeqAccess<'de> for DeserializerSeqVisitor<'a, 'de> {
seed.deserialize(&mut *self.de).map(Some)
}
- fn size_hint(&self) -> (usize, Option<usize>) {
- let len = self.len.unwrap_or(0);
- (len, self.len)
+ fn size_hint(&self) -> Option<usize> {
+ self.len
}
}
@@ -439,9 +438,8 @@ impl<'de, 'a> MapAccess<'de> for DeserializerMapVisitor<'a, 'de> {
seed.deserialize(&mut *self.de)
}
- fn size_hint(&self) -> (usize, Option<usize>) {
- let len = self.len.unwrap_or(0);
- (len, self.len)
+ fn size_hint(&self) -> Option<usize> {
+ self.len
}
}
| [
"875"
] | serde-rs__serde-879 | Change size_hint from (usize, Option<usize>) to Option<usize>
The size_hint for iterators is `(lower, Option<upper>)` because if you filter, take, chain, etc then you can get these elaborate constraints. That never happens when deserializing. The deserializer either knows ahead of time how many elements there are or it doesn't know.
| 0.9 | 637332de2d2fa8008a8d35fbcd90d0d1ce221957 | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 3999f3e36..c955498b9 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -16,6 +16,9 @@ use de::MapAccess;
use de::from_primitive::FromPrimitive;
+#[cfg(any(feature = "std", feature = "collections"))]
+use private::de::size_hint;
+
////////////////////////////////////////////////////////////////////////////////
struct UnitVisitor;
@@ -344,7 +347,7 @@ impl<'de> Visitor<'de> for CStringVisitor {
where
A: SeqAccess<'de>,
{
- let len = cmp::min(seq.size_hint().0, 4096);
+ let len = size_hint::cautious(seq.size_hint());
let mut values = Vec::with_capacity(len);
while let Some(value) = try!(seq.next_element()) {
@@ -557,16 +560,16 @@ macro_rules! seq_impl {
seq_impl!(
BinaryHeap<T>,
BinaryHeapVisitor<T: Ord>,
- visitor,
+ seq,
BinaryHeap::new(),
- BinaryHeap::with_capacity(cmp::min(visitor.size_hint().0, 4096)),
+ BinaryHeap::with_capacity(size_hint::cautious(seq.size_hint())),
BinaryHeap::push);
#[cfg(any(feature = "std", feature = "collections"))]
seq_impl!(
BTreeSet<T>,
BTreeSetVisitor<T: Eq + Ord>,
- visitor,
+ seq,
BTreeSet::new(),
BTreeSet::new(),
BTreeSet::insert);
@@ -575,7 +578,7 @@ seq_impl!(
seq_impl!(
LinkedList<T>,
LinkedListVisitor,
- visitor,
+ seq,
LinkedList::new(),
LinkedList::new(),
LinkedList::push_back);
@@ -585,27 +588,27 @@ seq_impl!(
HashSet<T, S>,
HashSetVisitor<T: Eq + Hash,
S: BuildHasher + Default>,
- visitor,
+ seq,
HashSet::with_hasher(S::default()),
- HashSet::with_capacity_and_hasher(cmp::min(visitor.size_hint().0, 4096), S::default()),
+ HashSet::with_capacity_and_hasher(size_hint::cautious(seq.size_hint()), S::default()),
HashSet::insert);
#[cfg(any(feature = "std", feature = "collections"))]
seq_impl!(
Vec<T>,
VecVisitor,
- visitor,
+ seq,
Vec::new(),
- Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096)),
+ Vec::with_capacity(size_hint::cautious(seq.size_hint())),
Vec::push);
#[cfg(any(feature = "std", feature = "collections"))]
seq_impl!(
VecDeque<T>,
VecDequeVisitor,
- visitor,
+ seq,
VecDeque::new(),
- VecDeque::with_capacity(cmp::min(visitor.size_hint().0, 4096)),
+ VecDeque::with_capacity(size_hint::cautious(seq.size_hint())),
VecDeque::push_back);
////////////////////////////////////////////////////////////////////////////////
@@ -865,7 +868,7 @@ macro_rules! map_impl {
map_impl!(
BTreeMap<K, V>,
BTreeMapVisitor<K: Ord>,
- visitor,
+ map,
BTreeMap::new(),
BTreeMap::new());
@@ -874,9 +877,9 @@ map_impl!(
HashMap<K, V, S>,
HashMapVisitor<K: Eq + Hash,
S: BuildHasher + Default>,
- visitor,
+ map,
HashMap::with_hasher(S::default()),
- HashMap::with_capacity_and_hasher(cmp::min(visitor.size_hint().0, 4096), S::default()));
+ HashMap::with_capacity_and_hasher(size_hint::cautious(map.size_hint()), S::default()));
////////////////////////////////////////////////////////////////////////////////
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index dc67021b2..af45dbb31 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -1376,10 +1376,10 @@ pub trait SeqAccess<'de> {
self.next_element_seed(PhantomData)
}
- /// Return the lower and upper bound of items remaining in the sequence.
+ /// Returns the number of elements remaining in the sequence, if known.
#[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- (0, None)
+ fn size_hint(&self) -> Option<usize> {
+ None
}
}
@@ -1406,7 +1406,7 @@ where
}
#[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
+ fn size_hint(&self) -> Option<usize> {
(**self).size_hint()
}
}
@@ -1504,10 +1504,10 @@ pub trait MapAccess<'de> {
self.next_entry_seed(PhantomData, PhantomData)
}
- /// Return the lower and upper bound of items remaining in the sequence.
+ /// Returns the number of entries remaining in the map, if known.
#[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- (0, None)
+ fn size_hint(&self) -> Option<usize> {
+ None
}
}
@@ -1572,7 +1572,7 @@ where
}
#[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
+ fn size_hint(&self) -> Option<usize> {
(**self).size_hint()
}
}
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index a521c9a6e..921a4ac56 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -11,6 +11,7 @@
use lib::*;
use de::{self, IntoDeserializer, Expected, SeqAccess};
+use private::de::size_hint;
use self::private::{First, Second};
////////////////////////////////////////////////////////////////////////////////
@@ -545,8 +546,8 @@ where
}
}
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
+ fn size_hint(&self) -> Option<usize> {
+ size_hint::from_bounds(&self.iter)
}
}
@@ -799,8 +800,8 @@ where
}
}
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
+ fn size_hint(&self) -> Option<usize> {
+ size_hint::from_bounds(&self.iter)
}
}
@@ -827,8 +828,8 @@ where
}
}
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
+ fn size_hint(&self) -> Option<usize> {
+ size_hint::from_bounds(&self.iter)
}
}
@@ -910,7 +911,7 @@ where
if pair_visitor.1.is_none() {
Ok(pair)
} else {
- let remaining = pair_visitor.size_hint().0;
+ let remaining = pair_visitor.size_hint().unwrap();
// First argument is the number of elements in the data, second
// argument is the number of elements expected by the Deserialize.
Err(de::Error::invalid_length(2, &ExpectedInSeq(2 - remaining)))
@@ -954,15 +955,14 @@ where
}
}
- fn size_hint(&self) -> (usize, Option<usize>) {
- let len = if self.0.is_some() {
- 2
+ fn size_hint(&self) -> Option<usize> {
+ if self.0.is_some() {
+ Some(2)
} else if self.1.is_some() {
- 1
+ Some(1)
} else {
- 0
- };
- (len, Some(len))
+ Some(0)
+ }
}
}
diff --git a/serde/src/private/de.rs b/serde/src/private/de.rs
index 7ad86def5..957052a35 100644
--- a/serde/src/private/de.rs
+++ b/serde/src/private/de.rs
@@ -187,6 +187,29 @@ where
deserializer.deserialize_str(CowBytesVisitor)
}
+pub mod size_hint {
+ use lib::*;
+
+ pub fn from_bounds<I>(iter: &I) -> Option<usize>
+ where I: Iterator
+ {
+ helper(iter.size_hint())
+ }
+
+ pub fn cautious(hint: Option<usize>) -> usize {
+ cmp::min(hint.unwrap_or(0), 4096)
+ }
+
+ fn helper(bounds: (usize, Option<usize>)) -> Option<usize> {
+ match bounds {
+ (lower, Some(upper)) if lower == upper => {
+ Some(upper)
+ }
+ _ => None,
+ }
+ }
+}
+
#[cfg(any(feature = "std", feature = "collections"))]
mod content {
// This module is private and nothing here should be used outside of
@@ -203,6 +226,7 @@ mod content {
use de::{self, Deserialize, DeserializeSeed, Deserializer, Visitor, SeqAccess, MapAccess,
EnumAccess, Unexpected};
+ use super::size_hint;
/// Used from generated code to buffer the contents of the Deserializer when
/// deserializing untagged enums and internally tagged enums.
@@ -428,7 +452,7 @@ mod content {
where
V: SeqAccess<'de>,
{
- let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096));
+ let mut vec = Vec::with_capacity(size_hint::cautious(visitor.size_hint()));
while let Some(e) = try!(visitor.next_element()) {
vec.push(e);
}
@@ -439,7 +463,7 @@ mod content {
where
V: MapAccess<'de>,
{
- let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096));
+ let mut vec = Vec::with_capacity(size_hint::cautious(visitor.size_hint()));
while let Some(kv) = try!(visitor.next_entry()) {
vec.push(kv);
}
@@ -764,7 +788,7 @@ mod content {
V: MapAccess<'de>,
{
let mut tag = None;
- let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096));
+ let mut vec = Vec::with_capacity(size_hint::cautious(visitor.size_hint()));
while let Some(k) =
try!(visitor.next_key_seed(TagOrContentVisitor::new(self.tag_name))) {
match k {
@@ -1153,8 +1177,8 @@ mod content {
}
}
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
+ fn size_hint(&self) -> Option<usize> {
+ size_hint::from_bounds(&self.iter)
}
}
@@ -1209,8 +1233,8 @@ mod content {
}
}
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
+ fn size_hint(&self) -> Option<usize> {
+ size_hint::from_bounds(&self.iter)
}
}
@@ -1546,8 +1570,8 @@ mod content {
}
}
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
+ fn size_hint(&self) -> Option<usize> {
+ size_hint::from_bounds(&self.iter)
}
}
@@ -1603,8 +1627,8 @@ mod content {
}
}
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
+ fn size_hint(&self) -> Option<usize> {
+ size_hint::from_bounds(&self.iter)
}
}
| serde-rs/serde | 2017-04-14T20:28:29Z | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 | |
878 | diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index b6ce5725b..cef4bcaed 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -97,12 +97,12 @@ impl<'de> Deserializer<'de> {
impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
type Error = Error;
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit
seq bytes byte_buf map identifier ignored_any
}
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: Visitor<'de>,
{
@@ -192,7 +192,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
self.next_token();
visitor.visit_some(self)
}
- Some(_) => self.deserialize(visitor),
+ Some(_) => self.deserialize_any(visitor),
None => Err(Error::EndOfTokens),
}
}
@@ -239,7 +239,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
Err(Error::InvalidName(n))
}
}
- Some(_) => self.deserialize(visitor),
+ Some(_) => self.deserialize_any(visitor),
None => Err(Error::EndOfTokens),
}
}
@@ -257,7 +257,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
Err(Error::InvalidName(n))
}
}
- Some(_) => self.deserialize(visitor),
+ Some(_) => self.deserialize_any(visitor),
None => Err(Error::EndOfTokens),
}
}
@@ -271,7 +271,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
self.next_token();
self.visit_seq(Some(len), Token::SeqEnd, visitor)
}
- Some(_) => self.deserialize(visitor),
+ Some(_) => self.deserialize_any(visitor),
None => Err(Error::EndOfTokens),
}
}
@@ -302,7 +302,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
self.next_token();
self.visit_seq(Some(len), Token::TupleStructEnd, visitor)
}
- Some(_) => self.deserialize(visitor),
+ Some(_) => self.deserialize_any(visitor),
None => Err(Error::EndOfTokens),
}
}
@@ -349,7 +349,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
Err(Error::InvalidName(n))
}
}
- Some(_) => self.deserialize(visitor),
+ Some(_) => self.deserialize_any(visitor),
None => Err(Error::EndOfTokens),
}
}
@@ -376,7 +376,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
self.next_token();
self.visit_map(Some(fields.len()), Token::MapEnd, visitor)
}
- Some(_) => self.deserialize(visitor),
+ Some(_) => self.deserialize_any(visitor),
None => Err(Error::EndOfTokens),
}
}
@@ -529,7 +529,7 @@ impl<'de, 'a> VariantAccess<'de> for DeserializerEnumVisitor<'a, 'de> {
Err(Error::UnexpectedToken(token))
}
}
- Some(_) => de::Deserializer::deserialize(self.de, visitor),
+ Some(_) => de::Deserializer::deserialize_any(self.de, visitor),
None => Err(Error::EndOfTokens),
}
}
@@ -559,7 +559,7 @@ impl<'de, 'a> VariantAccess<'de> for DeserializerEnumVisitor<'a, 'de> {
Err(Error::UnexpectedToken(token))
}
}
- Some(_) => de::Deserializer::deserialize(self.de, visitor),
+ Some(_) => de::Deserializer::deserialize_any(self.de, visitor),
None => Err(Error::EndOfTokens),
}
}
@@ -649,14 +649,14 @@ struct BytesDeserializer {
impl<'de> de::Deserializer<'de> for BytesDeserializer {
type Error = Error;
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_bytes(self.value)
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
struct identifier tuple enum ignored_any byte_buf
| [
"874"
] | serde-rs__serde-878 | Rename Deserializer::deserialize to deserialize_any
- I think the current method is overused unintentionally and I think a better name would clarify the point of the method.
- The current name causes ambiguities when both Deserialize and Deserializer are in scope. In particular, `serde_json::Value::deserialize` is ambiguous and requires less-readable workarounds.
- The name `deserialize_any` nicely relates to `deserialize_ignored_any`.
| 0.9 | 1798d1af6e3de3083d4d3ff8610e2b215a855f32 | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index b7ec32b19..3999f3e36 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -1070,7 +1070,7 @@ impl<'de> Deserialize<'de> for OsStringKind {
}
}
- deserializer.deserialize(KindVisitor)
+ deserializer.deserialize_identifier(KindVisitor)
}
}
@@ -1581,7 +1581,7 @@ where
}
}
- deserializer.deserialize(FieldVisitor)
+ deserializer.deserialize_identifier(FieldVisitor)
}
}
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index 86398eb35..dc67021b2 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -763,22 +763,22 @@ where
/// to look at the serialized data and tell what it represents. For example
/// the JSON deserializer may see an opening curly brace (`{`) and know that
/// it is seeing a map. If the data format supports
-/// `Deserializer::deserialize`, it will drive the Visitor using whatever
+/// `Deserializer::deserialize_any`, it will drive the Visitor using whatever
/// type it sees in the input. JSON uses this approach when deserializing
/// `serde_json::Value` which is an enum that can represent any JSON
/// document. Without knowing what is in a JSON document, we can deserialize
-/// it to `serde_json::Value` by going through `Deserializer::deserialize`.
+/// it to `serde_json::Value` by going through `Deserializer::deserialize_any`.
///
/// 2. The various `deserialize_*` methods. Non-self-describing formats like
/// Bincode need to be told what is in the input in order to deserialize it.
/// The `deserialize_*` methods are hints to the deserializer for how to
/// interpret the next piece of input. Non-self-describing formats are not
/// able to deserialize something like `serde_json::Value` which relies on
-/// `Deserializer::deserialize`.
+/// `Deserializer::deserialize_any`.
///
/// When implementing `Deserialize`, you should avoid relying on
-/// `Deserializer::deserialize` unless you need to be told by the Deserializer
-/// what type is in the input. Know that relying on `Deserializer::deserialize`
+/// `Deserializer::deserialize_any` unless you need to be told by the Deserializer
+/// what type is in the input. Know that relying on `Deserializer::deserialize_any`
/// means your data type will be able to deserialize from self-describing
/// formats only, ruling out Bincode and many others.
pub trait Deserializer<'de>: Sized {
@@ -790,12 +790,12 @@ pub trait Deserializer<'de>: Sized {
/// on what data type is in the input.
///
/// When implementing `Deserialize`, you should avoid relying on
- /// `Deserializer::deserialize` unless you need to be told by the
+ /// `Deserializer::deserialize_any` unless you need to be told by the
/// Deserializer what type is in the input. Know that relying on
- /// `Deserializer::deserialize` means your data type will be able to
+ /// `Deserializer::deserialize_any` means your data type will be able to
/// deserialize from self-describing formats only, ruling out Bincode and
/// many others.
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>;
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 0917d5498..a521c9a6e 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -88,13 +88,13 @@ where
{
type Error = E;
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
seq_fixed_size bytes map unit_struct newtype_struct tuple_struct struct
identifier tuple enum ignored_any byte_buf
}
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
@@ -140,13 +140,13 @@ macro_rules! primitive_deserializer {
{
type Error = E;
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit
option seq seq_fixed_size bytes map unit_struct newtype_struct
tuple_struct struct identifier tuple enum ignored_any byte_buf
}
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
@@ -197,13 +197,13 @@ where
{
type Error = E;
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
struct identifier tuple ignored_any byte_buf
}
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
@@ -267,7 +267,7 @@ where
{
type Error = E;
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
@@ -286,7 +286,7 @@ where
visitor.visit_enum(self)
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
struct identifier tuple ignored_any byte_buf
@@ -340,7 +340,7 @@ where
{
type Error = E;
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
@@ -359,7 +359,7 @@ where
visitor.visit_enum(self)
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
struct identifier tuple ignored_any byte_buf
@@ -414,7 +414,7 @@ where
{
type Error = E;
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
@@ -436,7 +436,7 @@ where
visitor.visit_enum(self)
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
struct identifier tuple ignored_any byte_buf
@@ -508,7 +508,7 @@ where
{
type Error = E;
- fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
@@ -517,7 +517,7 @@ where
Ok(v)
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
struct identifier tuple enum ignored_any byte_buf
@@ -624,14 +624,14 @@ where
{
type Error = V_::Error;
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_seq(self.visitor)
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
struct identifier tuple enum ignored_any byte_buf
@@ -712,7 +712,7 @@ where
{
type Error = E;
- fn deserialize<V_>(mut self, visitor: V_) -> Result<V_::Value, Self::Error>
+ fn deserialize_any<V_>(mut self, visitor: V_) -> Result<V_::Value, Self::Error>
where
V_: de::Visitor<'de>,
{
@@ -740,7 +740,7 @@ where
self.deserialize_seq(visitor)
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
bytes map unit_struct newtype_struct tuple_struct struct identifier
tuple enum ignored_any byte_buf
@@ -888,13 +888,13 @@ where
{
type Error = E;
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
bytes map unit_struct newtype_struct tuple_struct struct identifier
tuple enum ignored_any byte_buf
}
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
@@ -1029,14 +1029,14 @@ where
{
type Error = V_::Error;
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_map(self.visitor)
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
struct identifier tuple enum ignored_any byte_buf
diff --git a/serde/src/macros.rs b/serde/src/macros.rs
index f75eebf9a..6b7ea6e22 100644
--- a/serde/src/macros.rs
+++ b/serde/src/macros.rs
@@ -30,7 +30,7 @@
/// # impl<'de> Deserializer<'de> for MyDeserializer {
/// # type Error = value::Error;
/// #
-/// # fn deserialize<V>(self, _: V) -> Result<V::Value, Self::Error>
+/// # fn deserialize_any<V>(self, _: V) -> Result<V::Value, Self::Error>
/// # where V: Visitor<'de>
/// # {
/// # unimplemented!()
@@ -40,10 +40,10 @@
/// fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
/// where V: Visitor<'de>
/// {
-/// self.deserialize(visitor)
+/// self.deserialize_any(visitor)
/// }
/// #
-/// # forward_to_deserialize! {
+/// # forward_to_deserialize_any! {
/// # u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
/// # seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
/// # tuple_struct struct identifier tuple enum ignored_any
@@ -53,9 +53,9 @@
/// # fn main() {}
/// ```
///
-/// The `forward_to_deserialize!` macro implements these simple forwarding
-/// methods so that they forward directly to [`Deserializer::deserialize`]. You
-/// can choose which methods to forward.
+/// The `forward_to_deserialize_any!` macro implements these simple forwarding
+/// methods so that they forward directly to [`Deserializer::deserialize_any`].
+/// You can choose which methods to forward.
///
/// ```rust
/// # #[macro_use]
@@ -68,7 +68,7 @@
/// impl<'de> Deserializer<'de> for MyDeserializer {
/// # type Error = value::Error;
/// #
-/// fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+/// fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
/// where V: Visitor<'de>
/// {
/// /* ... */
@@ -76,7 +76,7 @@
/// # unimplemented!()
/// }
///
-/// forward_to_deserialize! {
+/// forward_to_deserialize_any! {
/// bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
/// seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
/// tuple_struct struct identifier tuple enum ignored_any
@@ -104,13 +104,13 @@
/// # impl<'q, V> Deserializer<'q> for MyDeserializer<V> {
/// # type Error = value::Error;
/// #
-/// # fn deserialize<W>(self, visitor: W) -> Result<W::Value, Self::Error>
+/// # fn deserialize_any<W>(self, visitor: W) -> Result<W::Value, Self::Error>
/// # where W: Visitor<'q>
/// # {
/// # unimplemented!()
/// # }
/// #
-/// forward_to_deserialize! {
+/// forward_to_deserialize_any! {
/// <W: Visitor<'q>>
/// bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
/// seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
@@ -123,21 +123,21 @@
///
/// [`Deserializer`]: trait.Deserializer.html
/// [`Visitor`]: de/trait.Visitor.html
-/// [`Deserializer::deserialize`]: trait.Deserializer.html#tymethod.deserialize
+/// [`Deserializer::deserialize_any`]: trait.Deserializer.html#tymethod.deserialize_any
#[macro_export]
-macro_rules! forward_to_deserialize {
+macro_rules! forward_to_deserialize_any {
(<$visitor:ident: Visitor<$lifetime:tt>> $($func:ident)*) => {
- $(forward_to_deserialize_helper!{$func<$lifetime, $visitor>})*
+ $(forward_to_deserialize_any_helper!{$func<$lifetime, $visitor>})*
};
// This case must be after the previous one.
($($func:ident)*) => {
- $(forward_to_deserialize_helper!{$func<'de, V>})*
+ $(forward_to_deserialize_any_helper!{$func<'de, V>})*
};
}
#[doc(hidden)]
#[macro_export]
-macro_rules! forward_to_deserialize_method {
+macro_rules! forward_to_deserialize_any_method {
($func:ident<$l:tt, $v:ident>($($arg:ident : $ty:ty),*)) => {
#[inline]
fn $func<$v>(self, $($arg: $ty,)* visitor: $v) -> $crate::export::Result<$v::Value, Self::Error>
@@ -147,99 +147,99 @@ macro_rules! forward_to_deserialize_method {
$(
let _ = $arg;
)*
- self.deserialize(visitor)
+ self.deserialize_any(visitor)
}
};
}
#[doc(hidden)]
#[macro_export]
-macro_rules! forward_to_deserialize_helper {
+macro_rules! forward_to_deserialize_any_helper {
(bool<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_bool<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_bool<$l, $v>()}
};
(u8<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_u8<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_u8<$l, $v>()}
};
(u16<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_u16<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_u16<$l, $v>()}
};
(u32<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_u32<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_u32<$l, $v>()}
};
(u64<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_u64<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_u64<$l, $v>()}
};
(i8<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_i8<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_i8<$l, $v>()}
};
(i16<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_i16<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_i16<$l, $v>()}
};
(i32<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_i32<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_i32<$l, $v>()}
};
(i64<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_i64<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_i64<$l, $v>()}
};
(f32<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_f32<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_f32<$l, $v>()}
};
(f64<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_f64<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_f64<$l, $v>()}
};
(char<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_char<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_char<$l, $v>()}
};
(str<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_str<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_str<$l, $v>()}
};
(string<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_string<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_string<$l, $v>()}
};
(unit<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_unit<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_unit<$l, $v>()}
};
(option<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_option<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_option<$l, $v>()}
};
(seq<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_seq<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_seq<$l, $v>()}
};
(seq_fixed_size<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_seq_fixed_size<$l, $v>(len: usize)}
+ forward_to_deserialize_any_method!{deserialize_seq_fixed_size<$l, $v>(len: usize)}
};
(bytes<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_bytes<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_bytes<$l, $v>()}
};
(byte_buf<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_byte_buf<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_byte_buf<$l, $v>()}
};
(map<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_map<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_map<$l, $v>()}
};
(unit_struct<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_unit_struct<$l, $v>(name: &'static str)}
+ forward_to_deserialize_any_method!{deserialize_unit_struct<$l, $v>(name: &'static str)}
};
(newtype_struct<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_newtype_struct<$l, $v>(name: &'static str)}
+ forward_to_deserialize_any_method!{deserialize_newtype_struct<$l, $v>(name: &'static str)}
};
(tuple_struct<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_tuple_struct<$l, $v>(name: &'static str, len: usize)}
+ forward_to_deserialize_any_method!{deserialize_tuple_struct<$l, $v>(name: &'static str, len: usize)}
};
(struct<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_struct<$l, $v>(name: &'static str, fields: &'static [&'static str])}
+ forward_to_deserialize_any_method!{deserialize_struct<$l, $v>(name: &'static str, fields: &'static [&'static str])}
};
(identifier<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_identifier<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_identifier<$l, $v>()}
};
(tuple<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_tuple<$l, $v>(len: usize)}
+ forward_to_deserialize_any_method!{deserialize_tuple<$l, $v>(len: usize)}
};
(enum<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_enum<$l, $v>(name: &'static str, variants: &'static [&'static str])}
+ forward_to_deserialize_any_method!{deserialize_enum<$l, $v>(name: &'static str, variants: &'static [&'static str])}
};
(ignored_any<$l:tt, $v:ident>) => {
- forward_to_deserialize_method!{deserialize_ignored_any<$l, $v>()}
+ forward_to_deserialize_any_method!{deserialize_ignored_any<$l, $v>()}
};
}
diff --git a/serde/src/private/de.rs b/serde/src/private/de.rs
index d5c03061d..7ad86def5 100644
--- a/serde/src/private/de.rs
+++ b/serde/src/private/de.rs
@@ -33,7 +33,7 @@ where
{
type Error = E;
- fn deserialize<V>(self, _visitor: V) -> Result<V::Value, E>
+ fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, E>
where
V: Visitor<'de>,
{
@@ -47,7 +47,7 @@ where
visitor.visit_none()
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
seq_fixed_size bytes byte_buf map unit_struct newtype_struct
tuple_struct struct identifier tuple enum ignored_any
@@ -271,7 +271,7 @@ mod content {
{
// Untagged and internally tagged enums are only supported in
// self-describing formats.
- deserializer.deserialize(ContentVisitor)
+ deserializer.deserialize_any(ContentVisitor)
}
}
@@ -481,7 +481,7 @@ mod content {
{
// Internally tagged enums are only supported in self-describing
// formats.
- deserializer.deserialize(self)
+ deserializer.deserialize_any(self)
}
}
@@ -745,7 +745,7 @@ mod content {
{
// Internally tagged enums are only supported in self-describing
// formats.
- deserializer.deserialize(self)
+ deserializer.deserialize_any(self)
}
}
@@ -854,7 +854,7 @@ mod content {
{
type Error = E;
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
@@ -969,7 +969,7 @@ mod content {
)
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
identifier tuple ignored_any
@@ -1057,7 +1057,7 @@ mod content {
{
match self.value {
Some(Content::Seq(v)) => {
- de::Deserializer::deserialize(SeqDeserializer::new(v), visitor)
+ de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor)
}
Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant"),),
None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"tuple variant"),),
@@ -1074,7 +1074,7 @@ mod content {
{
match self.value {
Some(Content::Map(v)) => {
- de::Deserializer::deserialize(MapDeserializer::new(v), visitor)
+ de::Deserializer::deserialize_any(MapDeserializer::new(v), visitor)
}
Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant"),),
_ => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"struct variant"),),
@@ -1109,7 +1109,7 @@ mod content {
type Error = E;
#[inline]
- fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
@@ -1127,7 +1127,7 @@ mod content {
}
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
tuple_struct struct identifier tuple enum ignored_any
@@ -1221,14 +1221,14 @@ mod content {
type Error = E;
#[inline]
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_map(self)
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
tuple_struct struct identifier tuple enum ignored_any
@@ -1250,7 +1250,7 @@ mod content {
{
type Error = E;
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, E>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, E>
where
V: Visitor<'de>,
{
@@ -1365,7 +1365,7 @@ mod content {
)
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
identifier tuple ignored_any
@@ -1450,7 +1450,7 @@ mod content {
{
match self.value {
Some(&Content::Seq(ref v)) => {
- de::Deserializer::deserialize(SeqRefDeserializer::new(v), visitor)
+ de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor)
}
Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"tuple variant"),),
None => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"tuple variant"),),
@@ -1467,7 +1467,7 @@ mod content {
{
match self.value {
Some(&Content::Map(ref v)) => {
- de::Deserializer::deserialize(MapRefDeserializer::new(v), visitor)
+ de::Deserializer::deserialize_any(MapRefDeserializer::new(v), visitor)
}
Some(other) => Err(de::Error::invalid_type(other.unexpected(), &"struct variant"),),
_ => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"struct variant"),),
@@ -1502,7 +1502,7 @@ mod content {
type Error = E;
#[inline]
- fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
@@ -1520,7 +1520,7 @@ mod content {
}
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
tuple_struct struct identifier tuple enum ignored_any
@@ -1615,14 +1615,14 @@ mod content {
type Error = E;
#[inline]
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
visitor.visit_map(self)
}
- forward_to_deserialize! {
+ forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
tuple_struct struct identifier tuple enum ignored_any
diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 994b9a9ba..6eb3846bd 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -497,7 +497,7 @@ fn deserialize_struct(
};
let dispatch = if let Some(deserializer) = deserializer {
quote! {
- _serde::Deserializer::deserialize(#deserializer, #visitor_expr)
+ _serde::Deserializer::deserialize_any(#deserializer, #visitor_expr)
}
} else if is_enum {
quote! {
@@ -729,7 +729,7 @@ fn deserialize_internally_tagged_enum(
#variants_stmt
- let __tagged = try!(_serde::Deserializer::deserialize(
+ let __tagged = try!(_serde::Deserializer::deserialize_any(
__deserializer,
_serde::private::de::TaggedContentVisitor::<__Field>::new(#tag)));
@@ -1083,7 +1083,7 @@ fn deserialize_internally_tagged_variant(
let type_name = params.type_name();
let variant_name = variant.ident.as_ref();
quote_block! {
- try!(_serde::Deserializer::deserialize(#deserializer, _serde::private::de::InternallyTaggedUnitVisitor::new(#type_name, #variant_name)));
+ try!(_serde::Deserializer::deserialize_any(#deserializer, _serde::private::de::InternallyTaggedUnitVisitor::new(#type_name, #variant_name)));
_serde::export::Ok(#this::#variant_ident)
}
}
@@ -1109,7 +1109,7 @@ fn deserialize_untagged_variant(
let variant_name = variant.ident.as_ref();
quote_expr! {
_serde::export::Result::map(
- _serde::Deserializer::deserialize(
+ _serde::Deserializer::deserialize_any(
#deserializer,
_serde::private::de::UntaggedUnitVisitor::new(#type_name, #variant_name)
),
| serde-rs/serde | 2017-04-14T19:51:27Z | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 | |
876 | diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index c30f6e273..b6ce5725b 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -6,8 +6,8 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use serde::de::{self, Deserialize, DeserializeSeed, EnumVisitor, IntoDeserializer, MapVisitor,
- SeqVisitor, VariantVisitor, Visitor};
+use serde::de::{self, Deserialize, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess,
+ SeqAccess, VariantAccess, Visitor};
use serde::de::value::{MapVisitorDeserializer, SeqVisitorDeserializer};
use error::Error;
@@ -390,10 +390,10 @@ struct DeserializerSeqVisitor<'a, 'de: 'a> {
end: Token,
}
-impl<'de, 'a> SeqVisitor<'de> for DeserializerSeqVisitor<'a, 'de> {
+impl<'de, 'a> SeqAccess<'de> for DeserializerSeqVisitor<'a, 'de> {
type Error = Error;
- fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
+ fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
where
T: DeserializeSeed<'de>,
{
@@ -418,10 +418,10 @@ struct DeserializerMapVisitor<'a, 'de: 'a> {
end: Token,
}
-impl<'de, 'a> MapVisitor<'de> for DeserializerMapVisitor<'a, 'de> {
+impl<'de, 'a> MapAccess<'de> for DeserializerMapVisitor<'a, 'de> {
type Error = Error;
- fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
+ fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
where
K: DeserializeSeed<'de>,
{
@@ -432,7 +432,7 @@ impl<'de, 'a> MapVisitor<'de> for DeserializerMapVisitor<'a, 'de> {
seed.deserialize(&mut *self.de).map(Some)
}
- fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
+ fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
where
V: DeserializeSeed<'de>,
{
@@ -451,11 +451,11 @@ struct DeserializerEnumVisitor<'a, 'de: 'a> {
de: &'a mut Deserializer<'de>,
}
-impl<'de, 'a> EnumVisitor<'de> for DeserializerEnumVisitor<'a, 'de> {
+impl<'de, 'a> EnumAccess<'de> for DeserializerEnumVisitor<'a, 'de> {
type Error = Error;
type Variant = Self;
- fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self), Error>
+ fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self), Error>
where
V: DeserializeSeed<'de>,
{
@@ -477,10 +477,10 @@ impl<'de, 'a> EnumVisitor<'de> for DeserializerEnumVisitor<'a, 'de> {
}
}
-impl<'de, 'a> VariantVisitor<'de> for DeserializerEnumVisitor<'a, 'de> {
+impl<'de, 'a> VariantAccess<'de> for DeserializerEnumVisitor<'a, 'de> {
type Error = Error;
- fn visit_unit(self) -> Result<(), Error> {
+ fn deserialize_unit(self) -> Result<(), Error> {
match self.de.tokens.first() {
Some(&Token::UnitVariant(_, _)) => {
self.de.next_token();
@@ -491,7 +491,7 @@ impl<'de, 'a> VariantVisitor<'de> for DeserializerEnumVisitor<'a, 'de> {
}
}
- fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
+ fn deserialize_newtype_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
where
T: DeserializeSeed<'de>,
{
@@ -505,7 +505,7 @@ impl<'de, 'a> VariantVisitor<'de> for DeserializerEnumVisitor<'a, 'de> {
}
}
- fn visit_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Error>
+ fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Error>
where
V: Visitor<'de>,
{
@@ -534,7 +534,7 @@ impl<'de, 'a> VariantVisitor<'de> for DeserializerEnumVisitor<'a, 'de> {
}
}
- fn visit_struct<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Error>
+ fn deserialize_struct<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Error>
where
V: Visitor<'de>,
{
@@ -589,10 +589,10 @@ impl<'a, 'de> EnumMapVisitor<'a, 'de> {
}
}
-impl<'de, 'a> MapVisitor<'de> for EnumMapVisitor<'a, 'de> {
+impl<'de, 'a> MapAccess<'de> for EnumMapVisitor<'a, 'de> {
type Error = Error;
- fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
+ fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
where
K: DeserializeSeed<'de>,
{
@@ -608,7 +608,7 @@ impl<'de, 'a> MapVisitor<'de> for EnumMapVisitor<'a, 'de> {
}
}
- fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
+ fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
where
V: DeserializeSeed<'de>,
{
| [
"873"
] | serde-rs__serde-876 | Rename Seq/Map/Enum/VariantVisitor
Possible new names:
- `serde::de::SeqAccess`
- `serde::de::MapAccess`
- `serde::de::EnumAccess`
- `serde::de::VariantAccess`
I dislike that Visitor and SeqVisitor are both "visitors" but one of them is the responsibility of the data structure and the other is the responsibility of the data format. I have seen this trip people up where they aren't sure which one(s) they need to implement. I believe the current naming scheme is unhelpful.
Conceptually the only thing doing any visiting is the data structure's Visitor. The SeqVisitor etc have never been visitors but are providing access to the data contained inside a seq/map/enum/variant.
With the new scheme the data structure would be responsible for providing Deserialize(..) and Visitor, while the data format would be responsible for providing Deserializer and (..)Access.
Thoughts @oli-obk @nox?
| 0.9 | f2de0509f5cbabad34e20dded361a65347afc96c | diff --git a/serde/src/de/ignored_any.rs b/serde/src/de/ignored_any.rs
index b8ff0c756..a4f3abe26 100644
--- a/serde/src/de/ignored_any.rs
+++ b/serde/src/de/ignored_any.rs
@@ -8,7 +8,7 @@
use lib::*;
-use de::{Deserialize, Deserializer, Visitor, SeqVisitor, MapVisitor, Error};
+use de::{Deserialize, Deserializer, Visitor, SeqAccess, MapAccess, Error};
/// An efficient way of discarding data from a deserializer.
///
@@ -20,7 +20,7 @@ use de::{Deserialize, Deserializer, Visitor, SeqVisitor, MapVisitor, Error};
/// use std::fmt;
/// use std::marker::PhantomData;
///
-/// use serde::de::{self, Deserialize, DeserializeSeed, Deserializer, Visitor, SeqVisitor, IgnoredAny};
+/// use serde::de::{self, Deserialize, DeserializeSeed, Deserializer, Visitor, SeqAccess, IgnoredAny};
///
/// /// A seed that can be used to deserialize only the `n`th element of a sequence
/// /// while efficiently discarding elements of any type before or after index `n`.
@@ -53,19 +53,19 @@ use de::{Deserialize, Deserializer, Visitor, SeqVisitor, MapVisitor, Error};
/// write!(formatter, "a sequence in which we care about element {}", self.n)
/// }
///
-/// fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
-/// where V: SeqVisitor<'de>
+/// fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
+/// where A: SeqAccess<'de>
/// {
/// // Skip over the first `n` elements.
/// for i in 0..self.n {
/// // It is an error if the sequence ends before we get to element `n`.
-/// if seq.visit::<IgnoredAny>()?.is_none() {
+/// if seq.next_element::<IgnoredAny>()?.is_none() {
/// return Err(de::Error::invalid_length(i, &self));
/// }
/// }
///
/// // Deserialize the one we care about.
-/// let nth = match seq.visit()? {
+/// let nth = match seq.next_element()? {
/// Some(nth) => nth,
/// None => {
/// return Err(de::Error::invalid_length(self.n, &self));
@@ -73,7 +73,7 @@ use de::{Deserialize, Deserializer, Visitor, SeqVisitor, MapVisitor, Error};
/// };
///
/// // Skip over any remaining elements in the sequence after `n`.
-/// while let Some(IgnoredAny) = seq.visit()? {
+/// while let Some(IgnoredAny) = seq.next_element()? {
/// // ignore
/// }
///
@@ -173,22 +173,22 @@ impl<'de> Visitor<'de> for IgnoredAny {
}
#[inline]
- fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
+ fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
- V: SeqVisitor<'de>,
+ A: SeqAccess<'de>,
{
- while let Some(IgnoredAny) = try!(visitor.visit()) {
+ while let Some(IgnoredAny) = try!(seq.next_element()) {
// Gobble
}
Ok(IgnoredAny)
}
#[inline]
- fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
+ fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
- V: MapVisitor<'de>,
+ A: MapAccess<'de>,
{
- while let Some((IgnoredAny, IgnoredAny)) = try!(visitor.visit()) {
+ while let Some((IgnoredAny, IgnoredAny)) = try!(map.next_entry()) {
// Gobble
}
Ok(IgnoredAny)
diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 222df6246..b7ec32b19 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -8,11 +8,11 @@
use lib::*;
-use de::{Deserialize, Deserializer, EnumVisitor, Error, SeqVisitor, Unexpected, VariantVisitor,
+use de::{Deserialize, Deserializer, EnumAccess, Error, SeqAccess, Unexpected, VariantAccess,
Visitor};
#[cfg(any(feature = "std", feature = "collections"))]
-use de::MapVisitor;
+use de::MapAccess;
use de::from_primitive::FromPrimitive;
@@ -340,14 +340,14 @@ impl<'de> Visitor<'de> for CStringVisitor {
formatter.write_str("byte array")
}
- fn visit_seq<V>(self, mut visitor: V) -> Result<CString, V::Error>
+ fn visit_seq<A>(self, mut seq: A) -> Result<CString, A::Error>
where
- V: SeqVisitor<'de>,
+ A: SeqAccess<'de>,
{
- let len = cmp::min(visitor.size_hint().0, 4096);
+ let len = cmp::min(seq.size_hint().0, 4096);
let mut values = Vec::with_capacity(len);
- while let Some(value) = try!(visitor.visit()) {
+ while let Some(value) = try!(seq.next_element()) {
values.push(value);
}
@@ -495,7 +495,7 @@ macro_rules! seq_impl {
(
$ty:ident < T $(, $typaram:ident)* >,
$visitor_ty:ident $( < $($boundparam:ident : $bound1:ident $(+ $bound2:ident)*),* > )*,
- $visitor:ident,
+ $access:ident,
$ctor:expr,
$with_capacity:expr,
$insert:expr
@@ -524,13 +524,13 @@ macro_rules! seq_impl {
}
#[inline]
- fn visit_seq<V>(self, mut $visitor: V) -> Result<Self::Value, V::Error>
+ fn visit_seq<A>(self, mut $access: A) -> Result<Self::Value, A::Error>
where
- V: SeqVisitor<'de>,
+ A: SeqAccess<'de>,
{
let mut values = $with_capacity;
- while let Some(value) = try!($visitor.visit()) {
+ while let Some(value) = try!($access.next_element()) {
$insert(&mut values, value);
}
@@ -628,9 +628,9 @@ impl<'de, T> Visitor<'de> for ArrayVisitor<[T; 0]> {
}
#[inline]
- fn visit_seq<V>(self, _: V) -> Result<[T; 0], V::Error>
+ fn visit_seq<A>(self, _: A) -> Result<[T; 0], A::Error>
where
- V: SeqVisitor<'de>,
+ A: SeqAccess<'de>,
{
Ok([])
}
@@ -660,12 +660,12 @@ macro_rules! array_impls {
}
#[inline]
- fn visit_seq<V>(self, mut visitor: V) -> Result<[T; $len], V::Error>
+ fn visit_seq<A>(self, mut seq: A) -> Result<[T; $len], A::Error>
where
- V: SeqVisitor<'de>,
+ A: SeqAccess<'de>,
{
$(
- let $name = match try!(visitor.visit()) {
+ let $name = match try!(seq.next_element()) {
Some(val) => val,
None => return Err(Error::invalid_length($n, &self)),
};
@@ -749,12 +749,12 @@ macro_rules! tuple_impls {
#[inline]
#[allow(non_snake_case)]
- fn visit_seq<V>(self, mut visitor: V) -> Result<($($name,)+), V::Error>
+ fn visit_seq<A>(self, mut seq: A) -> Result<($($name,)+), A::Error>
where
- V: SeqVisitor<'de>,
+ A: SeqAccess<'de>,
{
$(
- let $name = match try!(visitor.visit()) {
+ let $name = match try!(seq.next_element()) {
Some(value) => value,
None => return Err(Error::invalid_length($n, &self)),
};
@@ -802,7 +802,7 @@ macro_rules! map_impl {
(
$ty:ident < K, V $(, $typaram:ident)* >,
$visitor_ty:ident < $($boundparam:ident : $bound1:ident $(+ $bound2:ident)*),* >,
- $visitor:ident,
+ $access:ident,
$ctor:expr,
$with_capacity:expr
) => {
@@ -831,13 +831,13 @@ macro_rules! map_impl {
}
#[inline]
- fn visit_map<Visitor>(self, mut $visitor: Visitor) -> Result<Self::Value, Visitor::Error>
+ fn visit_map<A>(self, mut $access: A) -> Result<Self::Value, A::Error>
where
- Visitor: MapVisitor<'de>,
+ A: MapAccess<'de>,
{
let mut values = $with_capacity;
- while let Some((key, value)) = try!($visitor.visit()) {
+ while let Some((key, value)) = try!($access.next_entry()) {
values.insert(key, value);
}
@@ -1086,29 +1086,29 @@ impl<'de> Visitor<'de> for OsStringVisitor {
}
#[cfg(unix)]
- fn visit_enum<V>(self, visitor: V) -> Result<OsString, V::Error>
+ fn visit_enum<A>(self, data: A) -> Result<OsString, A::Error>
where
- V: EnumVisitor<'de>,
+ A: EnumAccess<'de>,
{
use std::os::unix::ffi::OsStringExt;
- match try!(visitor.visit_variant()) {
- (OsStringKind::Unix, variant) => variant.visit_newtype().map(OsString::from_vec),
+ match try!(data.variant()) {
+ (OsStringKind::Unix, variant) => variant.deserialize_newtype().map(OsString::from_vec),
(OsStringKind::Windows, _) => Err(Error::custom("cannot deserialize Windows OS string on Unix",),),
}
}
#[cfg(windows)]
- fn visit_enum<V>(self, visitor: V) -> Result<OsString, V::Error>
+ fn visit_enum<A>(self, data: A) -> Result<OsString, A::Error>
where
- V: EnumVisitor<'de>,
+ A: EnumAccess<'de>,
{
use std::os::windows::ffi::OsStringExt;
- match try!(visitor.visit_variant()) {
+ match try!(data.variant()) {
(OsStringKind::Windows, variant) => {
variant
- .visit_newtype::<Vec<u16>>()
+ .deserialize_newtype::<Vec<u16>>()
.map(|vec| OsString::from_wide(&vec))
}
(OsStringKind::Unix, _) => Err(Error::custom("cannot deserialize Unix OS string on Windows",),),
@@ -1285,17 +1285,17 @@ impl<'de> Deserialize<'de> for Duration {
formatter.write_str("struct Duration")
}
- fn visit_seq<V>(self, mut visitor: V) -> Result<Duration, V::Error>
+ fn visit_seq<A>(self, mut seq: A) -> Result<Duration, A::Error>
where
- V: SeqVisitor<'de>,
+ A: SeqAccess<'de>,
{
- let secs: u64 = match try!(visitor.visit()) {
+ let secs: u64 = match try!(seq.next_element()) {
Some(value) => value,
None => {
return Err(Error::invalid_length(0, &self));
}
};
- let nanos: u32 = match try!(visitor.visit()) {
+ let nanos: u32 = match try!(seq.next_element()) {
Some(value) => value,
None => {
return Err(Error::invalid_length(1, &self));
@@ -1304,35 +1304,35 @@ impl<'de> Deserialize<'de> for Duration {
Ok(Duration::new(secs, nanos))
}
- fn visit_map<V>(self, mut visitor: V) -> Result<Duration, V::Error>
+ fn visit_map<A>(self, mut map: A) -> Result<Duration, A::Error>
where
- V: MapVisitor<'de>,
+ A: MapAccess<'de>,
{
let mut secs: Option<u64> = None;
let mut nanos: Option<u32> = None;
- while let Some(key) = try!(visitor.visit_key::<Field>()) {
+ while let Some(key) = try!(map.next_key()) {
match key {
Field::Secs => {
if secs.is_some() {
- return Err(<V::Error as Error>::duplicate_field("secs"));
+ return Err(<A::Error as Error>::duplicate_field("secs"));
}
- secs = Some(try!(visitor.visit_value()));
+ secs = Some(try!(map.next_value()));
}
Field::Nanos => {
if nanos.is_some() {
- return Err(<V::Error as Error>::duplicate_field("nanos"));
+ return Err(<A::Error as Error>::duplicate_field("nanos"));
}
- nanos = Some(try!(visitor.visit_value()));
+ nanos = Some(try!(map.next_value()));
}
}
}
let secs = match secs {
Some(secs) => secs,
- None => return Err(<V::Error as Error>::missing_field("secs")),
+ None => return Err(<A::Error as Error>::missing_field("secs")),
};
let nanos = match nanos {
Some(nanos) => nanos,
- None => return Err(<V::Error as Error>::missing_field("nanos")),
+ None => return Err(<A::Error as Error>::missing_field("nanos")),
};
Ok(Duration::new(secs, nanos))
}
@@ -1425,17 +1425,17 @@ where
formatter.write_str("struct Range")
}
- fn visit_seq<V>(self, mut visitor: V) -> Result<ops::Range<Idx>, V::Error>
+ fn visit_seq<A>(self, mut seq: A) -> Result<ops::Range<Idx>, A::Error>
where
- V: SeqVisitor<'de>,
+ A: SeqAccess<'de>,
{
- let start: Idx = match try!(visitor.visit()) {
+ let start: Idx = match try!(seq.next_element()) {
Some(value) => value,
None => {
return Err(Error::invalid_length(0, &self));
}
};
- let end: Idx = match try!(visitor.visit()) {
+ let end: Idx = match try!(seq.next_element()) {
Some(value) => value,
None => {
return Err(Error::invalid_length(1, &self));
@@ -1444,35 +1444,35 @@ where
Ok(start..end)
}
- fn visit_map<V>(self, mut visitor: V) -> Result<ops::Range<Idx>, V::Error>
+ fn visit_map<A>(self, mut map: A) -> Result<ops::Range<Idx>, A::Error>
where
- V: MapVisitor<'de>,
+ A: MapAccess<'de>,
{
let mut start: Option<Idx> = None;
let mut end: Option<Idx> = None;
- while let Some(key) = try!(visitor.visit_key::<Field>()) {
+ while let Some(key) = try!(map.next_key()) {
match key {
Field::Start => {
if start.is_some() {
- return Err(<V::Error as Error>::duplicate_field("start"));
+ return Err(<A::Error as Error>::duplicate_field("start"));
}
- start = Some(try!(visitor.visit_value()));
+ start = Some(try!(map.next_value()));
}
Field::End => {
if end.is_some() {
- return Err(<V::Error as Error>::duplicate_field("end"));
+ return Err(<A::Error as Error>::duplicate_field("end"));
}
- end = Some(try!(visitor.visit_value()));
+ end = Some(try!(map.next_value()));
}
}
}
let start = match start {
Some(start) => start,
- None => return Err(<V::Error as Error>::missing_field("start")),
+ None => return Err(<A::Error as Error>::missing_field("start")),
};
let end = match end {
Some(end) => end,
- None => return Err(<V::Error as Error>::missing_field("end")),
+ None => return Err(<A::Error as Error>::missing_field("end")),
};
Ok(start..end)
}
@@ -1598,13 +1598,13 @@ where
formatter.write_str("enum Result")
}
- fn visit_enum<V>(self, visitor: V) -> Result<Result<T, E>, V::Error>
+ fn visit_enum<A>(self, data: A) -> Result<Result<T, E>, A::Error>
where
- V: EnumVisitor<'de>,
+ A: EnumAccess<'de>,
{
- match try!(visitor.visit_variant()) {
- (Field::Ok, variant) => variant.visit_newtype().map(Ok),
- (Field::Err, variant) => variant.visit_newtype().map(Err),
+ match try!(data.variant()) {
+ (Field::Ok, variant) => variant.deserialize_newtype().map(Ok),
+ (Field::Err, variant) => variant.deserialize_newtype().map(Err),
}
}
}
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index 35e00531d..86398eb35 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -585,7 +585,7 @@ where
/// use std::fmt;
/// use std::marker::PhantomData;
///
-/// use serde::de::{Deserialize, DeserializeSeed, Deserializer, Visitor, SeqVisitor};
+/// use serde::de::{Deserialize, DeserializeSeed, Deserializer, Visitor, SeqAccess};
///
/// // A DeserializeSeed implementation that uses stateful deserialization to
/// // append array elements onto the end of an existing vector. The preexisting
@@ -618,12 +618,12 @@ where
/// write!(formatter, "an array of integers")
/// }
///
-/// fn visit_seq<V>(self, mut visitor: V) -> Result<(), V::Error>
-/// where V: SeqVisitor<'de>
+/// fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error>
+/// where A: SeqAccess<'de>
/// {
/// // Visit each element in the inner array and push it onto
/// // the existing vector.
-/// while let Some(elem) = visitor.visit()? {
+/// while let Some(elem) = seq.next_element()? {
/// self.0.push(elem);
/// }
/// Ok(())
@@ -648,14 +648,14 @@ where
/// write!(formatter, "an array of arrays")
/// }
///
-/// fn visit_seq<V>(self, mut visitor: V) -> Result<Vec<T>, V::Error>
-/// where V: SeqVisitor<'de>
+/// fn visit_seq<A>(self, mut seq: A) -> Result<Vec<T>, A::Error>
+/// where A: SeqAccess<'de>
/// {
/// // Create a single Vec to hold the flattened contents.
/// let mut vec = Vec::new();
///
/// // Each iteration through this loop is one inner array.
-/// while let Some(()) = visitor.visit_seed(ExtendVec(&mut vec))? {
+/// while let Some(()) = seq.next_element_seed(ExtendVec(&mut vec))? {
/// // Nothing to do; inner array has been appended into `vec`.
/// }
///
@@ -1260,29 +1260,29 @@ pub trait Visitor<'de>: Sized {
}
/// Deserialize `Value` as a sequence of elements.
- fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error>
+ fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
where
- V: SeqVisitor<'de>,
+ A: SeqAccess<'de>,
{
- let _ = visitor;
+ let _ = seq;
Err(Error::invalid_type(Unexpected::Seq, &self))
}
/// Deserialize `Value` as a key-value map.
- fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error>
+ fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
where
- V: MapVisitor<'de>,
+ A: MapAccess<'de>,
{
- let _ = visitor;
+ let _ = map;
Err(Error::invalid_type(Unexpected::Map, &self))
}
/// Deserialize `Value` as an enum.
- fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error>
+ fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
where
- V: EnumVisitor<'de>,
+ A: EnumAccess<'de>,
{
- let _ = visitor;
+ let _ = data;
Err(Error::invalid_type(Unexpected::Enum, &self))
}
@@ -1345,11 +1345,11 @@ pub trait Visitor<'de>: Sized {
////////////////////////////////////////////////////////////////////////////////
-/// `SeqVisitor` visits each item in a sequence.
+/// Provides a `Visitor` access to each element of a sequence in the input.
///
/// This is a trait that a `Deserializer` passes to a `Visitor` implementation,
/// which deserializes each item in a sequence.
-pub trait SeqVisitor<'de> {
+pub trait SeqAccess<'de> {
/// The error type that can be returned if some error occurs during
/// deserialization.
type Error: Error;
@@ -1357,9 +1357,9 @@ pub trait SeqVisitor<'de> {
/// This returns `Ok(Some(value))` for the next value in the sequence, or
/// `Ok(None)` if there are no more remaining items.
///
- /// `Deserialize` implementations should typically use `SeqVisitor::visit`
- /// instead.
- fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
+ /// `Deserialize` implementations should typically use
+ /// `SeqAcccess::next_element` instead.
+ fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: DeserializeSeed<'de>;
@@ -1367,13 +1367,13 @@ pub trait SeqVisitor<'de> {
/// `Ok(None)` if there are no more remaining items.
///
/// This method exists as a convenience for `Deserialize` implementations.
- /// `SeqVisitor` implementations should not override the default behavior.
+ /// `SeqAccess` implementations should not override the default behavior.
#[inline]
- fn visit<T>(&mut self) -> Result<Option<T>, Self::Error>
+ fn next_element<T>(&mut self) -> Result<Option<T>, Self::Error>
where
T: Deserialize<'de>,
{
- self.visit_seed(PhantomData)
+ self.next_element_seed(PhantomData)
}
/// Return the lower and upper bound of items remaining in the sequence.
@@ -1383,26 +1383,26 @@ pub trait SeqVisitor<'de> {
}
}
-impl<'de, 'a, V> SeqVisitor<'de> for &'a mut V
+impl<'de, 'a, V> SeqAccess<'de> for &'a mut V
where
- V: SeqVisitor<'de>,
+ V: SeqAccess<'de>,
{
type Error = V::Error;
#[inline]
- fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, V::Error>
+ fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, V::Error>
where
T: DeserializeSeed<'de>,
{
- (**self).visit_seed(seed)
+ (**self).next_element_seed(seed)
}
#[inline]
- fn visit<T>(&mut self) -> Result<Option<T>, V::Error>
+ fn next_element<T>(&mut self) -> Result<Option<T>, V::Error>
where
T: Deserialize<'de>,
{
- (**self).visit()
+ (**self).next_element()
}
#[inline]
@@ -1413,10 +1413,10 @@ where
////////////////////////////////////////////////////////////////////////////////
-/// `MapVisitor` visits each item in a sequence.
+/// Provides a `Visitor` access to each entry of a map in the input.
///
/// This is a trait that a `Deserializer` passes to a `Visitor` implementation.
-pub trait MapVisitor<'de> {
+pub trait MapAccess<'de> {
/// The error type that can be returned if some error occurs during
/// deserialization.
type Error: Error;
@@ -1425,29 +1425,29 @@ pub trait MapVisitor<'de> {
/// if there are no more remaining entries.
///
/// `Deserialize` implementations should typically use
- /// `MapVisitor::visit_key` or `MapVisitor::visit` instead.
- fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
+ /// `MapAccess::next_key` or `MapAccess::next_entry` instead.
+ fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
where
K: DeserializeSeed<'de>;
/// This returns a `Ok(value)` for the next value in the map.
///
/// `Deserialize` implementations should typically use
- /// `MapVisitor::visit_value` instead.
- fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
+ /// `MapAccess::next_value` instead.
+ fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
where
V: DeserializeSeed<'de>;
/// This returns `Ok(Some((key, value)))` for the next (key-value) pair in
/// the map, or `Ok(None)` if there are no more remaining items.
///
- /// `MapVisitor` implementations should override the default behavior if a
+ /// `MapAccess` implementations should override the default behavior if a
/// more efficient implementation is possible.
///
- /// `Deserialize` implementations should typically use `MapVisitor::visit`
- /// instead.
+ /// `Deserialize` implementations should typically use
+ /// `MapAccess::next_entry` instead.
#[inline]
- fn visit_seed<K, V>(
+ fn next_entry_seed<K, V>(
&mut self,
kseed: K,
vseed: V,
@@ -1456,9 +1456,9 @@ pub trait MapVisitor<'de> {
K: DeserializeSeed<'de>,
V: DeserializeSeed<'de>,
{
- match try!(self.visit_key_seed(kseed)) {
+ match try!(self.next_key_seed(kseed)) {
Some(key) => {
- let value = try!(self.visit_value_seed(vseed));
+ let value = try!(self.next_value_seed(vseed));
Ok(Some((key, value)))
}
None => Ok(None),
@@ -1469,39 +1469,39 @@ pub trait MapVisitor<'de> {
/// if there are no more remaining entries.
///
/// This method exists as a convenience for `Deserialize` implementations.
- /// `MapVisitor` implementations should not override the default behavior.
+ /// `MapAccess` implementations should not override the default behavior.
#[inline]
- fn visit_key<K>(&mut self) -> Result<Option<K>, Self::Error>
+ fn next_key<K>(&mut self) -> Result<Option<K>, Self::Error>
where
K: Deserialize<'de>,
{
- self.visit_key_seed(PhantomData)
+ self.next_key_seed(PhantomData)
}
/// This returns a `Ok(value)` for the next value in the map.
///
/// This method exists as a convenience for `Deserialize` implementations.
- /// `MapVisitor` implementations should not override the default behavior.
+ /// `MapAccess` implementations should not override the default behavior.
#[inline]
- fn visit_value<V>(&mut self) -> Result<V, Self::Error>
+ fn next_value<V>(&mut self) -> Result<V, Self::Error>
where
V: Deserialize<'de>,
{
- self.visit_value_seed(PhantomData)
+ self.next_value_seed(PhantomData)
}
/// This returns `Ok(Some((key, value)))` for the next (key-value) pair in
/// the map, or `Ok(None)` if there are no more remaining items.
///
/// This method exists as a convenience for `Deserialize` implementations.
- /// `MapVisitor` implementations should not override the default behavior.
+ /// `MapAccess` implementations should not override the default behavior.
#[inline]
- fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>
+ fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>
where
K: Deserialize<'de>,
V: Deserialize<'de>,
{
- self.visit_seed(PhantomData, PhantomData)
+ self.next_entry_seed(PhantomData, PhantomData)
}
/// Return the lower and upper bound of items remaining in the sequence.
@@ -1511,30 +1511,30 @@ pub trait MapVisitor<'de> {
}
}
-impl<'de, 'a, V_> MapVisitor<'de> for &'a mut V_
+impl<'de, 'a, V_> MapAccess<'de> for &'a mut V_
where
- V_: MapVisitor<'de>,
+ V_: MapAccess<'de>,
{
type Error = V_::Error;
#[inline]
- fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
+ fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
where
K: DeserializeSeed<'de>,
{
- (**self).visit_key_seed(seed)
+ (**self).next_key_seed(seed)
}
#[inline]
- fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
+ fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
where
V: DeserializeSeed<'de>,
{
- (**self).visit_value_seed(seed)
+ (**self).next_value_seed(seed)
}
#[inline]
- fn visit_seed<K, V>(
+ fn next_entry_seed<K, V>(
&mut self,
kseed: K,
vseed: V,
@@ -1543,32 +1543,32 @@ where
K: DeserializeSeed<'de>,
V: DeserializeSeed<'de>,
{
- (**self).visit_seed(kseed, vseed)
+ (**self).next_entry_seed(kseed, vseed)
}
#[inline]
- fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, V_::Error>
+ fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, V_::Error>
where
K: Deserialize<'de>,
V: Deserialize<'de>,
{
- (**self).visit()
+ (**self).next_entry()
}
#[inline]
- fn visit_key<K>(&mut self) -> Result<Option<K>, V_::Error>
+ fn next_key<K>(&mut self) -> Result<Option<K>, V_::Error>
where
K: Deserialize<'de>,
{
- (**self).visit_key()
+ (**self).next_key()
}
#[inline]
- fn visit_value<V>(&mut self) -> Result<V, V_::Error>
+ fn next_value<V>(&mut self) -> Result<V, V_::Error>
where
V: Deserialize<'de>,
{
- (**self).visit_value()
+ (**self).next_value()
}
#[inline]
@@ -1579,44 +1579,45 @@ where
////////////////////////////////////////////////////////////////////////////////
-/// `EnumVisitor` is a visitor that is created by the `Deserializer` and passed
-/// to the `Deserialize` in order to identify which variant of an enum to
-/// deserialize.
-pub trait EnumVisitor<'de>: Sized {
+/// Provides a `Visitor` access to the data of an enum in the input.
+///
+/// `EnumAccess` is created by the `Deserializer` and passed to the
+/// `Visitor` in order to identify which variant of an enum to deserialize.
+pub trait EnumAccess<'de>: Sized {
/// The error type that can be returned if some error occurs during
/// deserialization.
type Error: Error;
/// The `Visitor` that will be used to deserialize the content of the enum
/// variant.
- type Variant: VariantVisitor<'de, Error = Self::Error>;
+ type Variant: VariantAccess<'de, Error = Self::Error>;
- /// `visit_variant` is called to identify which variant to deserialize.
+ /// `variant` is called to identify which variant to deserialize.
///
- /// `Deserialize` implementations should typically use
- /// `EnumVisitor::visit_variant` instead.
- fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
+ /// `Deserialize` implementations should typically use `EnumAccess::variant`
+ /// instead.
+ fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
where
V: DeserializeSeed<'de>;
- /// `visit_variant` is called to identify which variant to deserialize.
+ /// `variant` is called to identify which variant to deserialize.
///
/// This method exists as a convenience for `Deserialize` implementations.
- /// `EnumVisitor` implementations should not override the default behavior.
+ /// `EnumAccess` implementations should not override the default behavior.
#[inline]
- fn visit_variant<V>(self) -> Result<(V, Self::Variant), Self::Error>
+ fn variant<V>(self) -> Result<(V, Self::Variant), Self::Error>
where
V: Deserialize<'de>,
{
- self.visit_variant_seed(PhantomData)
+ self.variant_seed(PhantomData)
}
}
-/// `VariantVisitor` is a visitor that is created by the `Deserializer` and
+/// `VariantAccess` is a visitor that is created by the `Deserializer` and
/// passed to the `Deserialize` to deserialize the content of a particular enum
/// variant.
-pub trait VariantVisitor<'de>: Sized {
+pub trait VariantAccess<'de>: Sized {
/// The error type that can be returned if some error occurs during
- /// deserialization. Must match the error type of our `EnumVisitor`.
+ /// deserialization. Must match the error type of our `EnumAccess`.
type Error: Error;
/// Called when deserializing a variant with no values.
@@ -1625,55 +1626,55 @@ pub trait VariantVisitor<'de>: Sized {
/// `invalid_type` error should be constructed:
///
/// ```rust
- /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantVisitor, Unexpected};
+ /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
/// #
/// # struct X;
/// #
- /// # impl<'de> VariantVisitor<'de> for X {
+ /// # impl<'de> VariantAccess<'de> for X {
/// # type Error = value::Error;
/// #
- /// fn visit_unit(self) -> Result<(), Self::Error> {
+ /// fn deserialize_unit(self) -> Result<(), Self::Error> {
/// // What the data actually contained; suppose it is a tuple variant.
/// let unexp = Unexpected::TupleVariant;
/// Err(de::Error::invalid_type(unexp, &"unit variant"))
/// }
/// #
- /// # fn visit_newtype_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
+ /// # fn deserialize_newtype_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
/// # where T: DeserializeSeed<'de>
/// # { unimplemented!() }
/// #
- /// # fn visit_tuple<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
+ /// # fn deserialize_tuple<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
/// # where V: Visitor<'de>
/// # { unimplemented!() }
/// #
- /// # fn visit_struct<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
+ /// # fn deserialize_struct<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
/// # where V: Visitor<'de>
/// # { unimplemented!() }
/// # }
/// ```
- fn visit_unit(self) -> Result<(), Self::Error>;
+ fn deserialize_unit(self) -> Result<(), Self::Error>;
/// Called when deserializing a variant with a single value.
///
/// `Deserialize` implementations should typically use
- /// `VariantVisitor::visit_newtype` instead.
+ /// `VariantAccess::deserialize_newtype` instead.
///
/// If the data contains a different type of variant, the following
/// `invalid_type` error should be constructed:
///
/// ```rust
- /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantVisitor, Unexpected};
+ /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
/// #
/// # struct X;
/// #
- /// # impl<'de> VariantVisitor<'de> for X {
+ /// # impl<'de> VariantAccess<'de> for X {
/// # type Error = value::Error;
/// #
- /// # fn visit_unit(self) -> Result<(), Self::Error> {
+ /// # fn deserialize_unit(self) -> Result<(), Self::Error> {
/// # unimplemented!()
/// # }
/// #
- /// fn visit_newtype_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
+ /// fn deserialize_newtype_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
/// where T: DeserializeSeed<'de>
/// {
/// // What the data actually contained; suppose it is a unit variant.
@@ -1681,30 +1682,30 @@ pub trait VariantVisitor<'de>: Sized {
/// Err(de::Error::invalid_type(unexp, &"newtype variant"))
/// }
/// #
- /// # fn visit_tuple<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
+ /// # fn deserialize_tuple<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
/// # where V: Visitor<'de>
/// # { unimplemented!() }
/// #
- /// # fn visit_struct<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
+ /// # fn deserialize_struct<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
/// # where V: Visitor<'de>
/// # { unimplemented!() }
/// # }
/// ```
- fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
+ fn deserialize_newtype_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
where
T: DeserializeSeed<'de>;
/// Called when deserializing a variant with a single value.
///
/// This method exists as a convenience for `Deserialize` implementations.
- /// `VariantVisitor` implementations should not override the default
+ /// `VariantAccess` implementations should not override the default
/// behavior.
#[inline]
- fn visit_newtype<T>(self) -> Result<T, Self::Error>
+ fn deserialize_newtype<T>(self) -> Result<T, Self::Error>
where
T: Deserialize<'de>,
{
- self.visit_newtype_seed(PhantomData)
+ self.deserialize_newtype_seed(PhantomData)
}
/// Called when deserializing a tuple-like variant.
@@ -1715,24 +1716,24 @@ pub trait VariantVisitor<'de>: Sized {
/// `invalid_type` error should be constructed:
///
/// ```rust
- /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantVisitor, Unexpected};
+ /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
/// #
/// # struct X;
/// #
- /// # impl<'de> VariantVisitor<'de> for X {
+ /// # impl<'de> VariantAccess<'de> for X {
/// # type Error = value::Error;
/// #
- /// # fn visit_unit(self) -> Result<(), Self::Error> {
+ /// # fn deserialize_unit(self) -> Result<(), Self::Error> {
/// # unimplemented!()
/// # }
/// #
- /// # fn visit_newtype_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
+ /// # fn deserialize_newtype_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
/// # where T: DeserializeSeed<'de>
/// # { unimplemented!() }
/// #
- /// fn visit_tuple<V>(self,
- /// _len: usize,
- /// _visitor: V) -> Result<V::Value, Self::Error>
+ /// fn deserialize_tuple<V>(self,
+ /// _len: usize,
+ /// _visitor: V) -> Result<V::Value, Self::Error>
/// where V: Visitor<'de>
/// {
/// // What the data actually contained; suppose it is a unit variant.
@@ -1740,12 +1741,12 @@ pub trait VariantVisitor<'de>: Sized {
/// Err(de::Error::invalid_type(unexp, &"tuple variant"))
/// }
/// #
- /// # fn visit_struct<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
+ /// # fn deserialize_struct<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
/// # where V: Visitor<'de>
/// # { unimplemented!() }
/// # }
/// ```
- fn visit_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>;
@@ -1757,28 +1758,28 @@ pub trait VariantVisitor<'de>: Sized {
/// `invalid_type` error should be constructed:
///
/// ```rust
- /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantVisitor, Unexpected};
+ /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
/// #
/// # struct X;
/// #
- /// # impl<'de> VariantVisitor<'de> for X {
+ /// # impl<'de> VariantAccess<'de> for X {
/// # type Error = value::Error;
/// #
- /// # fn visit_unit(self) -> Result<(), Self::Error> {
+ /// # fn deserialize_unit(self) -> Result<(), Self::Error> {
/// # unimplemented!()
/// # }
/// #
- /// # fn visit_newtype_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
+ /// # fn deserialize_newtype_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
/// # where T: DeserializeSeed<'de>
/// # { unimplemented!() }
/// #
- /// # fn visit_tuple<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
+ /// # fn deserialize_tuple<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
/// # where V: Visitor<'de>
/// # { unimplemented!() }
/// #
- /// fn visit_struct<V>(self,
- /// _fields: &'static [&'static str],
- /// _visitor: V) -> Result<V::Value, Self::Error>
+ /// fn deserialize_struct<V>(self,
+ /// _fields: &'static [&'static str],
+ /// _visitor: V) -> Result<V::Value, Self::Error>
/// where V: Visitor<'de>
/// {
/// // What the data actually contained; suppose it is a unit variant.
@@ -1787,7 +1788,7 @@ pub trait VariantVisitor<'de>: Sized {
/// }
/// # }
/// ```
- fn visit_struct<V>(
+ fn deserialize_struct<V>(
self,
fields: &'static [&'static str],
visitor: V,
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 2e611551f..0917d5498 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -10,7 +10,7 @@
use lib::*;
-use de::{self, IntoDeserializer, Expected, SeqVisitor};
+use de::{self, IntoDeserializer, Expected, SeqAccess};
use self::private::{First, Second};
////////////////////////////////////////////////////////////////////////////////
@@ -223,14 +223,14 @@ where
}
}
-impl<'de, E> de::EnumVisitor<'de> for U32Deserializer<E>
+impl<'de, E> de::EnumAccess<'de> for U32Deserializer<E>
where
E: de::Error,
{
type Error = E;
type Variant = private::UnitOnly<E>;
- fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
+ fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
where
T: de::DeserializeSeed<'de>,
{
@@ -293,14 +293,14 @@ where
}
}
-impl<'de, 'a, E> de::EnumVisitor<'de> for StrDeserializer<'a, E>
+impl<'de, 'a, E> de::EnumAccess<'de> for StrDeserializer<'a, E>
where
E: de::Error,
{
type Error = E;
type Variant = private::UnitOnly<E>;
- fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
+ fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
where
T: de::DeserializeSeed<'de>,
{
@@ -367,14 +367,14 @@ where
}
#[cfg(any(feature = "std", feature = "collections"))]
-impl<'de, 'a, E> de::EnumVisitor<'de> for StringDeserializer<E>
+impl<'de, 'a, E> de::EnumAccess<'de> for StringDeserializer<E>
where
E: de::Error,
{
type Error = E;
type Variant = private::UnitOnly<E>;
- fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
+ fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
where
T: de::DeserializeSeed<'de>,
{
@@ -444,14 +444,14 @@ where
}
#[cfg(any(feature = "std", feature = "collections"))]
-impl<'de, 'a, E> de::EnumVisitor<'de> for CowStrDeserializer<'a, E>
+impl<'de, 'a, E> de::EnumAccess<'de> for CowStrDeserializer<'a, E>
where
E: de::Error,
{
type Error = E;
type Variant = private::UnitOnly<E>;
- fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
+ fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
where
T: de::DeserializeSeed<'de>,
{
@@ -524,7 +524,7 @@ where
}
}
-impl<'de, I, T, E> de::SeqVisitor<'de> for SeqDeserializer<I, E>
+impl<'de, I, T, E> de::SeqAccess<'de> for SeqDeserializer<I, E>
where
I: Iterator<Item = T>,
T: IntoDeserializer<'de, E>,
@@ -532,7 +532,7 @@ where
{
type Error = E;
- fn visit_seed<V>(&mut self, seed: V) -> Result<Option<V::Value>, Self::Error>
+ fn next_element_seed<V>(&mut self, seed: V) -> Result<Option<V::Value>, Self::Error>
where
V: de::DeserializeSeed<'de>,
{
@@ -605,7 +605,7 @@ where
////////////////////////////////////////////////////////////////////////////////
-/// A helper deserializer that deserializes a sequence using a `SeqVisitor`.
+/// A helper deserializer that deserializes a sequence using a `SeqAccess`.
#[derive(Clone, Debug)]
pub struct SeqVisitorDeserializer<V_> {
visitor: V_,
@@ -620,7 +620,7 @@ impl<V_> SeqVisitorDeserializer<V_> {
impl<'de, V_> de::Deserializer<'de> for SeqVisitorDeserializer<V_>
where
- V_: de::SeqVisitor<'de>,
+ V_: de::SeqAccess<'de>,
{
type Error = V_::Error;
@@ -747,7 +747,7 @@ where
}
}
-impl<'de, I, E> de::MapVisitor<'de> for MapDeserializer<'de, I, E>
+impl<'de, I, E> de::MapAccess<'de> for MapDeserializer<'de, I, E>
where
I: Iterator,
I::Item: private::Pair,
@@ -757,7 +757,7 @@ where
{
type Error = E;
- fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
+ fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
@@ -770,18 +770,18 @@ where
}
}
- fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
+ fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
let value = self.value.take();
// Panic because this indicates a bug in the program rather than an
// expected failure.
- let value = value.expect("MapVisitor::visit_value called before visit_key");
+ let value = value.expect("MapAccess::visit_value called before visit_key");
seed.deserialize(value.into_deserializer())
}
- fn visit_seed<TK, TV>(&mut self,
+ fn next_entry_seed<TK, TV>(&mut self,
kseed: TK,
vseed: TV)
-> Result<Option<(TK::Value, TV::Value)>, Self::Error>
@@ -804,7 +804,7 @@ where
}
}
-impl<'de, I, E> de::SeqVisitor<'de> for MapDeserializer<'de, I, E>
+impl<'de, I, E> de::SeqAccess<'de> for MapDeserializer<'de, I, E>
where
I: Iterator,
I::Item: private::Pair,
@@ -814,7 +814,7 @@ where
{
type Error = E;
- fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
+ fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
@@ -876,7 +876,7 @@ where
}
}
-// Used in the `impl SeqVisitor for MapDeserializer` to visit the map as a
+// Used in the `impl SeqAccess for MapDeserializer` to visit the map as a
// sequence of pairs.
struct PairDeserializer<A, B, E>(A, B, PhantomData<E>);
@@ -933,7 +933,7 @@ where
struct PairVisitor<A, B, E>(Option<A>, Option<B>, PhantomData<E>);
-impl<'de, A, B, E> de::SeqVisitor<'de> for PairVisitor<A, B, E>
+impl<'de, A, B, E> de::SeqAccess<'de> for PairVisitor<A, B, E>
where
A: IntoDeserializer<'de, E>,
B: IntoDeserializer<'de, E>,
@@ -941,7 +941,7 @@ where
{
type Error = E;
- fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
+ fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
@@ -1010,7 +1010,7 @@ where
////////////////////////////////////////////////////////////////////////////////
-/// A helper deserializer that deserializes a map using a `MapVisitor`.
+/// A helper deserializer that deserializes a map using a `MapAccess`.
#[derive(Clone, Debug)]
pub struct MapVisitorDeserializer<V_> {
visitor: V_,
@@ -1025,7 +1025,7 @@ impl<V_> MapVisitorDeserializer<V_> {
impl<'de, V_> de::Deserializer<'de> for MapVisitorDeserializer<V_>
where
- V_: de::MapVisitor<'de>,
+ V_: de::MapAccess<'de>,
{
type Error = V_::Error;
@@ -1059,31 +1059,31 @@ mod private {
(t, UnitOnly { marker: PhantomData })
}
- impl<'de, E> de::VariantVisitor<'de> for UnitOnly<E>
+ impl<'de, E> de::VariantAccess<'de> for UnitOnly<E>
where
E: de::Error,
{
type Error = E;
- fn visit_unit(self) -> Result<(), Self::Error> {
+ fn deserialize_unit(self) -> Result<(), Self::Error> {
Ok(())
}
- fn visit_newtype_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
+ fn deserialize_newtype_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant"),)
}
- fn visit_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"),)
}
- fn visit_struct<V>(
+ fn deserialize_struct<V>(
self,
_fields: &'static [&'static str],
_visitor: V,
diff --git a/serde/src/private/de.rs b/serde/src/private/de.rs
index 844a9d7bb..d5c03061d 100644
--- a/serde/src/private/de.rs
+++ b/serde/src/private/de.rs
@@ -201,8 +201,8 @@ mod content {
use lib::*;
- use de::{self, Deserialize, DeserializeSeed, Deserializer, Visitor, SeqVisitor, MapVisitor,
- EnumVisitor, Unexpected};
+ use de::{self, Deserialize, DeserializeSeed, Deserializer, Visitor, SeqAccess, MapAccess,
+ EnumAccess, Unexpected};
/// Used from generated code to buffer the contents of the Deserializer when
/// deserializing untagged enums and internally tagged enums.
@@ -426,10 +426,10 @@ mod content {
fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
where
- V: SeqVisitor<'de>,
+ V: SeqAccess<'de>,
{
let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096));
- while let Some(e) = try!(visitor.visit()) {
+ while let Some(e) = try!(visitor.next_element()) {
vec.push(e);
}
Ok(Content::Seq(vec))
@@ -437,10 +437,10 @@ mod content {
fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
where
- V: MapVisitor<'de>,
+ V: MapAccess<'de>,
{
let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096));
- while let Some(kv) = try!(visitor.visit()) {
+ while let Some(kv) = try!(visitor.next_entry()) {
vec.push(kv);
}
Ok(Content::Map(vec))
@@ -448,7 +448,7 @@ mod content {
fn visit_enum<V>(self, _visitor: V) -> Result<Self::Value, V::Error>
where
- V: EnumVisitor<'de>,
+ V: EnumAccess<'de>,
{
Err(de::Error::custom("untagged and internally tagged enums do not support enum input",),)
}
@@ -682,7 +682,7 @@ mod content {
fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error>
where
- V: SeqVisitor<'de>,
+ V: SeqAccess<'de>,
{
ContentVisitor
.visit_seq(visitor)
@@ -691,7 +691,7 @@ mod content {
fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error>
where
- V: MapVisitor<'de>,
+ V: MapAccess<'de>,
{
ContentVisitor
.visit_map(visitor)
@@ -700,7 +700,7 @@ mod content {
fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error>
where
- V: EnumVisitor<'de>,
+ V: EnumAccess<'de>,
{
ContentVisitor
.visit_enum(visitor)
@@ -761,21 +761,21 @@ mod content {
fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
where
- V: MapVisitor<'de>,
+ V: MapAccess<'de>,
{
let mut tag = None;
let mut vec = Vec::with_capacity(cmp::min(visitor.size_hint().0, 4096));
while let Some(k) =
- try!(visitor.visit_key_seed(TagOrContentVisitor::new(self.tag_name))) {
+ try!(visitor.next_key_seed(TagOrContentVisitor::new(self.tag_name))) {
match k {
TagOrContent::Tag => {
if tag.is_some() {
return Err(de::Error::duplicate_field(self.tag_name));
}
- tag = Some(try!(visitor.visit_value()));
+ tag = Some(try!(visitor.next_value()));
}
TagOrContent::Content(k) => {
- let v = try!(visitor.visit_value());
+ let v = try!(visitor.next_value());
vec.push((k, v));
}
}
@@ -995,14 +995,14 @@ mod content {
err: PhantomData<E>,
}
- impl<'de, E> de::EnumVisitor<'de> for EnumDeserializer<E>
+ impl<'de, E> de::EnumAccess<'de> for EnumDeserializer<E>
where
E: de::Error,
{
type Error = E;
type Variant = VariantDeserializer<Self::Error>;
- fn visit_variant_seed<V>(
+ fn variant_seed<V>(
self,
seed: V,
) -> Result<(V::Value, VariantDeserializer<E>), Self::Error>
@@ -1026,20 +1026,20 @@ mod content {
err: PhantomData<E>,
}
- impl<'de, E> de::VariantVisitor<'de> for VariantDeserializer<E>
+ impl<'de, E> de::VariantAccess<'de> for VariantDeserializer<E>
where
E: de::Error,
{
type Error = E;
- fn visit_unit(self) -> Result<(), E> {
+ fn deserialize_unit(self) -> Result<(), E> {
match self.value {
Some(value) => de::Deserialize::deserialize(ContentDeserializer::new(value)),
None => Ok(()),
}
}
- fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, E>
+ fn deserialize_newtype_seed<T>(self, seed: T) -> Result<T::Value, E>
where
T: de::DeserializeSeed<'de>,
{
@@ -1051,7 +1051,7 @@ mod content {
}
}
- fn visit_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
@@ -1064,7 +1064,7 @@ mod content {
}
}
- fn visit_struct<V>(
+ fn deserialize_struct<V>(
self,
_fields: &'static [&'static str],
visitor: V,
@@ -1134,13 +1134,13 @@ mod content {
}
}
- impl<'de, E> de::SeqVisitor<'de> for SeqDeserializer<E>
+ impl<'de, E> de::SeqAccess<'de> for SeqDeserializer<E>
where
E: de::Error,
{
type Error = E;
- fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
+ fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
@@ -1180,13 +1180,13 @@ mod content {
}
}
- impl<'de, E> de::MapVisitor<'de> for MapDeserializer<E>
+ impl<'de, E> de::MapAccess<'de> for MapDeserializer<E>
where
E: de::Error,
{
type Error = E;
- fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
+ fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
@@ -1199,7 +1199,7 @@ mod content {
}
}
- fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
+ fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
@@ -1391,14 +1391,14 @@ mod content {
err: PhantomData<E>,
}
- impl<'de, 'a, E> de::EnumVisitor<'de> for EnumRefDeserializer<'a, E>
+ impl<'de, 'a, E> de::EnumAccess<'de> for EnumRefDeserializer<'a, E>
where
E: de::Error,
{
type Error = E;
type Variant = VariantRefDeserializer<'a, Self::Error>;
- fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
+ fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
where
V: de::DeserializeSeed<'de>,
{
@@ -1419,20 +1419,20 @@ mod content {
err: PhantomData<E>,
}
- impl<'de, 'a, E> de::VariantVisitor<'de> for VariantRefDeserializer<'a, E>
+ impl<'de, 'a, E> de::VariantAccess<'de> for VariantRefDeserializer<'a, E>
where
E: de::Error,
{
type Error = E;
- fn visit_unit(self) -> Result<(), E> {
+ fn deserialize_unit(self) -> Result<(), E> {
match self.value {
Some(value) => de::Deserialize::deserialize(ContentRefDeserializer::new(value)),
None => Ok(()),
}
}
- fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, E>
+ fn deserialize_newtype_seed<T>(self, seed: T) -> Result<T::Value, E>
where
T: de::DeserializeSeed<'de>,
{
@@ -1444,7 +1444,7 @@ mod content {
}
}
- fn visit_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
+ fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: de::Visitor<'de>,
{
@@ -1457,7 +1457,7 @@ mod content {
}
}
- fn visit_struct<V>(
+ fn deserialize_struct<V>(
self,
_fields: &'static [&'static str],
visitor: V,
@@ -1527,13 +1527,13 @@ mod content {
}
}
- impl<'de, 'a, E> de::SeqVisitor<'de> for SeqRefDeserializer<'a, E>
+ impl<'de, 'a, E> de::SeqAccess<'de> for SeqRefDeserializer<'a, E>
where
E: de::Error,
{
type Error = E;
- fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
+ fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
@@ -1573,13 +1573,13 @@ mod content {
}
}
- impl<'de, 'a, E> de::MapVisitor<'de> for MapRefDeserializer<'a, E>
+ impl<'de, 'a, E> de::MapAccess<'de> for MapRefDeserializer<'a, E>
where
E: de::Error,
{
type Error = E;
- fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
+ fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
@@ -1593,7 +1593,7 @@ mod content {
}
}
- fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
+ fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
where
T: de::DeserializeSeed<'de>,
{
@@ -1678,7 +1678,7 @@ mod content {
fn visit_map<V>(self, _: V) -> Result<(), V::Error>
where
- V: MapVisitor<'de>,
+ V: MapAccess<'de>,
{
Ok(())
}
diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 6d07458d7..994b9a9ba 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -292,7 +292,7 @@ fn deserialize_tuple(
let dispatch = if let Some(deserializer) = deserializer {
quote!(_serde::Deserializer::deserialize_tuple(#deserializer, #nfields, #visitor_expr))
} else if is_enum {
- quote!(_serde::de::VariantVisitor::visit_tuple(__visitor, #nfields, #visitor_expr))
+ quote!(_serde::de::VariantAccess::deserialize_tuple(__variant, #nfields, #visitor_expr))
} else if nfields == 1 {
let type_name = item_attrs.name().deserialize_name();
quote!(_serde::Deserializer::deserialize_newtype_struct(__deserializer, #type_name, #visitor_expr))
@@ -307,7 +307,7 @@ fn deserialize_tuple(
let visitor_var = if all_skipped {
quote!(_)
} else {
- quote!(mut __visitor)
+ quote!(mut __seq)
};
quote_block! {
@@ -326,8 +326,8 @@ fn deserialize_tuple(
#visit_newtype_struct
#[inline]
- fn visit_seq<__V>(self, #visitor_var: __V) -> _serde::export::Result<Self::Value, __V::Error>
- where __V: _serde::de::SeqVisitor<'de>
+ fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error>
+ where __A: _serde::de::SeqAccess<'de>
{
#visit_seq
}
@@ -364,7 +364,7 @@ fn deserialize_seq(
let visit = match field.attrs.deserialize_with() {
None => {
let field_ty = &field.ty;
- quote!(try!(_serde::de::SeqVisitor::visit::<#field_ty>(&mut __visitor)))
+ quote!(try!(_serde::de::SeqAccess::next_element::<#field_ty>(&mut __seq)))
}
Some(path) => {
let (wrapper, wrapper_ty) = wrap_deserialize_with(
@@ -372,7 +372,7 @@ fn deserialize_seq(
quote!({
#wrapper
_serde::export::Option::map(
- try!(_serde::de::SeqVisitor::visit::<#wrapper_ty>(&mut __visitor)),
+ try!(_serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq)),
|__wrap| __wrap.value)
})
}
@@ -501,7 +501,7 @@ fn deserialize_struct(
}
} else if is_enum {
quote! {
- _serde::de::VariantVisitor::visit_struct(__visitor, FIELDS, #visitor_expr)
+ _serde::de::VariantAccess::deserialize_struct(__variant, FIELDS, #visitor_expr)
}
} else {
let type_name = item_attrs.name().deserialize_name();
@@ -516,7 +516,7 @@ fn deserialize_struct(
let visitor_var = if all_skipped {
quote!(_)
} else {
- quote!(mut __visitor)
+ quote!(mut __seq)
};
let visit_seq = if is_untagged {
@@ -525,8 +525,8 @@ fn deserialize_struct(
} else {
Some(quote! {
#[inline]
- fn visit_seq<__V>(self, #visitor_var: __V) -> _serde::export::Result<Self::Value, __V::Error>
- where __V: _serde::de::SeqVisitor<'de>
+ fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error>
+ where __A: _serde::de::SeqAccess<'de>
{
#visit_seq
}
@@ -551,8 +551,8 @@ fn deserialize_struct(
#visit_seq
#[inline]
- fn visit_map<__V>(self, mut __visitor: __V) -> _serde::export::Result<Self::Value, __V::Error>
- where __V: _serde::de::MapVisitor<'de>
+ fn visit_map<__A>(self, mut __map: __A) -> _serde::export::Result<Self::Value, __A::Error>
+ where __A: _serde::de::MapAccess<'de>
{
#visit_map
}
@@ -624,7 +624,7 @@ fn deserialize_externally_tagged_enum(
Match(deserialize_externally_tagged_variant(params, variant, item_attrs),);
quote! {
- (__Field::#variant_name, __visitor) => #block
+ (__Field::#variant_name, __variant) => #block
}
},
);
@@ -637,15 +637,15 @@ fn deserialize_externally_tagged_enum(
// all variants have `#[serde(skip_deserializing)]`.
quote! {
// FIXME: Once we drop support for Rust 1.15:
- // let _serde::export::Err(__err) = _serde::de::EnumVisitor::visit_variant::<__Field>(__visitor);
+ // let _serde::export::Err(__err) = _serde::de::EnumAccess::variant::<__Field>(__data);
// _serde::export::Err(__err)
_serde::export::Result::map(
- _serde::de::EnumVisitor::visit_variant::<__Field>(__visitor),
+ _serde::de::EnumAccess::variant::<__Field>(__data),
|(__impossible, _)| match __impossible {})
}
} else {
quote! {
- match try!(_serde::de::EnumVisitor::visit_variant(__visitor)) {
+ match try!(_serde::de::EnumAccess::variant(__data)) {
#(#variant_arms)*
}
}
@@ -666,8 +666,8 @@ fn deserialize_externally_tagged_enum(
_serde::export::Formatter::write_str(formatter, #expecting)
}
- fn visit_enum<__V>(self, __visitor: __V) -> _serde::export::Result<Self::Value, __V::Error>
- where __V: _serde::de::EnumVisitor<'de>
+ fn visit_enum<__A>(self, __data: __A) -> _serde::export::Result<Self::Value, __A::Error>
+ where __A: _serde::de::EnumAccess<'de>
{
#match_variant
}
@@ -807,7 +807,7 @@ fn deserialize_adjacently_tagged_enum(
}
let mut missing_content = quote! {
- _serde::export::Err(<__V::Error as _serde::de::Error>::missing_field(#content))
+ _serde::export::Err(<__A::Error as _serde::de::Error>::missing_field(#content))
};
if variants.iter().any(is_unit) {
let fallthrough = if variants.iter().all(is_unit) {
@@ -842,12 +842,12 @@ fn deserialize_adjacently_tagged_enum(
let visit_third_key = quote! {
// Visit the third key in the map, hopefully there isn't one.
- match try!(_serde::de::MapVisitor::visit_key_seed(&mut __visitor, #tag_or_content)) {
+ match try!(_serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content)) {
_serde::export::Some(_serde::private::de::TagOrContentField::Tag) => {
- _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#tag))
+ _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag))
}
_serde::export::Some(_serde::private::de::TagOrContentField::Content) => {
- _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#content))
+ _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content))
}
_serde::export::None => _serde::export::Ok(__ret),
}
@@ -888,24 +888,24 @@ fn deserialize_adjacently_tagged_enum(
_serde::export::Formatter::write_str(formatter, #expecting)
}
- fn visit_map<__V>(self, mut __visitor: __V) -> _serde::export::Result<Self::Value, __V::Error>
- where __V: _serde::de::MapVisitor<'de>
+ fn visit_map<__A>(self, mut __map: __A) -> _serde::export::Result<Self::Value, __A::Error>
+ where __A: _serde::de::MapAccess<'de>
{
// Visit the first key.
- match try!(_serde::de::MapVisitor::visit_key_seed(&mut __visitor, #tag_or_content)) {
+ match try!(_serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content)) {
// First key is the tag.
_serde::export::Some(_serde::private::de::TagOrContentField::Tag) => {
// Parse the tag.
- let __field = try!(_serde::de::MapVisitor::visit_value(&mut __visitor));
+ let __field = try!(_serde::de::MapAccess::next_value(&mut __map));
// Visit the second key.
- match try!(_serde::de::MapVisitor::visit_key_seed(&mut __visitor, #tag_or_content)) {
+ match try!(_serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content)) {
// Second key is a duplicate of the tag.
_serde::export::Some(_serde::private::de::TagOrContentField::Tag) => {
- _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#tag))
+ _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag))
}
// Second key is the content.
_serde::export::Some(_serde::private::de::TagOrContentField::Content) => {
- let __ret = try!(_serde::de::MapVisitor::visit_value_seed(&mut __visitor,
+ let __ret = try!(_serde::de::MapAccess::next_value_seed(&mut __map,
__Seed {
field: __field,
marker: _serde::export::PhantomData,
@@ -921,14 +921,14 @@ fn deserialize_adjacently_tagged_enum(
// First key is the content.
_serde::export::Some(_serde::private::de::TagOrContentField::Content) => {
// Buffer up the content.
- let __content = try!(_serde::de::MapVisitor::visit_value::<_serde::private::de::Content>(&mut __visitor));
+ let __content = try!(_serde::de::MapAccess::next_value::<_serde::private::de::Content>(&mut __map));
// Visit the second key.
- match try!(_serde::de::MapVisitor::visit_key_seed(&mut __visitor, #tag_or_content)) {
+ match try!(_serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content)) {
// Second key is the tag.
_serde::export::Some(_serde::private::de::TagOrContentField::Tag) => {
- let __deserializer = _serde::private::de::ContentDeserializer::<__V::Error>::new(__content);
+ let __deserializer = _serde::private::de::ContentDeserializer::<__A::Error>::new(__content);
// Parse the tag.
- let __ret = try!(match try!(_serde::de::MapVisitor::visit_value(&mut __visitor)) {
+ let __ret = try!(match try!(_serde::de::MapAccess::next_value(&mut __map)) {
// Deserialize the buffered content now that we know the variant.
#(#variant_arms)*
});
@@ -937,29 +937,29 @@ fn deserialize_adjacently_tagged_enum(
}
// Second key is a duplicate of the content.
_serde::export::Some(_serde::private::de::TagOrContentField::Content) => {
- _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#content))
+ _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content))
}
// There is no second key.
_serde::export::None => {
- _serde::export::Err(<__V::Error as _serde::de::Error>::missing_field(#tag))
+ _serde::export::Err(<__A::Error as _serde::de::Error>::missing_field(#tag))
}
}
}
// There is no first key.
_serde::export::None => {
- _serde::export::Err(<__V::Error as _serde::de::Error>::missing_field(#tag))
+ _serde::export::Err(<__A::Error as _serde::de::Error>::missing_field(#tag))
}
}
}
- fn visit_seq<__V>(self, mut __visitor: __V) -> _serde::export::Result<Self::Value, __V::Error>
- where __V: _serde::de::SeqVisitor<'de>
+ fn visit_seq<__A>(self, mut __seq: __A) -> _serde::export::Result<Self::Value, __A::Error>
+ where __A: _serde::de::SeqAccess<'de>
{
// Visit the first element - the tag.
- match try!(_serde::de::SeqVisitor::visit(&mut __visitor)) {
+ match try!(_serde::de::SeqAccess::next_element(&mut __seq)) {
_serde::export::Some(__field) => {
// Visit the second element - the content.
- match try!(_serde::de::SeqVisitor::visit_seed(&mut __visitor,
+ match try!(_serde::de::SeqAccess::next_element_seed(&mut __seq,
__Seed {
field: __field,
marker: _serde::export::PhantomData,
@@ -1041,7 +1041,7 @@ fn deserialize_externally_tagged_variant(
Style::Unit => {
let this = ¶ms.this;
quote_block! {
- try!(_serde::de::VariantVisitor::visit_unit(__visitor));
+ try!(_serde::de::VariantAccess::deserialize_unit(__variant));
_serde::export::Ok(#this::#variant_ident)
}
}
@@ -1156,7 +1156,7 @@ fn deserialize_externally_tagged_newtype_variant(
let field_ty = &field.ty;
quote_expr! {
_serde::export::Result::map(
- _serde::de::VariantVisitor::visit_newtype::<#field_ty>(__visitor),
+ _serde::de::VariantAccess::deserialize_newtype::<#field_ty>(__variant),
#this::#variant_ident)
}
}
@@ -1165,7 +1165,7 @@ fn deserialize_externally_tagged_newtype_variant(
quote_block! {
#wrapper
_serde::export::Result::map(
- _serde::de::VariantVisitor::visit_newtype::<#wrapper_ty>(__visitor),
+ _serde::de::VariantAccess::deserialize_newtype::<#wrapper_ty>(__variant),
|__wrapper| #this::#variant_ident(__wrapper.value))
}
}
@@ -1380,7 +1380,7 @@ fn deserialize_map(
None => {
let field_ty = &field.ty;
quote! {
- try!(_serde::de::MapVisitor::visit_value::<#field_ty>(&mut __visitor))
+ try!(_serde::de::MapAccess::next_value::<#field_ty>(&mut __map))
}
}
Some(path) => {
@@ -1388,14 +1388,14 @@ fn deserialize_map(
params, field.ty, path);
quote!({
#wrapper
- try!(_serde::de::MapVisitor::visit_value::<#wrapper_ty>(&mut __visitor)).value
+ try!(_serde::de::MapAccess::next_value::<#wrapper_ty>(&mut __map)).value
})
}
};
quote! {
__Field::#name => {
if _serde::export::Option::is_some(&#name) {
- return _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#deser_name));
+ return _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#deser_name));
}
#name = _serde::export::Some(#visit);
}
@@ -1407,7 +1407,7 @@ fn deserialize_map(
None
} else {
Some(quote! {
- _ => { let _ = try!(_serde::de::MapVisitor::visit_value::<_serde::de::IgnoredAny>(&mut __visitor)); }
+ _ => { let _ = try!(_serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)); }
})
};
@@ -1417,14 +1417,14 @@ fn deserialize_map(
let match_keys = if item_attrs.deny_unknown_fields() && all_skipped {
quote! {
// FIXME: Once we drop support for Rust 1.15:
- // let _serde::export::None::<__Field> = try!(_serde::de::MapVisitor::visit_key(&mut __visitor));
+ // let _serde::export::None::<__Field> = try!(_serde::de::MapAccess::next_key(&mut __map));
_serde::export::Option::map(
- try!(_serde::de::MapVisitor::visit_key::<__Field>(&mut __visitor)),
+ try!(_serde::de::MapAccess::next_key::<__Field>(&mut __map)),
|__impossible| match __impossible {});
}
} else {
quote! {
- while let _serde::export::Some(__key) = try!(_serde::de::MapVisitor::visit_key::<__Field>(&mut __visitor)) {
+ while let _serde::export::Some(__key) = try!(_serde::de::MapAccess::next_key::<__Field>(&mut __map)) {
match __key {
#(#value_arms)*
#ignored_arm
@@ -1577,7 +1577,7 @@ fn expr_is_missing(field: &Field, item_attrs: &attr::Item) -> Fragment {
}
Some(_) => {
quote_expr! {
- return _serde::export::Err(<__V::Error as _serde::de::Error>::missing_field(#name))
+ return _serde::export::Err(<__A::Error as _serde::de::Error>::missing_field(#name))
}
}
}
| serde-rs/serde | 2017-04-14T19:15:57Z | Trait naming could use some guidelines - https://github.com/brson/rust-api-guidelines/issues/28. | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 |
869 | diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index 243c8eb68..75996fc59 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -1,6 +1,6 @@
-use serde::de::{self, Deserialize, DeserializeSeed, EnumVisitor, MapVisitor, SeqVisitor,
- VariantVisitor, Visitor};
-use serde::de::value::{ValueDeserializer, MapVisitorDeserializer, SeqVisitorDeserializer};
+use serde::de::{self, Deserialize, DeserializeSeed, EnumVisitor, IntoDeserializer,
+ MapVisitor, SeqVisitor, VariantVisitor, Visitor};
+use serde::de::value::{MapVisitorDeserializer, SeqVisitorDeserializer};
use error::Error;
use token::Token;
diff --git a/test_suite/tests/test_value.rs b/test_suite/tests/test_value.rs
index fc4441632..08b1c3c3a 100644
--- a/test_suite/tests/test_value.rs
+++ b/test_suite/tests/test_value.rs
@@ -3,7 +3,7 @@ extern crate serde_derive;
extern crate serde;
use serde::Deserialize;
-use serde::de::value::{self, ValueDeserializer};
+use serde::de::{value, IntoDeserializer};
#[test]
fn test_u32_to_enum() {
@@ -13,7 +13,7 @@ fn test_u32_to_enum() {
B,
}
- let deserializer = ValueDeserializer::<value::Error>::into_deserializer(1u32);
+ let deserializer = IntoDeserializer::<value::Error>::into_deserializer(1u32);
let e: E = E::deserialize(deserializer).unwrap();
assert_eq!(E::B, e);
}
| [
"867"
] | serde-rs__serde-869 | Rename ValueDeserializer trait to IntoDeserializer
This would be more consistent with IntoIterator, IntoFuture, etc.
| 0.9 | aed5a77540cda0365d245621876f69058445b7a3 | diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index 7e0404900..06ae2e451 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -1658,6 +1658,17 @@ pub trait VariantVisitor<'de>: Sized {
///////////////////////////////////////////////////////////////////////////////
+/// This trait converts primitive types into a deserializer.
+pub trait IntoDeserializer<'de, E: Error = value::Error> {
+ /// The actual deserializer type.
+ type Deserializer: Deserializer<'de, Error = E>;
+
+ /// Convert this value into a deserializer.
+ fn into_deserializer(self) -> Self::Deserializer;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
/// Used in error messages.
///
/// - expected `a`
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 5a261334e..83e50a56f 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -2,7 +2,7 @@
use lib::*;
-use de::{self, Expected, SeqVisitor};
+use de::{self, IntoDeserializer, Expected, SeqVisitor};
///////////////////////////////////////////////////////////////////////////////
@@ -50,18 +50,7 @@ impl error::Error for Error {
///////////////////////////////////////////////////////////////////////////////
-/// This trait converts primitive types into a deserializer.
-pub trait ValueDeserializer<'de, E: de::Error = Error> {
- /// The actual deserializer type.
- type Deserializer: de::Deserializer<'de, Error = E>;
-
- /// Convert this value into a deserializer.
- fn into_deserializer(self) -> Self::Deserializer;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-impl<'de, E> ValueDeserializer<'de, E> for ()
+impl<'de, E> IntoDeserializer<'de, E> for ()
where E: de::Error
{
type Deserializer = UnitDeserializer<E>;
@@ -110,7 +99,7 @@ macro_rules! primitive_deserializer {
marker: PhantomData<E>
}
- impl<'de, E> ValueDeserializer<'de, E> for $ty
+ impl<'de, E> IntoDeserializer<'de, E> for $ty
where E: de::Error,
{
type Deserializer = $name<E>;
@@ -163,7 +152,7 @@ pub struct U32Deserializer<E> {
marker: PhantomData<E>,
}
-impl<'de, E> ValueDeserializer<'de, E> for u32
+impl<'de, E> IntoDeserializer<'de, E> for u32
where E: de::Error
{
type Deserializer = U32Deserializer<E>;
@@ -225,7 +214,7 @@ pub struct StrDeserializer<'a, E> {
marker: PhantomData<E>,
}
-impl<'de, 'a, E> ValueDeserializer<'de, E> for &'a str
+impl<'de, 'a, E> IntoDeserializer<'de, E> for &'a str
where E: de::Error
{
type Deserializer = StrDeserializer<'a, E>;
@@ -289,7 +278,7 @@ pub struct StringDeserializer<E> {
}
#[cfg(any(feature = "std", feature = "collections"))]
-impl<'de, E> ValueDeserializer<'de, E> for String
+impl<'de, E> IntoDeserializer<'de, E> for String
where E: de::Error
{
type Deserializer = StringDeserializer<E>;
@@ -355,7 +344,7 @@ pub struct CowStrDeserializer<'a, E> {
}
#[cfg(any(feature = "std", feature = "collections"))]
-impl<'de, 'a, E> ValueDeserializer<'de, E> for Cow<'a, str>
+impl<'de, 'a, E> IntoDeserializer<'de, E> for Cow<'a, str>
where E: de::Error
{
type Deserializer = CowStrDeserializer<'a, E>;
@@ -455,7 +444,7 @@ impl<I, E> SeqDeserializer<I, E>
impl<'de, I, T, E> de::Deserializer<'de> for SeqDeserializer<I, E>
where I: Iterator<Item = T>,
- T: ValueDeserializer<'de, E>,
+ T: IntoDeserializer<'de, E>,
E: de::Error
{
type Error = E;
@@ -477,7 +466,7 @@ impl<'de, I, T, E> de::Deserializer<'de> for SeqDeserializer<I, E>
impl<'de, I, T, E> de::SeqVisitor<'de> for SeqDeserializer<I, E>
where I: Iterator<Item = T>,
- T: ValueDeserializer<'de, E>,
+ T: IntoDeserializer<'de, E>,
E: de::Error
{
type Error = E;
@@ -514,8 +503,8 @@ impl Expected for ExpectedInSeq {
///////////////////////////////////////////////////////////////////////////////
#[cfg(any(feature = "std", feature = "collections"))]
-impl<'de, T, E> ValueDeserializer<'de, E> for Vec<T>
- where T: ValueDeserializer<'de, E>,
+impl<'de, T, E> IntoDeserializer<'de, E> for Vec<T>
+ where T: IntoDeserializer<'de, E>,
E: de::Error
{
type Deserializer = SeqDeserializer<<Vec<T> as IntoIterator>::IntoIter, E>;
@@ -526,8 +515,8 @@ impl<'de, T, E> ValueDeserializer<'de, E> for Vec<T>
}
#[cfg(any(feature = "std", feature = "collections"))]
-impl<'de, T, E> ValueDeserializer<'de, E> for BTreeSet<T>
- where T: ValueDeserializer<'de, E> + Eq + Ord,
+impl<'de, T, E> IntoDeserializer<'de, E> for BTreeSet<T>
+ where T: IntoDeserializer<'de, E> + Eq + Ord,
E: de::Error
{
type Deserializer = SeqDeserializer<<BTreeSet<T> as IntoIterator>::IntoIter, E>;
@@ -538,8 +527,8 @@ impl<'de, T, E> ValueDeserializer<'de, E> for BTreeSet<T>
}
#[cfg(feature = "std")]
-impl<'de, T, E> ValueDeserializer<'de, E> for HashSet<T>
- where T: ValueDeserializer<'de, E> + Eq + Hash,
+impl<'de, T, E> IntoDeserializer<'de, E> for HashSet<T>
+ where T: IntoDeserializer<'de, E> + Eq + Hash,
E: de::Error
{
type Deserializer = SeqDeserializer<<HashSet<T> as IntoIterator>::IntoIter, E>;
@@ -589,8 +578,8 @@ impl<'de, V_> de::Deserializer<'de> for SeqVisitorDeserializer<V_>
pub struct MapDeserializer<'de, I, E>
where I: Iterator,
I::Item: private::Pair,
- <I::Item as private::Pair>::First: ValueDeserializer<'de, E>,
- <I::Item as private::Pair>::Second: ValueDeserializer<'de, E>,
+ <I::Item as private::Pair>::First: IntoDeserializer<'de, E>,
+ <I::Item as private::Pair>::Second: IntoDeserializer<'de, E>,
E: de::Error
{
iter: iter::Fuse<I>,
@@ -603,8 +592,8 @@ pub struct MapDeserializer<'de, I, E>
impl<'de, I, E> MapDeserializer<'de, I, E>
where I: Iterator,
I::Item: private::Pair,
- <I::Item as private::Pair>::First: ValueDeserializer<'de, E>,
- <I::Item as private::Pair>::Second: ValueDeserializer<'de, E>,
+ <I::Item as private::Pair>::First: IntoDeserializer<'de, E>,
+ <I::Item as private::Pair>::Second: IntoDeserializer<'de, E>,
E: de::Error
{
/// Construct a new `MapDeserializer<I, K, V, E>`.
@@ -650,8 +639,8 @@ impl<'de, I, E> MapDeserializer<'de, I, E>
impl<'de, I, E> de::Deserializer<'de> for MapDeserializer<'de, I, E>
where I: Iterator,
I::Item: private::Pair,
- <I::Item as private::Pair>::First: ValueDeserializer<'de, E>,
- <I::Item as private::Pair>::Second: ValueDeserializer<'de, E>,
+ <I::Item as private::Pair>::First: IntoDeserializer<'de, E>,
+ <I::Item as private::Pair>::Second: IntoDeserializer<'de, E>,
E: de::Error
{
type Error = E;
@@ -691,8 +680,8 @@ impl<'de, I, E> de::Deserializer<'de> for MapDeserializer<'de, I, E>
impl<'de, I, E> de::MapVisitor<'de> for MapDeserializer<'de, I, E>
where I: Iterator,
I::Item: private::Pair,
- <I::Item as private::Pair>::First: ValueDeserializer<'de, E>,
- <I::Item as private::Pair>::Second: ValueDeserializer<'de, E>,
+ <I::Item as private::Pair>::First: IntoDeserializer<'de, E>,
+ <I::Item as private::Pair>::Second: IntoDeserializer<'de, E>,
E: de::Error
{
type Error = E;
@@ -744,8 +733,8 @@ impl<'de, I, E> de::MapVisitor<'de> for MapDeserializer<'de, I, E>
impl<'de, I, E> de::SeqVisitor<'de> for MapDeserializer<'de, I, E>
where I: Iterator,
I::Item: private::Pair,
- <I::Item as private::Pair>::First: ValueDeserializer<'de, E>,
- <I::Item as private::Pair>::Second: ValueDeserializer<'de, E>,
+ <I::Item as private::Pair>::First: IntoDeserializer<'de, E>,
+ <I::Item as private::Pair>::Second: IntoDeserializer<'de, E>,
E: de::Error
{
type Error = E;
@@ -772,8 +761,8 @@ impl<'de, I, E> de::SeqVisitor<'de> for MapDeserializer<'de, I, E>
struct PairDeserializer<A, B, E>(A, B, PhantomData<E>);
impl<'de, A, B, E> de::Deserializer<'de> for PairDeserializer<A, B, E>
- where A: ValueDeserializer<'de, E>,
- B: ValueDeserializer<'de, E>,
+ where A: IntoDeserializer<'de, E>,
+ B: IntoDeserializer<'de, E>,
E: de::Error
{
type Error = E;
@@ -821,8 +810,8 @@ impl<'de, A, B, E> de::Deserializer<'de> for PairDeserializer<A, B, E>
struct PairVisitor<A, B, E>(Option<A>, Option<B>, PhantomData<E>);
impl<'de, A, B, E> de::SeqVisitor<'de> for PairVisitor<A, B, E>
- where A: ValueDeserializer<'de, E>,
- B: ValueDeserializer<'de, E>,
+ where A: IntoDeserializer<'de, E>,
+ B: IntoDeserializer<'de, E>,
E: de::Error
{
type Error = E;
@@ -866,9 +855,9 @@ impl Expected for ExpectedInMap {
///////////////////////////////////////////////////////////////////////////////
#[cfg(any(feature = "std", feature = "collections"))]
-impl<'de, K, V, E> ValueDeserializer<'de, E> for BTreeMap<K, V>
- where K: ValueDeserializer<'de, E> + Eq + Ord,
- V: ValueDeserializer<'de, E>,
+impl<'de, K, V, E> IntoDeserializer<'de, E> for BTreeMap<K, V>
+ where K: IntoDeserializer<'de, E> + Eq + Ord,
+ V: IntoDeserializer<'de, E>,
E: de::Error
{
type Deserializer = MapDeserializer<'de, <BTreeMap<K, V> as IntoIterator>::IntoIter, E>;
@@ -879,9 +868,9 @@ impl<'de, K, V, E> ValueDeserializer<'de, E> for BTreeMap<K, V>
}
#[cfg(feature = "std")]
-impl<'de, K, V, E> ValueDeserializer<'de, E> for HashMap<K, V>
- where K: ValueDeserializer<'de, E> + Eq + Hash,
- V: ValueDeserializer<'de, E>,
+impl<'de, K, V, E> IntoDeserializer<'de, E> for HashMap<K, V>
+ where K: IntoDeserializer<'de, E> + Eq + Hash,
+ V: IntoDeserializer<'de, E>,
E: de::Error
{
type Deserializer = MapDeserializer<'de, <HashMap<K, V> as IntoIterator>::IntoIter, E>;
diff --git a/serde/src/private/de.rs b/serde/src/private/de.rs
index 394c72cb9..9d56071d3 100644
--- a/serde/src/private/de.rs
+++ b/serde/src/private/de.rs
@@ -1410,7 +1410,7 @@ mod content {
}
}
- impl<'de, E> de::value::ValueDeserializer<'de, E> for ContentDeserializer<E>
+ impl<'de, E> de::IntoDeserializer<'de, E> for ContentDeserializer<E>
where E: de::Error
{
type Deserializer = Self;
@@ -1420,7 +1420,7 @@ mod content {
}
}
- impl<'de, 'a, E> de::value::ValueDeserializer<'de, E> for ContentRefDeserializer<'a, E>
+ impl<'de, 'a, E> de::IntoDeserializer<'de, E> for ContentRefDeserializer<'a, E>
where E: de::Error
{
type Deserializer = Self;
| serde-rs/serde | 2017-04-12T06:21:23Z | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 | |
860 | diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index fcbb762b2..243c8eb68 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -78,7 +78,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit
- seq bytes byte_buf map struct_field ignored_any
+ seq bytes byte_buf map identifier ignored_any
}
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
@@ -645,6 +645,6 @@ impl<'de> de::Deserializer<'de> for BytesDeserializer {
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
- struct struct_field tuple enum ignored_any byte_buf
+ struct identifier tuple enum ignored_any byte_buf
}
}
diff --git a/serde_test/src/ser.rs b/serde_test/src/ser.rs
index 2a82970f7..f6c401eed 100644
--- a/serde_test/src/ser.rs
+++ b/serde_test/src/ser.rs
@@ -146,7 +146,7 @@ impl<'s, 'a> ser::Serializer for &'s mut Serializer<'a> {
fn serialize_unit_variant(self,
name: &'static str,
- _variant_index: usize,
+ _variant_index: u32,
variant: &'static str)
-> Result<(), Error> {
if self.tokens.first() == Some(&Token::Enum(name)) {
@@ -168,7 +168,7 @@ impl<'s, 'a> ser::Serializer for &'s mut Serializer<'a> {
fn serialize_newtype_variant<T: ?Sized>(self,
name: &'static str,
- _variant_index: usize,
+ _variant_index: u32,
variant: &'static str,
value: &T)
-> Result<(), Error>
@@ -217,7 +217,7 @@ impl<'s, 'a> ser::Serializer for &'s mut Serializer<'a> {
fn serialize_tuple_variant(self,
name: &'static str,
- _variant_index: usize,
+ _variant_index: u32,
variant: &'static str,
len: usize)
-> Result<Self, Error> {
@@ -237,7 +237,7 @@ impl<'s, 'a> ser::Serializer for &'s mut Serializer<'a> {
fn serialize_struct_variant(self,
name: &'static str,
- _variant_index: usize,
+ _variant_index: u32,
variant: &'static str,
len: usize)
-> Result<Self, Error> {
| [
"722"
] | serde-rs__serde-860 | Struct fields and variant tags both go through deserialize_struct_field
In `#[derive(Deserialize)]` we are generating effectively the same Deserialize implementation for deciding which struct field is next vs which variant we are looking at. As a result, both implementations go through Deserializer::deserialize_struct_field which is unexpected for Deserializer authors trying to implement `EnumVisitor::visit_variant`.
| 0.9 | 517270a9432d00eb755a89349f0d3931ed162844 | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 597938127..ffe3291c5 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -1232,7 +1232,7 @@ impl<'de> Deserialize<'de> for Duration {
}
}
- deserializer.deserialize_struct_field(FieldVisitor)
+ deserializer.deserialize_identifier(FieldVisitor)
}
}
@@ -1358,7 +1358,7 @@ impl<'de, Idx: Deserialize<'de>> Deserialize<'de> for std::ops::Range<Idx> {
}
}
- deserializer.deserialize_struct_field(FieldVisitor)
+ deserializer.deserialize_identifier(FieldVisitor)
}
}
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index 453a531bc..754fa12e7 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -911,8 +911,8 @@ pub trait Deserializer<'de>: Sized {
where V: Visitor<'de>;
/// Hint that the `Deserialize` type is expecting the name of a struct
- /// field.
- fn deserialize_struct_field<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ /// field or the discriminant of an enum variant.
+ fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'de>;
/// Hint that the `Deserialize` type is expecting an enum value with a
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 3b157b0ca..1323450d6 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -108,7 +108,7 @@ impl<'de, E> de::Deserializer<'de> for UnitDeserializer<E>
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
seq_fixed_size bytes map unit_struct newtype_struct tuple_struct struct
- struct_field tuple enum ignored_any byte_buf
+ identifier tuple enum ignored_any byte_buf
}
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
@@ -155,7 +155,7 @@ macro_rules! primitive_deserializer {
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit
option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any byte_buf
+ tuple_struct struct identifier tuple enum ignored_any byte_buf
}
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
@@ -208,7 +208,7 @@ impl<'de, E> de::Deserializer<'de> for U32Deserializer<E>
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
- struct struct_field tuple ignored_any byte_buf
+ struct identifier tuple ignored_any byte_buf
}
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
@@ -286,7 +286,7 @@ impl<'de, 'a, E> de::Deserializer<'de> for StrDeserializer<'a, E>
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
- struct struct_field tuple ignored_any byte_buf
+ struct identifier tuple ignored_any byte_buf
}
}
@@ -351,7 +351,7 @@ impl<'de, E> de::Deserializer<'de> for StringDeserializer<E>
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
- struct struct_field tuple ignored_any byte_buf
+ struct identifier tuple ignored_any byte_buf
}
}
@@ -420,7 +420,7 @@ impl<'de, 'a, E> de::Deserializer<'de> for CowStrDeserializer<'a, E>
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
- struct struct_field tuple ignored_any byte_buf
+ struct identifier tuple ignored_any byte_buf
}
}
@@ -495,7 +495,7 @@ impl<'de, I, T, E> de::Deserializer<'de> for SeqDeserializer<I, E>
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
- struct struct_field tuple enum ignored_any byte_buf
+ struct identifier tuple enum ignored_any byte_buf
}
}
@@ -603,7 +603,7 @@ impl<'de, V_> de::Deserializer<'de> for SeqVisitorDeserializer<V_>
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
- struct struct_field tuple enum ignored_any byte_buf
+ struct identifier tuple enum ignored_any byte_buf
}
}
@@ -707,7 +707,7 @@ impl<'de, I, E> de::Deserializer<'de> for MapDeserializer<'de, I, E>
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
- bytes map unit_struct newtype_struct tuple_struct struct struct_field
+ bytes map unit_struct newtype_struct tuple_struct struct identifier
tuple enum ignored_any byte_buf
}
}
@@ -804,7 +804,7 @@ impl<'de, A, B, E> de::Deserializer<'de> for PairDeserializer<A, B, E>
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
- bytes map unit_struct newtype_struct tuple_struct struct struct_field
+ bytes map unit_struct newtype_struct tuple_struct struct identifier
tuple enum ignored_any byte_buf
}
@@ -945,7 +945,7 @@ impl<'de, V_> de::Deserializer<'de> for MapVisitorDeserializer<V_>
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
- struct struct_field tuple enum ignored_any byte_buf
+ struct identifier tuple enum ignored_any byte_buf
}
}
diff --git a/serde/src/macros.rs b/serde/src/macros.rs
index 5873e1a70..80ababfa0 100644
--- a/serde/src/macros.rs
+++ b/serde/src/macros.rs
@@ -89,8 +89,8 @@ macro_rules! forward_to_deserialize_helper {
(struct) => {
forward_to_deserialize_method!{deserialize_struct(&'static str, &'static [&'static str])}
};
- (struct_field) => {
- forward_to_deserialize_method!{deserialize_struct_field()}
+ (identifier) => {
+ forward_to_deserialize_method!{deserialize_identifier()}
};
(tuple) => {
forward_to_deserialize_method!{deserialize_tuple(usize)}
@@ -143,7 +143,7 @@ macro_rules! forward_to_deserialize_helper {
/// # forward_to_deserialize! {
/// # u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
/// # seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
-/// # tuple_struct struct struct_field tuple enum ignored_any
+/// # tuple_struct struct identifier tuple enum ignored_any
/// # }
/// # }
/// #
@@ -176,7 +176,7 @@ macro_rules! forward_to_deserialize_helper {
/// forward_to_deserialize! {
/// bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
/// seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
-/// tuple_struct struct struct_field tuple enum ignored_any
+/// tuple_struct struct identifier tuple enum ignored_any
/// }
/// }
/// #
diff --git a/serde/src/private/de.rs b/serde/src/private/de.rs
index f4e95dc63..2d019b427 100644
--- a/serde/src/private/de.rs
+++ b/serde/src/private/de.rs
@@ -52,7 +52,7 @@ pub fn missing_field<'de, V, E>(field: &'static str) -> Result<V, E>
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
seq_fixed_size bytes byte_buf map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
+ tuple_struct struct identifier tuple enum ignored_any
}
}
@@ -855,7 +855,7 @@ mod content {
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
- struct_field tuple ignored_any
+ identifier tuple ignored_any
}
}
@@ -996,7 +996,7 @@ mod content {
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
+ tuple_struct struct identifier tuple enum ignored_any
}
}
@@ -1085,7 +1085,7 @@ mod content {
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
+ tuple_struct struct identifier tuple enum ignored_any
}
}
@@ -1202,7 +1202,7 @@ mod content {
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
- struct_field tuple ignored_any
+ identifier tuple ignored_any
}
}
@@ -1341,7 +1341,7 @@ mod content {
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
+ tuple_struct struct identifier tuple enum ignored_any
}
}
@@ -1430,7 +1430,7 @@ mod content {
forward_to_deserialize! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
+ tuple_struct struct identifier tuple enum ignored_any
}
}
diff --git a/serde/src/private/macros.rs b/serde/src/private/macros.rs
index 4d40c510d..f0e0703a3 100644
--- a/serde/src/private/macros.rs
+++ b/serde/src/private/macros.rs
@@ -66,13 +66,13 @@ macro_rules! __serialize_unimplemented_helper {
__serialize_unimplemented_method!(serialize_unit_struct(&str) -> Ok);
};
(unit_variant) => {
- __serialize_unimplemented_method!(serialize_unit_variant(&str, usize, &str) -> Ok);
+ __serialize_unimplemented_method!(serialize_unit_variant(&str, u32, &str) -> Ok);
};
(newtype_struct) => {
__serialize_unimplemented_method!(serialize_newtype_struct<T>(&str, &T) -> Ok);
};
(newtype_variant) => {
- __serialize_unimplemented_method!(serialize_newtype_variant<T>(&str, usize, &str, &T) -> Ok);
+ __serialize_unimplemented_method!(serialize_newtype_variant<T>(&str, u32, &str, &T) -> Ok);
};
(seq) => {
type SerializeSeq = $crate::ser::Impossible<Self::Ok, Self::Error>;
@@ -91,7 +91,7 @@ macro_rules! __serialize_unimplemented_helper {
};
(tuple_variant) => {
type SerializeTupleVariant = $crate::ser::Impossible<Self::Ok, Self::Error>;
- __serialize_unimplemented_method!(serialize_tuple_variant(&str, usize, &str, usize) -> SerializeTupleVariant);
+ __serialize_unimplemented_method!(serialize_tuple_variant(&str, u32, &str, usize) -> SerializeTupleVariant);
};
(map) => {
type SerializeMap = $crate::ser::Impossible<Self::Ok, Self::Error>;
@@ -103,7 +103,7 @@ macro_rules! __serialize_unimplemented_helper {
};
(struct_variant) => {
type SerializeStructVariant = $crate::ser::Impossible<Self::Ok, Self::Error>;
- __serialize_unimplemented_method!(serialize_struct_variant(&str, usize, &str, usize) -> SerializeStructVariant);
+ __serialize_unimplemented_method!(serialize_struct_variant(&str, u32, &str, usize) -> SerializeStructVariant);
};
}
diff --git a/serde/src/private/ser.rs b/serde/src/private/ser.rs
index 333cb7425..f307d3d78 100644
--- a/serde/src/private/ser.rs
+++ b/serde/src/private/ser.rs
@@ -190,7 +190,7 @@ impl<S> Serializer for TaggedSerializer<S>
fn serialize_unit_variant(self,
_: &'static str,
- _: usize,
+ _: u32,
inner_variant: &'static str)
-> Result<Self::Ok, Self::Error> {
let mut map = try!(self.delegate.serialize_map(Some(2)));
@@ -210,7 +210,7 @@ impl<S> Serializer for TaggedSerializer<S>
fn serialize_newtype_variant<T: ?Sized>(self,
_: &'static str,
- _: usize,
+ _: u32,
inner_variant: &'static str,
inner_value: &T)
-> Result<Self::Ok, Self::Error>
@@ -244,7 +244,7 @@ impl<S> Serializer for TaggedSerializer<S>
#[cfg(not(any(feature = "std", feature = "collections")))]
fn serialize_tuple_variant(self,
_: &'static str,
- _: usize,
+ _: u32,
_: &'static str,
_: usize)
-> Result<Self::SerializeTupleVariant, Self::Error> {
@@ -256,7 +256,7 @@ impl<S> Serializer for TaggedSerializer<S>
#[cfg(any(feature = "std", feature = "collections"))]
fn serialize_tuple_variant(self,
_: &'static str,
- _: usize,
+ _: u32,
inner_variant: &'static str,
len: usize)
-> Result<Self::SerializeTupleVariant, Self::Error> {
@@ -284,7 +284,7 @@ impl<S> Serializer for TaggedSerializer<S>
#[cfg(not(any(feature = "std", feature = "collections")))]
fn serialize_struct_variant(self,
_: &'static str,
- _: usize,
+ _: u32,
_: &'static str,
_: usize)
-> Result<Self::SerializeStructVariant, Self::Error> {
@@ -296,7 +296,7 @@ impl<S> Serializer for TaggedSerializer<S>
#[cfg(any(feature = "std", feature = "collections"))]
fn serialize_struct_variant(self,
_: &'static str,
- _: usize,
+ _: u32,
inner_variant: &'static str,
len: usize)
-> Result<Self::SerializeStructVariant, Self::Error> {
@@ -450,18 +450,18 @@ mod content {
Unit,
UnitStruct(&'static str),
- UnitVariant(&'static str, usize, &'static str),
+ UnitVariant(&'static str, u32, &'static str),
NewtypeStruct(&'static str, Box<Content>),
- NewtypeVariant(&'static str, usize, &'static str, Box<Content>),
+ NewtypeVariant(&'static str, u32, &'static str, Box<Content>),
Seq(Vec<Content>),
SeqFixedSize(Vec<Content>),
Tuple(Vec<Content>),
TupleStruct(&'static str, Vec<Content>),
- TupleVariant(&'static str, usize, &'static str, Vec<Content>),
+ TupleVariant(&'static str, u32, &'static str, Vec<Content>),
Map(Vec<(Content, Content)>),
Struct(&'static str, Vec<(&'static str, Content)>),
- StructVariant(&'static str, usize, &'static str, Vec<(&'static str, Content)>),
+ StructVariant(&'static str, u32, &'static str, Vec<(&'static str, Content)>),
}
impl Serialize for Content {
@@ -651,7 +651,7 @@ mod content {
fn serialize_unit_variant(self,
name: &'static str,
- variant_index: usize,
+ variant_index: u32,
variant: &'static str)
-> Result<Content, E> {
Ok(Content::UnitVariant(name, variant_index, variant))
@@ -666,7 +666,7 @@ mod content {
fn serialize_newtype_variant<T: ?Sized + Serialize>(self,
name: &'static str,
- variant_index: usize,
+ variant_index: u32,
variant: &'static str,
value: &T)
-> Result<Content, E> {
@@ -712,7 +712,7 @@ mod content {
fn serialize_tuple_variant(self,
name: &'static str,
- variant_index: usize,
+ variant_index: u32,
variant: &'static str,
len: usize)
-> Result<Self::SerializeTupleVariant, E> {
@@ -743,7 +743,7 @@ mod content {
fn serialize_struct_variant(self,
name: &'static str,
- variant_index: usize,
+ variant_index: u32,
variant: &'static str,
len: usize)
-> Result<Self::SerializeStructVariant, E> {
@@ -831,7 +831,7 @@ mod content {
struct SerializeTupleVariant<E> {
name: &'static str,
- variant_index: usize,
+ variant_index: u32,
variant: &'static str,
fields: Vec<Content>,
error: PhantomData<E>,
@@ -922,7 +922,7 @@ mod content {
struct SerializeStructVariant<E> {
name: &'static str,
- variant_index: usize,
+ variant_index: u32,
variant: &'static str,
fields: Vec<(&'static str, Content)>,
error: PhantomData<E>,
diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs
index 332bdfabf..1a20646a7 100644
--- a/serde/src/ser/mod.rs
+++ b/serde/src/ser/mod.rs
@@ -449,7 +449,7 @@ pub trait Serializer: Sized {
/// ```
fn serialize_unit_variant(self,
name: &'static str,
- variant_index: usize,
+ variant_index: u32,
variant: &'static str)
-> Result<Self::Ok, Self::Error>;
@@ -504,7 +504,7 @@ pub trait Serializer: Sized {
/// ```
fn serialize_newtype_variant<T: ?Sized + Serialize>(self,
name: &'static str,
- variant_index: usize,
+ variant_index: u32,
variant: &'static str,
value: &T)
-> Result<Self::Ok, Self::Error>;
@@ -686,7 +686,7 @@ pub trait Serializer: Sized {
/// ```
fn serialize_tuple_variant(self,
name: &'static str,
- variant_index: usize,
+ variant_index: u32,
variant: &'static str,
len: usize)
-> Result<Self::SerializeTupleVariant, Self::Error>;
@@ -806,7 +806,7 @@ pub trait Serializer: Sized {
/// ```
fn serialize_struct_variant(self,
name: &'static str,
- variant_index: usize,
+ variant_index: u32,
variant: &'static str,
len: usize)
-> Result<Self::SerializeStructVariant, Self::Error>;
diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index c8c291c9e..077b072f9 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -1274,7 +1274,7 @@ fn deserialize_field_visitor(fields: Vec<(String, Ident)>,
}
}
- _serde::Deserializer::deserialize_struct_field(__deserializer, __FieldVisitor)
+ _serde::Deserializer::deserialize_identifier(__deserializer, __FieldVisitor)
}
}
}
diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index 7b893e440..cb5e8e85d 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -6,6 +6,8 @@ use fragment::{Fragment, Stmts, Match};
use internals::ast::{Body, Field, Item, Style, Variant};
use internals::{self, attr};
+use std::u32;
+
pub fn expand_derive_serialize(item: &syn::DeriveInput) -> Result<Tokens, String> {
let ctxt = internals::Ctxt::new();
let item = Item::from_ast(&ctxt, item);
@@ -210,6 +212,8 @@ fn serialize_struct(params: &Parameters,
fields: &[Field],
item_attrs: &attr::Item)
-> Fragment {
+ assert!(fields.len() as u64 <= u32::MAX as u64);
+
let serialize_fields =
serialize_struct_visitor(fields,
params,
@@ -247,6 +251,8 @@ fn serialize_item_enum(params: &Parameters,
variants: &[Variant],
item_attrs: &attr::Item)
-> Fragment {
+ assert!(variants.len() as u64 <= u32::MAX as u64);
+
let self_var = ¶ms.self_var;
let arms: Vec<_> = variants.iter()
@@ -254,7 +260,7 @@ fn serialize_item_enum(params: &Parameters,
.map(|(variant_index, variant)| {
serialize_variant(params,
variant,
- variant_index,
+ variant_index as u32,
item_attrs)
})
.collect();
@@ -268,7 +274,7 @@ fn serialize_item_enum(params: &Parameters,
fn serialize_variant(params: &Parameters,
variant: &Variant,
- variant_index: usize,
+ variant_index: u32,
item_attrs: &attr::Item)
-> Tokens {
let this = ¶ms.this;
@@ -349,7 +355,7 @@ fn serialize_variant(params: &Parameters,
fn serialize_externally_tagged_variant(params: &Parameters,
variant: &Variant,
- variant_index: usize,
+ variant_index: u32,
item_attrs: &attr::Item)
-> Fragment {
let type_name = item_attrs.name().serialize_name();
@@ -587,7 +593,7 @@ fn serialize_untagged_variant(params: &Parameters,
enum TupleVariant {
ExternallyTagged {
type_name: String,
- variant_index: usize,
+ variant_index: u32,
variant_name: String,
},
Untagged,
@@ -637,7 +643,7 @@ fn serialize_tuple_variant(context: TupleVariant,
enum StructVariant<'a> {
ExternallyTagged {
- variant_index: usize,
+ variant_index: u32,
variant_name: String,
},
InternallyTagged { tag: &'a str, variant_name: String },
| serde-rs/serde | 2017-04-09T20:55:07Z | The workaround for binary formats is to go through U32Deserializer. Something like:
```rust
fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
where V: de::DeserializeSeed
{
// instead of `seed.deserialize(&mut *self.de)`
let idx: u32 = Deserialize::deserialize(&mut *self.de)?;
let val = seed.deserialize(idx.into_deserializer())?;
Ok((val, /* ... */))
}
``` | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 |
859 | diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index bff0b48bb..43fa0bf37 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -242,14 +242,6 @@ declare_tests! {
UnitStruct => &[
Token::UnitStruct("UnitStruct"),
],
- UnitStruct => &[
- Token::Seq(Some(0)),
- Token::SeqEnd,
- ],
- UnitStruct => &[
- Token::Seq(None),
- Token::SeqEnd,
- ],
}
test_newtype_struct {
NewtypeStruct(1) => &[
@@ -1036,4 +1028,11 @@ declare_error_tests! {
],
Error::Message("invalid type: floating point `0`, expected isize".into()),
}
+ test_unit_struct_from_seq<UnitStruct> {
+ &[
+ Token::Seq(Some(0)),
+ Token::SeqEnd,
+ ],
+ Error::Message("invalid type: sequence, expected unit struct UnitStruct".into()),
+ }
}
| [
"857"
] | serde-rs__serde-859 | Remove conversion from empty seq to unit struct
[This function](https://github.com/serde-rs/serde/blob/v0.9.13/serde_derive/src/de.rs#L153-L158) should be removed to match the handling of () in #839.
| 0.9 | cc933b9cdb0f787dd33a6ff01e7a65b4627e73a0 | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 5c84a6494..4c4ffe14e 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -168,13 +168,6 @@ fn deserialize_unit_struct(ident: &syn::Ident, item_attrs: &attr::Item) -> Fragm
{
_serde::export::Ok(#ident)
}
-
- #[inline]
- fn visit_seq<__V>(self, _: __V) -> _serde::export::Result<#ident, __V::Error>
- where __V: _serde::de::SeqVisitor<'de>
- {
- _serde::export::Ok(#ident)
- }
}
_serde::Deserializer::deserialize_unit_struct(__deserializer, #type_name, __Visitor)
| serde-rs/serde | 2017-04-09T20:08:33Z | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 | |
858 | diff --git a/test_suite/tests/compile-fail/remote/bad_getter.rs b/test_suite/tests/compile-fail/remote/bad_getter.rs
new file mode 100644
index 000000000..3495a10b4
--- /dev/null
+++ b/test_suite/tests/compile-fail/remote/bad_getter.rs
@@ -0,0 +1,17 @@
+#[macro_use]
+extern crate serde_derive;
+
+mod remote {
+ pub struct S {
+ a: u8,
+ }
+}
+
+#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[serde(remote = "remote::S")]
+struct S {
+ #[serde(getter = "~~~")] //~^^^ HELP: failed to parse path: "~~~"
+ a: u8,
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/remote/bad_remote.rs b/test_suite/tests/compile-fail/remote/bad_remote.rs
new file mode 100644
index 000000000..5ef17670a
--- /dev/null
+++ b/test_suite/tests/compile-fail/remote/bad_remote.rs
@@ -0,0 +1,16 @@
+#[macro_use]
+extern crate serde_derive;
+
+mod remote {
+ pub struct S {
+ a: u8,
+ }
+}
+
+#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[serde(remote = "~~~")] //~^ HELP: failed to parse path: "~~~"
+struct S {
+ a: u8,
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/remote/enum_getter.rs b/test_suite/tests/compile-fail/remote/enum_getter.rs
new file mode 100644
index 000000000..e012cbe11
--- /dev/null
+++ b/test_suite/tests/compile-fail/remote/enum_getter.rs
@@ -0,0 +1,19 @@
+#[macro_use]
+extern crate serde_derive;
+
+mod remote {
+ pub enum E {
+ A { a: u8 }
+ }
+}
+
+#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+#[serde(remote = "remote::E")]
+pub enum E {
+ A {
+ #[serde(getter = "get_a")] //~^^^^ HELP: #[serde(getter = "...")] is not allowed in an enum
+ a: u8,
+ }
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/remote/missing_field.rs b/test_suite/tests/compile-fail/remote/missing_field.rs
new file mode 100644
index 000000000..3be802a65
--- /dev/null
+++ b/test_suite/tests/compile-fail/remote/missing_field.rs
@@ -0,0 +1,17 @@
+#[macro_use]
+extern crate serde_derive;
+
+mod remote {
+ pub struct S {
+ pub a: u8,
+ pub b: u8,
+ }
+}
+
+#[derive(Serialize, Deserialize)] //~ ERROR: missing field `b` in initializer of `remote::S`
+#[serde(remote = "remote::S")]
+struct S {
+ a: u8, //~^^^ ERROR: missing field `b` in initializer of `remote::S`
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/remote/nonremote_getter.rs b/test_suite/tests/compile-fail/remote/nonremote_getter.rs
new file mode 100644
index 000000000..11271e5a8
--- /dev/null
+++ b/test_suite/tests/compile-fail/remote/nonremote_getter.rs
@@ -0,0 +1,16 @@
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+struct S {
+ #[serde(getter = "S::get")] //~^^ HELP: #[serde(getter = "...")] can only be used in structs that have #[serde(remote = "...")]
+ a: u8,
+}
+
+impl S {
+ fn get(&self) -> u8 {
+ self.a
+ }
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/remote/unknown_field.rs b/test_suite/tests/compile-fail/remote/unknown_field.rs
new file mode 100644
index 000000000..8f2fa4814
--- /dev/null
+++ b/test_suite/tests/compile-fail/remote/unknown_field.rs
@@ -0,0 +1,16 @@
+#[macro_use]
+extern crate serde_derive;
+
+mod remote {
+ pub struct S {
+ pub a: u8,
+ }
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(remote = "remote::S")]
+struct S {
+ b: u8, //~^^^ ERROR: no field `b` on type `&remote::S`
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/remote/wrong_de.rs b/test_suite/tests/compile-fail/remote/wrong_de.rs
new file mode 100644
index 000000000..58a05e198
--- /dev/null
+++ b/test_suite/tests/compile-fail/remote/wrong_de.rs
@@ -0,0 +1,12 @@
+#[macro_use]
+extern crate serde_derive;
+
+mod remote {
+ pub struct S(pub u16);
+}
+
+#[derive(Deserialize)] //~ ERROR: mismatched types
+#[serde(remote = "remote::S")]
+struct S(u8); //~^^ expected u16, found u8
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/remote/wrong_getter.rs b/test_suite/tests/compile-fail/remote/wrong_getter.rs
new file mode 100644
index 000000000..f767263df
--- /dev/null
+++ b/test_suite/tests/compile-fail/remote/wrong_getter.rs
@@ -0,0 +1,23 @@
+#[macro_use]
+extern crate serde_derive;
+
+mod remote {
+ pub struct S {
+ a: u8,
+ }
+
+ impl S {
+ pub fn get(&self) -> u16 {
+ self.a as u16
+ }
+ }
+}
+
+#[derive(Serialize)] //~ ERROR: mismatched types
+#[serde(remote = "remote::S")]
+struct S {
+ #[serde(getter = "remote::S::get")]
+ a: u8, //~^^^^ expected u8, found u16
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/remote/wrong_ser.rs b/test_suite/tests/compile-fail/remote/wrong_ser.rs
new file mode 100644
index 000000000..bd4ca1a26
--- /dev/null
+++ b/test_suite/tests/compile-fail/remote/wrong_ser.rs
@@ -0,0 +1,16 @@
+#[macro_use]
+extern crate serde_derive;
+
+mod remote {
+ pub struct S {
+ pub a: u16,
+ }
+}
+
+#[derive(Serialize)] //~ ERROR: mismatched types
+#[serde(remote = "remote::S")]
+struct S {
+ a: u8, //~^^^ expected u8, found u16
+}
+
+fn main() {}
diff --git a/test_suite/tests/test_remote.rs b/test_suite/tests/test_remote.rs
new file mode 100644
index 000000000..4f21a09ac
--- /dev/null
+++ b/test_suite/tests/test_remote.rs
@@ -0,0 +1,184 @@
+#[macro_use]
+extern crate serde_derive;
+
+extern crate serde;
+
+mod remote {
+ pub struct Unit;
+
+ pub struct PrimitivePriv(u8);
+
+ pub struct PrimitivePub(pub u8);
+
+ pub struct NewtypePriv(Unit);
+
+ pub struct NewtypePub(pub Unit);
+
+ pub struct TuplePriv(u8, Unit);
+
+ pub struct TuplePub(pub u8, pub Unit);
+
+ pub struct StructPriv {
+ a: u8,
+ b: Unit,
+ }
+
+ pub struct StructPub {
+ pub a: u8,
+ pub b: Unit,
+ }
+
+ impl PrimitivePriv {
+ pub fn new(a: u8) -> Self {
+ PrimitivePriv(a)
+ }
+
+ pub fn get(&self) -> u8 {
+ self.0
+ }
+ }
+
+ impl NewtypePriv {
+ pub fn new(a: Unit) -> Self {
+ NewtypePriv(a)
+ }
+
+ pub fn get(&self) -> &Unit {
+ &self.0
+ }
+ }
+
+ impl TuplePriv {
+ pub fn new(a: u8, b: Unit) -> Self {
+ TuplePriv(a, b)
+ }
+
+ pub fn first(&self) -> u8 {
+ self.0
+ }
+
+ pub fn second(&self) -> &Unit {
+ &self.1
+ }
+ }
+
+ impl StructPriv {
+ pub fn new(a: u8, b: Unit) -> Self {
+ StructPriv { a: a, b: b }
+ }
+
+ pub fn a(&self) -> u8 {
+ self.a
+ }
+
+ pub fn b(&self) -> &Unit {
+ &self.b
+ }
+ }
+}
+
+#[derive(Serialize, Deserialize)]
+struct Test {
+ #[serde(with = "UnitDef")]
+ unit: remote::Unit,
+
+ #[serde(with = "PrimitivePrivDef")]
+ primitive_priv: remote::PrimitivePriv,
+
+ #[serde(with = "PrimitivePubDef")]
+ primitive_pub: remote::PrimitivePub,
+
+ #[serde(with = "NewtypePrivDef")]
+ newtype_priv: remote::NewtypePriv,
+
+ #[serde(with = "NewtypePubDef")]
+ newtype_pub: remote::NewtypePub,
+
+ #[serde(with = "TuplePrivDef")]
+ tuple_priv: remote::TuplePriv,
+
+ #[serde(with = "TuplePubDef")]
+ tuple_pub: remote::TuplePub,
+
+ #[serde(with = "StructPrivDef")]
+ struct_priv: remote::StructPriv,
+
+ #[serde(with = "StructPubDef")]
+ struct_pub: remote::StructPub,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(remote = "remote::Unit")]
+struct UnitDef;
+
+#[derive(Serialize, Deserialize)]
+#[serde(remote = "remote::PrimitivePriv")]
+struct PrimitivePrivDef(#[serde(getter = "remote::PrimitivePriv::get")] u8);
+
+#[derive(Serialize, Deserialize)]
+#[serde(remote = "remote::PrimitivePub")]
+struct PrimitivePubDef(u8);
+
+#[derive(Serialize, Deserialize)]
+#[serde(remote = "remote::NewtypePriv")]
+struct NewtypePrivDef(#[serde(getter = "remote::NewtypePriv::get", with = "UnitDef")] remote::Unit);
+
+#[derive(Serialize, Deserialize)]
+#[serde(remote = "remote::NewtypePub")]
+struct NewtypePubDef(#[serde(with = "UnitDef")] remote::Unit);
+
+#[derive(Serialize, Deserialize)]
+#[serde(remote = "remote::TuplePriv")]
+struct TuplePrivDef(
+ #[serde(getter = "remote::TuplePriv::first")] u8,
+ #[serde(getter = "remote::TuplePriv::second", with = "UnitDef")] remote::Unit);
+
+#[derive(Serialize, Deserialize)]
+#[serde(remote = "remote::TuplePub")]
+struct TuplePubDef(u8, #[serde(with = "UnitDef")] remote::Unit);
+
+#[derive(Serialize, Deserialize)]
+#[serde(remote = "remote::StructPriv")]
+struct StructPrivDef {
+ #[serde(getter = "remote::StructPriv::a")]
+ a: u8,
+
+ #[serde(getter = "remote::StructPriv::b")]
+ #[serde(with= "UnitDef")]
+ b: remote::Unit,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(remote = "remote::StructPub")]
+struct StructPubDef {
+ #[allow(dead_code)]
+ a: u8,
+
+ #[allow(dead_code)]
+ #[serde(with= "UnitDef")]
+ b: remote::Unit,
+}
+
+impl From<PrimitivePrivDef> for remote::PrimitivePriv {
+ fn from(def: PrimitivePrivDef) -> Self {
+ remote::PrimitivePriv::new(def.0)
+ }
+}
+
+impl From<NewtypePrivDef> for remote::NewtypePriv {
+ fn from(def: NewtypePrivDef) -> Self {
+ remote::NewtypePriv::new(def.0)
+ }
+}
+
+impl From<TuplePrivDef> for remote::TuplePriv {
+ fn from(def: TuplePrivDef) -> Self {
+ remote::TuplePriv::new(def.0, def.1)
+ }
+}
+
+impl From<StructPrivDef> for remote::StructPriv {
+ fn from(def: StructPrivDef) -> Self {
+ remote::StructPriv::new(def.a, def.b)
+ }
+}
| [
"496"
] | serde-rs__serde-858 | Improve the newtype wrapper situation
Something like:
``` rust
serde_newtype! {
#[derive(Serialize, Deserialize)]
pub struct MyDuration(time::Duration);
struct time::Duration {
secs: u64,
nanos: u32,
}
}
```
| 0.9 | 528ec3cdd870abf801ca5cb3a47cdcc1a0f5cfc7 | diff --git a/serde/src/private/ser.rs b/serde/src/private/ser.rs
index c8d09d0b8..333cb7425 100644
--- a/serde/src/private/ser.rs
+++ b/serde/src/private/ser.rs
@@ -8,6 +8,12 @@ use self::content::{SerializeTupleVariantAsMapValue, SerializeStructVariantAsMap
#[cfg(feature = "std")]
use std::error;
+/// Used to check that serde(getter) attributes return the expected type.
+/// Not public API.
+pub fn constrain<T: ?Sized>(t: &T) -> &T {
+ t
+}
+
/// Not public API.
pub fn serialize_tagged_newtype<S, T>(serializer: S,
type_ident: &'static str,
diff --git a/serde_codegen_internals/src/ast.rs b/serde_codegen_internals/src/ast.rs
index 0a50691eb..462d061f4 100644
--- a/serde_codegen_internals/src/ast.rs
+++ b/serde_codegen_internals/src/ast.rs
@@ -1,5 +1,6 @@
use syn;
use attr;
+use check;
use Ctxt;
pub struct Item<'a> {
@@ -62,12 +63,14 @@ impl<'a> Item<'a> {
}
}
- Item {
+ let item = Item {
ident: item.ident.clone(),
attrs: attrs,
body: body,
generics: &item.generics,
- }
+ };
+ check::check(cx, &item);
+ item
}
}
@@ -81,6 +84,10 @@ impl<'a> Body<'a> {
Body::Struct(_, ref fields) => Box::new(fields.iter()),
}
}
+
+ pub fn has_getter(&self) -> bool {
+ self.all_fields().any(|f| f.attrs.getter().is_some())
+ }
}
fn enum_from_ast<'a>(cx: &Ctxt, variants: &'a [syn::Variant]) -> Vec<Variant<'a>> {
diff --git a/serde_codegen_internals/src/attr.rs b/serde_codegen_internals/src/attr.rs
index 9e957ad90..cb4ddd8ae 100644
--- a/serde_codegen_internals/src/attr.rs
+++ b/serde_codegen_internals/src/attr.rs
@@ -102,6 +102,7 @@ pub struct Item {
tag: EnumTag,
from_type: Option<syn::Ty>,
into_type: Option<syn::Ty>,
+ remote: Option<syn::Path>,
}
/// Styles of representing an enum.
@@ -151,6 +152,7 @@ impl Item {
let mut content = Attr::none(cx, "content");
let mut from_type = Attr::none(cx, "from");
let mut into_type = Attr::none(cx, "into");
+ let mut remote = Attr::none(cx, "remote");
for meta_items in item.attrs.iter().filter_map(get_serde_meta_items) {
for meta_item in meta_items {
@@ -290,6 +292,13 @@ impl Item {
}
}
+ // Parse `#[serde(remote = "...")]`
+ MetaItem(NameValue(ref name, ref lit)) if name == "remote" => {
+ if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
+ remote.set(path);
+ }
+ }
+
MetaItem(ref meta_item) => {
cx.error(format!("unknown serde container attribute `{}`",
meta_item.name()));
@@ -361,6 +370,7 @@ impl Item {
tag: tag,
from_type: from_type.get(),
into_type: into_type.get(),
+ remote: remote.get(),
}
}
@@ -399,6 +409,10 @@ impl Item {
pub fn into_type(&self) -> Option<&syn::Ty> {
self.into_type.as_ref()
}
+
+ pub fn remote(&self) -> Option<&syn::Path> {
+ self.remote.as_ref()
+ }
}
/// Represents variant attribute information
@@ -531,6 +545,7 @@ pub struct Field {
ser_bound: Option<Vec<syn::WherePredicate>>,
de_bound: Option<Vec<syn::WherePredicate>>,
borrowed_lifetimes: BTreeSet<syn::Lifetime>,
+ getter: Option<syn::Path>,
}
/// Represents the default to use for a field when deserializing.
@@ -558,6 +573,7 @@ impl Field {
let mut ser_bound = Attr::none(cx, "bound");
let mut de_bound = Attr::none(cx, "bound");
let mut borrowed_lifetimes = Attr::none(cx, "borrow");
+ let mut getter = Attr::none(cx, "getter");
let ident = match field.ident {
Some(ref ident) => ident.to_string(),
@@ -676,6 +692,13 @@ impl Field {
}
}
+ // Parse `#[serde(getter = "...")]`
+ MetaItem(NameValue(ref name, ref lit)) if name == "getter" => {
+ if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
+ getter.set(path);
+ }
+ }
+
MetaItem(ref meta_item) => {
cx.error(format!("unknown serde field attribute `{}`", meta_item.name()));
}
@@ -737,6 +760,7 @@ impl Field {
ser_bound: ser_bound.get(),
de_bound: de_bound.get(),
borrowed_lifetimes: borrowed_lifetimes,
+ getter: getter.get(),
}
}
@@ -788,6 +812,10 @@ impl Field {
pub fn borrowed_lifetimes(&self) -> &BTreeSet<syn::Lifetime> {
&self.borrowed_lifetimes
}
+
+ pub fn getter(&self) -> Option<&syn::Path> {
+ self.getter.as_ref()
+ }
}
type SerAndDe<T> = (Option<T>, Option<T>);
diff --git a/serde_codegen_internals/src/check.rs b/serde_codegen_internals/src/check.rs
new file mode 100644
index 000000000..fd4d4e7d6
--- /dev/null
+++ b/serde_codegen_internals/src/check.rs
@@ -0,0 +1,20 @@
+use ast::{Body, Item};
+use Ctxt;
+
+/// Cross-cutting checks that require looking at more than a single attrs
+/// object. Simpler checks should happen when parsing and building the attrs.
+pub fn check(cx: &Ctxt, item: &Item) {
+ match item.body {
+ Body::Enum(_) => {
+ if item.body.has_getter() {
+ cx.error("#[serde(getter = \"...\")] is not allowed in an enum");
+ }
+ }
+ Body::Struct(_, _) => {
+ if item.body.has_getter() && item.attrs.remote().is_none() {
+ cx.error("#[serde(getter = \"...\")] can only be used in structs \
+ that have #[serde(remote = \"...\")]");
+ }
+ }
+ }
+}
diff --git a/serde_codegen_internals/src/lib.rs b/serde_codegen_internals/src/lib.rs
index d5baf00b9..6353330b0 100644
--- a/serde_codegen_internals/src/lib.rs
+++ b/serde_codegen_internals/src/lib.rs
@@ -9,3 +9,4 @@ mod ctxt;
pub use ctxt::Ctxt;
mod case;
+mod check;
diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 4c4ffe14e..c8c291c9e 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -14,17 +14,25 @@ pub fn expand_derive_deserialize(item: &syn::DeriveInput) -> Result<Tokens, Stri
try!(ctxt.check());
let ident = &item.ident;
- let generics = build_generics(&item);
- let borrowed = borrowed_lifetimes(&item);
- let params = Parameters { generics: generics, borrowed: borrowed };
- let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(¶ms);
+ let params = Parameters::new(&item);
let dummy_const = Ident::new(format!("_IMPL_DESERIALIZE_FOR_{}", ident));
let body = Stmts(deserialize_body(&item, ¶ms));
- Ok(quote! {
- #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
- const #dummy_const: () = {
- extern crate serde as _serde;
+ let impl_item = if let Some(remote) = item.attrs.remote() {
+ let (impl_generics, ty_generics, where_clause) = item.generics.split_for_impl();
+ let de_lifetime = params.de_lifetime_def();
+ quote! {
+ impl #impl_generics #ident #ty_generics #where_clause {
+ fn deserialize<#de_lifetime, __D>(__deserializer: __D) -> _serde::export::Result<#remote #ty_generics, __D::Error>
+ where __D: _serde::Deserializer<'de>
+ {
+ #body
+ }
+ }
+ }
+ } else {
+ let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(¶ms);
+ quote! {
#[automatically_derived]
impl #de_impl_generics _serde::Deserialize<'de> for #ident #ty_generics #where_clause {
fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error>
@@ -33,13 +41,72 @@ pub fn expand_derive_deserialize(item: &syn::DeriveInput) -> Result<Tokens, Stri
#body
}
}
+ }
+ };
+
+ Ok(quote! {
+ #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
+ const #dummy_const: () = {
+ extern crate serde as _serde;
+ #impl_item
};
})
}
struct Parameters {
+ /// Name of the type the `derive` is on.
+ local: syn::Ident,
+
+ /// Path to the type the impl is for. Either a single `Ident` for local
+ /// types or `some::remote::Ident` for remote types. Does not include
+ /// generic parameters.
+ this: syn::Path,
+
+ /// Generics including any explicit and inferred bounds for the impl.
generics: syn::Generics,
+
+ /// Lifetimes borrowed from the deserializer. These will become bounds on
+ /// the `'de` lifetime of the deserializer.
borrowed: BTreeSet<syn::Lifetime>,
+
+ /// At least one field has a serde(getter) attribute, implying that the
+ /// remote type has a private field.
+ has_getter: bool,
+}
+
+impl Parameters {
+ fn new(item: &Item) -> Self {
+ let local = item.ident.clone();
+ let this = match item.attrs.remote() {
+ Some(remote) => remote.clone(),
+ None => item.ident.clone().into(),
+ };
+ let generics = build_generics(item);
+ let borrowed = borrowed_lifetimes(item);
+ let has_getter = item.body.has_getter();
+
+ Parameters {
+ local: local,
+ this: this,
+ generics: generics,
+ borrowed: borrowed,
+ has_getter: has_getter,
+ }
+ }
+
+ /// Type name to use in error messages and `&'static str` arguments to
+ /// various Deserializer methods.
+ fn type_name(&self) -> &str {
+ self.this.segments.last().unwrap().ident.as_ref()
+ }
+
+ fn de_lifetime_def(&self) -> syn::LifetimeDef {
+ syn::LifetimeDef {
+ attrs: Vec::new(),
+ lifetime: syn::Lifetime::new("'de"),
+ bounds: self.borrowed.iter().cloned().collect(),
+ }
+ }
}
// All the generics in the input, plus a bound `T: Deserialize` for each generic
@@ -109,14 +176,13 @@ fn deserialize_body(item: &Item, params: &Parameters) -> Fragment {
} else {
match item.body {
Body::Enum(ref variants) => {
- deserialize_item_enum(&item.ident, params, variants, &item.attrs)
+ deserialize_item_enum(params, variants, &item.attrs)
}
Body::Struct(Style::Struct, ref fields) => {
if fields.iter().any(|field| field.ident.is_none()) {
panic!("struct has unnamed fields");
}
- deserialize_struct(&item.ident,
- None,
+ deserialize_struct(None,
params,
fields,
&item.attrs,
@@ -127,14 +193,13 @@ fn deserialize_body(item: &Item, params: &Parameters) -> Fragment {
if fields.iter().any(|field| field.ident.is_some()) {
panic!("tuple struct has named fields");
}
- deserialize_tuple(&item.ident,
- None,
+ deserialize_tuple(None,
params,
fields,
&item.attrs,
None)
}
- Body::Struct(Style::Unit, _) => deserialize_unit_struct(&item.ident, &item.attrs),
+ Body::Struct(Style::Unit, _) => deserialize_unit_struct(params, &item.attrs),
}
}
}
@@ -147,26 +212,27 @@ fn deserialize_from(from_type: &syn::Ty) -> Fragment {
}
}
-fn deserialize_unit_struct(ident: &syn::Ident, item_attrs: &attr::Item) -> Fragment {
+fn deserialize_unit_struct(params: &Parameters, item_attrs: &attr::Item) -> Fragment {
+ let this = ¶ms.this;
let type_name = item_attrs.name().deserialize_name();
- let expecting = format!("unit struct {}", ident);
+ let expecting = format!("unit struct {}", params.type_name());
quote_block! {
struct __Visitor;
impl<'de> _serde::de::Visitor<'de> for __Visitor {
- type Value = #ident;
+ type Value = #this;
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
_serde::export::fmt::Formatter::write_str(formatter, #expecting)
}
#[inline]
- fn visit_unit<__E>(self) -> _serde::export::Result<#ident, __E>
+ fn visit_unit<__E>(self) -> _serde::export::Result<Self::Value, __E>
where __E: _serde::de::Error
{
- _serde::export::Ok(#ident)
+ _serde::export::Ok(#this)
}
}
@@ -174,38 +240,48 @@ fn deserialize_unit_struct(ident: &syn::Ident, item_attrs: &attr::Item) -> Fragm
}
}
-fn deserialize_tuple(ident: &syn::Ident,
- variant_ident: Option<&syn::Ident>,
+fn deserialize_tuple(variant_ident: Option<&syn::Ident>,
params: &Parameters,
fields: &[Field],
item_attrs: &attr::Item,
deserializer: Option<Tokens>)
-> Fragment {
+ let this = ¶ms.this;
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params);
+ // 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.
+ let construct = if params.has_getter {
+ let local = ¶ms.local;
+ quote!(#local)
+ } else {
+ quote!(#this)
+ };
+
let is_enum = variant_ident.is_some();
let type_path = match variant_ident {
- Some(variant_ident) => quote!(#ident::#variant_ident),
- None => quote!(#ident),
+ Some(variant_ident) => quote!(#construct::#variant_ident),
+ None => construct,
};
let expecting = match variant_ident {
- Some(variant_ident) => format!("tuple variant {}::{}", ident, variant_ident),
- None => format!("tuple struct {}", ident),
+ Some(variant_ident) => format!("tuple variant {}::{}", params.type_name(), variant_ident),
+ None => format!("tuple struct {}", params.type_name()),
};
let nfields = fields.len();
let visit_newtype_struct = if !is_enum && nfields == 1 {
- Some(deserialize_newtype_struct(ident, &type_path, params, &fields[0]))
+ Some(deserialize_newtype_struct(&type_path, params, &fields[0]))
} else {
None
};
- let visit_seq = Stmts(deserialize_seq(ident, &type_path, params, fields, false, item_attrs));
+ let visit_seq = Stmts(deserialize_seq(&type_path, params, fields, false, item_attrs));
let visitor_expr = quote! {
__Visitor {
- marker: _serde::export::PhantomData::<#ident #ty_generics>,
+ marker: _serde::export::PhantomData::<#this #ty_generics>,
lifetime: _serde::export::PhantomData,
}
};
@@ -230,12 +306,12 @@ fn deserialize_tuple(ident: &syn::Ident,
quote_block! {
struct __Visitor #de_impl_generics #where_clause {
- marker: _serde::export::PhantomData<#ident #ty_generics>,
+ marker: _serde::export::PhantomData<#this #ty_generics>,
lifetime: _serde::export::PhantomData<&'de ()>,
}
impl #de_impl_generics _serde::de::Visitor<'de> for __Visitor #de_ty_generics #where_clause {
- type Value = #ident #ty_generics;
+ type Value = #this #ty_generics;
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
_serde::export::fmt::Formatter::write_str(formatter, #expecting)
@@ -255,8 +331,7 @@ fn deserialize_tuple(ident: &syn::Ident,
}
}
-fn deserialize_seq(ident: &syn::Ident,
- type_path: &Tokens,
+fn deserialize_seq(type_path: &Tokens,
params: &Parameters,
fields: &[Field],
is_struct: bool,
@@ -285,7 +360,7 @@ fn deserialize_seq(ident: &syn::Ident,
}
Some(path) => {
let (wrapper, wrapper_ty) = wrap_deserialize_with(
- ident, params, field.ty, path);
+ params, field.ty, path);
quote!({
#wrapper
_serde::export::Option::map(
@@ -307,7 +382,7 @@ fn deserialize_seq(ident: &syn::Ident,
}
});
- let result = if is_struct {
+ let mut result = if is_struct {
let names = fields.iter().map(|f| &f.ident);
quote! {
#type_path { #( #names: #vars ),* }
@@ -318,14 +393,20 @@ fn deserialize_seq(ident: &syn::Ident,
}
};
+ if params.has_getter {
+ let this = ¶ms.this;
+ result = quote! {
+ _serde::export::Into::<#this>::into(#result)
+ };
+ }
+
quote_block! {
#(#let_values)*
_serde::export::Ok(#result)
}
}
-fn deserialize_newtype_struct(ident: &syn::Ident,
- type_path: &Tokens,
+fn deserialize_newtype_struct(type_path: &Tokens,
params: &Parameters,
field: &Field)
-> Tokens {
@@ -338,25 +419,33 @@ fn deserialize_newtype_struct(ident: &syn::Ident,
}
Some(path) => {
let (wrapper, wrapper_ty) =
- wrap_deserialize_with(ident, params, field.ty, path);
+ wrap_deserialize_with(params, field.ty, path);
quote!({
#wrapper
try!(<#wrapper_ty as _serde::Deserialize>::deserialize(__e)).value
})
}
};
+
+ let mut result = quote!(#type_path(#value));
+ if params.has_getter {
+ let this = ¶ms.this;
+ result = quote! {
+ _serde::export::Into::<#this>::into(#result)
+ };
+ }
+
quote! {
#[inline]
fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::export::Result<Self::Value, __E::Error>
where __E: _serde::Deserializer<'de>
{
- _serde::export::Ok(#type_path(#value))
+ _serde::export::Ok(#result)
}
}
}
-fn deserialize_struct(ident: &syn::Ident,
- variant_ident: Option<&syn::Ident>,
+fn deserialize_struct(variant_ident: Option<&syn::Ident>,
params: &Parameters,
fields: &[Field],
item_attrs: &attr::Item,
@@ -365,28 +454,39 @@ fn deserialize_struct(ident: &syn::Ident,
let is_enum = variant_ident.is_some();
let is_untagged = deserializer.is_some();
+ let this = ¶ms.this;
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params);
+ // 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.
+ let construct = if params.has_getter {
+ let local = ¶ms.local;
+ quote!(#local)
+ } else {
+ quote!(#this)
+ };
+
let type_path = match variant_ident {
- Some(variant_ident) => quote!(#ident::#variant_ident),
- None => quote!(#ident),
+ Some(variant_ident) => quote!(#construct::#variant_ident),
+ None => construct,
};
let expecting = match variant_ident {
- Some(variant_ident) => format!("struct variant {}::{}", ident, variant_ident),
- None => format!("struct {}", ident),
+ Some(variant_ident) => format!("struct variant {}::{}", params.type_name(), variant_ident),
+ None => format!("struct {}", params.type_name()),
};
- let visit_seq = Stmts(deserialize_seq(ident, &type_path, params, fields, true, item_attrs));
+ let visit_seq = Stmts(deserialize_seq(&type_path, params, fields, true, item_attrs));
let (field_visitor, fields_stmt, visit_map) =
- deserialize_struct_visitor(ident, type_path, params, fields, item_attrs);
+ deserialize_struct_visitor(type_path, params, fields, item_attrs);
let field_visitor = Stmts(field_visitor);
let fields_stmt = Stmts(fields_stmt);
let visit_map = Stmts(visit_map);
let visitor_expr = quote! {
__Visitor {
- marker: _serde::export::PhantomData::<#ident #ty_generics>,
+ marker: _serde::export::PhantomData::<#this #ty_generics>,
lifetime: _serde::export::PhantomData,
}
};
@@ -430,12 +530,12 @@ fn deserialize_struct(ident: &syn::Ident,
#field_visitor
struct __Visitor #de_impl_generics #where_clause {
- marker: _serde::export::PhantomData<#ident #ty_generics>,
+ marker: _serde::export::PhantomData<#this #ty_generics>,
lifetime: _serde::export::PhantomData<&'de ()>,
}
impl #de_impl_generics _serde::de::Visitor<'de> for __Visitor #de_ty_generics #where_clause {
- type Value = #ident #ty_generics;
+ type Value = #this #ty_generics;
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
_serde::export::fmt::Formatter::write_str(formatter, #expecting)
@@ -457,46 +557,43 @@ fn deserialize_struct(ident: &syn::Ident,
}
}
-fn deserialize_item_enum(ident: &syn::Ident,
- params: &Parameters,
+fn deserialize_item_enum(params: &Parameters,
variants: &[Variant],
item_attrs: &attr::Item)
-> Fragment {
match *item_attrs.tag() {
attr::EnumTag::External => {
- deserialize_externally_tagged_enum(ident, params, variants, item_attrs)
+ deserialize_externally_tagged_enum(params, variants, item_attrs)
}
attr::EnumTag::Internal { ref tag } => {
- deserialize_internally_tagged_enum(ident,
- params,
+ deserialize_internally_tagged_enum(params,
variants,
item_attrs,
tag)
}
attr::EnumTag::Adjacent { ref tag, ref content } => {
- deserialize_adjacently_tagged_enum(ident,
- params,
+ deserialize_adjacently_tagged_enum(params,
variants,
item_attrs,
tag,
content)
}
attr::EnumTag::None => {
- deserialize_untagged_enum(ident, params, variants, item_attrs)
+ deserialize_untagged_enum(params, variants, item_attrs)
}
}
}
-fn deserialize_externally_tagged_enum(ident: &syn::Ident,
- params: &Parameters,
+fn deserialize_externally_tagged_enum(params: &Parameters,
variants: &[Variant],
item_attrs: &attr::Item)
-> Fragment {
+ let this = ¶ms.this;
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params);
let type_name = item_attrs.name().deserialize_name();
- let expecting = format!("enum {}", ident);
+ let expecting = format!("enum {}", params.type_name());
let variant_names_idents: Vec<_> = variants.iter()
.enumerate()
@@ -520,8 +617,7 @@ fn deserialize_externally_tagged_enum(ident: &syn::Ident,
.map(|(i, variant)| {
let variant_name = field_i(i);
- let block = Match(deserialize_externally_tagged_variant(ident,
- params,
+ let block = Match(deserialize_externally_tagged_variant(params,
variant,
item_attrs));
@@ -554,12 +650,12 @@ fn deserialize_externally_tagged_enum(ident: &syn::Ident,
#variant_visitor
struct __Visitor #de_impl_generics #where_clause {
- marker: _serde::export::PhantomData<#ident #ty_generics>,
+ marker: _serde::export::PhantomData<#this #ty_generics>,
lifetime: _serde::export::PhantomData<&'de ()>,
}
impl #de_impl_generics _serde::de::Visitor<'de> for __Visitor #de_ty_generics #where_clause {
- type Value = #ident #ty_generics;
+ type Value = #this #ty_generics;
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
_serde::export::fmt::Formatter::write_str(formatter, #expecting)
@@ -576,14 +672,13 @@ fn deserialize_externally_tagged_enum(ident: &syn::Ident,
_serde::Deserializer::deserialize_enum(__deserializer, #type_name, VARIANTS,
__Visitor {
- marker: _serde::export::PhantomData::<#ident #ty_generics>,
+ marker: _serde::export::PhantomData::<#this #ty_generics>,
lifetime: _serde::export::PhantomData,
})
}
}
-fn deserialize_internally_tagged_enum(ident: &syn::Ident,
- params: &Parameters,
+fn deserialize_internally_tagged_enum(params: &Parameters,
variants: &[Variant],
item_attrs: &attr::Item,
tag: &str)
@@ -611,7 +706,6 @@ fn deserialize_internally_tagged_enum(ident: &syn::Ident,
let variant_name = field_i(i);
let block = Match(deserialize_internally_tagged_variant(
- ident,
params,
variant,
item_attrs,
@@ -638,13 +732,13 @@ fn deserialize_internally_tagged_enum(ident: &syn::Ident,
}
}
-fn deserialize_adjacently_tagged_enum(ident: &syn::Ident,
- params: &Parameters,
+fn deserialize_adjacently_tagged_enum(params: &Parameters,
variants: &[Variant],
item_attrs: &attr::Item,
tag: &str,
content: &str)
-> Fragment {
+ let this = ¶ms.this;
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params);
let variant_names_idents: Vec<_> = variants.iter()
@@ -669,7 +763,6 @@ fn deserialize_adjacently_tagged_enum(ident: &syn::Ident,
let variant_index = field_i(i);
let block = Match(deserialize_untagged_variant(
- ident,
params,
variant,
item_attrs,
@@ -682,7 +775,7 @@ fn deserialize_adjacently_tagged_enum(ident: &syn::Ident,
})
.collect();
- let expecting = format!("adjacently tagged enum {}", ident);
+ let expecting = format!("adjacently tagged enum {}", params.type_name());
let type_name = item_attrs.name().deserialize_name();
let tag_or_content = quote! {
@@ -717,7 +810,7 @@ fn deserialize_adjacently_tagged_enum(ident: &syn::Ident,
let variant_index = field_i(i);
let variant_ident = &variant.ident;
quote! {
- __Field::#variant_index => _serde::export::Ok(#ident::#variant_ident),
+ __Field::#variant_index => _serde::export::Ok(#this::#variant_ident),
}
});
missing_content = quote! {
@@ -748,12 +841,12 @@ fn deserialize_adjacently_tagged_enum(ident: &syn::Ident,
struct __Seed #de_impl_generics #where_clause {
field: __Field,
- marker: _serde::export::PhantomData<#ident #ty_generics>,
+ marker: _serde::export::PhantomData<#this #ty_generics>,
lifetime: _serde::export::PhantomData<&'de ()>,
}
impl #de_impl_generics _serde::de::DeserializeSeed<'de> for __Seed #de_ty_generics #where_clause {
- type Value = #ident #ty_generics;
+ type Value = #this #ty_generics;
fn deserialize<__D>(self, __deserializer: __D) -> _serde::export::Result<Self::Value, __D::Error>
where __D: _serde::Deserializer<'de>
@@ -765,12 +858,12 @@ fn deserialize_adjacently_tagged_enum(ident: &syn::Ident,
}
struct __Visitor #de_impl_generics #where_clause {
- marker: _serde::export::PhantomData<#ident #ty_generics>,
+ marker: _serde::export::PhantomData<#this #ty_generics>,
lifetime: _serde::export::PhantomData<&'de ()>,
}
impl #de_impl_generics _serde::de::Visitor<'de> for __Visitor #de_ty_generics #where_clause {
- type Value = #ident #ty_generics;
+ type Value = #this #ty_generics;
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
_serde::export::fmt::Formatter::write_str(formatter, #expecting)
@@ -871,14 +964,13 @@ fn deserialize_adjacently_tagged_enum(ident: &syn::Ident,
const FIELDS: &'static [&'static str] = &[#tag, #content];
_serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS,
__Visitor {
- marker: _serde::export::PhantomData::<#ident #ty_generics>,
+ marker: _serde::export::PhantomData::<#this #ty_generics>,
lifetime: _serde::export::PhantomData,
})
}
}
-fn deserialize_untagged_enum(ident: &syn::Ident,
- params: &Parameters,
+fn deserialize_untagged_enum(params: &Parameters,
variants: &[Variant],
item_attrs: &attr::Item)
-> Fragment {
@@ -886,7 +978,6 @@ fn deserialize_untagged_enum(ident: &syn::Ident,
.filter(|variant| !variant.attrs.skip_deserializing())
.map(|variant| {
Expr(deserialize_untagged_variant(
- ident,
params,
variant,
item_attrs,
@@ -900,7 +991,7 @@ fn deserialize_untagged_enum(ident: &syn::Ident,
// largest number of fields. I'm not sure I like that. Maybe it would be
// better to save all the errors and combine them into one message that
// explains why none of the variants matched.
- let fallthrough_msg = format!("data did not match any variant of untagged enum {}", ident);
+ let fallthrough_msg = format!("data did not match any variant of untagged enum {}", params.type_name());
quote_block! {
let __content = try!(<_serde::private::de::Content as _serde::Deserialize>::deserialize(__deserializer));
@@ -915,8 +1006,7 @@ fn deserialize_untagged_enum(ident: &syn::Ident,
}
}
-fn deserialize_externally_tagged_variant(ident: &syn::Ident,
- params: &Parameters,
+fn deserialize_externally_tagged_variant(params: &Parameters,
variant: &Variant,
item_attrs: &attr::Item)
-> Fragment {
@@ -924,28 +1014,26 @@ fn deserialize_externally_tagged_variant(ident: &syn::Ident,
match variant.style {
Style::Unit => {
+ let this = ¶ms.this;
quote_block! {
try!(_serde::de::VariantVisitor::visit_unit(__visitor));
- _serde::export::Ok(#ident::#variant_ident)
+ _serde::export::Ok(#this::#variant_ident)
}
}
Style::Newtype => {
- deserialize_externally_tagged_newtype_variant(ident,
- variant_ident,
+ deserialize_externally_tagged_newtype_variant(variant_ident,
params,
&variant.fields[0])
}
Style::Tuple => {
- deserialize_tuple(ident,
- Some(variant_ident),
+ deserialize_tuple(Some(variant_ident),
params,
&variant.fields,
item_attrs,
None)
}
Style::Struct => {
- deserialize_struct(ident,
- Some(variant_ident),
+ deserialize_struct(Some(variant_ident),
params,
&variant.fields,
item_attrs,
@@ -954,8 +1042,7 @@ fn deserialize_externally_tagged_variant(ident: &syn::Ident,
}
}
-fn deserialize_internally_tagged_variant(ident: &syn::Ident,
- params: &Parameters,
+fn deserialize_internally_tagged_variant(params: &Parameters,
variant: &Variant,
item_attrs: &attr::Item,
deserializer: Tokens)
@@ -964,16 +1051,16 @@ fn deserialize_internally_tagged_variant(ident: &syn::Ident,
match variant.style {
Style::Unit => {
- let type_name = ident.as_ref();
+ let this = ¶ms.this;
+ let type_name = params.type_name();
let variant_name = variant.ident.as_ref();
quote_block! {
try!(_serde::Deserializer::deserialize(#deserializer, _serde::private::de::InternallyTaggedUnitVisitor::new(#type_name, #variant_name)));
- _serde::export::Ok(#ident::#variant_ident)
+ _serde::export::Ok(#this::#variant_ident)
}
}
Style::Newtype | Style::Struct => {
- deserialize_untagged_variant(ident,
- params,
+ deserialize_untagged_variant(params,
variant,
item_attrs,
deserializer)
@@ -982,8 +1069,7 @@ fn deserialize_internally_tagged_variant(ident: &syn::Ident,
}
}
-fn deserialize_untagged_variant(ident: &syn::Ident,
- params: &Parameters,
+fn deserialize_untagged_variant(params: &Parameters,
variant: &Variant,
item_attrs: &attr::Item,
deserializer: Tokens)
@@ -992,7 +1078,8 @@ fn deserialize_untagged_variant(ident: &syn::Ident,
match variant.style {
Style::Unit => {
- let type_name = ident.as_ref();
+ let this = ¶ms.this;
+ let type_name = params.type_name();
let variant_name = variant.ident.as_ref();
quote_expr! {
_serde::export::Result::map(
@@ -1000,27 +1087,24 @@ fn deserialize_untagged_variant(ident: &syn::Ident,
#deserializer,
_serde::private::de::UntaggedUnitVisitor::new(#type_name, #variant_name)
),
- |()| #ident::#variant_ident)
+ |()| #this::#variant_ident)
}
}
Style::Newtype => {
- deserialize_untagged_newtype_variant(ident,
- variant_ident,
+ deserialize_untagged_newtype_variant(variant_ident,
params,
&variant.fields[0],
deserializer)
}
Style::Tuple => {
- deserialize_tuple(ident,
- Some(variant_ident),
+ deserialize_tuple(Some(variant_ident),
params,
&variant.fields,
item_attrs,
Some(deserializer))
}
Style::Struct => {
- deserialize_struct(ident,
- Some(variant_ident),
+ deserialize_struct(Some(variant_ident),
params,
&variant.fields,
item_attrs,
@@ -1029,56 +1113,56 @@ fn deserialize_untagged_variant(ident: &syn::Ident,
}
}
-fn deserialize_externally_tagged_newtype_variant(ident: &syn::Ident,
- variant_ident: &syn::Ident,
+fn deserialize_externally_tagged_newtype_variant(variant_ident: &syn::Ident,
params: &Parameters,
field: &Field)
-> Fragment {
+ let this = ¶ms.this;
match field.attrs.deserialize_with() {
None => {
let field_ty = &field.ty;
quote_expr! {
_serde::export::Result::map(
_serde::de::VariantVisitor::visit_newtype::<#field_ty>(__visitor),
- #ident::#variant_ident)
+ #this::#variant_ident)
}
}
Some(path) => {
let (wrapper, wrapper_ty) =
- wrap_deserialize_with(ident, params, field.ty, path);
+ wrap_deserialize_with(params, field.ty, path);
quote_block! {
#wrapper
_serde::export::Result::map(
_serde::de::VariantVisitor::visit_newtype::<#wrapper_ty>(__visitor),
- |__wrapper| #ident::#variant_ident(__wrapper.value))
+ |__wrapper| #this::#variant_ident(__wrapper.value))
}
}
}
}
-fn deserialize_untagged_newtype_variant(ident: &syn::Ident,
- variant_ident: &syn::Ident,
+fn deserialize_untagged_newtype_variant(variant_ident: &syn::Ident,
params: &Parameters,
field: &Field,
deserializer: Tokens)
-> Fragment {
+ let this = ¶ms.this;
match field.attrs.deserialize_with() {
None => {
let field_ty = &field.ty;
quote_expr! {
_serde::export::Result::map(
<#field_ty as _serde::Deserialize>::deserialize(#deserializer),
- #ident::#variant_ident)
+ #this::#variant_ident)
}
}
Some(path) => {
let (wrapper, wrapper_ty) =
- wrap_deserialize_with(ident, params, field.ty, path);
+ wrap_deserialize_with(params, field.ty, path);
quote_block! {
#wrapper
_serde::export::Result::map(
<#wrapper_ty as _serde::Deserialize>::deserialize(#deserializer),
- |__wrapper| #ident::#variant_ident(__wrapper.value))
+ |__wrapper| #this::#variant_ident(__wrapper.value))
}
}
}
@@ -1196,8 +1280,7 @@ fn deserialize_field_visitor(fields: Vec<(String, Ident)>,
}
}
-fn deserialize_struct_visitor(ident: &syn::Ident,
- struct_path: Tokens,
+fn deserialize_struct_visitor(struct_path: Tokens,
params: &Parameters,
fields: &[Field],
item_attrs: &attr::Item)
@@ -1217,13 +1300,12 @@ fn deserialize_struct_visitor(ident: &syn::Ident,
let field_visitor = deserialize_field_visitor(field_names_idents, item_attrs, false);
- let visit_map = deserialize_map(ident, struct_path, params, fields, item_attrs);
+ let visit_map = deserialize_map(struct_path, params, fields, item_attrs);
(field_visitor, fields_stmt, visit_map)
}
-fn deserialize_map(ident: &syn::Ident,
- struct_path: Tokens,
+fn deserialize_map(struct_path: Tokens,
params: &Parameters,
fields: &[Field],
item_attrs: &attr::Item)
@@ -1259,7 +1341,7 @@ fn deserialize_map(ident: &syn::Ident,
}
Some(path) => {
let (wrapper, wrapper_ty) = wrap_deserialize_with(
- ident, params, field.ty, path);
+ params, field.ty, path);
quote!({
#wrapper
try!(_serde::de::MapVisitor::visit_value::<#wrapper_ty>(&mut __visitor)).value
@@ -1347,6 +1429,14 @@ fn deserialize_map(ident: &syn::Ident,
}
};
+ let mut result = quote!(#struct_path { #(#result),* });
+ if params.has_getter {
+ let this = ¶ms.this;
+ result = quote! {
+ _serde::export::Into::<#this>::into(#result)
+ };
+ }
+
quote_block! {
#(#let_values)*
@@ -1356,7 +1446,7 @@ fn deserialize_map(ident: &syn::Ident,
#(#extract_values)*
- _serde::export::Ok(#struct_path { #(#result),* })
+ _serde::export::Ok(#result)
}
}
@@ -1366,17 +1456,17 @@ fn field_i(i: usize) -> Ident {
/// This function wraps the expression in `#[serde(deserialize_with = "...")]`
/// in a trait to prevent it from accessing the internal `Deserialize` state.
-fn wrap_deserialize_with(ident: &syn::Ident,
- params: &Parameters,
+fn wrap_deserialize_with(params: &Parameters,
field_ty: &syn::Ty,
deserialize_with: &syn::Path)
-> (Tokens, Tokens) {
+ let this = ¶ms.this;
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params);
let wrapper = quote! {
struct __DeserializeWith #de_impl_generics #where_clause {
value: #field_ty,
- phantom: _serde::export::PhantomData<#ident #ty_generics>,
+ phantom: _serde::export::PhantomData<#this #ty_generics>,
lifetime: _serde::export::PhantomData<&'de ()>,
}
@@ -1437,11 +1527,7 @@ struct DeImplGenerics<'a>(&'a Parameters);
impl<'a> ToTokens for DeImplGenerics<'a> {
fn to_tokens(&self, tokens: &mut Tokens) {
let mut generics = self.0.generics.clone();
- generics.lifetimes.insert(0, syn::LifetimeDef {
- attrs: Vec::new(),
- lifetime: syn::Lifetime::new("'de"),
- bounds: self.0.borrowed.iter().cloned().collect(),
- });
+ generics.lifetimes.insert(0, self.0.de_lifetime_def());
let (impl_generics, _, _) = generics.split_for_impl();
impl_generics.to_tokens(tokens);
}
diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index 51826928b..7b893e440 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -12,15 +12,23 @@ pub fn expand_derive_serialize(item: &syn::DeriveInput) -> Result<Tokens, String
try!(ctxt.check());
let ident = &item.ident;
- let generics = build_generics(&item);
- let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
+ let params = Parameters::new(&item);
+ let (impl_generics, ty_generics, where_clause) = params.generics.split_for_impl();
let dummy_const = Ident::new(format!("_IMPL_SERIALIZE_FOR_{}", ident));
- let body = Stmts(serialize_body(&item, &generics));
+ let body = Stmts(serialize_body(&item, ¶ms));
- Ok(quote! {
- #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
- const #dummy_const: () = {
- extern crate serde as _serde;
+ let impl_item = if let Some(remote) = item.attrs.remote() {
+ quote! {
+ impl #impl_generics #ident #ty_generics #where_clause {
+ fn serialize<__S>(__self: &#remote #ty_generics, __serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error>
+ where __S: _serde::Serializer
+ {
+ #body
+ }
+ }
+ }
+ } else {
+ quote! {
#[automatically_derived]
impl #impl_generics _serde::Serialize for #ident #ty_generics #where_clause {
fn serialize<__S>(&self, __serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error>
@@ -29,10 +37,66 @@ pub fn expand_derive_serialize(item: &syn::DeriveInput) -> Result<Tokens, String
#body
}
}
+ }
+ };
+
+ Ok(quote! {
+ #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
+ const #dummy_const: () = {
+ extern crate serde as _serde;
+ #impl_item
};
})
}
+struct Parameters {
+ /// Variable holding the value being serialized. Either `self` for local
+ /// types or `__self` for remote types.
+ self_var: Ident,
+
+ /// Path to the type the impl is for. Either a single `Ident` for local
+ /// types or `some::remote::Ident` for remote types. Does not include
+ /// generic parameters.
+ this: syn::Path,
+
+ /// Generics including any explicit and inferred bounds for the impl.
+ generics: syn::Generics,
+
+ /// Type has a `serde(remote = "...")` attribute.
+ is_remote: bool,
+}
+
+impl Parameters {
+ fn new(item: &Item) -> Self {
+ let is_remote = item.attrs.remote().is_some();
+ let self_var = if is_remote {
+ Ident::new("__self")
+ } else {
+ Ident::new("self")
+ };
+
+ let this = match item.attrs.remote() {
+ Some(remote) => remote.clone(),
+ None => item.ident.clone().into(),
+ };
+
+ let generics = build_generics(item);
+
+ Parameters {
+ self_var: self_var,
+ this: this,
+ generics: generics,
+ is_remote: is_remote,
+ }
+ }
+
+ /// Type name to use in error messages and `&'static str` arguments to
+ /// various Serializer methods.
+ fn type_name(&self) -> &str {
+ self.this.segments.last().unwrap().ident.as_ref()
+ }
+}
+
// All the generics in the input, plus a bound `T: Serialize` for each generic
// field type that will be serialized by us.
fn build_generics(item: &Item) -> syn::Generics {
@@ -60,38 +124,39 @@ fn needs_serialize_bound(attrs: &attr::Field) -> bool {
!attrs.skip_serializing() && attrs.serialize_with().is_none() && attrs.ser_bound().is_none()
}
-fn serialize_body(item: &Item, generics: &syn::Generics) -> Fragment {
+fn serialize_body(item: &Item, params: &Parameters) -> Fragment {
if let Some(into_type) = item.attrs.into_type() {
- serialize_into(into_type)
+ serialize_into(params, into_type)
} else {
match item.body {
Body::Enum(ref variants) => {
- serialize_item_enum(&item.ident, generics, variants, &item.attrs)
+ serialize_item_enum(params, variants, &item.attrs)
}
Body::Struct(Style::Struct, ref fields) => {
if fields.iter().any(|field| field.ident.is_none()) {
panic!("struct has unnamed fields");
}
- serialize_struct(&item.ident, generics, fields, &item.attrs)
+ serialize_struct(params, fields, &item.attrs)
}
Body::Struct(Style::Tuple, ref fields) => {
if fields.iter().any(|field| field.ident.is_some()) {
panic!("tuple struct has named fields");
}
- serialize_tuple_struct(&item.ident, generics, fields, &item.attrs)
+ serialize_tuple_struct(params, fields, &item.attrs)
}
Body::Struct(Style::Newtype, ref fields) => {
- serialize_newtype_struct(&item.ident, generics, &fields[0], &item.attrs)
+ serialize_newtype_struct(params, &fields[0], &item.attrs)
}
Body::Struct(Style::Unit, _) => serialize_unit_struct(&item.attrs),
}
}
}
-fn serialize_into(into_type: &syn::Ty) -> Fragment {
+fn serialize_into(params: &Parameters, into_type: &syn::Ty) -> Fragment {
+ let self_var = ¶ms.self_var;
quote_block! {
_serde::Serialize::serialize(
- &<Self as _serde::export::Into<#into_type>>::into(_serde::export::Clone::clone(self)),
+ &_serde::export::Into::<#into_type>::into(_serde::export::Clone::clone(#self_var)),
__serializer)
}
}
@@ -104,16 +169,15 @@ fn serialize_unit_struct(item_attrs: &attr::Item) -> Fragment {
}
}
-fn serialize_newtype_struct(ident: &syn::Ident,
- generics: &syn::Generics,
+fn serialize_newtype_struct(params: &Parameters,
field: &Field,
item_attrs: &attr::Item)
-> Fragment {
let type_name = item_attrs.name().serialize_name();
- let mut field_expr = quote!(&self.0);
+ let mut field_expr = get_field(params, field, 0);
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(ident, generics, field.ty, path, field_expr);
+ field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
}
quote_expr! {
@@ -121,15 +185,13 @@ fn serialize_newtype_struct(ident: &syn::Ident,
}
}
-fn serialize_tuple_struct(ident: &syn::Ident,
- generics: &syn::Generics,
+fn serialize_tuple_struct(params: &Parameters,
fields: &[Field],
item_attrs: &attr::Item)
-> Fragment {
let serialize_stmts =
- serialize_tuple_struct_visitor(ident,
- fields,
- generics,
+ serialize_tuple_struct_visitor(fields,
+ params,
false,
quote!(_serde::ser::SerializeTupleStruct::serialize_field));
@@ -144,15 +206,13 @@ fn serialize_tuple_struct(ident: &syn::Ident,
}
}
-fn serialize_struct(ident: &syn::Ident,
- generics: &syn::Generics,
+fn serialize_struct(params: &Parameters,
fields: &[Field],
item_attrs: &attr::Item)
-> Fragment {
let serialize_fields =
- serialize_struct_visitor(ident,
- fields,
- generics,
+ serialize_struct_visitor(fields,
+ params,
false,
quote!(_serde::ser::SerializeStruct::serialize_field));
@@ -165,12 +225,13 @@ fn serialize_struct(ident: &syn::Ident,
let let_mut = mut_if(serialized_fields.peek().is_some());
let len = serialized_fields.map(|field| {
- let ident = field.ident.clone().expect("struct has unnamed fields");
- let field_expr = quote!(&self.#ident);
-
match field.attrs.skip_serializing_if() {
- Some(path) => quote!(if #path(#field_expr) { 0 } else { 1 }),
None => quote!(1),
+ Some(path) => {
+ let ident = field.ident.clone().expect("struct has unnamed fields");
+ let field_expr = get_field(params, field, ident);
+ quote!(if #path(#field_expr) { 0 } else { 1 })
+ }
}
})
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
@@ -182,16 +243,16 @@ fn serialize_struct(ident: &syn::Ident,
}
}
-fn serialize_item_enum(ident: &syn::Ident,
- generics: &syn::Generics,
+fn serialize_item_enum(params: &Parameters,
variants: &[Variant],
item_attrs: &attr::Item)
-> Fragment {
+ let self_var = ¶ms.self_var;
+
let arms: Vec<_> = variants.iter()
.enumerate()
.map(|(variant_index, variant)| {
- serialize_variant(ident,
- generics,
+ serialize_variant(params,
variant,
variant_index,
item_attrs)
@@ -199,23 +260,23 @@ fn serialize_item_enum(ident: &syn::Ident,
.collect();
quote_expr! {
- match *self {
+ match *#self_var {
#(#arms)*
}
}
}
-fn serialize_variant(ident: &syn::Ident,
- generics: &syn::Generics,
+fn serialize_variant(params: &Parameters,
variant: &Variant,
variant_index: usize,
item_attrs: &attr::Item)
-> Tokens {
+ let this = ¶ms.this;
let variant_ident = variant.ident.clone();
if variant.attrs.skip_serializing() {
let skipped_msg = format!("the enum variant {}::{} cannot be serialized",
- ident, variant_ident);
+ params.type_name(), variant_ident);
let skipped_err = quote! {
_serde::export::Err(_serde::ser::Error::custom(#skipped_msg))
};
@@ -225,26 +286,26 @@ fn serialize_variant(ident: &syn::Ident,
Style::Struct => quote!( {..} ),
};
quote! {
- #ident::#variant_ident #fields_pat => #skipped_err,
+ #this::#variant_ident #fields_pat => #skipped_err,
}
} else {
// variant wasn't skipped
let case = match variant.style {
Style::Unit => {
quote! {
- #ident::#variant_ident
+ #this::#variant_ident
}
}
Style::Newtype => {
quote! {
- #ident::#variant_ident(ref __field0)
+ #this::#variant_ident(ref __field0)
}
}
Style::Tuple => {
let field_names = (0..variant.fields.len())
.map(|i| Ident::new(format!("__field{}", i)));
quote! {
- #ident::#variant_ident(#(ref #field_names),*)
+ #this::#variant_ident(#(ref #field_names),*)
}
}
Style::Struct => {
@@ -252,35 +313,32 @@ fn serialize_variant(ident: &syn::Ident,
.iter()
.map(|f| f.ident.clone().expect("struct variant has unnamed fields"));
quote! {
- #ident::#variant_ident { #(ref #fields),* }
+ #this::#variant_ident { #(ref #fields),* }
}
}
};
let body = Match(match *item_attrs.tag() {
attr::EnumTag::External => {
- serialize_externally_tagged_variant(ident,
- generics,
+ serialize_externally_tagged_variant(params,
variant,
variant_index,
item_attrs)
}
attr::EnumTag::Internal { ref tag } => {
- serialize_internally_tagged_variant(ident,
- generics,
+ serialize_internally_tagged_variant(params,
variant,
item_attrs,
tag)
}
attr::EnumTag::Adjacent { ref tag, ref content } => {
- serialize_adjacently_tagged_variant(ident,
- generics,
+ serialize_adjacently_tagged_variant(params,
variant,
item_attrs,
tag,
content)
}
- attr::EnumTag::None => serialize_untagged_variant(ident, generics, variant, item_attrs),
+ attr::EnumTag::None => serialize_untagged_variant(params, variant, item_attrs),
});
quote! {
@@ -289,8 +347,7 @@ fn serialize_variant(ident: &syn::Ident,
}
}
-fn serialize_externally_tagged_variant(ident: &syn::Ident,
- generics: &syn::Generics,
+fn serialize_externally_tagged_variant(params: &Parameters,
variant: &Variant,
variant_index: usize,
item_attrs: &attr::Item)
@@ -313,7 +370,7 @@ fn serialize_externally_tagged_variant(ident: &syn::Ident,
let field = &variant.fields[0];
let mut field_expr = quote!(__field0);
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(ident, generics, field.ty, path, field_expr);
+ field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
}
quote_expr! {
@@ -332,8 +389,7 @@ fn serialize_externally_tagged_variant(ident: &syn::Ident,
variant_index: variant_index,
variant_name: variant_name,
},
- ident,
- generics,
+ params,
&variant.fields)
}
Style::Struct => {
@@ -341,16 +397,14 @@ fn serialize_externally_tagged_variant(ident: &syn::Ident,
variant_index: variant_index,
variant_name: variant_name,
},
- ident,
- generics,
+ params,
&variant.fields,
&type_name)
}
}
}
-fn serialize_internally_tagged_variant(ident: &syn::Ident,
- generics: &syn::Generics,
+fn serialize_internally_tagged_variant(params: &Parameters,
variant: &Variant,
item_attrs: &attr::Item,
tag: &str)
@@ -358,7 +412,7 @@ fn serialize_internally_tagged_variant(ident: &syn::Ident,
let type_name = item_attrs.name().serialize_name();
let variant_name = variant.attrs.name().serialize_name();
- let enum_ident_str = ident.as_ref();
+ let enum_ident_str = params.type_name();
let variant_ident_str = variant.ident.as_ref();
match variant.style {
@@ -375,7 +429,7 @@ fn serialize_internally_tagged_variant(ident: &syn::Ident,
let field = &variant.fields[0];
let mut field_expr = quote!(__field0);
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(ident, generics, field.ty, path, field_expr);
+ field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
}
quote_expr! {
@@ -394,8 +448,7 @@ fn serialize_internally_tagged_variant(ident: &syn::Ident,
tag: tag,
variant_name: variant_name,
},
- ident,
- generics,
+ params,
&variant.fields,
&type_name)
}
@@ -403,13 +456,13 @@ fn serialize_internally_tagged_variant(ident: &syn::Ident,
}
}
-fn serialize_adjacently_tagged_variant(ident: &syn::Ident,
- generics: &syn::Generics,
+fn serialize_adjacently_tagged_variant(params: &Parameters,
variant: &Variant,
item_attrs: &attr::Item,
tag: &str,
content: &str)
-> Fragment {
+ let this = ¶ms.this;
let type_name = item_attrs.name().serialize_name();
let variant_name = variant.attrs.name().serialize_name();
@@ -427,7 +480,7 @@ fn serialize_adjacently_tagged_variant(ident: &syn::Ident,
let field = &variant.fields[0];
let mut field_expr = quote!(__field0);
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(ident, generics, field.ty, path, field_expr);
+ field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
}
quote_expr! {
@@ -436,14 +489,12 @@ fn serialize_adjacently_tagged_variant(ident: &syn::Ident,
}
Style::Tuple => {
serialize_tuple_variant(TupleVariant::Untagged,
- ident,
- generics,
+ params,
&variant.fields)
}
Style::Struct => {
serialize_struct_variant(StructVariant::Untagged,
- ident,
- generics,
+ params,
&variant.fields,
&variant_name)
}
@@ -466,15 +517,15 @@ fn serialize_adjacently_tagged_variant(ident: &syn::Ident,
}
};
- let (_, ty_generics, where_clause) = generics.split_for_impl();
+ let (_, ty_generics, where_clause) = params.generics.split_for_impl();
- let wrapper_generics = bound::with_lifetime_bound(generics, "'__a");
+ let wrapper_generics = bound::with_lifetime_bound(¶ms.generics, "'__a");
let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl();
quote_block! {
struct __AdjacentlyTagged #wrapper_generics #where_clause {
data: (#(&'__a #fields_ty,)*),
- phantom: _serde::export::PhantomData<#ident #ty_generics>,
+ phantom: _serde::export::PhantomData<#this #ty_generics>,
}
impl #wrapper_impl_generics _serde::Serialize for __AdjacentlyTagged #wrapper_ty_generics #where_clause {
@@ -493,14 +544,13 @@ fn serialize_adjacently_tagged_variant(ident: &syn::Ident,
try!(_serde::ser::SerializeStruct::serialize_field(
&mut __struct, #content, &__AdjacentlyTagged {
data: (#(#fields_ident,)*),
- phantom: _serde::export::PhantomData::<#ident #ty_generics>,
+ phantom: _serde::export::PhantomData::<#this #ty_generics>,
}));
_serde::ser::SerializeStruct::end(__struct)
}
}
-fn serialize_untagged_variant(ident: &syn::Ident,
- generics: &syn::Generics,
+fn serialize_untagged_variant(params: &Parameters,
variant: &Variant,
item_attrs: &attr::Item)
-> Fragment {
@@ -514,7 +564,7 @@ fn serialize_untagged_variant(ident: &syn::Ident,
let field = &variant.fields[0];
let mut field_expr = quote!(__field0);
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(ident, generics, field.ty, path, field_expr);
+ field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
}
quote_expr! {
@@ -522,13 +572,12 @@ fn serialize_untagged_variant(ident: &syn::Ident,
}
}
Style::Tuple => {
- serialize_tuple_variant(TupleVariant::Untagged, ident, generics, &variant.fields)
+ serialize_tuple_variant(TupleVariant::Untagged, params, &variant.fields)
}
Style::Struct => {
let type_name = item_attrs.name().serialize_name();
serialize_struct_variant(StructVariant::Untagged,
- ident,
- generics,
+ params,
&variant.fields,
&type_name)
}
@@ -545,8 +594,7 @@ enum TupleVariant {
}
fn serialize_tuple_variant(context: TupleVariant,
- ident: &syn::Ident,
- generics: &syn::Generics,
+ params: &Parameters,
fields: &[Field])
-> Fragment {
let method = match context {
@@ -557,7 +605,7 @@ fn serialize_tuple_variant(context: TupleVariant,
};
let serialize_stmts =
- serialize_tuple_struct_visitor(ident, fields, generics, true, method);
+ serialize_tuple_struct_visitor(fields, params, true, method);
let len = serialize_stmts.len();
let let_mut = mut_if(len > 0);
@@ -597,8 +645,7 @@ enum StructVariant<'a> {
}
fn serialize_struct_variant<'a>(context: StructVariant<'a>,
- ident: &syn::Ident,
- generics: &syn::Generics,
+ params: &Parameters,
fields: &[Field],
name: &str)
-> Fragment {
@@ -610,7 +657,7 @@ fn serialize_struct_variant<'a>(context: StructVariant<'a>,
StructVariant::Untagged => quote!(_serde::ser::SerializeStruct::serialize_field),
};
- let serialize_fields = serialize_struct_visitor(ident, fields, generics, true, method);
+ let serialize_fields = serialize_struct_visitor(fields, params, true, method);
let mut serialized_fields = fields.iter()
.filter(|&field| !field.attrs.skip_serializing())
@@ -672,9 +719,8 @@ fn serialize_struct_variant<'a>(context: StructVariant<'a>,
}
}
-fn serialize_tuple_struct_visitor(ident: &syn::Ident,
- fields: &[Field],
- generics: &syn::Generics,
+fn serialize_tuple_struct_visitor(fields: &[Field],
+ params: &Parameters,
is_enum: bool,
func: Tokens)
-> Vec<Tokens> {
@@ -685,8 +731,7 @@ fn serialize_tuple_struct_visitor(ident: &syn::Ident,
let id = Ident::new(format!("__field{}", i));
quote!(#id)
} else {
- let i = Ident::new(i);
- quote!(&self.#i)
+ get_field(params, field, i)
};
let skip = field.attrs
@@ -695,7 +740,7 @@ fn serialize_tuple_struct_visitor(ident: &syn::Ident,
if let Some(path) = field.attrs.serialize_with() {
field_expr =
- wrap_serialize_with(ident, generics, field.ty, path, field_expr);
+ wrap_serialize_with(params, field.ty, path, field_expr);
}
let ser = quote! {
@@ -710,9 +755,8 @@ fn serialize_tuple_struct_visitor(ident: &syn::Ident,
.collect()
}
-fn serialize_struct_visitor(ident: &syn::Ident,
- fields: &[Field],
- generics: &syn::Generics,
+fn serialize_struct_visitor(fields: &[Field],
+ params: &Parameters,
is_enum: bool,
func: Tokens)
-> Vec<Tokens> {
@@ -723,7 +767,7 @@ fn serialize_struct_visitor(ident: &syn::Ident,
let mut field_expr = if is_enum {
quote!(#field_ident)
} else {
- quote!(&self.#field_ident)
+ get_field(params, field, field_ident)
};
let key_expr = field.attrs.name().serialize_name();
@@ -734,7 +778,7 @@ fn serialize_struct_visitor(ident: &syn::Ident,
if let Some(path) = field.attrs.serialize_with() {
field_expr =
- wrap_serialize_with(ident, generics, field.ty, path, field_expr)
+ wrap_serialize_with(params, field.ty, path, field_expr)
}
let ser = quote! {
@@ -749,21 +793,21 @@ fn serialize_struct_visitor(ident: &syn::Ident,
.collect()
}
-fn wrap_serialize_with(ident: &syn::Ident,
- generics: &syn::Generics,
+fn wrap_serialize_with(params: &Parameters,
field_ty: &syn::Ty,
serialize_with: &syn::Path,
value: Tokens)
-> Tokens {
- let (_, ty_generics, where_clause) = generics.split_for_impl();
+ let this = ¶ms.this;
+ let (_, ty_generics, where_clause) = params.generics.split_for_impl();
- let wrapper_generics = bound::with_lifetime_bound(generics, "'__a");
+ let wrapper_generics = bound::with_lifetime_bound(¶ms.generics, "'__a");
let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl();
quote!({
struct __SerializeWith #wrapper_impl_generics #where_clause {
value: &'__a #field_ty,
- phantom: _serde::export::PhantomData<#ident #ty_generics>,
+ phantom: _serde::export::PhantomData<#this #ty_generics>,
}
impl #wrapper_impl_generics _serde::Serialize for __SerializeWith #wrapper_ty_generics #where_clause {
@@ -776,7 +820,7 @@ fn wrap_serialize_with(ident: &syn::Ident,
&__SerializeWith {
value: #value,
- phantom: _serde::export::PhantomData::<#ident #ty_generics>,
+ phantom: _serde::export::PhantomData::<#this #ty_generics>,
}
})
}
@@ -790,3 +834,27 @@ fn wrap_serialize_with(ident: &syn::Ident,
fn mut_if(is_mut: bool) -> Option<Tokens> {
if is_mut { Some(quote!(mut)) } else { None }
}
+
+fn get_field<I>(params: &Parameters, field: &Field, ident: I) -> Tokens
+ where I: Into<Ident>
+{
+ let self_var = ¶ms.self_var;
+ match (params.is_remote, field.attrs.getter()) {
+ (false, None) => {
+ let ident = ident.into();
+ quote!(&#self_var.#ident)
+ }
+ (true, None) => {
+ let ty = field.ty;
+ let ident = ident.into();
+ quote!(_serde::private::ser::constrain::<#ty>(&#self_var.#ident))
+ }
+ (true, Some(getter)) => {
+ let ty = field.ty;
+ quote!(_serde::private::ser::constrain::<#ty>(&#getter(#self_var)))
+ }
+ (false, Some(_)) => {
+ unreachable!("getter is only allowed for remote impls");
+ }
+ }
+}
| serde-rs/serde | 2017-04-09T17:20:43Z | @nox points out the approach from hyper_serde could be more convenient in some cases so we can provide that instead / in addition to the above. That approach is to define a single shared `Ser<T>` and `De<T>` wrapper in the user's crate and then implement Serialize for `Ser<time::Duration>` and Deserialize for `De<time::Duration>`. Then provide functions to use with serialize_with and deserialize_with that take any `Ser<T>` or `De<T>`. That lets you use the intended type like time::Duration inside all of your structs rather than using a newtype wrapper inside your structs.
That could look like:
``` rust
// just once
serde_remote_init!(SerdeWrapper);
// for each struct
serde_remote_derive! {
#[derive(Serialize, Deserialize)]
struct time::Duration {
secs: u64,
nanos: u32,
}
}
#[derive(Serialize, Deserialize)]
struct Mine {
#[serde(serialize_with = "SerdeWrapper::serialize",
deserialize_with = "SerdeWrapper::deserialize")]
dur: time::Duration,
}
```
I wonder if I can make this work:
```rust
#[derive(Serialize, Deserialize)]
#[serde(remote = "time::Duration")]
struct Duration {
secs: u64,
nanos: u32,
}
#[derive(Serialize, Deserialize)]
struct Mine {
#[serde(with = "Duration")]
dur: time::Duration,
}
```
Private fields make it less nice but here is a proof of concept:
```rust
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
use serde::ser::{Serializer, SerializeStruct};
use std::time;
// #[derive(Serialize)]
// #[serde(remote = "time::Duration")]
struct Duration {
// #[serde(getter = "time::Duration::as_secs")]
secs: u64,
// #[serde(getter = "time::Duration::subsec_nanos")]
nanos: u32,
}
impl Duration {
fn serialize<S>(remote: &time::Duration, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
let mut state = serializer.serialize_struct("Duration", 2)?;
state.serialize_field("secs", &time::Duration::as_secs(&remote))?;
state.serialize_field("nanos", &time::Duration::subsec_nanos(&remote))?;
state.end()
}
}
#[derive(Serialize)]
struct Mine {
#[serde(with = "Duration")]
dur: time::Duration,
}
fn main() {
let mine = Mine { dur: time::Duration::new(1, 2) };
println!("{}", serde_json::to_string(&mine).unwrap());
}
```
#### Proposed semantics
If the remote struct has all public fields then it works with just a remote attribute.
```rust
#[derive(Serialize, Deserialize)]
#[serde(remote = "time::Duration")]
struct Duration {
secs: u64,
nanos: u32,
}
```
If the remote struct has one or more private fields, you provide a getter for any private fields and an Into conversion in the deserialization direction. The Into conversion is executed if there is at least one getter attribute.
```rust
#[derive(Serialize, Deserialize)]
#[serde(remote = "time::Duration")]
struct Duration {
#[serde(getter = "time::Duration::as_secs")]
secs: u64,
#[serde(getter = "time::Duration::subsec_nanos")]
nanos: u32,
}
impl From<Duration> for time::Duration {
fn from(helper: Duration) -> time::Duration {
time::Duration::new(helper.secs, helper.nanos)
}
}
``` | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 |
848 | diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index 68e63505c..c1e68a92b 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -295,6 +295,11 @@ fn test_gen() {
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct UnitDenyUnknown;
+
+ #[derive(Serialize, Deserialize)]
+ struct EmptyArray {
+ empty: [X; 0],
+ }
}
//////////////////////////////////////////////////////////////////////////
| [
"821"
] | serde-rs__serde-848 | Do not require T: Deserialize in order to deserialize [T; 0]
The current impl is:
```rust
impl<T> Deserialize for [T; 0] where T: Deserialize
```
The `T: Deserialize` is not necessary.
| 0.9 | 2fe67d3d72534a011ef7c63065e4fb70f73cdddd | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 21f557f93..eefe3215d 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -625,9 +625,7 @@ impl<A> ArrayVisitor<A> {
}
}
-impl<'de, T> Visitor<'de> for ArrayVisitor<[T; 0]>
- where T: Deserialize<'de>
-{
+impl<'de, T> Visitor<'de> for ArrayVisitor<[T; 0]> {
type Value = [T; 0];
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
@@ -642,9 +640,8 @@ impl<'de, T> Visitor<'de> for ArrayVisitor<[T; 0]>
}
}
-impl<'de, T> Deserialize<'de> for [T; 0]
- where T: Deserialize<'de>
-{
+// Does not require T: Deserialize<'de>.
+impl<'de, T> Deserialize<'de> for [T; 0] {
fn deserialize<D>(deserializer: D) -> Result<[T; 0], D::Error>
where D: Deserializer<'de>
{
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index a9bfaf092..6cfa32a91 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -143,6 +143,16 @@ impl<T> Serialize for PhantomData<T> {
///////////////////////////////////////////////////////////////////////////////
+// Does not require T: Serialize.
+impl<T> Serialize for [T; 0] {
+ #[inline]
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where S: Serializer
+ {
+ try!(serializer.serialize_seq_fixed_size(0)).end()
+ }
+}
+
macro_rules! array_impls {
($len:expr) => {
impl<T> Serialize for [T; $len] where T: Serialize {
@@ -160,7 +170,6 @@ macro_rules! array_impls {
}
}
-array_impls!(0);
array_impls!(1);
array_impls!(2);
array_impls!(3);
| serde-rs/serde | 2017-04-06T00:34:37Z | Serialize for [T; 0] as well. | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 |
566 | diff --git a/serde_derive/tests/compile-fail/duplicate-attribute/rename-and-ser.rs b/serde_derive/tests/compile-fail/duplicate-attribute/rename-and-ser.rs
new file mode 100644
index 000000000..312583af1
--- /dev/null
+++ b/serde_derive/tests/compile-fail/duplicate-attribute/rename-and-ser.rs
@@ -0,0 +1,12 @@
+#![feature(rustc_macro)]
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
+struct S {
+ #[serde(rename="x", serialize="y")] //~^^ HELP: unknown serde field attribute `serialize`
+ x: (),
+}
+
+fn main() {}
diff --git a/serde_derive/tests/compile-fail/duplicate-attribute/rename-rename-de.rs b/serde_derive/tests/compile-fail/duplicate-attribute/rename-rename-de.rs
new file mode 100644
index 000000000..e6d6876a0
--- /dev/null
+++ b/serde_derive/tests/compile-fail/duplicate-attribute/rename-rename-de.rs
@@ -0,0 +1,13 @@
+#![feature(rustc_macro)]
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
+struct S {
+ #[serde(rename="x")]
+ #[serde(rename(deserialize="y"))] //~^^^ HELP: duplicate serde attribute `rename`
+ x: (),
+}
+
+fn main() {}
diff --git a/serde_derive/tests/compile-fail/duplicate-attribute/rename-ser-rename-ser.rs b/serde_derive/tests/compile-fail/duplicate-attribute/rename-ser-rename-ser.rs
new file mode 100644
index 000000000..d6937559a
--- /dev/null
+++ b/serde_derive/tests/compile-fail/duplicate-attribute/rename-ser-rename-ser.rs
@@ -0,0 +1,12 @@
+#![feature(rustc_macro)]
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
+struct S {
+ #[serde(rename(serialize="x"), rename(serialize="y"))] //~^^ HELP: duplicate serde attribute `rename`
+ x: (),
+}
+
+fn main() {}
diff --git a/serde_derive/tests/compile-fail/duplicate-attribute/rename-ser-rename.rs b/serde_derive/tests/compile-fail/duplicate-attribute/rename-ser-rename.rs
new file mode 100644
index 000000000..dcb0f69e0
--- /dev/null
+++ b/serde_derive/tests/compile-fail/duplicate-attribute/rename-ser-rename.rs
@@ -0,0 +1,13 @@
+#![feature(rustc_macro)]
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
+struct S {
+ #[serde(rename(serialize="x"))]
+ #[serde(rename="y")] //~^^^ HELP: duplicate serde attribute `rename`
+ x: (),
+}
+
+fn main() {}
diff --git a/serde_derive/tests/compile-fail/duplicate-attribute/rename-ser-ser.rs b/serde_derive/tests/compile-fail/duplicate-attribute/rename-ser-ser.rs
new file mode 100644
index 000000000..af9116e53
--- /dev/null
+++ b/serde_derive/tests/compile-fail/duplicate-attribute/rename-ser-ser.rs
@@ -0,0 +1,12 @@
+#![feature(rustc_macro)]
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
+struct S {
+ #[serde(rename(serialize="x", serialize="y"))] //~^^ HELP: duplicate serde attribute `rename`
+ x: (),
+}
+
+fn main() {}
diff --git a/serde_derive/tests/compile-fail/duplicate-attribute/two-rename-ser.rs b/serde_derive/tests/compile-fail/duplicate-attribute/two-rename-ser.rs
new file mode 100644
index 000000000..a518839d4
--- /dev/null
+++ b/serde_derive/tests/compile-fail/duplicate-attribute/two-rename-ser.rs
@@ -0,0 +1,13 @@
+#![feature(rustc_macro)]
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
+struct S {
+ #[serde(rename(serialize="x"))]
+ #[serde(rename(serialize="y"))] //~^^^ HELP: duplicate serde attribute `rename`
+ x: (),
+}
+
+fn main() {}
diff --git a/serde_derive/tests/compile-fail/str_ref_deser.rs b/serde_derive/tests/compile-fail/str_ref_deser.rs
new file mode 100644
index 000000000..9a99e72b4
--- /dev/null
+++ b/serde_derive/tests/compile-fail/str_ref_deser.rs
@@ -0,0 +1,11 @@
+#![feature(rustc_macro)]
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize, Deserialize)] //~ ERROR: custom derive attribute panicked
+struct Test<'a> {
+ s: &'a str, //~^^ HELP: Serde does not support deserializing fields of type &str
+}
+
+fn main() {}
diff --git a/serde_derive/tests/compile-fail/unknown-attribute/container.rs b/serde_derive/tests/compile-fail/unknown-attribute/container.rs
new file mode 100644
index 000000000..2b0e1cb22
--- /dev/null
+++ b/serde_derive/tests/compile-fail/unknown-attribute/container.rs
@@ -0,0 +1,12 @@
+#![feature(rustc_macro)]
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
+#[serde(abc="xyz")] //~^ HELP: unknown serde container attribute `abc`
+struct A {
+ x: u32,
+}
+
+fn main() { }
diff --git a/serde_derive/tests/compile-fail/unknown-attribute/field.rs b/serde_derive/tests/compile-fail/unknown-attribute/field.rs
new file mode 100644
index 000000000..1b2d8e6c1
--- /dev/null
+++ b/serde_derive/tests/compile-fail/unknown-attribute/field.rs
@@ -0,0 +1,12 @@
+#![feature(rustc_macro)]
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
+struct C {
+ #[serde(abc="xyz")] //~^^ HELP: unknown serde field attribute `abc`
+ x: u32,
+}
+
+fn main() { }
diff --git a/serde_derive/tests/compile-fail/unknown-attribute/variant.rs b/serde_derive/tests/compile-fail/unknown-attribute/variant.rs
new file mode 100644
index 000000000..239fcc89d
--- /dev/null
+++ b/serde_derive/tests/compile-fail/unknown-attribute/variant.rs
@@ -0,0 +1,12 @@
+#![feature(rustc_macro)]
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
+enum E {
+ #[serde(abc="xyz")] //~^^ HELP: unknown serde variant attribute `abc`
+ V,
+}
+
+fn main() { }
diff --git a/serde_macros/tests/compile_tests.rs b/serde_derive/tests/compile_tests.rs
similarity index 100%
rename from serde_macros/tests/compile_tests.rs
rename to serde_derive/tests/compile_tests.rs
diff --git a/serde_macros/tests/run-pass/identity-op.rs b/serde_derive/tests/run-pass/identity-op.rs
similarity index 80%
rename from serde_macros/tests/run-pass/identity-op.rs
rename to serde_derive/tests/run-pass/identity-op.rs
index dcf8117a3..47e2c750a 100644
--- a/serde_macros/tests/run-pass/identity-op.rs
+++ b/serde_derive/tests/run-pass/identity-op.rs
@@ -1,8 +1,9 @@
-#![feature(custom_derive, plugin)]
-#![plugin(serde_macros, clippy)]
-
+#![feature(rustc_macro)]
#![deny(identity_op)]
+#[macro_use]
+extern crate serde_derive;
+
// The derived implementation uses 0+1 to add up the number of fields
// serialized, which Clippy warns about. If the expansion info is registered
// correctly, the Clippy lint is not triggered.
diff --git a/serde_derive/tests/test.rs b/serde_derive/tests/test.rs
index ff8ac572c..80239edf9 100644
--- a/serde_derive/tests/test.rs
+++ b/serde_derive/tests/test.rs
@@ -6,3 +6,5 @@ extern crate serde_derive;
extern crate test;
include!("../../testing/tests/test.rs.in");
+
+mod compile_tests;
diff --git a/serde_macros/tests/compile-fail/duplicate_attributes.rs b/serde_macros/tests/compile-fail/duplicate_attributes.rs
deleted file mode 100644
index 61c986979..000000000
--- a/serde_macros/tests/compile-fail/duplicate_attributes.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-#![feature(custom_attribute, custom_derive, plugin)]
-#![plugin(serde_macros)]
-
-#[derive(Serialize)] //~ ERROR: 6 errors:
-struct S {
- #[serde(rename(serialize="x"))]
- #[serde(rename(serialize="y"))] // ERROR: duplicate serde attribute `rename`
- a: (),
-
- #[serde(rename(serialize="x"))]
- #[serde(rename="y")] // ERROR: duplicate serde attribute `rename`
- b: (),
-
- #[serde(rename(serialize="x"))]
- #[serde(rename(deserialize="y"))] // ok
- c: (),
-
- #[serde(rename="x")]
- #[serde(rename(deserialize="y"))] // ERROR: duplicate serde attribute `rename`
- d: (),
-
- #[serde(rename(serialize="x", serialize="y"))] // ERROR: duplicate serde attribute `rename`
- e: (),
-
- #[serde(rename="x", serialize="y")] // ERROR: unknown serde field attribute `serialize`
- f: (),
-
- #[serde(rename(serialize="x"), rename(serialize="y"))] // ERROR: duplicate serde attribute `rename`
- g: (),
-}
-
-fn main() {}
diff --git a/serde_macros/tests/compile-fail/reject-unknown-attributes.rs b/serde_macros/tests/compile-fail/reject-unknown-attributes.rs
deleted file mode 100644
index 3295b3ad0..000000000
--- a/serde_macros/tests/compile-fail/reject-unknown-attributes.rs
+++ /dev/null
@@ -1,30 +0,0 @@
-#![feature(custom_attribute, custom_derive, plugin)]
-#![plugin(serde_macros)]
-
-extern crate serde;
-
-#[derive(Serialize)] //~ unknown serde container attribute `abc`
-#[serde(abc="xyz")]
-struct A {
- x: u32,
-}
-
-#[derive(Deserialize)] //~ unknown serde container attribute `abc`
-#[serde(abc="xyz")]
-struct B {
- x: u32,
-}
-
-#[derive(Serialize)] //~ unknown serde field attribute `abc`
-struct C {
- #[serde(abc="xyz")]
- x: u32,
-}
-
-#[derive(Deserialize)] //~ unknown serde field attribute `abc`
-struct D {
- #[serde(abc="xyz")]
- x: u32,
-}
-
-fn main() { }
diff --git a/serde_macros/tests/compile-fail/str_ref_deser.rs b/serde_macros/tests/compile-fail/str_ref_deser.rs
deleted file mode 100644
index 610ed680e..000000000
--- a/serde_macros/tests/compile-fail/str_ref_deser.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-#![feature(custom_attribute, custom_derive, plugin)]
-#![plugin(serde_macros)]
-
-#[derive(Serialize, Deserialize)] //~ ERROR: Serde does not support deserializing fields of type &str
-struct Test<'a> {
- s: &'a str,
-}
-
-fn main() {}
diff --git a/serde_macros/tests/test.rs b/serde_macros/tests/test.rs
deleted file mode 100644
index e04627877..000000000
--- a/serde_macros/tests/test.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-#![feature(test, custom_attribute, custom_derive, plugin)]
-#![plugin(serde_macros)]
-
-extern crate test;
-
-include!("../../testing/tests/test.rs.in");
-
-mod compile_tests;
| [
"565"
] | serde-rs__serde-566 | Delete serde_macros
This requires moving the compile-tests over to the serde_derive crate.
| 0.8 | 8b7b886036c5a58aa9b30e777612ef0f1c4f6d7a | diff --git a/serde_derive/Cargo.toml b/serde_derive/Cargo.toml
index 51985b25b..329609646 100644
--- a/serde_derive/Cargo.toml
+++ b/serde_derive/Cargo.toml
@@ -21,6 +21,7 @@ default-features = false
features = ["with-syn"]
[dev-dependencies]
+compiletest_rs = "^0.2.0"
fnv = "1.0"
serde = { version = "0.8.10", path = "../serde" }
serde_test = { version = "0.8.10", path = "../serde_test" }
diff --git a/serde_macros/.cargo/config b/serde_macros/.cargo/config
deleted file mode 100644
index 7f1ab8d35..000000000
--- a/serde_macros/.cargo/config
+++ /dev/null
@@ -1,2 +0,0 @@
-# To prevent compiletest from seeing two versions of serde
-paths = ["../serde"]
diff --git a/serde_macros/.gitignore b/serde_macros/.gitignore
deleted file mode 100644
index 4fffb2f89..000000000
--- a/serde_macros/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-/target
-/Cargo.lock
diff --git a/serde_macros/Cargo.toml b/serde_macros/Cargo.toml
deleted file mode 100644
index 62b5e6823..000000000
--- a/serde_macros/Cargo.toml
+++ /dev/null
@@ -1,41 +0,0 @@
-[package]
-name = "serde_macros"
-version = "0.8.9"
-authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
-license = "MIT/Apache-2.0"
-description = "Macros to auto-generate implementations for the serde framework"
-homepage = "https://serde.rs"
-repository = "https://github.com/serde-rs/serde"
-documentation = "https://serde.rs/codegen.html"
-keywords = ["serde", "serialization"]
-include = ["Cargo.toml", "src/**/*.rs"]
-
-[lib]
-name = "serde_macros"
-plugin = true
-
-[features]
-unstable-testing = [
- "clippy",
- "serde/unstable-testing",
- "serde_codegen/unstable-testing"
-]
-
-[dependencies]
-clippy = { version = "^0.*", optional = true }
-serde_codegen = { version = "=0.8.9", default-features = false, features = ["unstable"], path = "../serde_codegen" }
-
-[dev-dependencies]
-compiletest_rs = "^0.2.0"
-fnv = "1.0"
-rustc-serialize = "^0.3.16"
-serde = { version = "0.8.9", path = "../serde" }
-serde_test = { version = "0.8.9", path = "../serde_test" }
-
-[[test]]
-name = "test"
-path = "tests/test.rs"
-
-[[bench]]
-name = "bench"
-path = "benches/bench.rs"
diff --git a/serde_macros/benches/bench.rs b/serde_macros/benches/bench.rs
deleted file mode 100644
index ec15c18c7..000000000
--- a/serde_macros/benches/bench.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-#![feature(custom_attribute, custom_derive, plugin, test)]
-#![cfg_attr(feature = "clippy", plugin(clippy))]
-#![plugin(serde_macros)]
-
-extern crate rustc_serialize;
-extern crate serde;
-extern crate test;
-
-include!("../../testing/benches/bench.rs.in");
diff --git a/serde_macros/src/lib.rs b/serde_macros/src/lib.rs
deleted file mode 100644
index 077fdccf1..000000000
--- a/serde_macros/src/lib.rs
+++ /dev/null
@@ -1,12 +0,0 @@
-#![feature(plugin_registrar, rustc_private)]
-#![cfg_attr(feature = "clippy", feature(plugin))]
-#![cfg_attr(feature = "clippy", plugin(clippy))]
-
-extern crate serde_codegen;
-extern crate rustc_plugin;
-
-#[plugin_registrar]
-#[doc(hidden)]
-pub fn plugin_registrar(reg: &mut rustc_plugin::Registry) {
- serde_codegen::register(reg);
-}
| serde-rs/serde | 2016-09-28T19:00:08Z | 88a4ed9cd72c7901b025dd8c8d86c69cfc6b157f | |
558 | diff --git a/testing/tests/test_macros.rs b/testing/tests/test_macros.rs
index a6b1d167c..6e5e1d823 100644
--- a/testing/tests/test_macros.rs
+++ b/testing/tests/test_macros.rs
@@ -600,3 +600,28 @@ fn test_default_ty_param() {
]
);
}
+
+#[test]
+fn test_enum_state_field() {
+ #[derive(Debug, PartialEq, Serialize, Deserialize)]
+ enum SomeEnum {
+ Key { key: char, state: bool },
+ }
+
+ assert_tokens(
+ &SomeEnum::Key { key: 'a', state: true },
+ &[
+ Token::EnumMapStart("SomeEnum", "Key", 2),
+
+ Token::EnumMapSep,
+ Token::Str("key"),
+ Token::Char('a'),
+
+ Token::EnumMapSep,
+ Token::Str("state"),
+ Token::Bool(true),
+
+ Token::EnumMapEnd,
+ ]
+ );
+}
| [
"557"
] | serde-rs__serde-558 | Using the word "state" breaks Serde.
This breaks serde:
```
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum SomeEnum {
Key { key: char, state: bool },
}
```
I get this error:
```
error[E0277]: the trait bound `<__S as message::_IMPL_SERIALIZE_FOR_SurfaceId::_serde::Serializer>::StructVariantState: message::_IMPL_SERIALIZE_FOR_SurfaceId::_serde::Serialize` is not satisfied
--> src/message.rs:36:19
|
36| #[derive(Serialize, Deserialize, Debug, Clone)]
| ^ trait `<__S as message::_IMPL_SERIALIZE_FOR_SurfaceId::_serde::Serializer>::StructVariantState: message::_IMPL_SERIALIZE_FOR_SurfaceId::_serde::Serialize` not satisfied
|
= help: consider adding a `where <__S as message::_IMPL_SERIALIZE_FOR_SurfaceId::_serde::Serializer>::StructVariantState: message::_IMPL_SERIALIZE_FOR_SurfaceId::_serde::Serialize` bound
```
It works fine without the Serialize derive (no errors or warnings):
```
#[derive(Deserialize, Debug, Clone)]
pub enum SomeEnum {
Key { key: char, state: bool },
}
```
Another way to fix it is by changing one letter to make `state` into `stata`:
```
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum SomeEnum {
Key { key: char, stata: bool },
}
```
The presence of the member `state` breaks #[derive(Serialize)].
According to aatch on the Rust IRC, it was likely due to [this](https://github.com/serde-rs/serde/blob/master/serde_codegen/src/ser.rs#L520).
I don't know how to fix this myself, but this should point somebody in the right direction.
| 0.8 | 429de89276f056b132cda2115e5f122c035e0a88 | diff --git a/serde_codegen/src/ser.rs b/serde_codegen/src/ser.rs
index d4883e8ec..7023c9b65 100644
--- a/serde_codegen/src/ser.rs
+++ b/serde_codegen/src/ser.rs
@@ -230,9 +230,9 @@ fn serialize_tuple_struct(
let let_mut = mut_if(cx, len > 0);
quote_block!(cx, {
- let $let_mut state = try!(_serializer.serialize_tuple_struct($type_name, $len));
+ let $let_mut __serde_state = try!(_serializer.serialize_tuple_struct($type_name, $len));
$serialize_stmts
- _serializer.serialize_tuple_struct_end(state)
+ _serializer.serialize_tuple_struct_end(__serde_state)
}).unwrap()
}
@@ -275,9 +275,9 @@ fn serialize_struct(
.fold(quote_expr!(cx, 0), |sum, expr| quote_expr!(cx, $sum + $expr));
quote_block!(cx, {
- let $let_mut state = try!(_serializer.serialize_struct($type_name, $len));
+ let $let_mut __serde_state = try!(_serializer.serialize_struct($type_name, $len));
$serialize_fields
- _serializer.serialize_struct_end(state)
+ _serializer.serialize_struct_end(__serde_state)
}).unwrap()
}
@@ -469,9 +469,13 @@ fn serialize_tuple_variant(
let let_mut = mut_if(cx, len > 0);
quote_block!(cx, {
- let $let_mut state = try!(_serializer.serialize_tuple_variant($type_name, $variant_index, $variant_name, $len));
+ let $let_mut __serde_state = try!(_serializer.serialize_tuple_variant(
+ $type_name,
+ $variant_index,
+ $variant_name,
+ $len));
$serialize_stmts
- _serializer.serialize_tuple_variant_end(state)
+ _serializer.serialize_tuple_variant_end(__serde_state)
}).unwrap()
}
@@ -517,14 +521,14 @@ fn serialize_struct_variant(
.fold(quote_expr!(cx, 0), |sum, expr| quote_expr!(cx, $sum + $expr));
quote_block!(cx, {
- let $let_mut state = try!(_serializer.serialize_struct_variant(
+ let $let_mut __serde_state = try!(_serializer.serialize_struct_variant(
$item_name,
$variant_index,
$variant_name,
$len,
));
$serialize_fields
- _serializer.serialize_struct_variant_end(state)
+ _serializer.serialize_struct_variant_end(__serde_state)
}).unwrap()
}
@@ -555,7 +559,7 @@ fn serialize_tuple_struct_visitor(
}
let ser = quote_expr!(cx,
- try!(_serializer.$func(&mut state, $field_expr));
+ try!(_serializer.$func(&mut __serde_state, $field_expr));
);
match skip {
@@ -596,7 +600,7 @@ fn serialize_struct_visitor(
}
let ser = quote_expr!(cx,
- try!(_serializer.$func(&mut state, $key_expr, $field_expr));
+ try!(_serializer.$func(&mut __serde_state, $key_expr, $field_expr));
);
match skip {
@@ -659,8 +663,8 @@ fn name_expr(
// Serialization of an empty struct results in code like:
//
-// let mut state = try!(serializer.serialize_struct("S", 0));
-// serializer.serialize_struct_end(state)
+// let mut __serde_state = try!(serializer.serialize_struct("S", 0));
+// serializer.serialize_struct_end(__serde_state)
//
// where we want to omit the `mut` to avoid a warning.
fn mut_if(cx: &ExtCtxt, is_mut: bool) -> Vec<TokenTree> {
| serde-rs/serde | 2016-09-27T04:12:00Z | Workin on it.
| 88a4ed9cd72c7901b025dd8c8d86c69cfc6b157f |
536 | diff --git a/testing/tests/test_gen.rs b/testing/tests/test_gen.rs
index 7d648f57d..3e2fe3823 100644
--- a/testing/tests/test_gen.rs
+++ b/testing/tests/test_gen.rs
@@ -187,6 +187,16 @@ fn test_gen() {
#[serde(bound(deserialize = "T::Owned: Deserialize"))]
struct CowT<'a, T: ?Sized + 'a + ToOwned>(Cow<'a, T>);
assert::<CowT<str>>();
+
+ #[derive(Serialize, Deserialize)]
+ struct EmptyStruct {}
+ assert::<EmptyStruct>();
+
+ #[derive(Serialize, Deserialize)]
+ enum EmptyEnumVariant {
+ EmptyStruct {},
+ }
+ assert::<EmptyEnumVariant>();
}
//////////////////////////////////////////////////////////////////////////
| [
"534"
] | serde-rs__serde-536 | `struct S {}`: variable does not need to be mutable
``` rust
#![feature(plugin, custom_derive)]
#![plugin(serde_macros)]
#[derive(Serialize)]
struct S {}
fn main() {
let _ = S {};
}
```
```
warning: variable does not need to be mutable, #[warn(unused_mut)] on by default
--> src/main.rs:4:10
|
4 | #[derive(Serialize)]
| ^^^^^^^^^^
```
| 0.8 | 248d937f9a969a5dec5ffef7ae0e100e3c3fec5f | diff --git a/serde_codegen/src/ser.rs b/serde_codegen/src/ser.rs
index 266dc4826..1639d067a 100644
--- a/serde_codegen/src/ser.rs
+++ b/serde_codegen/src/ser.rs
@@ -4,6 +4,7 @@ use syntax::ast::{self, Ident, MetaItem};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ptr::P;
+use syntax::tokenstream::TokenTree;
use bound;
use span;
@@ -226,9 +227,10 @@ fn serialize_tuple_struct(
let type_name = name_expr(builder, item_attrs.name());
let len = serialize_stmts.len();
+ let let_mut = mut_if(cx, len > 0);
quote_block!(cx, {
- let mut state = try!(_serializer.serialize_tuple_struct($type_name, $len));
+ let $let_mut state = try!(_serializer.serialize_tuple_struct($type_name, $len));
$serialize_stmts
_serializer.serialize_tuple_struct_end(state)
}).unwrap()
@@ -253,8 +255,14 @@ fn serialize_struct(
);
let type_name = name_expr(builder, item_attrs.name());
- let len = fields.iter()
+
+ let mut serialized_fields = fields.iter()
.filter(|&field| !field.attrs.skip_serializing())
+ .peekable();
+
+ let let_mut = mut_if(cx, serialized_fields.peek().is_some());
+
+ let len = serialized_fields
.map(|field| {
let ident = field.ident.expect("struct has unnamed fields");
let field_expr = quote_expr!(cx, &self.$ident);
@@ -267,7 +275,7 @@ fn serialize_struct(
.fold(quote_expr!(cx, 0), |sum, expr| quote_expr!(cx, $sum + $expr));
quote_block!(cx, {
- let mut state = try!(_serializer.serialize_struct($type_name, $len));
+ let $let_mut state = try!(_serializer.serialize_struct($type_name, $len));
$serialize_fields
_serializer.serialize_struct_end(state)
}).unwrap()
@@ -458,9 +466,10 @@ fn serialize_tuple_variant(
);
let len = serialize_stmts.len();
+ let let_mut = mut_if(cx, len > 0);
quote_block!(cx, {
- let mut state = try!(_serializer.serialize_tuple_variant($type_name, $variant_index, $variant_name, $len));
+ let $let_mut state = try!(_serializer.serialize_tuple_variant($type_name, $variant_index, $variant_name, $len));
$serialize_stmts
_serializer.serialize_tuple_variant_end(state)
}).unwrap()
@@ -488,8 +497,14 @@ fn serialize_struct_variant(
);
let item_name = name_expr(builder, item_attrs.name());
- let len = fields.iter()
+
+ let mut serialized_fields = fields.iter()
.filter(|&field| !field.attrs.skip_serializing())
+ .peekable();
+
+ let let_mut = mut_if(cx, serialized_fields.peek().is_some());
+
+ let len = serialized_fields
.map(|field| {
let ident = field.ident.expect("struct has unnamed fields");
let field_expr = quote_expr!(cx, $ident);
@@ -502,7 +517,7 @@ fn serialize_struct_variant(
.fold(quote_expr!(cx, 0), |sum, expr| quote_expr!(cx, $sum + $expr));
quote_block!(cx, {
- let mut state = try!(_serializer.serialize_struct_variant(
+ let $let_mut state = try!(_serializer.serialize_struct_variant(
$item_name,
$variant_index,
$variant_name,
@@ -637,3 +652,17 @@ fn name_expr(
) -> P<ast::Expr> {
builder.expr().str(name.serialize_name())
}
+
+// Serialization of an empty struct results in code like:
+//
+// let mut state = try!(serializer.serialize_struct("S", 0));
+// serializer.serialize_struct_end(state)
+//
+// where we want to omit the `mut` to avoid a warning.
+fn mut_if(cx: &ExtCtxt, is_mut: bool) -> Vec<TokenTree> {
+ if is_mut {
+ quote_tokens!(cx, mut)
+ } else {
+ Vec::new()
+ }
+}
| serde-rs/serde | 2016-09-02T18:43:30Z | The generated code looks like:
``` rust
impl Serialize for S {
fn serialize<__S>(&self, serializer: &mut __S) -> Result<(), __S::Error>
where __S: Serializer
{
let mut state = try!(serializer.serialize_struct("S", 0));
serializer.serialize_struct_end(state)
}
}
```
| 88a4ed9cd72c7901b025dd8c8d86c69cfc6b157f |
523 | diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index 121dcd3db..30180943e 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -3,7 +3,6 @@ use std::iter;
use serde::de::{
self,
Deserialize,
- EnumVisitor,
MapVisitor,
SeqVisitor,
VariantVisitor,
@@ -268,13 +267,13 @@ impl<I> de::Deserializer for Deserializer<I>
name: &str,
_variants: &'static [&'static str],
mut visitor: V) -> Result<V::Value, Error>
- where V: EnumVisitor,
+ where V: Visitor,
{
match self.tokens.peek() {
Some(&Token::EnumStart(n)) if name == n => {
self.tokens.next();
- visitor.visit(DeserializerVariantVisitor {
+ visitor.visit_enum(DeserializerVariantVisitor {
de: self,
})
}
@@ -282,7 +281,7 @@ impl<I> de::Deserializer for Deserializer<I>
| Some(&Token::EnumNewType(n, _))
| Some(&Token::EnumSeqStart(n, _, _))
| Some(&Token::EnumMapStart(n, _, _)) if name == n => {
- visitor.visit(DeserializerVariantVisitor {
+ visitor.visit_enum(DeserializerVariantVisitor {
de: self,
})
}
| [
"521"
] | serde-rs__serde-523 | Make deserialize_enum less of a special case
`deserialize_enum` is the only Deserializer method that does not take a Visitor argument. Can we find a way to make this API more consistent?
| 0.8 | ad34c14c8c62e0a0c1aa7ed94751934adeed229a | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 8cad930a3..b6c67451a 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -65,7 +65,6 @@ use core::num::Zero;
use de::{
Deserialize,
Deserializer,
- EnumVisitor,
Error,
MapVisitor,
SeqVisitor,
@@ -1122,7 +1121,7 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
{
struct FieldVisitor;
- impl ::de::Visitor for FieldVisitor {
+ impl Visitor for FieldVisitor {
type Value = Field;
#[cfg(any(feature = "std", feature = "collections"))]
@@ -1171,15 +1170,15 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
}
}
- struct Visitor<T, E>(PhantomData<Result<T, E>>);
+ struct ResultVisitor<T, E>(PhantomData<Result<T, E>>);
- impl<T, E> EnumVisitor for Visitor<T, E>
+ impl<T, E> Visitor for ResultVisitor<T, E>
where T: Deserialize,
E: Deserialize
{
type Value = Result<T, E>;
- fn visit<V>(&mut self, mut visitor: V) -> Result<Result<T, E>, V::Error>
+ fn visit_enum<V>(&mut self, mut visitor: V) -> Result<Result<T, E>, V::Error>
where V: VariantVisitor
{
match try!(visitor.visit_variant()) {
@@ -1197,7 +1196,7 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
const VARIANTS: &'static [&'static str] = &["Ok", "Err"];
- deserializer.deserialize_enum("Result", VARIANTS, Visitor(PhantomData))
+ deserializer.deserialize_enum("Result", VARIANTS, ResultVisitor(PhantomData))
}
}
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index 210b36b03..e356bc94d 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -169,6 +169,9 @@ pub enum Type {
/// Represents a unit variant.
UnitVariant,
+ /// Represents a newtype variant.
+ NewtypeVariant,
+
/// Represents a `&[u8]` type.
Bytes,
}
@@ -176,38 +179,39 @@ pub enum Type {
impl fmt::Display for Type {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let display = match *self {
- Type::Bool => "bool",
- Type::Usize => "usize",
- Type::U8 => "u8",
- Type::U16 => "u16",
- Type::U32 => "u32",
- Type::U64 => "u64",
- Type::Isize => "isize",
- Type::I8 => "i8",
- Type::I16 => "i16",
- Type::I32 => "i32",
- Type::I64 => "i64",
- Type::F32 => "f32",
- Type::F64 => "f64",
- Type::Char => "char",
- Type::Str => "str",
- Type::String => "string",
- Type::Unit => "unit",
- Type::Option => "option",
- Type::Seq => "seq",
- Type::Map => "map",
- Type::UnitStruct => "unit struct",
- Type::NewtypeStruct => "newtype struct",
- Type::TupleStruct => "tuple struct",
- Type::Struct => "struct",
- Type::FieldName => "field name",
- Type::Tuple => "tuple",
- Type::Enum => "enum",
- Type::VariantName => "variant name",
- Type::StructVariant => "struct variant",
- Type::TupleVariant => "tuple variant",
- Type::UnitVariant => "unit variant",
- Type::Bytes => "bytes",
+ Type::Bool => "bool",
+ Type::Usize => "usize",
+ Type::U8 => "u8",
+ Type::U16 => "u16",
+ Type::U32 => "u32",
+ Type::U64 => "u64",
+ Type::Isize => "isize",
+ Type::I8 => "i8",
+ Type::I16 => "i16",
+ Type::I32 => "i32",
+ Type::I64 => "i64",
+ Type::F32 => "f32",
+ Type::F64 => "f64",
+ Type::Char => "char",
+ Type::Str => "str",
+ Type::String => "string",
+ Type::Unit => "unit",
+ Type::Option => "option",
+ Type::Seq => "seq",
+ Type::Map => "map",
+ Type::UnitStruct => "unit struct",
+ Type::NewtypeStruct => "newtype struct",
+ Type::TupleStruct => "tuple struct",
+ Type::Struct => "struct",
+ Type::FieldName => "field name",
+ Type::Tuple => "tuple",
+ Type::Enum => "enum",
+ Type::VariantName => "variant name",
+ Type::StructVariant => "struct variant",
+ Type::TupleVariant => "tuple variant",
+ Type::UnitVariant => "unit variant",
+ Type::NewtypeVariant => "newtype variant",
+ Type::Bytes => "bytes",
};
display.fmt(formatter)
}
@@ -399,7 +403,7 @@ pub trait Deserializer {
name: &'static str,
variants: &'static [&'static str],
visitor: V) -> Result<V::Value, Self::Error>
- where V: EnumVisitor;
+ where V: Visitor;
/// This method hints that the `Deserialize` type needs to deserialize a value whose type
/// doesn't matter because it is ignored.
@@ -591,6 +595,14 @@ pub trait Visitor {
Err(Error::invalid_type(Type::Map))
}
+ /// `visit_enum` deserializes a `VariantVisitor` into a `Value`.
+ fn visit_enum<V>(&mut self, visitor: V) -> Result<Self::Value, V::Error>
+ where V: VariantVisitor,
+ {
+ let _ = visitor;
+ Err(Error::invalid_type(Type::Enum))
+ }
+
/// `visit_bytes` deserializes a `&[u8]` into a `Value`.
fn visit_bytes<E>(&mut self, v: &[u8]) -> Result<Self::Value, E>
where E: Error,
@@ -743,19 +755,6 @@ impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
///////////////////////////////////////////////////////////////////////////////
-/// `EnumVisitor` is a visitor that is created by the `Deserialize` and passed to the
-/// `Deserializer` in order to deserialize enums.
-pub trait EnumVisitor {
- /// The value produced by this visitor.
- type Value;
-
- /// Visit the specific variant with the `VariantVisitor`.
- fn visit<V>(&mut self, visitor: V) -> Result<Self::Value, V::Error>
- where V: VariantVisitor;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
/// `VariantVisitor` is a visitor that is created by the `Deserializer` and passed to the
/// `Deserialize` in order to deserialize a specific enum variant.
pub trait VariantVisitor {
@@ -767,9 +766,7 @@ pub trait VariantVisitor {
where V: Deserialize;
/// `visit_unit` is called when deserializing a variant with no values.
- fn visit_unit(&mut self) -> Result<(), Self::Error> {
- Err(Error::invalid_type(Type::UnitVariant))
- }
+ fn visit_unit(&mut self) -> Result<(), Self::Error>;
/// `visit_newtype` is called when deserializing a variant with a single value.
/// A good default is often to use the `visit_tuple` method to deserialize a `(value,)`.
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 00b07107e..def6814e5 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -286,9 +286,9 @@ impl<'a, E> de::Deserializer for StrDeserializer<'a, E>
_name: &str,
_variants: &'static [&'static str],
mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::EnumVisitor,
+ where V: de::Visitor,
{
- visitor.visit(self)
+ visitor.visit_enum(self)
}
forward_to_deserialize! {
@@ -316,8 +316,7 @@ impl<'a, E> de::VariantVisitor for StrDeserializer<'a, E>
fn visit_newtype<T>(&mut self) -> Result<T, Self::Error>
where T: super::Deserialize,
{
- let (value,) = try!(self.visit_tuple(1, super::impls::TupleVisitor1::new()));
- Ok(value)
+ Err(super::Error::invalid_type(super::Type::NewtypeVariant))
}
fn visit_tuple<V>(&mut self,
@@ -373,9 +372,9 @@ impl<E> de::Deserializer for StringDeserializer<E>
_name: &str,
_variants: &'static [&'static str],
mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::EnumVisitor,
+ where V: de::Visitor,
{
- visitor.visit(self)
+ visitor.visit_enum(self)
}
forward_to_deserialize! {
@@ -404,8 +403,7 @@ impl<'a, E> de::VariantVisitor for StringDeserializer<E>
fn visit_newtype<T>(&mut self) -> Result<T, Self::Error>
where T: super::Deserialize,
{
- let (value,) = try!(self.visit_tuple(1, super::impls::TupleVisitor1::new()));
- Ok(value)
+ Err(super::Error::invalid_type(super::Type::NewtypeVariant))
}
fn visit_tuple<V>(&mut self,
@@ -462,9 +460,9 @@ impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E>
_name: &str,
_variants: &'static [&'static str],
mut visitor: V) -> Result<V::Value, Self::Error>
- where V: de::EnumVisitor,
+ where V: de::Visitor,
{
- visitor.visit(self)
+ visitor.visit_enum(self)
}
forward_to_deserialize! {
@@ -493,8 +491,7 @@ impl<'a, E> de::VariantVisitor for CowStrDeserializer<'a, E>
fn visit_newtype<T>(&mut self) -> Result<T, Self::Error>
where T: super::Deserialize,
{
- let (value,) = try!(self.visit_tuple(1, super::impls::TupleVisitor1::new()));
- Ok(value)
+ Err(super::Error::invalid_type(super::Type::NewtypeVariant))
}
fn visit_tuple<V>(&mut self,
diff --git a/serde/src/macros.rs b/serde/src/macros.rs
index 6064c87ee..d8673ca4d 100644
--- a/serde/src/macros.rs
+++ b/serde/src/macros.rs
@@ -26,34 +26,6 @@ macro_rules! forward_to_deserialize_method {
};
}
-#[cfg(feature = "std")]
-#[doc(hidden)]
-#[macro_export]
-macro_rules! forward_to_deserialize_enum {
- () => {
- #[inline]
- fn deserialize_enum<__V>(&mut self, _: &str, _: &[&str], _: __V) -> ::std::result::Result<__V::Value, Self::Error>
- where __V: $crate::de::EnumVisitor
- {
- Err($crate::de::Error::invalid_type($crate::de::Type::Enum))
- }
- };
-}
-
-#[cfg(not(feature = "std"))]
-#[doc(hidden)]
-#[macro_export]
-macro_rules! forward_to_deserialize_enum {
- () => {
- #[inline]
- fn deserialize_enum<__V>(&mut self, _: &str, _: &[&str], _: __V) -> ::core::result::Result<__V::Value, Self::Error>
- where __V: $crate::de::EnumVisitor
- {
- Err($crate::de::Error::invalid_type($crate::de::Type::Enum))
- }
- };
-}
-
#[doc(hidden)]
#[macro_export]
macro_rules! forward_to_deserialize_helper {
@@ -141,12 +113,12 @@ macro_rules! forward_to_deserialize_helper {
(tuple) => {
forward_to_deserialize_method!{deserialize_tuple(usize)}
};
+ (enum) => {
+ forward_to_deserialize_method!{deserialize_enum(&'static str, &'static [&'static str])}
+ };
(ignored_any) => {
forward_to_deserialize_method!{deserialize_ignored_any()}
};
- (enum) => {
- forward_to_deserialize_enum!();
- };
}
/// Helper to forward `Deserializer` methods to `Deserializer::deserialize`.
diff --git a/serde_codegen/src/de.rs b/serde_codegen/src/de.rs
index 877b6a052..6088aa0d4 100644
--- a/serde_codegen/src/de.rs
+++ b/serde_codegen/src/de.rs
@@ -545,10 +545,10 @@ fn deserialize_item_enum(
#visitor_item
- impl #impl_generics _serde::de::EnumVisitor for #visitor_ty #where_clause {
+ impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
type Value = #ty;
- fn visit<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<#ty, __V::Error>
+ fn visit_enum<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<#ty, __V::Error>
where __V: _serde::de::VariantVisitor,
{
match try!(visitor.visit_variant()) {
| serde-rs/serde | 2016-08-24T01:34:12Z | 88a4ed9cd72c7901b025dd8c8d86c69cfc6b157f | |
510 | diff --git a/serde_macros/tests/run-pass/identity-op.rs b/serde_macros/tests/run-pass/identity-op.rs
index a82f100da..dcf8117a3 100644
--- a/serde_macros/tests/run-pass/identity-op.rs
+++ b/serde_macros/tests/run-pass/identity-op.rs
@@ -1,5 +1,5 @@
#![feature(custom_derive, plugin)]
-#![plugin(serde_macros)]
+#![plugin(serde_macros, clippy)]
#![deny(identity_op)]
diff --git a/testing/Cargo.toml b/testing/Cargo.toml
index 471ac26de..2604154cf 100644
--- a/testing/Cargo.toml
+++ b/testing/Cargo.toml
@@ -12,7 +12,7 @@ keywords = ["serialization"]
build = "build.rs"
[features]
-unstable-testing = ["serde/unstable-testing", "serde_codegen/unstable-testing"]
+unstable-testing = ["clippy", "serde/unstable-testing", "serde_codegen/unstable-testing"]
[build-dependencies]
serde_codegen = { path = "../serde_codegen", features = ["with-syntex"] }
| [
"500",
"505"
] | serde-rs__serde-510 | Useless attribute: #[allow(unused_imports)]
I see hundreds of these in the Travis output.
```
warning: useless lint attribute, #[warn(useless_attribute)] on by default
--> /home/travis/build/serde-rs/serde/testing/target/debug/build/serde_codegen-603f0181a943aed4/out/lib.rs:3456:159
|
3456 | #[allow(unused_imports)]
| ^^^^^^^^^^^^^^^^^^^^^^^^
/home/travis/build/serde-rs/serde/serde_codegen/src/lib.rs:33:1: 33:47 note: in this expansion of include!
|
help: if you just forgot a `!`, use
| #![allow(unused_imports)]
= help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#useless_attribute
```
Re-enable clippy
[This commit](https://github.com/serde-rs/serde/pull/498/commits/2bc1d62e50b799e06b51742a8490b546395e04ec) needs to be reverted after https://github.com/Manishearth/rust-clippy/pull/1174 is fixed and Clippy compiles on nightly.
| 0.8 | 7aba920decb5fae1cc30819f50793efd6b49a8a0 | diff --git a/serde/Cargo.toml b/serde/Cargo.toml
index 1e7419365..30b89fbc1 100644
--- a/serde/Cargo.toml
+++ b/serde/Cargo.toml
@@ -18,7 +18,7 @@ std = []
unstable = []
alloc = ["unstable"]
collections = ["alloc"]
-unstable-testing = ["unstable", "std"]
+unstable-testing = ["clippy", "unstable", "std"]
[dependencies]
clippy = { version = "^0.*", optional = true }
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index f8e98bf8f..9a74f9e0c 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -128,7 +128,7 @@ impl fmt::Display for Error {
write!(formatter, "Unknown variant: {}", variant)
}
Error::UnknownField(ref field) => write!(formatter, "Unknown field: {}", field),
- Error::MissingField(ref field) => write!(formatter, "Missing field: {}", field),
+ Error::MissingField(field) => write!(formatter, "Missing field: {}", field),
}
}
}
diff --git a/serde_codegen/Cargo.toml b/serde_codegen/Cargo.toml
index f5b20603b..1395ca4f9 100644
--- a/serde_codegen/Cargo.toml
+++ b/serde_codegen/Cargo.toml
@@ -14,7 +14,7 @@ include = ["Cargo.toml", "build.rs", "src/**/*.rs", "src/lib.rs.in"]
[features]
default = ["with-syntex"]
unstable = ["quasi_macros"]
-unstable-testing = []
+unstable-testing = ["clippy"]
with-syntex = [
"quasi/with-syntex",
"quasi_codegen",
diff --git a/serde_codegen_internals/Cargo.toml b/serde_codegen_internals/Cargo.toml
index 3181eb195..62b24f2e4 100644
--- a/serde_codegen_internals/Cargo.toml
+++ b/serde_codegen_internals/Cargo.toml
@@ -12,7 +12,7 @@ include = ["Cargo.toml", "src/**/*.rs"]
[features]
default = ["with-syntex"]
-unstable-testing = []
+unstable-testing = ["clippy"]
with-syntex = ["syntex_syntax", "syntex_errors"]
[dependencies]
diff --git a/serde_codegen_internals/src/attr.rs b/serde_codegen_internals/src/attr.rs
index 0b2ebf727..8d8d595ba 100644
--- a/serde_codegen_internals/src/attr.rs
+++ b/serde_codegen_internals/src/attr.rs
@@ -449,12 +449,14 @@ impl Field {
}
}
+type SerAndDe<T> = (Option<Spanned<T>>, Option<Spanned<T>>);
+
fn get_ser_and_de<T, F>(
cx: &ExtCtxt,
attribute: &'static str,
items: &[P<ast::MetaItem>],
f: F
-) -> Result<(Option<Spanned<T>>, Option<Spanned<T>>), ()>
+) -> Result<SerAndDe<T>, ()>
where F: Fn(&ExtCtxt, &str, &ast::Lit) -> Result<T, ()>,
{
let mut ser_item = Attr::none(cx, attribute);
@@ -492,21 +494,21 @@ fn get_ser_and_de<T, F>(
fn get_renames(
cx: &ExtCtxt,
items: &[P<ast::MetaItem>],
-) -> Result<(Option<Spanned<InternedString>>, Option<Spanned<InternedString>>), ()> {
+) -> Result<SerAndDe<InternedString>, ()> {
get_ser_and_de(cx, "rename", items, get_str_from_lit)
}
fn get_where_predicates(
cx: &ExtCtxt,
items: &[P<ast::MetaItem>],
-) -> Result<(Option<Spanned<Vec<ast::WherePredicate>>>, Option<Spanned<Vec<ast::WherePredicate>>>), ()> {
+) -> Result<SerAndDe<Vec<ast::WherePredicate>>, ()> {
get_ser_and_de(cx, "bound", items, parse_lit_into_where)
}
pub fn get_serde_meta_items(attr: &ast::Attribute) -> Option<&[P<ast::MetaItem>]> {
match attr.node.value.node {
ast::MetaItemKind::List(ref name, ref items) if name == &"serde" => {
- attr::mark_used(&attr);
+ attr::mark_used(attr);
Some(items)
}
_ => None
@@ -570,7 +572,7 @@ fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<Interned
name,
lit_to_string(lit)));
- return Err(());
+ Err(())
}
}
}
diff --git a/serde_macros/Cargo.toml b/serde_macros/Cargo.toml
index 4f41e676f..07e851104 100644
--- a/serde_macros/Cargo.toml
+++ b/serde_macros/Cargo.toml
@@ -17,6 +17,7 @@ plugin = true
[features]
unstable-testing = [
+ "clippy",
"skeptic",
"serde_json",
"serde/unstable-testing",
| serde-rs/serde | 2016-08-19T16:49:23Z | why do we have that attribute anyway?
something with old rust version support?
so our codebase has the `unused_imports` character sequence exactly once, and that one is not linting. It's all in the generated code. Is aster/syntex generating those?
quasi generates those `unused_imports`: https://github.com/serde-rs/quasi/blob/d554e9eee0f0ef48a07a3825414f28806a77bbb9/quasi_codegen/src/lib.rs#L747
since that is the only useful lint attribute on a `use` that I can think of, I'll just whitelist it.
| 88a4ed9cd72c7901b025dd8c8d86c69cfc6b157f |
509 | diff --git a/testing/tests/test_gen.rs b/testing/tests/test_gen.rs
index 0acfdb36c..7d648f57d 100644
--- a/testing/tests/test_gen.rs
+++ b/testing/tests/test_gen.rs
@@ -6,6 +6,7 @@ extern crate serde;
use self::serde::ser::{Serialize, Serializer};
use self::serde::de::{Deserialize, Deserializer};
+use std::borrow::Cow;
use std::marker::PhantomData;
//////////////////////////////////////////////////////////////////////////
@@ -177,6 +178,15 @@ fn test_gen() {
e: E,
}
assert::<WithTraits2<X, X>>();
+
+ #[derive(Serialize, Deserialize)]
+ struct CowStr<'a>(Cow<'a, str>);
+ assert::<CowStr>();
+
+ #[derive(Serialize, Deserialize)]
+ #[serde(bound(deserialize = "T::Owned: Deserialize"))]
+ struct CowT<'a, T: ?Sized + 'a + ToOwned>(Cow<'a, T>);
+ assert::<CowT<str>>();
}
//////////////////////////////////////////////////////////////////////////
| [
"507"
] | serde-rs__serde-509 | Deriving Deserialize for structs with Cow<'a, str> fails
Consider the following code:
``` rust
#[derive(Deserialize)]
struct S<'a>(Cow<'a, str>);
```
This fails with a cryptic error message:
```
error[E0207]: the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates
--> <quote expansion>:1:2
|
1 | <'a>
| ^^ unconstrained lifetime parameter
```
I believe `Deserialize` is implemented for `Cow<'a, str>`, so I think this should work.
| 0.8 | 6723da67b33a6e01bafbf98785e631ee1991b40b | diff --git a/serde_codegen/src/de.rs b/serde_codegen/src/de.rs
index bbcb30e9e..b630ede0c 100644
--- a/serde_codegen/src/de.rs
+++ b/serde_codegen/src/de.rs
@@ -192,7 +192,7 @@ fn deserialize_visitor(
builder: &aster::AstBuilder,
generics: &ast::Generics,
) -> (P<ast::Item>, P<ast::Ty>, P<ast::Expr>) {
- if generics.ty_params.is_empty() {
+ if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
(
builder.item().unit_struct("__Visitor"),
builder.ty().id("__Visitor"),
| serde-rs/serde | 2016-08-19T15:13:12Z | The buggy generated code looks like this:
``` rust
struct __Visitor;
impl<'a> _serde::de::Visitor for __Visitor {
// ^^ unconstrained lifetime parameter
type Value = S<'a>;
```
we can assume that any lifetimes during deserialization are `'static` and thus simply replace them. They should be coercible to the target lifetime. If/When we get a deserialization strategy that borrows the object that it deserializes from, we can revise this.
Interestingly this works and I can deserialize `S<str>`:
``` rust
#[derive(Deserialize)]
#[serde(bound = "T::Owned: Deserialize")]
struct S<'a, T: ?Sized + 'a + ToOwned>(Cow<'a, T>);
```
because it generates this code:
``` rust
struct __Visitor<'a, T: ?Sized + 'a + ToOwned>(::std::marker::PhantomData<&'a ()>,
::std::marker::PhantomData<T>)
where T::Owned: Deserialize;
impl<'a, T: ?Sized + 'a + ToOwned> _serde::de::Visitor for __Visitor<'a, T>
where T::Owned: Deserialize
{
type Value = S<'a, T>;
```
@oli-obk maybe we should stick with this `PhantomData<&'a ()>` approach and just make it work when there are no type parameters.
> Interestingly this works
amusing.
> maybe we should stick with this PhantomData<&'a ()> approach and just make it work when there are no type parameters.
Yea, we probably just need to take out a few things from the bound-attribute code path
| 88a4ed9cd72c7901b025dd8c8d86c69cfc6b157f |
476 | diff --git a/testing/tests/test_de.rs b/testing/tests/test_de.rs
index 63b6b6f7d..162bf0166 100644
--- a/testing/tests/test_de.rs
+++ b/testing/tests/test_de.rs
@@ -1,6 +1,7 @@
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::net;
use std::path::PathBuf;
+use std::time::Duration;
use serde::Deserialize;
@@ -745,6 +746,28 @@ declare_tests! {
Token::SeqEnd,
],
}
+ test_duration {
+ Duration::new(1, 2) => &[
+ Token::StructStart("Duration", 2),
+ Token::StructSep,
+ Token::Str("secs"),
+ Token::U64(1),
+
+ Token::StructSep,
+ Token::Str("nanos"),
+ Token::U32(2),
+ Token::StructEnd,
+ ],
+ Duration::new(1, 2) => &[
+ Token::SeqStart(Some(2)),
+ Token::SeqSep,
+ Token::I64(1),
+
+ Token::SeqSep,
+ Token::I64(2),
+ Token::SeqEnd,
+ ],
+ }
test_net_ipv4addr {
"1.2.3.4".parse::<net::Ipv4Addr>().unwrap() => &[Token::Str("1.2.3.4")],
}
diff --git a/testing/tests/test_ser.rs b/testing/tests/test_ser.rs
index 5fc7bf127..525735339 100644
--- a/testing/tests/test_ser.rs
+++ b/testing/tests/test_ser.rs
@@ -2,6 +2,7 @@ use std::collections::{BTreeMap, HashMap, HashSet};
use std::net;
use std::path::{Path, PathBuf};
use std::str;
+use std::time::Duration;
extern crate serde_test;
use self::serde_test::{
@@ -324,6 +325,19 @@ declare_ser_tests! {
Token::SeqEnd,
],
}
+ test_duration {
+ Duration::new(1, 2) => &[
+ Token::StructStart("Duration", 2),
+ Token::StructSep,
+ Token::Str("secs"),
+ Token::U64(1),
+
+ Token::StructSep,
+ Token::Str("nanos"),
+ Token::U32(2),
+ Token::StructEnd,
+ ],
+ }
test_net_ipv4addr {
"1.2.3.4".parse::<net::Ipv4Addr>().unwrap() => &[Token::Str("1.2.3.4")],
}
| [
"339"
] | serde-rs__serde-476 | impl Serialize and Deserialize for std::time::Duration
| 0.8 | b289edd4a436e1a1a0edb5428929760e2138c865 | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index e2319d17d..0c33ec5f1 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -53,6 +53,9 @@ use alloc::arc::Arc;
#[cfg(all(feature = "unstable", feature = "alloc", not(feature = "std")))]
use alloc::boxed::Box;
+#[cfg(feature = "std")]
+use std::time::Duration;
+
#[cfg(feature = "unstable")]
use core::nonzero::{NonZero, Zeroable};
@@ -982,6 +985,135 @@ impl<'a, T: ?Sized> Deserialize for Cow<'a, T> where T: ToOwned, T::Owned: Deser
///////////////////////////////////////////////////////////////////////////////
+// This is a cleaned-up version of the impl generated by:
+//
+// #[derive(Deserialize)]
+// #[serde(deny_unknown_fields)]
+// struct Duration {
+// secs: u64,
+// nanos: u32,
+// }
+#[cfg(feature = "std")]
+impl Deserialize for Duration {
+ fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+ where D: Deserializer,
+ {
+ enum Field { Secs, Nanos };
+
+ impl Deserialize for Field {
+ fn deserialize<D>(deserializer: &mut D) -> Result<Field, D::Error>
+ where D: Deserializer,
+ {
+ struct FieldVisitor;
+
+ impl Visitor for FieldVisitor {
+ type Value = Field;
+
+ fn visit_usize<E>(&mut self, value: usize) -> Result<Field, E>
+ where E: Error,
+ {
+ match value {
+ 0usize => Ok(Field::Secs),
+ 1usize => Ok(Field::Nanos),
+ _ => Err(Error::invalid_value("expected a field")),
+ }
+ }
+
+ fn visit_str<E>(&mut self, value: &str) -> Result<Field, E>
+ where E: Error,
+ {
+ match value {
+ "secs" => Ok(Field::Secs),
+ "nanos" => Ok(Field::Nanos),
+ _ => Err(Error::unknown_field(value)),
+ }
+ }
+
+ fn visit_bytes<E>(&mut self, value: &[u8]) -> Result<Field, E>
+ where E: Error,
+ {
+ match value {
+ b"secs" => Ok(Field::Secs),
+ b"nanos" => Ok(Field::Nanos),
+ _ => {
+ let value = String::from_utf8_lossy(value);
+ Err(Error::unknown_field(&value))
+ }
+ }
+ }
+ }
+
+ deserializer.deserialize_struct_field(FieldVisitor)
+ }
+ }
+
+ struct DurationVisitor;
+
+ impl Visitor for DurationVisitor {
+ type Value = Duration;
+
+ fn visit_seq<V>(&mut self, mut visitor: V) -> Result<Duration, V::Error>
+ where V: SeqVisitor,
+ {
+ let secs: u64 = match try!(visitor.visit()) {
+ Some(value) => value,
+ None => {
+ try!(visitor.end());
+ return Err(Error::invalid_length(0));
+ }
+ };
+ let nanos: u32 = match try!(visitor.visit()) {
+ Some(value) => value,
+ None => {
+ try!(visitor.end());
+ return Err(Error::invalid_length(1));
+ }
+ };
+ try!(visitor.end());
+ Ok(Duration::new(secs, nanos))
+ }
+
+ fn visit_map<V>(&mut self, mut visitor: V) -> Result<Duration, V::Error>
+ where V: MapVisitor,
+ {
+ let mut secs: Option<u64> = None;
+ let mut nanos: Option<u32> = None;
+ while let Some(key) = try!(visitor.visit_key::<Field>()) {
+ match key {
+ Field::Secs => {
+ if secs.is_some() {
+ return Err(<V::Error as Error>::duplicate_field("secs"));
+ }
+ secs = Some(try!(visitor.visit_value()));
+ }
+ Field::Nanos => {
+ if nanos.is_some() {
+ return Err(<V::Error as Error>::duplicate_field("nanos"));
+ }
+ nanos = Some(try!(visitor.visit_value()));
+ }
+ }
+ }
+ try!(visitor.end());
+ let secs = match secs {
+ Some(secs) => secs,
+ None => try!(visitor.missing_field("secs")),
+ };
+ let nanos = match nanos {
+ Some(nanos) => nanos,
+ None => try!(visitor.missing_field("nanos")),
+ };
+ Ok(Duration::new(secs, nanos))
+ }
+ }
+
+ const FIELDS: &'static [&'static str] = &["secs", "nanos"];
+ deserializer.deserialize_struct("Duration", FIELDS, DurationVisitor)
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
#[cfg(feature = "unstable")]
impl<T> Deserialize for NonZero<T> where T: Deserialize + PartialEq + Zeroable + Zero {
fn deserialize<D>(deserializer: &mut D) -> Result<NonZero<T>, D::Error> where D: Deserializer {
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index 374ea6276..6679d2f34 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -50,6 +50,8 @@ use std::path;
use std::rc::Rc;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::rc::Rc;
+#[cfg(feature = "std")]
+use std::time::Duration;
#[cfg(feature = "std")]
use std::sync::Arc;
@@ -624,6 +626,20 @@ impl<T, E> Serialize for Result<T, E> where T: Serialize, E: Serialize {
///////////////////////////////////////////////////////////////////////////////
+#[cfg(feature = "std")]
+impl Serialize for Duration {
+ fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ where S: Serializer,
+ {
+ let mut state = try!(serializer.serialize_struct("Duration", 2));
+ try!(serializer.serialize_struct_elt(&mut state, "secs", self.as_secs()));
+ try!(serializer.serialize_struct_elt(&mut state, "nanos", self.subsec_nanos()));
+ serializer.serialize_struct_end(state)
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
#[cfg(all(feature = "std", feature = "unstable"))]
impl Serialize for net::IpAddr {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
| serde-rs/serde | 2016-08-04T00:24:00Z | Do you have a particular format in mind for this?
I don't, but visiting the fields -- seconds and nanos -- seems like a reasonable option.
| 88a4ed9cd72c7901b025dd8c8d86c69cfc6b157f |
475 | diff --git a/serde_macros/tests/skeptic.rs b/serde_macros/tests/skeptic.rs
new file mode 100644
index 000000000..47e632d0f
--- /dev/null
+++ b/serde_macros/tests/skeptic.rs
@@ -0,0 +1,3 @@
+#![cfg(feature = "unstable-testing")]
+
+include!(concat!(env!("OUT_DIR"), "/skeptic-tests.rs"));
diff --git a/serde_macros/tests/test.rs b/serde_macros/tests/test.rs
index e04627877..94d8338ba 100644
--- a/serde_macros/tests/test.rs
+++ b/serde_macros/tests/test.rs
@@ -6,3 +6,4 @@ extern crate test;
include!("../../testing/tests/test.rs.in");
mod compile_tests;
+mod skeptic;
| [
"474"
] | serde-rs__serde-475 | Update examples without macros in README for 0.8
It seems that the example for https://github.com/serde-rs/serde#serialization-without-macros and possibly deserialization do not work in 0.8.
There is no `serde::ser::MapVisitor` for example
| 0.8 | 84fa3fba58a8f55d15eae7bfbf4ba70d29a6391d | diff --git a/README.md b/README.md
index 31b97bc11..3c136b84f 100644
--- a/README.md
+++ b/README.md
@@ -356,11 +356,8 @@ impl serde::Serialize for i32 {
```
As you can see it's pretty simple. More complex types like `BTreeMap` need to
-pass a
-[MapVisitor](http://serde-rs.github.io/serde/serde/serde/ser/trait.MapVisitor.html)
-to the
-[Serializer](http://serde-rs.github.io/serde/serde/serde/ser/trait.Serializer.html)
-in order to walk through the type:
+use a multi-step process (init, elements, end) in order to walk through the
+type:
```rust,ignore
impl<K, V> Serialize for BTreeMap<K, V>
@@ -371,55 +368,17 @@ impl<K, V> Serialize for BTreeMap<K, V>
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: Serializer,
{
- serializer.serialize_map(MapIteratorVisitor::new(self.iter(), Some(self.len())))
- }
-}
-
-pub struct MapIteratorVisitor<Iter> {
- iter: Iter,
- len: Option<usize>,
-}
-
-impl<K, V, Iter> MapIteratorVisitor<Iter>
- where Iter: Iterator<Item=(K, V)>
-{
- #[inline]
- pub fn new(iter: Iter, len: Option<usize>) -> MapIteratorVisitor<Iter> {
- MapIteratorVisitor {
- iter: iter,
- len: len,
- }
- }
-}
-
-impl<K, V, I> MapVisitor for MapIteratorVisitor<I>
- where K: Serialize,
- V: Serialize,
- I: Iterator<Item=(K, V)>,
-{
- #[inline]
- fn visit<S>(&mut self, serializer: &mut S) -> Result<Option<()>, S::Error>
- where S: Serializer,
- {
- match self.iter.next() {
- Some((key, value)) => {
- let value = try!(serializer.serialize_map_elt(key, value));
- Ok(Some(value))
- }
- None => Ok(None)
+ let mut state = try!(serializer.serialize_map(Some(self.len())));
+ for (k, v) in self {
+ try!(serializer.serialize_map_elt(&mut state, k, v));
}
- }
-
- #[inline]
- fn len(&self) -> Option<usize> {
- self.len
+ serializer.serialize_map_end(state)
}
}
```
Serializing structs follow this same pattern. In fact, structs are represented
-as a named map. Its visitor uses a simple state machine to iterate through all
-the fields:
+as a named map, with a known length.
```rust
extern crate serde;
@@ -434,35 +393,10 @@ impl serde::Serialize for Point {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
- serializer.serialize_struct("Point", PointMapVisitor {
- value: self,
- state: 0,
- })
- }
-}
-
-struct PointMapVisitor<'a> {
- value: &'a Point,
- state: u8,
-}
-
-impl<'a> serde::ser::MapVisitor for PointMapVisitor<'a> {
- fn visit<S>(&mut self, serializer: &mut S) -> Result<Option<()>, S::Error>
- where S: serde::Serializer
- {
- match self.state {
- 0 => {
- self.state += 1;
- Ok(Some(try!(serializer.serialize_struct_elt("x", &self.value.x))))
- }
- 1 => {
- self.state += 1;
- Ok(Some(try!(serializer.serialize_struct_elt("y", &self.value.y))))
- }
- _ => {
- Ok(None)
- }
- }
+ let mut state = try!(serializer.serialize_struct("Point", 2));
+ try!(serializer.serialize_struct_elt(&mut state, "x", &self.x));
+ try!(serializer.serialize_struct_elt(&mut state, "y", &self.y));
+ serializer.serialize_struct_end(state)
}
}
diff --git a/serde_macros/Cargo.toml b/serde_macros/Cargo.toml
index aafbfe055..4791f416d 100644
--- a/serde_macros/Cargo.toml
+++ b/serde_macros/Cargo.toml
@@ -8,17 +8,29 @@ repository = "https://github.com/serde-rs/serde"
documentation = "https://github.com/serde-rs/serde"
keywords = ["serde", "serialization"]
include = ["Cargo.toml", "src/**/*.rs"]
+build = "build.rs"
[lib]
name = "serde_macros"
plugin = true
[features]
-unstable-testing = ["clippy", "serde/unstable-testing", "serde_codegen/unstable-testing"]
+unstable-testing = [
+ "clippy",
+ "skeptic",
+ "serde_json",
+ "serde/unstable-testing",
+ "serde_codegen/unstable-testing"
+]
+
+[build-dependencies]
+skeptic = { version = "^0.6.0", optional = true }
[dependencies]
clippy = { version = "^0.*", optional = true }
serde_codegen = { version = "=0.8.0", default-features = false, features = ["unstable"] }
+skeptic = { version = "^0.6.0", optional = true }
+serde_json = { version = "0.8.0", optional = true }
[dev-dependencies]
clippy = "^0.*"
@@ -32,6 +44,10 @@ serde_test = "0.8.0"
name = "test"
path = "tests/test.rs"
+[[test]]
+name = "skeptic"
+path = "tests/skeptic.rs"
+
[[bench]]
name = "bench"
path = "benches/bench.rs"
diff --git a/serde_macros/build.rs b/serde_macros/build.rs
new file mode 100644
index 000000000..0f5455004
--- /dev/null
+++ b/serde_macros/build.rs
@@ -0,0 +1,18 @@
+#[cfg(feature = "unstable-testing")]
+mod inner {
+ extern crate skeptic;
+
+ pub fn main() {
+ println!("cargo:rerun-if-changed=../README.md");
+ skeptic::generate_doc_tests(&["../README.md"]);
+ }
+}
+
+#[cfg(not(feature = "unstable-testing"))]
+mod inner {
+ pub fn main() {}
+}
+
+fn main() {
+ inner::main()
+}
| serde-rs/serde | 2016-08-03T14:07:11Z | 88a4ed9cd72c7901b025dd8c8d86c69cfc6b157f | |
456 | diff --git a/testing/tests/test_gen.rs b/testing/tests/test_gen.rs
index fcc4b7e42..cff40bf8b 100644
--- a/testing/tests/test_gen.rs
+++ b/testing/tests/test_gen.rs
@@ -92,6 +92,35 @@ struct ListNode<D> {
next: Box<ListNode<D>>,
}
+#[derive(Serialize, Deserialize)]
+struct RecursiveA {
+ b: Box<RecursiveB>,
+}
+
+#[derive(Serialize, Deserialize)]
+enum RecursiveB {
+ A(RecursiveA),
+}
+
+#[derive(Serialize, Deserialize)]
+struct RecursiveGenericA<T> {
+ t: T,
+ b: Box<RecursiveGenericB<T>>,
+}
+
+#[derive(Serialize, Deserialize)]
+enum RecursiveGenericB<T> {
+ T(T),
+ A(RecursiveGenericA<T>),
+}
+
+#[derive(Serialize)]
+#[allow(dead_code)]
+struct OptionStatic<'a> {
+ a: Option<&'a str>,
+ b: Option<&'static str>,
+}
+
#[derive(Serialize, Deserialize)]
#[serde(bound="D: SerializeWith + DeserializeWith")]
struct WithTraits1<D, E> {
@@ -132,4 +161,3 @@ trait DeserializeWith: Sized {
struct X;
fn ser_x<S: Serializer>(_: &X, _: &mut S) -> Result<(), S::Error> { panic!() }
fn de_x<D: Deserializer>(_: &mut D) -> Result<X, D::Error> { panic!() }
-
| [
"435",
"443"
] | serde-rs__serde-456 | Generated code triggers private_in_public future compatibility warnings.
If a private field of a public type contains a private type, the generated bounds result in warnings such as (example from Servo):
``` rust
<quote expansion>:1:12: 1:22 warning: private type in public interface, #[warn(private_in_public)] on by default
<quote expansion>:1 where Vec<GlyphEntry>: _serde::ser::Serialize,
^~~~~~~~~~
<quote expansion>:1:12: 1:22 warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
<quote expansion>:1:12: 1:22 note: for more information, see the explanation for E0446 (`--explain E0446`)
```
See https://github.com/rust-lang/rfcs/pull/1671#issuecomment-231555393 for more on the possible future of private types in bounds (i.e. no action may be necessary in the future if that RFC gets through).
derive(Serialize) regression with lifetimes
This used to work around version `0.7.10` of serde_codegen...
``` rust
#[derive(Serialize)]
struct S<'a> {
a: Option<&'static str>,
b: Option<&'a str>,
}
```
```
error: mismatched types [E0308]
#[derive(Serialize)]
help: run `rustc --explain E0308` to see a detailed explanation
note: expected type `serde::Serialize`
note: found type `serde::Serialize`
note: the lifetime 'a as defined on the impl at 31:9...
#[derive(Serialize)]
note: ...does not necessarily outlive the static lifetime
```
| null | 49ff56aa15f14c9aa26d5f3b24c917ba4d604241 | diff --git a/serde_codegen/src/bound.rs b/serde_codegen/src/bound.rs
index ea7da8e9b..0f4219592 100644
--- a/serde_codegen/src/bound.rs
+++ b/serde_codegen/src/bound.rs
@@ -1,7 +1,8 @@
+use std::collections::HashSet;
+
use aster::AstBuilder;
use syntax::ast;
-use syntax::ptr::P;
use syntax::visit;
use internals::ast::Item;
@@ -47,6 +48,17 @@ pub fn with_where_predicates_from_fields<F>(
.build()
}
+// Puts the given bound on any generic type parameters that are used in fields
+// for which filter returns true.
+//
+// For example, the following struct needs the bound `A: Serialize, B: Serialize`.
+//
+// struct S<'b, A, B: 'b, C> {
+// a: A,
+// b: Option<&'b B>
+// #[serde(skip_serializing)]
+// c: C,
+// }
pub fn with_bound<F>(
builder: &AstBuilder,
item: &Item,
@@ -56,95 +68,53 @@ pub fn with_bound<F>(
) -> ast::Generics
where F: Fn(&attr::Field) -> bool,
{
- builder.from_generics(generics.clone())
- .with_predicates(
- item.body.all_fields()
- .filter(|&field| filter(&field.attrs))
- .map(|field| &field.ty)
- .filter(|ty| !contains_recursion(ty, item.ident))
- .map(|ty| strip_reference(ty))
- .map(|ty| builder.where_predicate()
- // the type that is being bounded e.g. T
- .bound().build(ty.clone())
- // the bound e.g. Serialize
- .bound().trait_(bound.clone()).build()
- .build()))
- .build()
-}
-
-// We do not attempt to generate any bounds based on field types that are
-// directly recursive, as in:
-//
-// struct Test<D> {
-// next: Box<Test<D>>,
-// }
-//
-// This does not catch field types that are mutually recursive with some other
-// type. For those, we require bounds to be specified by a `bound` attribute if
-// the inferred ones are not correct.
-//
-// struct Test<D> {
-// #[serde(bound="D: Serialize + Deserialize")]
-// next: Box<Other<D>>,
-// }
-// struct Other<D> {
-// #[serde(bound="D: Serialize + Deserialize")]
-// next: Box<Test<D>>,
-// }
-fn contains_recursion(ty: &ast::Ty, ident: ast::Ident) -> bool {
- struct FindRecursion {
- ident: ast::Ident,
- found_recursion: bool,
+ struct FindTyParams {
+ // Set of all generic type parameters on the current struct (A, B, C in
+ // the example). Initialized up front.
+ all_ty_params: HashSet<ast::Name>,
+ // Set of generic type parameters used in fields for which filter
+ // returns true (A and B in the example). Filled in as the visitor sees
+ // them.
+ relevant_ty_params: HashSet<ast::Name>,
}
- impl visit::Visitor for FindRecursion {
+ impl visit::Visitor for FindTyParams {
fn visit_path(&mut self, path: &ast::Path, _id: ast::NodeId) {
- if !path.global
- && path.segments.len() == 1
- && path.segments[0].identifier == self.ident {
- self.found_recursion = true;
- } else {
- visit::walk_path(self, path);
+ if !path.global && path.segments.len() == 1 {
+ let id = path.segments[0].identifier.name;
+ if self.all_ty_params.contains(&id) {
+ self.relevant_ty_params.insert(id);
+ }
}
+ visit::walk_path(self, path);
}
}
- let mut visitor = FindRecursion {
- ident: ident,
- found_recursion: false,
- };
- visit::walk_ty(&mut visitor, ty);
- visitor.found_recursion
-}
+ let all_ty_params: HashSet<_> = generics.ty_params.iter()
+ .map(|ty_param| ty_param.ident.name)
+ .collect();
-// This is required to handle types that use both a reference and a value of
-// the same type, as in:
-//
-// enum Test<'a, T> where T: 'a {
-// Lifetime(&'a T),
-// NoLifetime(T),
-// }
-//
-// Preserving references, we would generate an impl like:
-//
-// impl<'a, T> Serialize for Test<'a, T>
-// where &'a T: Serialize,
-// T: Serialize { ... }
-//
-// And taking a reference to one of the elements would fail with:
-//
-// error: cannot infer an appropriate lifetime for pattern due
-// to conflicting requirements [E0495]
-// Test::NoLifetime(ref v) => { ... }
-// ^~~~~
-//
-// Instead, we strip references before adding `T: Serialize` bounds in order to
-// generate:
-//
-// impl<'a, T> Serialize for Test<'a, T>
-// where T: Serialize { ... }
-fn strip_reference(mut ty: &P<ast::Ty>) -> &P<ast::Ty> {
- while let ast::TyKind::Rptr(_, ref mut_ty) = ty.node {
- ty = &mut_ty.ty;
+ let relevant_tys = item.body.all_fields()
+ .filter(|&field| filter(&field.attrs))
+ .map(|field| &field.ty);
+
+ let mut visitor = FindTyParams {
+ all_ty_params: all_ty_params,
+ relevant_ty_params: HashSet::new(),
+ };
+ for ty in relevant_tys {
+ visit::walk_ty(&mut visitor, ty);
}
- ty
+
+ builder.from_generics(generics.clone())
+ .with_predicates(
+ generics.ty_params.iter()
+ .map(|ty_param| ty_param.ident.name)
+ .filter(|id| visitor.relevant_ty_params.contains(id))
+ .map(|id| builder.where_predicate()
+ // the type parameter that is being bounded e.g. T
+ .bound().build(builder.ty().id(id))
+ // the bound e.g. Serialize
+ .bound().trait_(bound.clone()).build()
+ .build()))
+ .build()
}
| serde-rs/serde | 2016-07-22T06:07:43Z |
I started looking into this. We generate code like the following:
``` rust
impl<'a> Serialize for S<'a>
where Option<&'static str>: Serialize,
Option<&'a str>: Serialize,
{
fn serialize<SER>(&self, _ser: &mut SER) -> Result<(), SER::Error>
where SER: Serializer,
{
unimplemented!()
}
}
```
The error message is coming from `Option<&'static str>: Serialize`. I need to figure out why, because that seems like a reasonable bound.
The option impl looks like this:
``` rust
impl<T> Serialize for Option<T> where T: Serialize { /* ... */ }
```
The ref impl looks like this:
``` rust
impl<'a, T: ?Sized> Serialize for &'a T where T: Serialize { /* ... */ }
```
And the str impl looks like this:
``` rust
impl Serialize for str { /* ... */ }
```
So it seems like `Option<&'static str>: Serialize` should be fine. Possibly a compiler issue? I will continue debugging after work.
| 8cb6607e827717136a819caa44d8e43702724883 |
129 | diff --git a/serde_tests/benches/bench_enum.rs b/serde_tests/benches/bench_enum.rs
index b97c20cc6..0367df8b6 100644
--- a/serde_tests/benches/bench_enum.rs
+++ b/serde_tests/benches/bench_enum.rs
@@ -20,13 +20,13 @@ pub enum Error {
}
impl serde::de::Error for Error {
- fn syntax_error() -> Error { Error::SyntaxError }
+ fn syntax(_: &str) -> Error { Error::SyntaxError }
- fn end_of_stream_error() -> Error { Error::EndOfStreamError }
+ fn end_of_stream() -> Error { Error::EndOfStreamError }
- fn unknown_field_error(_: &str) -> Error { Error::SyntaxError }
+ fn unknown_field(_: &str) -> Error { Error::SyntaxError }
- fn missing_field_error(_: &'static str) -> Error { Error::SyntaxError }
+ fn missing_field(_: &'static str) -> Error { Error::SyntaxError }
}
//////////////////////////////////////////////////////////////////////////////
diff --git a/serde_tests/benches/bench_map.rs b/serde_tests/benches/bench_map.rs
index d8c7c285d..2f5b1bcaa 100644
--- a/serde_tests/benches/bench_map.rs
+++ b/serde_tests/benches/bench_map.rs
@@ -17,13 +17,13 @@ pub enum Error {
}
impl serde::de::Error for Error {
- fn syntax_error() -> Error { Error::SyntaxError }
+ fn syntax(_: &str) -> Error { Error::SyntaxError }
- fn end_of_stream_error() -> Error { Error::EndOfStream }
+ fn end_of_stream() -> Error { Error::EndOfStream }
- fn unknown_field_error(_: &str) -> Error { Error::SyntaxError }
+ fn unknown_field(_: &str) -> Error { Error::SyntaxError }
- fn missing_field_error(_: &'static str) -> Error {
+ fn missing_field(_: &'static str) -> Error {
Error::MissingField
}
}
@@ -347,17 +347,17 @@ mod deserializer {
impl de::Deserializer<Error> for IsizeDeserializer {
#[inline]
- fn end_of_stream_error(&mut self) -> Error {
+ fn end_of_stream(&mut self) -> Error {
EndOfStream
}
#[inline]
- fn syntax_error(&mut self, _token: de::Token, _expected: &[de::TokenKind]) -> Error {
+ fn syntax(&mut self, _token: de::Token, _expected: &[de::TokenKind]) -> Error {
SyntaxError
}
#[inline]
- fn unexpected_name_error(&mut self, _token: de::Token) -> Error {
+ fn unexpected_name(&mut self, _token: de::Token) -> Error {
SyntaxError
}
diff --git a/serde_tests/benches/bench_struct.rs b/serde_tests/benches/bench_struct.rs
index 6c76eaef2..0e53d1a3f 100644
--- a/serde_tests/benches/bench_struct.rs
+++ b/serde_tests/benches/bench_struct.rs
@@ -33,13 +33,13 @@ pub enum Error {
}
impl serde::de::Error for Error {
- fn syntax_error() -> Error { Error::SyntaxError }
+ fn syntax(_: &str) -> Error { Error::SyntaxError }
- fn end_of_stream_error() -> Error { Error::EndOfStream }
+ fn end_of_stream() -> Error { Error::EndOfStream }
- fn unknown_field_error(_: &str) -> Error { Error::SyntaxError }
+ fn unknown_field(_: &str) -> Error { Error::SyntaxError }
- fn missing_field_error(_: &'static str) -> Error {
+ fn missing_field(_: &'static str) -> Error {
Error::MissingField
}
}
diff --git a/serde_tests/benches/bench_vec.rs b/serde_tests/benches/bench_vec.rs
index 9a16d9dde..450d3f1b8 100644
--- a/serde_tests/benches/bench_vec.rs
+++ b/serde_tests/benches/bench_vec.rs
@@ -15,13 +15,13 @@ pub enum Error {
}
impl serde::de::Error for Error {
- fn syntax_error() -> Error { Error::SyntaxError }
+ fn syntax(_: &str) -> Error { Error::SyntaxError }
- fn end_of_stream_error() -> Error { Error::EndOfStreamError }
+ fn end_of_stream() -> Error { Error::EndOfStreamError }
- fn unknown_field_error(_: &str) -> Error { Error::SyntaxError }
+ fn unknown_field(_: &str) -> Error { Error::SyntaxError }
- fn missing_field_error(_: &'static str) -> Error { Error::SyntaxError }
+ fn missing_field(_: &'static str) -> Error { Error::SyntaxError }
}
//////////////////////////////////////////////////////////////////////////////
diff --git a/serde_tests/tests/test_bytes.rs b/serde_tests/tests/test_bytes.rs
index 3ca97285a..d0e8227a1 100644
--- a/serde_tests/tests/test_bytes.rs
+++ b/serde_tests/tests/test_bytes.rs
@@ -9,13 +9,13 @@ use serde_json;
struct Error;
impl serde::de::Error for Error {
- fn syntax_error() -> Error { Error }
+ fn syntax(_: &str) -> Error { Error }
- fn end_of_stream_error() -> Error { Error }
+ fn end_of_stream() -> Error { Error }
- fn unknown_field_error(_field: &str) -> Error { Error }
+ fn unknown_field(_field: &str) -> Error { Error }
- fn missing_field_error(_field: &'static str) -> Error { Error }
+ fn missing_field(_field: &'static str) -> Error { Error }
}
///////////////////////////////////////////////////////////////////////////////
diff --git a/serde_tests/tests/test_de.rs b/serde_tests/tests/test_de.rs
index 6f45a0afa..5c9448891 100644
--- a/serde_tests/tests/test_de.rs
+++ b/serde_tests/tests/test_de.rs
@@ -68,15 +68,15 @@ enum Error {
}
impl de::Error for Error {
- fn syntax_error() -> Error { Error::SyntaxError }
+ fn syntax(_: &str) -> Error { Error::SyntaxError }
- fn end_of_stream_error() -> Error { Error::EndOfStreamError }
+ fn end_of_stream() -> Error { Error::EndOfStreamError }
- fn unknown_field_error(field: &str) -> Error {
+ fn unknown_field(field: &str) -> Error {
Error::UnknownFieldError(field.to_string())
}
- fn missing_field_error(field: &'static str) -> Error {
+ fn missing_field(field: &'static str) -> Error {
Error::MissingFieldError(field)
}
}
| [
"125"
] | serde-rs__serde-129 | Extend `de::Error` to signal more cases of errors
Maybe we could strip off the `_error` suffix, it's already clear due to the name of the trait. I usually call these method using `de::Error::syntax_error()`.
I often parse some data coming in via `visit_str` and other visitors into specialized types. There are additional error cases when a constraint is not met, for example parsing a string as UUID. How to handle such errors?
One could argue that these errors are not related to serialization/deserialization, but validation. That means that validation errors should be embedded (like it's done in `io::Error`?).
Otherwise we could add some more methods to `de::Error`. I'd like to change `fn syntax_error() -> Self` to `fn syntax(msg: &str) -> Self` because I (ab)use it to signal validation errors and have no way to transport which constraint was violated. Which error conditions you like to see included?
Current trait definition of `de::Error`:
``` rust
pub trait Error {
fn syntax_error() -> Self;
fn end_of_stream_error() -> Self;
fn unknown_field_error(field: &str) -> Self;
fn missing_field_error(field: &'static str) -> Self;
}
```
| 0.5 | 0482b756e897ccfdac0fe52f54a1ca0f4ba76042 | diff --git a/README.md b/README.md
index 624054f85..e00fa998b 100644
--- a/README.md
+++ b/README.md
@@ -275,7 +275,7 @@ to generate an error for a few common error conditions. Here's how it could be u
fn visit_string<E>(&mut self, _: String) -> Result<i32, E>
where E: Error,
{
- Err(serde::de::Error::syntax_error())
+ Err(serde::de::Error::syntax("expect a string"))
}
...
@@ -366,7 +366,7 @@ impl serde::Deserialize for PointField {
match value {
"x" => Ok(Field::X),
"y" => Ok(Field::Y),
- _ => Err(serde::de::Error::syntax_error()),
+ _ => Err(serde::de::Error::syntax("expected x or y")),
}
}
}
diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index e8b95f580..48a194f3a 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -85,7 +85,7 @@ impl Visitor for BoolVisitor {
match s.trim() {
"true" => Ok(true),
"false" => Ok(false),
- _ => Err(Error::syntax_error()),
+ _ => Err(Error::syntax("expected `true` or `false`")),
}
}
}
@@ -108,7 +108,7 @@ macro_rules! impl_deserialize_num_method {
{
match FromPrimitive::$from_method(v) {
Some(v) => Ok(v),
- None => Err(Error::syntax_error()),
+ None => Err(Error::syntax("expected a number")),
}
}
}
@@ -149,7 +149,7 @@ impl<
fn visit_str<E>(&mut self, v: &str) -> Result<T, E>
where E: Error,
{
- str::FromStr::from_str(v.trim()).or(Err(Error::syntax_error()))
+ str::FromStr::from_str(v.trim()).or(Err(Error::syntax("expected a str")))
}
}
@@ -200,12 +200,12 @@ impl Visitor for CharVisitor {
let mut iter = v.chars();
if let Some(v) = iter.next() {
if iter.next().is_some() {
- Err(Error::syntax_error())
+ Err(Error::syntax("expected a character"))
} else {
Ok(v)
}
} else {
- Err(Error::end_of_stream_error())
+ Err(Error::end_of_stream())
}
}
}
@@ -243,7 +243,7 @@ impl Visitor for StringVisitor {
{
match str::from_utf8(v) {
Ok(s) => Ok(s.to_string()),
- Err(_) => Err(Error::syntax_error()),
+ Err(_) => Err(Error::syntax("expected utf8 `&[u8]`")),
}
}
@@ -252,7 +252,7 @@ impl Visitor for StringVisitor {
{
match String::from_utf8(v) {
Ok(s) => Ok(s),
- Err(_) => Err(Error::syntax_error()),
+ Err(_) => Err(Error::syntax("expected utf8 `&[u8]`")),
}
}
}
@@ -495,7 +495,7 @@ macro_rules! array_impls {
$(
let $name = match try!(visitor.visit()) {
Some(val) => val,
- None => { return Err(Error::end_of_stream_error()); }
+ None => { return Err(Error::end_of_stream()); }
};
)+;
@@ -593,7 +593,7 @@ macro_rules! tuple_impls {
$(
let $name = match try!(visitor.visit()) {
Some(value) => value,
- None => { return Err(Error::end_of_stream_error()); }
+ None => { return Err(Error::end_of_stream()); }
};
)+;
@@ -848,7 +848,7 @@ impl<T> Deserialize for NonZero<T> where T: Deserialize + PartialEq + Zeroable +
fn deserialize<D>(deserializer: &mut D) -> Result<NonZero<T>, D::Error> where D: Deserializer {
let value = try!(Deserialize::deserialize(deserializer));
if value == Zero::zero() {
- return Err(Error::syntax_error())
+ return Err(Error::syntax("expected a non-zero value"))
}
unsafe {
Ok(NonZero::new(value))
@@ -881,7 +881,7 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
match value {
0 => Ok(Field::Ok),
1 => Ok(Field::Err),
- _ => Err(Error::unknown_field_error(&value.to_string())),
+ _ => Err(Error::unknown_field(&value.to_string())),
}
}
@@ -889,7 +889,7 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
match value {
"Ok" => Ok(Field::Ok),
"Err" => Ok(Field::Err),
- _ => Err(Error::unknown_field_error(value)),
+ _ => Err(Error::unknown_field(value)),
}
}
@@ -899,8 +899,8 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
b"Err" => Ok(Field::Err),
_ => {
match str::from_utf8(value) {
- Ok(value) => Err(Error::unknown_field_error(value)),
- Err(_) => Err(Error::syntax_error()),
+ Ok(value) => Err(Error::unknown_field(value)),
+ Err(_) => Err(Error::syntax("expected a `&[u8]`")),
}
}
}
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index 60c51edcc..db83bdc22 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -6,13 +6,13 @@ pub mod value;
///////////////////////////////////////////////////////////////////////////////
pub trait Error {
- fn syntax_error() -> Self;
+ fn syntax(msg: &str) -> Self;
- fn end_of_stream_error() -> Self;
+ fn end_of_stream() -> Self;
- fn unknown_field_error(field: &str) -> Self;
+ fn unknown_field(field: &str) -> Self;
- fn missing_field_error(field: &'static str) -> Self;
+ fn missing_field(field: &'static str) -> Self;
}
///////////////////////////////////////////////////////////////////////////////
@@ -273,7 +273,7 @@ pub trait Deserializer {
_visitor: V) -> Result<V::Value, Self::Error>
where V: EnumVisitor,
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected an enum"))
}
/// This method hints that the `Deserialize` type is expecting a `Vec<u8>`. This allows
@@ -304,7 +304,7 @@ pub trait Visitor {
fn visit_bool<E>(&mut self, _v: bool) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected a bool"))
}
fn visit_isize<E>(&mut self, v: isize) -> Result<Self::Value, E>
@@ -334,7 +334,7 @@ pub trait Visitor {
fn visit_i64<E>(&mut self, _v: i64) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected a i64"))
}
fn visit_usize<E>(&mut self, v: usize) -> Result<Self::Value, E>
@@ -364,7 +364,7 @@ pub trait Visitor {
fn visit_u64<E>(&mut self, _v: u64) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected a u64"))
}
fn visit_f32<E>(&mut self, v: f32) -> Result<Self::Value, E>
@@ -376,7 +376,7 @@ pub trait Visitor {
fn visit_f64<E>(&mut self, _v: f64) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected a f64"))
}
#[inline]
@@ -391,7 +391,7 @@ pub trait Visitor {
fn visit_str<E>(&mut self, _v: &str) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected a str"))
}
#[inline]
@@ -404,7 +404,7 @@ pub trait Visitor {
fn visit_unit<E>(&mut self) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected a unit"))
}
#[inline]
@@ -417,37 +417,37 @@ pub trait Visitor {
fn visit_none<E>(&mut self) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected an Option::None"))
}
fn visit_some<D>(&mut self, _deserializer: &mut D) -> Result<Self::Value, D::Error>
where D: Deserializer,
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected an Option::Some"))
}
fn visit_newtype_struct<D>(&mut self, _deserializer: &mut D) -> Result<Self::Value, D::Error>
where D: Deserializer,
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected a newtype struct"))
}
fn visit_seq<V>(&mut self, _visitor: V) -> Result<Self::Value, V::Error>
where V: SeqVisitor,
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected a sequence"))
}
fn visit_map<V>(&mut self, _visitor: V) -> Result<Self::Value, V::Error>
where V: MapVisitor,
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected a map"))
}
fn visit_bytes<E>(&mut self, _v: &[u8]) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected a &[u8]"))
}
fn visit_byte_buf<E>(&mut self, v: Vec<u8>) -> Result<Self::Value, E>
@@ -529,7 +529,7 @@ pub trait MapVisitor {
fn missing_field<V>(&mut self, field: &'static str) -> Result<V, Self::Error>
where V: Deserialize,
{
- Err(Error::missing_field_error(field))
+ Err(Error::missing_field(field))
}
}
@@ -593,7 +593,7 @@ pub trait VariantVisitor {
/// `visit_unit` is called when deserializing a variant with no values.
fn visit_unit(&mut self) -> Result<(), Self::Error> {
- Err(Error::syntax_error())
+ Err(Error::syntax("expected a univ variant"))
}
/// `visit_newtype` is called when deserializing a variant with a single value. By default this
@@ -612,7 +612,7 @@ pub trait VariantVisitor {
_visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected a tuple variant"))
}
/// `visit_struct` is called when deserializing a struct-like variant.
@@ -621,7 +621,7 @@ pub trait VariantVisitor {
_visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor
{
- Err(Error::syntax_error())
+ Err(Error::syntax("expected a struct variant"))
}
}
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 8ad281b77..b6c6f0feb 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -24,10 +24,10 @@ pub enum Error {
}
impl de::Error for Error {
- fn syntax_error() -> Self { Error::SyntaxError }
- fn end_of_stream_error() -> Self { Error::EndOfStreamError }
- fn unknown_field_error(field: &str) -> Self { Error::UnknownFieldError(field.to_string()) }
- fn missing_field_error(field: &'static str) -> Self { Error::MissingFieldError(field) }
+ fn syntax(_: &str) -> Self { Error::SyntaxError }
+ fn end_of_stream() -> Self { Error::EndOfStreamError }
+ fn unknown_field(field: &str) -> Self { Error::UnknownFieldError(String::from(field)) }
+ fn missing_field(field: &'static str) -> Self { Error::MissingFieldError(field) }
}
///////////////////////////////////////////////////////////////////////////////
@@ -89,7 +89,7 @@ macro_rules! primitive_deserializer {
{
match self.0.take() {
Some(v) => visitor.$method(v),
- None => Err(de::Error::end_of_stream_error()),
+ None => Err(de::Error::end_of_stream()),
}
}
}
@@ -132,7 +132,7 @@ impl<'a> de::Deserializer for StrDeserializer<'a> {
{
match self.0.take() {
Some(v) => visitor.visit_str(v),
- None => Err(de::Error::end_of_stream_error()),
+ None => Err(de::Error::end_of_stream()),
}
}
@@ -181,7 +181,7 @@ impl de::Deserializer for StringDeserializer {
{
match self.0.take() {
Some(string) => visitor.visit_string(string),
- None => Err(de::Error::end_of_stream_error()),
+ None => Err(de::Error::end_of_stream()),
}
}
@@ -261,7 +261,7 @@ impl<I, T> de::SeqVisitor for SeqDeserializer<I>
if self.len == 0 {
Ok(())
} else {
- Err(de::Error::end_of_stream_error())
+ Err(de::Error::end_of_stream())
}
}
@@ -374,7 +374,7 @@ impl<I, K, V> de::MapVisitor for MapDeserializer<I, K, V>
let mut de = value.into_deserializer();
de::Deserialize::deserialize(&mut de)
}
- None => Err(de::Error::syntax_error())
+ None => Err(de::Error::syntax("expected a map value"))
}
}
@@ -382,7 +382,7 @@ impl<I, K, V> de::MapVisitor for MapDeserializer<I, K, V>
if self.len == 0 {
Ok(())
} else {
- Err(de::Error::end_of_stream_error())
+ Err(de::Error::end_of_stream())
}
}
@@ -438,7 +438,7 @@ impl<'a> de::Deserializer for BytesDeserializer<'a> {
{
match self.0.take() {
Some(bytes) => visitor.visit_bytes(bytes),
- None => Err(de::Error::end_of_stream_error()),
+ None => Err(de::Error::end_of_stream()),
}
}
}
@@ -465,7 +465,7 @@ impl de::Deserializer for ByteBufDeserializer {
{
match self.0.take() {
Some(bytes) => visitor.visit_byte_buf(bytes),
- None => Err(de::Error::end_of_stream_error()),
+ None => Err(de::Error::end_of_stream()),
}
}
}
diff --git a/serde_codegen/src/de.rs b/serde_codegen/src/de.rs
index 580644404..8beb1b9e6 100644
--- a/serde_codegen/src/de.rs
+++ b/serde_codegen/src/de.rs
@@ -397,7 +397,7 @@ fn deserialize_seq(
let $name = match try!(visitor.visit()) {
Some(value) => { value },
None => {
- return Err(::serde::de::Error::end_of_stream_error());
+ return Err(::serde::de::Error::end_of_stream());
}
};
).unwrap()
@@ -431,7 +431,7 @@ fn deserialize_struct_as_seq(
let $name = match try!(visitor.visit()) {
Some(value) => { value },
None => {
- return Err(::serde::de::Error::end_of_stream_error());
+ return Err(::serde::de::Error::end_of_stream());
}
};
).unwrap()
@@ -804,7 +804,7 @@ fn deserialize_field_visitor(
let index_body = quote_expr!(cx,
match value {
$index_field_arms
- _ => { Err(::serde::de::Error::syntax_error()) }
+ _ => { Err(::serde::de::Error::syntax("expected a field")) }
}
);
@@ -829,7 +829,7 @@ fn deserialize_field_visitor(
quote_expr!(cx,
match value {
$default_field_arms
- _ => { Err(::serde::de::Error::unknown_field_error(value)) }
+ _ => { Err(::serde::de::Error::unknown_field(value)) }
})
} else {
let field_arms: Vec<_> = formats.iter()
@@ -851,7 +851,7 @@ fn deserialize_field_visitor(
match value {
$arms
_ => {
- Err(::serde::de::Error::unknown_field_error(value))
+ Err(::serde::de::Error::unknown_field(value))
}
}})
})
@@ -862,7 +862,7 @@ fn deserialize_field_visitor(
$fmt_matches
_ => match value {
$default_field_arms
- _ => { Err(::serde::de::Error::unknown_field_error(value)) }
+ _ => { Err(::serde::de::Error::unknown_field(value)) }
}
}
)
@@ -903,7 +903,13 @@ fn deserialize_field_visitor(
// TODO: would be better to generate a byte string literal match
match ::std::str::from_utf8(value) {
Ok(s) => self.visit_str(s),
- _ => Err(::serde::de::Error::syntax_error()),
+ _ => {
+ Err(
+ ::serde::de::Error::syntax(
+ "could not convert a byte string to a String"
+ )
+ )
+ }
}
}
}
diff --git a/serde_json/src/error.rs b/serde_json/src/error.rs
index beaa8a721..6621188bb 100644
--- a/serde_json/src/error.rs
+++ b/serde_json/src/error.rs
@@ -152,35 +152,35 @@ impl From<de::value::Error> for Error {
fn from(error: de::value::Error) -> Error {
match error {
de::value::Error::SyntaxError => {
- de::Error::syntax_error()
+ Error::SyntaxError(ErrorCode::ExpectedSomeValue, 0, 0)
}
de::value::Error::EndOfStreamError => {
- de::Error::end_of_stream_error()
+ de::Error::end_of_stream()
}
de::value::Error::UnknownFieldError(field) => {
Error::SyntaxError(ErrorCode::UnknownField(field), 0, 0)
}
de::value::Error::MissingFieldError(field) => {
- de::Error::missing_field_error(field)
+ de::Error::missing_field(field)
}
}
}
}
impl de::Error for Error {
- fn syntax_error() -> Error {
+ fn syntax(_: &str) -> Error {
Error::SyntaxError(ErrorCode::ExpectedSomeValue, 0, 0)
}
- fn end_of_stream_error() -> Error {
+ fn end_of_stream() -> Error {
Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 0, 0)
}
- fn unknown_field_error(field: &str) -> Error {
+ fn unknown_field(field: &str) -> Error {
Error::SyntaxError(ErrorCode::UnknownField(field.to_string()), 0, 0)
}
- fn missing_field_error(field: &'static str) -> Error {
+ fn missing_field(field: &'static str) -> Error {
Error::MissingFieldError(field)
}
}
diff --git a/serde_json/src/value.rs b/serde_json/src/value.rs
index 7b6c0bb02..b873ad2c6 100644
--- a/serde_json/src/value.rs
+++ b/serde_json/src/value.rs
@@ -650,7 +650,7 @@ impl de::Deserializer for Deserializer {
{
let value = match self.value.take() {
Some(value) => value,
- None => { return Err(de::Error::end_of_stream_error()); }
+ None => { return Err(de::Error::end_of_stream()); }
};
match value {
@@ -687,7 +687,7 @@ impl de::Deserializer for Deserializer {
match self.value {
Some(Value::Null) => visitor.visit_none(),
Some(_) => visitor.visit_some(self),
- None => Err(de::Error::end_of_stream_error()),
+ None => Err(de::Error::end_of_stream()),
}
}
@@ -700,20 +700,20 @@ impl de::Deserializer for Deserializer {
{
let value = match self.value.take() {
Some(Value::Object(value)) => value,
- Some(_) => { return Err(de::Error::syntax_error()); }
- None => { return Err(de::Error::end_of_stream_error()); }
+ Some(_) => { return Err(de::Error::syntax("expected an enum")); }
+ None => { return Err(de::Error::end_of_stream()); }
};
let mut iter = value.into_iter();
let (variant, value) = match iter.next() {
Some(v) => v,
- None => return Err(de::Error::syntax_error()),
+ None => return Err(de::Error::syntax("expected a variant name")),
};
// enums are encoded in json as maps with a single key:value pair
match iter.next() {
- Some(_) => Err(de::Error::syntax_error()),
+ Some(_) => Err(de::Error::syntax("expected map")),
None => visitor.visit(VariantDeserializer {
de: self,
val: Some(value),
@@ -768,7 +768,7 @@ impl<'a> de::VariantVisitor for VariantDeserializer<'a> {
visitor,
)
} else {
- Err(de::Error::syntax_error())
+ Err(de::Error::syntax("expected a tuple"))
}
}
@@ -788,7 +788,7 @@ impl<'a> de::VariantVisitor for VariantDeserializer<'a> {
visitor,
)
} else {
- Err(de::Error::syntax_error())
+ Err(de::Error::syntax("expected a struct"))
}
}
}
@@ -834,7 +834,7 @@ impl<'a> de::SeqVisitor for SeqDeserializer<'a> {
if self.len == 0 {
Ok(())
} else {
- Err(de::Error::end_of_stream_error())
+ Err(de::Error::end_of_stream())
}
}
@@ -879,7 +879,7 @@ impl<'a> de::MapVisitor for MapDeserializer<'a> {
if self.len == 0 {
Ok(())
} else {
- Err(de::Error::end_of_stream_error())
+ Err(de::Error::end_of_stream())
}
}
| serde-rs/serde | 2015-08-07T14:54:21Z | 7b773ac08880adece2f1bd809efcbd5828b23293 | |
127 | diff --git a/serde_tests/tests/test_json.rs b/serde_tests/tests/test_json.rs
index d8e177b76..934cbcc40 100644
--- a/serde_tests/tests/test_json.rs
+++ b/serde_tests/tests/test_json.rs
@@ -728,7 +728,7 @@ fn test_parse_number_errors() {
("1e", Error::SyntaxError(ErrorCode::InvalidNumber, 1, 2)),
("1e+", Error::SyntaxError(ErrorCode::InvalidNumber, 1, 3)),
("1a", Error::SyntaxError(ErrorCode::TrailingCharacters, 1, 2)),
- ("1e777777777777777777777777777", Error::SyntaxError(ErrorCode::InvalidNumber, 1, 23)),
+ ("1e777777777777777777777777777", Error::SyntaxError(ErrorCode::InvalidNumber, 1, 22)),
]);
}
@@ -804,8 +804,8 @@ fn test_parse_string() {
#[test]
fn test_parse_list() {
test_parse_err::<Vec<f64>>(vec![
- ("[", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 1)),
- ("[ ", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 2)),
+ ("[", Error::SyntaxError(ErrorCode::EOFWhileParsingList, 1, 1)),
+ ("[ ", Error::SyntaxError(ErrorCode::EOFWhileParsingList, 1, 2)),
("[1", Error::SyntaxError(ErrorCode::EOFWhileParsingList, 1, 2)),
("[1,", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 3)),
("[1,]", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 4)),
@@ -856,8 +856,8 @@ fn test_parse_list() {
#[test]
fn test_parse_object() {
test_parse_err::<BTreeMap<String, u32>>(vec![
- ("{", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 1)),
- ("{ ", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 2)),
+ ("{", Error::SyntaxError(ErrorCode::EOFWhileParsingObject, 1, 1)),
+ ("{ ", Error::SyntaxError(ErrorCode::EOFWhileParsingObject, 1, 2)),
("{1", Error::SyntaxError(ErrorCode::KeyMustBeAString, 1, 2)),
("{ \"a\"", Error::SyntaxError(ErrorCode::EOFWhileParsingObject, 1, 5)),
("{\"a\"", Error::SyntaxError(ErrorCode::EOFWhileParsingObject, 1, 4)),
@@ -909,7 +909,7 @@ fn test_parse_struct() {
test_parse_err::<Outer>(vec![
("5", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 1)),
("\"hello\"", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 7)),
- ("{\"inner\": true}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 15)),
+ ("{\"inner\": true}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 14)),
]);
test_parse_ok(vec![
@@ -988,9 +988,9 @@ fn test_parse_enum_errors() {
("{}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 2)),
("{\"Dog\":", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 7)),
("{\"Dog\":}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 8)),
- ("{\"unknown\":[]}", Error::SyntaxError(ErrorCode::UnknownField("unknown".to_string()), 1, 11)),
- ("{\"Dog\":{}}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 9)),
- ("{\"Frog\":{}}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 10)),
+ ("{\"unknown\":[]}", Error::SyntaxError(ErrorCode::UnknownField("unknown".to_string()), 1, 10)),
+ ("{\"Dog\":{}}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 8)),
+ ("{\"Frog\":{}}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 9)),
("{\"Cat\":[]}", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 9)),
]);
}
@@ -1311,3 +1311,40 @@ fn test_serialize_map_with_no_len() {
)
);
}
+
+#[test]
+fn test_deserialize_from_stream() {
+ use std::net;
+ use std::io::Read;
+ use std::thread;
+ use serde::Deserialize;
+
+ #[derive(Debug, PartialEq, Serialize, Deserialize)]
+ struct Message {
+ message: String,
+ }
+
+ let l = net::TcpListener::bind("localhost:20000").unwrap();
+
+ thread::spawn(|| {
+ let l = l;
+ for stream in l.incoming() {
+ let mut stream = stream.unwrap();
+ let read_stream = stream.try_clone().unwrap();
+
+ let mut de = serde_json::Deserializer::new(read_stream.bytes());
+ let request = Message::deserialize(&mut de).unwrap();
+ let response = Message { message: request.message };
+ serde_json::to_writer(&mut stream, &response).unwrap();
+ }
+ });
+
+ let mut stream = net::TcpStream::connect("localhost:20000").unwrap();
+ let request = Message { message: "hi there".to_string() };
+ serde_json::to_writer(&mut stream, &request).unwrap();
+
+ let mut de = serde_json::Deserializer::new(stream.bytes());
+ let response = Message::deserialize(&mut de).unwrap();
+
+ assert_eq!(request, response);
+}
| [
"89"
] | serde-rs__serde-127 | Allow deserializing without consuming the entire stream
My use case for this is deserializing more than one json object from a tcp connection. Currently you can't open one connection and send objects back and forth because `serde::json::de::from_reader` hangs until eof.
| 0.5 | 199ed417bd6afc2071d17759b8c7e0ab8d0ba4cc | diff --git a/serde_json/src/de.rs b/serde_json/src/de.rs
index 044918993..c66b50071 100644
--- a/serde_json/src/de.rs
+++ b/serde_json/src/de.rs
@@ -28,49 +28,61 @@ impl<Iter> Deserializer<Iter>
{
/// Creates the JSON parser from an `std::iter::Iterator`.
#[inline]
- pub fn new(rdr: Iter) -> Result<Deserializer<Iter>> {
- let mut deserializer = Deserializer {
+ pub fn new(rdr: Iter) -> Deserializer<Iter> {
+ Deserializer {
rdr: LineColIterator::new(rdr),
ch: None,
str_buf: Vec::with_capacity(128),
- };
-
- try!(deserializer.bump());
-
- Ok(deserializer)
+ }
}
#[inline]
pub fn end(&mut self) -> Result<()> {
try!(self.parse_whitespace());
- if self.eof() {
+ if try!(self.eof()) {
Ok(())
} else {
Err(self.error(ErrorCode::TrailingCharacters))
}
}
- fn eof(&self) -> bool { self.ch.is_none() }
+ fn eof(&mut self) -> Result<bool> {
+ Ok(try!(self.peek()).is_none())
+ }
- fn ch_or_null(&self) -> u8 { self.ch.unwrap_or(b'\x00') }
+ fn peek(&mut self) -> Result<Option<u8>> {
+ match self.ch {
+ Some(ch) => Ok(Some(ch)),
+ None => {
+ self.ch = try!(self.next_char());
+ Ok(self.ch)
+ }
+ }
+ }
- fn bump(&mut self) -> Result<()> {
- self.ch = match self.rdr.next() {
- Some(Err(err)) => { return Err(Error::IoError(err)); }
- Some(Ok(ch)) => Some(ch),
- None => None,
- };
+ fn peek_or_null(&mut self) -> Result<u8> {
+ Ok(try!(self.peek()).unwrap_or(b'\x00'))
+ }
- Ok(())
+ fn eat_char(&mut self) {
+ self.ch = None;
}
fn next_char(&mut self) -> Result<Option<u8>> {
- try!(self.bump());
- Ok(self.ch)
+ match self.ch.take() {
+ Some(ch) => Ok(Some(ch)),
+ None => {
+ match self.rdr.next() {
+ Some(Err(err)) => Err(Error::IoError(err)),
+ Some(Ok(ch)) => Ok(Some(ch)),
+ None => Ok(None),
+ }
+ }
+ }
}
- fn ch_is(&self, c: u8) -> bool {
- self.ch == Some(c)
+ fn next_char_or_null(&mut self) -> Result<u8> {
+ Ok(try!(self.next_char()).unwrap_or(b'\x00'))
}
fn error(&mut self, reason: ErrorCode) -> Error {
@@ -78,12 +90,14 @@ impl<Iter> Deserializer<Iter>
}
fn parse_whitespace(&mut self) -> Result<()> {
- while self.ch_is(b' ') ||
- self.ch_is(b'\n') ||
- self.ch_is(b'\t') ||
- self.ch_is(b'\r') { try!(self.bump()); }
-
- Ok(())
+ loop {
+ match try!(self.peek_or_null()) {
+ b' ' | b'\n' | b'\t' | b'\r' => {
+ self.eat_char();
+ }
+ _ => { return Ok(()); }
+ }
+ }
}
fn parse_value<V>(&mut self, mut visitor: V) -> Result<V::Value>
@@ -91,41 +105,45 @@ impl<Iter> Deserializer<Iter>
{
try!(self.parse_whitespace());
- if self.eof() {
+ if try!(self.eof()) {
return Err(self.error(ErrorCode::EOFWhileParsingValue));
}
- let value = match self.ch_or_null() {
+ let value = match try!(self.peek_or_null()) {
b'n' => {
+ self.eat_char();
try!(self.parse_ident(b"ull"));
visitor.visit_unit()
}
b't' => {
+ self.eat_char();
try!(self.parse_ident(b"rue"));
visitor.visit_bool(true)
}
b'f' => {
+ self.eat_char();
try!(self.parse_ident(b"alse"));
visitor.visit_bool(false)
}
b'-' => {
- try!(self.bump());
+ self.eat_char();
self.parse_integer(false, visitor)
}
b'0' ... b'9' => {
self.parse_integer(true, visitor)
}
b'"' => {
+ self.eat_char();
try!(self.parse_string());
let s = str::from_utf8(&self.str_buf).unwrap();
visitor.visit_str(s)
}
b'[' => {
- try!(self.bump());
+ self.eat_char();
visitor.visit_seq(SeqVisitor::new(self))
}
b'{' => {
- try!(self.bump());
+ self.eat_char();
visitor.visit_map(MapVisitor::new(self))
}
_ => {
@@ -147,19 +165,16 @@ impl<Iter> Deserializer<Iter>
}
}
- try!(self.bump());
Ok(())
}
fn parse_integer<V>(&mut self, pos: bool, visitor: V) -> Result<V::Value>
where V: de::Visitor,
{
- match self.ch_or_null() {
+ match try!(self.next_char_or_null()) {
b'0' => {
- try!(self.bump());
-
// There can be only one leading '0'.
- match self.ch_or_null() {
+ match try!(self.peek_or_null()) {
b'0' ... b'9' => {
Err(self.error(ErrorCode::InvalidNumber))
}
@@ -169,14 +184,12 @@ impl<Iter> Deserializer<Iter>
}
},
c @ b'1' ... b'9' => {
- try!(self.bump());
-
let mut res: u64 = (c as u64) - ('0' as u64);
loop {
- match self.ch_or_null() {
+ match try!(self.peek_or_null()) {
c @ b'0' ... b'9' => {
- try!(self.bump());
+ self.eat_char();
let digit = (c as u64) - ('0' as u64);
@@ -212,17 +225,15 @@ impl<Iter> Deserializer<Iter>
where V: de::Visitor,
{
loop {
- match self.ch_or_null() {
+ match try!(self.next_char_or_null()) {
c @ b'0' ... b'9' => {
- try!(self.bump());
-
let digit = (c as u64) - ('0' as u64);
res *= 10.0;
res += digit as f64;
}
_ => {
- match self.ch_or_null() {
+ match try!(self.peek_or_null()) {
b'.' => {
return self.parse_decimal(pos, res, visitor);
}
@@ -248,7 +259,7 @@ impl<Iter> Deserializer<Iter>
mut visitor: V) -> Result<V::Value>
where V: de::Visitor,
{
- match self.ch_or_null() {
+ match try!(self.peek_or_null()) {
b'.' => {
self.parse_decimal(pos, res as f64, visitor)
}
@@ -280,31 +291,31 @@ impl<Iter> Deserializer<Iter>
mut visitor: V) -> Result<V::Value>
where V: de::Visitor,
{
- try!(self.bump());
+ self.eat_char();
let mut dec = 0.1;
// Make sure a digit follows the decimal place.
- match self.ch_or_null() {
+ match try!(self.next_char_or_null()) {
c @ b'0' ... b'9' => {
- try!(self.bump());
res += (((c as u64) - (b'0' as u64)) as f64) * dec;
}
_ => { return Err(self.error(ErrorCode::InvalidNumber)); }
}
- while !self.eof() {
- match self.ch_or_null() {
+ loop {
+ match try!(self.peek_or_null()) {
c @ b'0' ... b'9' => {
+ self.eat_char();
+
dec /= 10.0;
res += (((c as u64) - (b'0' as u64)) as f64) * dec;
- try!(self.bump());
}
- _ => break,
+ _ => { break; }
}
}
- match self.ch_or_null() {
+ match try!(self.peek_or_null()) {
b'e' | b'E' => {
self.parse_exponent(pos, res, visitor)
}
@@ -325,27 +336,24 @@ impl<Iter> Deserializer<Iter>
mut visitor: V) -> Result<V::Value>
where V: de::Visitor,
{
- try!(self.bump());
+ self.eat_char();
- let pos_exp = match self.ch_or_null() {
- b'+' => { try!(self.bump()); true }
- b'-' => { try!(self.bump()); false }
+ let pos_exp = match try!(self.peek_or_null()) {
+ b'+' => { self.eat_char(); true }
+ b'-' => { self.eat_char(); false }
_ => { true }
};
// Make sure a digit follows the exponent place.
- let mut exp = match self.ch_or_null() {
- c @ b'0' ... b'9' => {
- try!(self.bump());
- (c as u64) - (b'0' as u64)
- }
+ let mut exp = match try!(self.next_char_or_null()) {
+ c @ b'0' ... b'9' => { (c as u64) - (b'0' as u64) }
_ => { return Err(self.error(ErrorCode::InvalidNumber)); }
};
loop {
- match self.ch_or_null() {
+ match try!(self.peek_or_null()) {
c @ b'0' ... b'9' => {
- try!(self.bump());
+ self.eat_char();
exp = try_or_invalid!(self, exp.checked_mul(10));
exp = try_or_invalid!(self, exp.checked_add((c as u64) - (b'0' as u64)));
@@ -376,9 +384,8 @@ impl<Iter> Deserializer<Iter>
fn decode_hex_escape(&mut self) -> Result<u16> {
let mut i = 0;
let mut n = 0u16;
- while i < 4 && !self.eof() {
- try!(self.bump());
- n = match self.ch_or_null() {
+ while i < 4 && !try!(self.eof()) {
+ n = match try!(self.next_char_or_null()) {
c @ b'0' ... b'9' => n * 16_u16 + ((c as u16) - (b'0' as u16)),
b'a' | b'A' => n * 16_u16 + 10_u16,
b'b' | b'B' => n * 16_u16 + 11_u16,
@@ -411,7 +418,6 @@ impl<Iter> Deserializer<Iter>
match ch {
b'"' => {
- try!(self.bump());
return Ok(());
}
b'\\' => {
@@ -492,13 +498,10 @@ impl<Iter> Deserializer<Iter>
fn parse_object_colon(&mut self) -> Result<()> {
try!(self.parse_whitespace());
- if self.ch_is(b':') {
- try!(self.bump());
- Ok(())
- } else if self.eof() {
- Err(self.error(ErrorCode::EOFWhileParsingObject))
- } else {
- Err(self.error(ErrorCode::ExpectedColon))
+ match try!(self.next_char()) {
+ Some(b':') => Ok(()),
+ Some(_) => Err(self.error(ErrorCode::ExpectedColon)),
+ None => Err(self.error(ErrorCode::EOFWhileParsingObject)),
}
}
}
@@ -515,24 +518,26 @@ impl<Iter> de::Deserializer for Deserializer<Iter>
self.parse_value(visitor)
}
+ /// Parses a `null` as a None, and any other values as a `Some(...)`.
#[inline]
fn visit_option<V>(&mut self, mut visitor: V) -> Result<V::Value>
where V: de::Visitor,
{
try!(self.parse_whitespace());
- if self.eof() {
- return Err(self.error(ErrorCode::EOFWhileParsingValue));
- }
-
- if self.ch_is(b'n') {
- try!(self.parse_ident(b"ull"));
- visitor.visit_none()
- } else {
- visitor.visit_some(self)
+ match try!(self.peek_or_null()) {
+ b'n' => {
+ self.eat_char();
+ try!(self.parse_ident(b"ull"));
+ visitor.visit_none()
+ }
+ _ => {
+ visitor.visit_some(self)
+ }
}
}
+ /// Parses a newtype struct as the underlying value.
#[inline]
fn visit_newtype_struct<V>(&mut self,
_name: &str,
@@ -542,6 +547,8 @@ impl<Iter> de::Deserializer for Deserializer<Iter>
visitor.visit_newtype_struct(self)
}
+ /// Parses an enum as an object like `{"$KEY":$VALUE}`, where $VALUE is either a straight
+ /// value, a `[..]`, or a `{..}`.
#[inline]
fn visit_enum<V>(&mut self,
_name: &str,
@@ -551,24 +558,28 @@ impl<Iter> de::Deserializer for Deserializer<Iter>
{
try!(self.parse_whitespace());
- if self.ch_is(b'{') {
- try!(self.bump());
- try!(self.parse_whitespace());
+ match try!(self.next_char_or_null()) {
+ b'{' => {
+ try!(self.parse_whitespace());
- let value = {
- try!(visitor.visit(&mut *self))
- };
+ let value = {
+ try!(visitor.visit(&mut *self))
+ };
- try!(self.parse_whitespace());
+ try!(self.parse_whitespace());
- if self.ch_is(b'}') {
- try!(self.bump());
- Ok(value)
- } else {
+ match try!(self.next_char_or_null()) {
+ b'}' => {
+ Ok(value)
+ }
+ _ => {
+ Err(self.error(ErrorCode::ExpectedSomeValue))
+ }
+ }
+ }
+ _ => {
Err(self.error(ErrorCode::ExpectedSomeValue))
}
- } else {
- Err(self.error(ErrorCode::ExpectedSomeValue))
}
}
@@ -602,19 +613,22 @@ impl<'a, Iter> de::SeqVisitor for SeqVisitor<'a, Iter>
{
try!(self.de.parse_whitespace());
- if self.de.ch_is(b']') {
- return Ok(None);
- }
-
- if self.first {
- self.first = false;
- } else {
- if self.de.ch_is(b',') {
- try!(self.de.bump());
- } else if self.de.eof() {
+ match try!(self.de.peek()) {
+ Some(b']') => {
+ return Ok(None);
+ }
+ Some(b',') if !self.first => {
+ self.de.eat_char();
+ }
+ Some(_) => {
+ if self.first {
+ self.first = false;
+ } else {
+ return Err(self.de.error(ErrorCode::ExpectedListCommaOrEnd));
+ }
+ }
+ None => {
return Err(self.de.error(ErrorCode::EOFWhileParsingList));
- } else {
- return Err(self.de.error(ErrorCode::ExpectedListCommaOrEnd));
}
}
@@ -625,12 +639,14 @@ impl<'a, Iter> de::SeqVisitor for SeqVisitor<'a, Iter>
fn end(&mut self) -> Result<()> {
try!(self.de.parse_whitespace());
- if self.de.ch_is(b']') {
- self.de.bump()
- } else if self.de.eof() {
- Err(self.de.error(ErrorCode::EOFWhileParsingList))
- } else {
- Err(self.de.error(ErrorCode::TrailingCharacters))
+ match try!(self.de.next_char()) {
+ Some(b']') => { Ok(()) }
+ Some(_) => {
+ Err(self.de.error(ErrorCode::TrailingCharacters))
+ }
+ None => {
+ Err(self.de.error(ErrorCode::EOFWhileParsingList))
+ }
}
}
}
@@ -659,32 +675,37 @@ impl<'a, Iter> de::MapVisitor for MapVisitor<'a, Iter>
{
try!(self.de.parse_whitespace());
- if self.de.ch_is(b'}') {
- return Ok(None);
- }
-
- if self.first {
- self.first = false;
- } else {
- if self.de.ch_is(b',') {
- try!(self.de.bump());
+ match try!(self.de.peek()) {
+ Some(b'}') => {
+ return Ok(None);
+ }
+ Some(b',') if !self.first => {
+ self.de.eat_char();
try!(self.de.parse_whitespace());
- } else if self.de.eof() {
+ }
+ Some(_) => {
+ if self.first {
+ self.first = false;
+ } else {
+ return Err(self.de.error(ErrorCode::ExpectedObjectCommaOrEnd));
+ }
+ }
+ None => {
return Err(self.de.error(ErrorCode::EOFWhileParsingObject));
- } else {
- return Err(self.de.error(ErrorCode::ExpectedObjectCommaOrEnd));
}
}
- if self.de.eof() {
- return Err(self.de.error(ErrorCode::EOFWhileParsingValue));
- }
-
- if !self.de.ch_is(b'"') {
- return Err(self.de.error(ErrorCode::KeyMustBeAString));
+ match try!(self.de.peek()) {
+ Some(b'"') => {
+ Ok(Some(try!(de::Deserialize::deserialize(self.de))))
+ }
+ Some(_) => {
+ Err(self.de.error(ErrorCode::KeyMustBeAString))
+ }
+ None => {
+ Err(self.de.error(ErrorCode::EOFWhileParsingValue))
+ }
}
-
- Ok(Some(try!(de::Deserialize::deserialize(self.de))))
}
fn visit_value<V>(&mut self) -> Result<V>
@@ -698,13 +719,14 @@ impl<'a, Iter> de::MapVisitor for MapVisitor<'a, Iter>
fn end(&mut self) -> Result<()> {
try!(self.de.parse_whitespace());
- if self.de.ch_is(b'}') {
- try!(self.de.bump());
- Ok(())
- } else if self.de.eof() {
- Err(self.de.error(ErrorCode::EOFWhileParsingObject))
- } else {
- Err(self.de.error(ErrorCode::TrailingCharacters))
+ match try!(self.de.next_char()) {
+ Some(b'}') => { Ok(()) }
+ Some(_) => {
+ Err(self.de.error(ErrorCode::TrailingCharacters))
+ }
+ None => {
+ Err(self.de.error(ErrorCode::EOFWhileParsingObject))
+ }
}
}
@@ -761,7 +783,7 @@ pub fn from_iter<I, T>(iter: I) -> Result<T>
where I: Iterator<Item=io::Result<u8>>,
T: de::Deserialize,
{
- let mut de = try!(Deserializer::new(iter));
+ let mut de = Deserializer::new(iter);
let value = try!(de::Deserialize::deserialize(&mut de));
// Make sure the whole stream has been consumed.
| serde-rs/serde | 2015-08-06T18:12:52Z | Hello @shaladdle! You should be able to directly use `serde::json::de::Deserializer` to do what you want.
Thanks for the response! Sorry for taking a while to reply. I was able to get some time to try again with your suggestion, but I still get the same behavior. The receiver doesn't finish deserialization unless the sender closes the connection. Here's an example:
``` rust
#![feature(custom_derive, plugin)]
#![plugin(serde_macros)]
extern crate serde;
use std::net;
use std::io::Read;
use std::thread;
use serde::Deserialize;
#[derive(Serialize, Deserialize, Debug)]
struct Request {
message: String,
}
#[derive(Serialize, Deserialize, Debug)]
struct Response {
message: String,
}
fn main() {
let l = net::TcpListener::bind("localhost:20000").unwrap();
thread::spawn(||{
let l = l;
for stream in l.incoming() {
let mut stream = stream.unwrap();
let read_stream = stream.try_clone().unwrap();
let mut de = serde::json::Deserializer::new(read_stream.bytes()).unwrap();
println!("deserializing");
let request = Request::deserialize(&mut de).unwrap();
println!("deserialized");
let response = Response{message: request.message};
serde::json::to_writer(&mut stream, &response).unwrap();
}
});
let mut stream = net::TcpStream::connect("localhost:20000").unwrap();
let request = Request{message: "hi there".to_string()};
serde::json::to_writer(&mut stream, &request).unwrap();
println!("message sent");
let mut de = serde::json::Deserializer::new(stream.bytes()).unwrap();
let response = Response::deserialize(&mut de).unwrap();
println!("response: {:?}", response);
}
```
I would expect to see something like the following for output:
```
message sent
deserializing
deserialized
response: "hi there"
```
but it hangs after "deserializing".
There was a strange behavior in `rustc-serialize`, that a just parsed token was not yielded back, because just after successful parsing the decoder has tried to read at least one more byte from the Read.
Try to send over your TCP socket something like this: `{}1`, and if it succeed, then that bug was migrated into this project here.
Ah right. Some of the JSON constructs require looking one character ahead, which could trigger this. Maybe we're doing an unnecessary read? This will require some investigation.
Ok what's going on is that when we parse the end of an object, we call `bump()` [here](https://github.com/serde-rs/serde/blob/master/serde/src/json/de.rs#L472) in order to say we've consumed this character. That function then reads the next character [here](https://github.com/serde-rs/serde/blob/master/serde/src/json/de.rs#L57) to prep for the next token. This character is being stored in an `Option<u8>`, where `None` means that we've read everything from our stream.
It shouldn't be _that_ hard to rewrite the parser to only fetch the next character when it actually needs it, but we'll have to be careful it doesn't impact performance.
| 7b773ac08880adece2f1bd809efcbd5828b23293 |
118 | diff --git a/serde_tests/tests/test_annotations.rs b/serde_tests/tests/test_annotations.rs
index 9a21e0bf7..9c963f8e2 100644
--- a/serde_tests/tests/test_annotations.rs
+++ b/serde_tests/tests/test_annotations.rs
@@ -1,3 +1,4 @@
+use std::default;
use serde_json;
#[derive(Debug, PartialEq, Serialize, Deserialize)]
@@ -30,6 +31,12 @@ enum SerEnum<A> {
},
}
+#[derive(Debug, PartialEq, Deserialize, Serialize)]
+struct SkipSerializingFields<A: default::Default> {
+ a: i8,
+ #[serde(skip_serializing, default)]
+ b: A,
+}
#[test]
fn test_default() {
@@ -71,3 +78,13 @@ fn test_enum_format_rename() {
let deserialized_value = serde_json::from_str(ans).unwrap();
assert_eq!(value, deserialized_value);
}
+
+#[test]
+fn test_skip_serializing_fields() {
+ let value = SkipSerializingFields { a: 1, b: 2 };
+ let serialized_value = serde_json::to_string(&value).unwrap();
+ assert_eq!(serialized_value, "{\"a\":1}");
+
+ let deserialized_value: SkipSerializingFields<_> = serde_json::from_str(&serialized_value).unwrap();
+ assert_eq!(SkipSerializingFields { a: 1, b: 0 }, deserialized_value);
+}
| [
"99"
] | serde-rs__serde-118 | Add annotation that never serializes a particular value
This is particularly useful when a structure contains a non-serializable cached value.
| 0.5 | 447d08bd9121b871ab6d646bdeba66321a948194 | diff --git a/serde_codegen/src/attr.rs b/serde_codegen/src/attr.rs
index 9f08969df..e40155461 100644
--- a/serde_codegen/src/attr.rs
+++ b/serde_codegen/src/attr.rs
@@ -16,14 +16,20 @@ pub enum FieldNames {
/// Represents field attribute information
pub struct FieldAttrs {
+ skip_serializing_field: bool,
names: FieldNames,
use_default: bool,
}
impl FieldAttrs {
/// Create a FieldAttr with a single default field name
- pub fn new(default_value: bool, name: P<ast::Expr>) -> FieldAttrs {
+ pub fn new(
+ skip_serializing_field: bool,
+ default_value: bool,
+ name: P<ast::Expr>,
+ ) -> FieldAttrs {
FieldAttrs {
+ skip_serializing_field: skip_serializing_field,
names: FieldNames::Global(name),
use_default: default_value,
}
@@ -31,12 +37,14 @@ impl FieldAttrs {
/// Create a FieldAttr with format specific field names
pub fn new_with_formats(
+ skip_serializing_field: bool,
default_value: bool,
default_name: P<ast::Expr>,
formats: HashMap<P<ast::Expr>, P<ast::Expr>>,
) -> FieldAttrs {
FieldAttrs {
- names: FieldNames::Format {
+ skip_serializing_field: skip_serializing_field,
+ names: FieldNames::Format {
formats: formats,
default: default_name,
},
@@ -104,4 +112,9 @@ impl FieldAttrs {
pub fn use_default(&self) -> bool {
self.use_default
}
+
+ /// Predicate for ignoring a field when serializing a value
+ pub fn skip_serializing_field(&self) -> bool {
+ self.skip_serializing_field
+ }
}
diff --git a/serde_codegen/src/de.rs b/serde_codegen/src/de.rs
index 3f949df00..f88f72980 100644
--- a/serde_codegen/src/de.rs
+++ b/serde_codegen/src/de.rs
@@ -483,6 +483,7 @@ fn deserialize_item_enum(
enum_def.variants.iter()
.map(|variant|
attr::FieldAttrs::new(
+ false,
true,
builder.expr().str(variant.node.name)))
.collect()
diff --git a/serde_codegen/src/field.rs b/serde_codegen/src/field.rs
index 676e6cb71..6f10eacfb 100644
--- a/serde_codegen/src/field.rs
+++ b/serde_codegen/src/field.rs
@@ -58,10 +58,18 @@ fn default_value(mi: &ast::MetaItem) -> bool {
}
}
+fn skip_serializing_field(mi: &ast::MetaItem) -> bool {
+ if let ast::MetaItem_::MetaWord(ref n) = mi.node {
+ n == &"skip_serializing"
+ } else {
+ false
+ }
+}
+
fn field_attrs<'a>(
builder: &aster::AstBuilder,
field: &'a ast::StructField,
-) -> (Rename<'a>, bool) {
+) -> (Rename<'a>, bool, bool) {
field.node.attrs.iter()
.find(|sa| {
if let ast::MetaList(ref n, _) = sa.node.value.node {
@@ -73,15 +81,18 @@ fn field_attrs<'a>(
.and_then(|sa| {
if let ast::MetaList(_, ref vals) = sa.node.value.node {
attr::mark_used(&sa);
- Some((vals.iter()
- .fold(None, |v, mi| v.or(rename(builder, mi)))
- .unwrap_or(Rename::None),
- vals.iter().any(|mi| default_value(mi))))
+ Some((
+ vals.iter()
+ .fold(None, |v, mi| v.or(rename(builder, mi)))
+ .unwrap_or(Rename::None),
+ vals.iter().any(|mi| default_value(mi)),
+ vals.iter().any(|mi| skip_serializing_field(mi)),
+ ))
} else {
- Some((Rename::None, false))
+ Some((Rename::None, false, false))
}
})
- .unwrap_or((Rename::None, false))
+ .unwrap_or((Rename::None, false, false))
}
pub fn struct_field_attrs(
@@ -92,23 +103,26 @@ pub fn struct_field_attrs(
struct_def.fields.iter()
.map(|field| {
match field_attrs(builder, field) {
- (Rename::Global(rename), default_value) =>
+ (Rename::Global(rename), default_value, skip_serializing_field) =>
FieldAttrs::new(
+ skip_serializing_field,
default_value,
builder.expr().build_lit(P(rename.clone()))),
- (Rename::Format(renames), default_value) => {
+ (Rename::Format(renames), default_value, skip_serializing_field) => {
let mut res = HashMap::new();
res.extend(
renames.into_iter()
.map(|(k,v)|
(k, builder.expr().build_lit(P(v.clone())))));
FieldAttrs::new_with_formats(
+ skip_serializing_field,
default_value,
default_field_name(cx, builder, field.node.kind),
res)
},
- (Rename::None, default_value) => {
+ (Rename::None, default_value, skip_serializing_field) => {
FieldAttrs::new(
+ skip_serializing_field,
default_value,
default_field_name(cx, builder, field.node.kind))
}
diff --git a/serde_codegen/src/ser.rs b/serde_codegen/src/ser.rs
index 8c74e1199..ab4f21ea3 100644
--- a/serde_codegen/src/ser.rs
+++ b/serde_codegen/src/ser.rs
@@ -550,6 +550,7 @@ fn serialize_struct_visitor<I>(
let arms: Vec<ast::Arm> = field_attrs.into_iter()
.zip(value_exprs)
+ .filter(|&(ref field, _)| !field.skip_serializing_field())
.enumerate()
.map(|(i, (field, value_expr))| {
let key_expr = field.serializer_key_expr(cx);
| serde-rs/serde | 2015-07-23T15:09:37Z | 7b773ac08880adece2f1bd809efcbd5828b23293 | |
117 | diff --git a/serde_tests/tests/test_macros.rs b/serde_tests/tests/test_macros.rs
index d7af98557..3c41ca4c7 100644
--- a/serde_tests/tests/test_macros.rs
+++ b/serde_tests/tests/test_macros.rs
@@ -131,6 +131,26 @@ enum Lifetimes<'a> {
NoLifetimeMap { a: i32 },
}
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
+pub struct GenericStruct<T> {
+ x: T,
+}
+
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
+pub struct GenericTupleStruct<T>(T);
+
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
+pub enum GenericEnumSeq<T, E> {
+ Ok(T),
+ Err(E),
+}
+
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
+pub enum GenericEnumMap<T, E> {
+ Ok { x: T },
+ Err { x: E },
+}
+
#[test]
fn test_named_unit() {
let named_unit = NamedUnit;
@@ -475,3 +495,29 @@ fn test_lifetimes() {
"{\"NoLifetimeMap\":{\"a\":5}}"
);
}
+
+#[test]
+fn test_generic() {
+ macro_rules! declare_tests {
+ ($($ty:ty : $value:expr => $str:expr,)+) => {
+ $({
+ let value: $ty = $value;
+
+ let string = serde_json::to_string(&value).unwrap();
+ assert_eq!(string, $str);
+
+ let expected: $ty = serde_json::from_str(&string).unwrap();
+ assert_eq!(value, expected);
+ })+
+ }
+ }
+
+ declare_tests!(
+ GenericStruct<u32> : GenericStruct { x: 5 } => "{\"x\":5}",
+ GenericTupleStruct<u32> : GenericTupleStruct(5) => "[5]",
+ GenericEnumSeq<u32, u32> : GenericEnumSeq::Ok(5) => "{\"Ok\":[5]}",
+ GenericEnumSeq<u32, u32> : GenericEnumSeq::Err(5) => "{\"Err\":[5]}",
+ GenericEnumMap<u32, u32> : GenericEnumMap::Ok { x: 5 } => "{\"Ok\":{\"x\":5}}",
+ GenericEnumMap<u32, u32> : GenericEnumMap::Err { x: 5 } => "{\"Err\":{\"x\":5}}",
+ );
+}
| [
"100"
] | serde-rs__serde-117 | #[derive(Serialize)] causes type errors when used on a generic enum
STR:
```
#[derive(Serialize)]
pub enum SerializableResult<T,E> {
Ok(T),
Err(E),
}
```
| 0.5 | 8663435a05d004ed982599ffbf72c875c4e08420 | diff --git a/serde_codegen/src/ser.rs b/serde_codegen/src/ser.rs
index ec8c6ccdc..8c74e1199 100644
--- a/serde_codegen/src/ser.rs
+++ b/serde_codegen/src/ser.rs
@@ -55,10 +55,7 @@ pub fn expand_derive_serialize(
&builder,
&item,
&impl_generics,
- builder.ty()
- .ref_()
- .lifetime("'__a")
- .build_ty(ty.clone()),
+ ty.clone(),
);
let where_clause = &impl_generics.where_clause;
@@ -184,7 +181,10 @@ fn serialize_tuple_struct(
cx,
builder,
ty.clone(),
- ty,
+ builder.ty()
+ .ref_()
+ .lifetime("'__a")
+ .build_ty(ty.clone()),
fields,
impl_generics,
);
@@ -197,7 +197,7 @@ fn serialize_tuple_struct(
serializer.visit_tuple_struct($type_name, Visitor {
value: self,
state: 0,
- _structure_ty: ::std::marker::PhantomData,
+ _structure_ty: ::std::marker::PhantomData::<&$ty>,
})
})
}
@@ -215,7 +215,10 @@ fn serialize_struct(
cx,
builder,
ty.clone(),
- ty,
+ builder.ty()
+ .ref_()
+ .lifetime("'__a")
+ .build_ty(ty.clone()),
struct_def,
impl_generics,
fields.iter().map(|field| quote_expr!(cx, &self.value.$field)),
@@ -229,7 +232,7 @@ fn serialize_struct(
serializer.visit_struct($type_name, Visitor {
value: self,
state: 0,
- _structure_ty: ::std::marker::PhantomData,
+ _structure_ty: ::std::marker::PhantomData::<&$ty>,
})
})
}
@@ -383,7 +386,7 @@ fn serialize_tuple_variant(
let (visitor_struct, visitor_impl) = serialize_tuple_struct_visitor(
cx,
builder,
- structure_ty,
+ structure_ty.clone(),
variant_ty,
args.len(),
generics,
@@ -392,9 +395,7 @@ fn serialize_tuple_variant(
let value_expr = builder.expr().tuple()
.with_exprs(
fields.iter().map(|field| {
- builder.expr()
- .addr_of()
- .id(field)
+ builder.expr().id(field)
})
)
.build();
@@ -405,7 +406,7 @@ fn serialize_tuple_variant(
serializer.visit_enum_seq($type_name, $variant_index, $variant_name, Visitor {
value: $value_expr,
state: 0,
- _structure_ty: ::std::marker::PhantomData,
+ _structure_ty: ::std::marker::PhantomData::<&$structure_ty>,
})
})
}
@@ -435,9 +436,7 @@ fn serialize_struct_variant(
let value_expr = builder.expr().tuple()
.with_exprs(
fields.iter().map(|field| {
- builder.expr()
- .addr_of()
- .id(field)
+ builder.expr().id(field)
})
)
.build();
@@ -445,7 +444,7 @@ fn serialize_struct_variant(
let (visitor_struct, visitor_impl) = serialize_struct_visitor(
cx,
builder,
- structure_ty,
+ structure_ty.clone(),
value_ty,
struct_def,
generics,
@@ -462,7 +461,7 @@ fn serialize_struct_variant(
serializer.visit_enum_map($type_name, $variant_index, $variant_name, Visitor {
value: $value_expr,
state: 0,
- _structure_ty: ::std::marker::PhantomData,
+ _structure_ty: ::std::marker::PhantomData::<&$structure_ty>,
})
})
}
@@ -502,19 +501,12 @@ fn serialize_tuple_struct_visitor(
.strip_bounds()
.build();
- // Variants don't necessarily reference all generic lifetimes and type parameters,
- // so to avoid a compilation failure, we'll just add a phantom type to capture these
- // unused values.
- let structure_ty = builder.ty()
- .phantom_data()
- .build(structure_ty);
-
(
quote_item!(cx,
struct Visitor $visitor_impl_generics $where_clause {
state: usize,
value: $variant_ty,
- _structure_ty: $structure_ty,
+ _structure_ty: ::std::marker::PhantomData<&'__a $structure_ty>,
}
).unwrap(),
@@ -590,19 +582,12 @@ fn serialize_struct_visitor<I>(
.strip_bounds()
.build();
- // Variants don't necessarily reference all generic lifetimes and type parameters,
- // so to avoid a compilation failure, we'll just add a phantom type to capture these
- // unused values.
- let structure_ty = builder.ty()
- .phantom_data()
- .build(structure_ty);
-
(
quote_item!(cx,
struct Visitor $visitor_impl_generics $where_clause {
state: usize,
value: $variant_ty,
- _structure_ty: $structure_ty,
+ _structure_ty: ::std::marker::PhantomData<&'__a $structure_ty>,
}
).unwrap(),
| serde-rs/serde | 2015-07-23T13:59:29Z | 7b773ac08880adece2f1bd809efcbd5828b23293 | |
115 | diff --git a/serde_tests/tests/test_json.rs b/serde_tests/tests/test_json.rs
index c29f82865..370632b14 100644
--- a/serde_tests/tests/test_json.rs
+++ b/serde_tests/tests/test_json.rs
@@ -1,5 +1,6 @@
-use std::fmt::Debug;
use std::collections::BTreeMap;
+use std::fmt::Debug;
+use std::marker::PhantomData;
use serde::de;
use serde::ser;
@@ -1079,3 +1080,174 @@ fn test_lookup() {
assert!(obj.lookup("y").unwrap() == &Value::U64(2));
assert!(obj.lookup("z").is_none());
}
+
+#[test]
+fn test_serialize_seq_with_no_len() {
+ #[derive(Clone, Debug, PartialEq)]
+ struct MyVec<T>(Vec<T>);
+
+ impl<T> ser::Serialize for MyVec<T>
+ where T: ser::Serialize,
+ {
+ #[inline]
+ fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ where S: ser::Serializer,
+ {
+ serializer.visit_seq(ser::impls::SeqIteratorVisitor::new(self.0.iter(), None))
+ }
+ }
+
+ struct Visitor<T> {
+ marker: PhantomData<MyVec<T>>,
+ }
+
+ impl<T> de::Visitor for Visitor<T>
+ where T: de::Deserialize,
+ {
+ type Value = MyVec<T>;
+
+ #[inline]
+ fn visit_unit<E>(&mut self) -> Result<MyVec<T>, E>
+ where E: de::Error,
+ {
+ Ok(MyVec(Vec::new()))
+ }
+
+ #[inline]
+ fn visit_seq<V>(&mut self, mut visitor: V) -> Result<MyVec<T>, V::Error>
+ where V: de::SeqVisitor,
+ {
+ let mut values = Vec::new();
+
+ while let Some(value) = try!(visitor.visit()) {
+ values.push(value);
+ }
+
+ try!(visitor.end());
+
+ Ok(MyVec(values))
+ }
+ }
+
+ impl<T> de::Deserialize for MyVec<T>
+ where T: de::Deserialize,
+ {
+ fn deserialize<D>(deserializer: &mut D) -> Result<MyVec<T>, D::Error>
+ where D: de::Deserializer,
+ {
+ deserializer.visit_map(Visitor { marker: PhantomData })
+ }
+ }
+
+ let mut vec = Vec::new();
+ vec.push(MyVec(Vec::new()));
+ vec.push(MyVec(Vec::new()));
+ let vec: MyVec<MyVec<u32>> = MyVec(vec);
+
+ test_encode_ok(&[
+ (
+ vec.clone(),
+ "[[],[]]",
+ ),
+ ]);
+
+ let s = json::to_string_pretty(&vec).unwrap();
+ assert_eq!(
+ s,
+ concat!(
+ "[\n",
+ " [\n",
+ " ],\n",
+ " [\n",
+ " ]\n",
+ "]"
+ )
+ );
+}
+
+#[test]
+fn test_serialize_map_with_no_len() {
+ #[derive(Clone, Debug, PartialEq)]
+ struct Map<K, V>(BTreeMap<K, V>);
+
+ impl<K, V> ser::Serialize for Map<K, V>
+ where K: ser::Serialize + Ord,
+ V: ser::Serialize,
+ {
+ #[inline]
+ fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ where S: ser::Serializer,
+ {
+ serializer.visit_map(ser::impls::MapIteratorVisitor::new(self.0.iter(), None))
+ }
+ }
+
+ struct Visitor<K, V> {
+ marker: PhantomData<Map<K, V>>,
+ }
+
+ impl<K, V> de::Visitor for Visitor<K, V>
+ where K: de::Deserialize + Eq + Ord,
+ V: de::Deserialize,
+ {
+ type Value = Map<K, V>;
+
+ #[inline]
+ fn visit_unit<E>(&mut self) -> Result<Map<K, V>, E>
+ where E: de::Error,
+ {
+ Ok(Map(BTreeMap::new()))
+ }
+
+ #[inline]
+ fn visit_map<Visitor>(&mut self, mut visitor: Visitor) -> Result<Map<K, V>, Visitor::Error>
+ where Visitor: de::MapVisitor,
+ {
+ let mut values = BTreeMap::new();
+
+ while let Some((key, value)) = try!(visitor.visit()) {
+ values.insert(key, value);
+ }
+
+ try!(visitor.end());
+
+ Ok(Map(values))
+ }
+ }
+
+ impl<K, V> de::Deserialize for Map<K, V>
+ where K: de::Deserialize + Eq + Ord,
+ V: de::Deserialize,
+ {
+ fn deserialize<D>(deserializer: &mut D) -> Result<Map<K, V>, D::Error>
+ where D: de::Deserializer,
+ {
+ deserializer.visit_map(Visitor { marker: PhantomData })
+ }
+ }
+
+ let mut map = BTreeMap::new();
+ map.insert("a", Map(BTreeMap::new()));
+ map.insert("b", Map(BTreeMap::new()));
+ let map: Map<_, Map<u32, u32>> = Map(map);
+
+ test_encode_ok(&[
+ (
+ map.clone(),
+ "{\"a\":{},\"b\":{}}",
+ ),
+ ]);
+
+ let s = json::to_string_pretty(&map).unwrap();
+ assert_eq!(
+ s,
+ concat!(
+ "{\n",
+ " \"a\": {\n",
+ " },\n",
+ " \"b\": {\n",
+ " }\n",
+ "}"
+ )
+ );
+}
| [
"101"
] | serde-rs__serde-115 | Incorrect JSON is generated when serializing an empty map with no up-front size provided
It'll generate things like `{"foo":{}"bar":{}}` (note no comma between `{}` and `"bar"`), which causes errors in deserialization. Supplying up-front sizes to all maps in the serialization code works around the problem.
| 0.4 | b2754c2c3bb9cae4ae7dc1d4ce5aa1275dc45dd4 | diff --git a/serde/src/json/ser.rs b/serde/src/json/ser.rs
index deaace30a..8c05948bc 100644
--- a/serde/src/json/ser.rs
+++ b/serde/src/json/ser.rs
@@ -206,9 +206,11 @@ impl<W, F> ser::Serializer for Serializer<W, F>
where T: ser::Serialize,
{
try!(self.formatter.comma(&mut self.writer, self.first));
+ try!(value.serialize(self));
+
self.first = false;
- value.serialize(self)
+ Ok(())
}
#[inline]
@@ -250,11 +252,14 @@ impl<W, F> ser::Serializer for Serializer<W, F>
V: ser::Serialize,
{
try!(self.formatter.comma(&mut self.writer, self.first));
- self.first = false;
try!(key.serialize(self));
try!(self.formatter.colon(&mut self.writer));
- value.serialize(self)
+ try!(value.serialize(self));
+
+ self.first = false;
+
+ Ok(())
}
#[inline]
| serde-rs/serde | 2015-07-22T16:49:46Z | b2754c2c3bb9cae4ae7dc1d4ce5aa1275dc45dd4 | |
114 | diff --git a/serde_macros/tests/test.rs b/serde_macros/tests/test.rs
index fd353e1b3..7e98981cf 100644
--- a/serde_macros/tests/test.rs
+++ b/serde_macros/tests/test.rs
@@ -2,6 +2,7 @@
#![plugin(serde_macros)]
extern crate serde;
+extern crate serde_json;
extern crate test;
include!("../../serde_tests/tests/test.rs.in");
diff --git a/serde_tests/Cargo.toml b/serde_tests/Cargo.toml
index 461ce3631..2fdf55101 100644
--- a/serde_tests/Cargo.toml
+++ b/serde_tests/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_tests"
-version = "0.4.3"
+version = "0.5.0"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "A generic serialization/deserialization framework"
@@ -19,6 +19,7 @@ serde_codegen = { version = "*", path = "../serde_codegen", features = ["with-sy
num = "*"
rustc-serialize = "*"
serde = { version = "*", path = "../serde" }
+serde_json = { version = "*", path = "../serde_json" }
syntex = "*"
[[test]]
diff --git a/serde_tests/benches/bench.rs b/serde_tests/benches/bench.rs
index 181c4c616..7cc2fc324 100644
--- a/serde_tests/benches/bench.rs
+++ b/serde_tests/benches/bench.rs
@@ -3,6 +3,7 @@
extern crate num;
extern crate rustc_serialize;
extern crate serde;
+extern crate serde_json;
extern crate test;
include!(concat!(env!("OUT_DIR"), "/bench.rs"));
diff --git a/serde_tests/benches/bench_log.rs b/serde_tests/benches/bench_log.rs
index 925b03ed2..4fa108da5 100644
--- a/serde_tests/benches/bench_log.rs
+++ b/serde_tests/benches/bench_log.rs
@@ -5,9 +5,9 @@ use test::Bencher;
use rustc_serialize;
use serde::de::{self, Deserialize, Deserializer};
-use serde::json::ser::escape_str;
-use serde::json;
use serde::ser::{self, Serialize, Serializer};
+use serde_json::ser::escape_str;
+use serde_json;
use std::str::FromStr;
use rustc_serialize::Encodable;
@@ -1123,18 +1123,18 @@ fn bench_encoder(b: &mut Bencher) {
#[test]
fn test_serializer() {
let log = Log::new();
- let json = json::to_vec(&log);
+ let json = serde_json::to_vec(&log);
assert_eq!(json, JSON_STR.as_bytes());
}
#[bench]
fn bench_serializer(b: &mut Bencher) {
let log = Log::new();
- let json = json::to_vec(&log);
+ let json = serde_json::to_vec(&log);
b.bytes = json.len() as u64;
b.iter(|| {
- let _ = json::to_vec(&log);
+ let _ = serde_json::to_vec(&log);
});
}
@@ -1142,7 +1142,7 @@ fn bench_serializer(b: &mut Bencher) {
fn test_serializer_vec() {
let log = Log::new();
let wr = Vec::with_capacity(1024);
- let mut serializer = json::Serializer::new(wr);
+ let mut serializer = serde_json::Serializer::new(wr);
log.serialize(&mut serializer).unwrap();
let json = serializer.into_inner();
@@ -1152,7 +1152,7 @@ fn test_serializer_vec() {
#[bench]
fn bench_serializer_vec(b: &mut Bencher) {
let log = Log::new();
- let json = json::to_vec(&log);
+ let json = serde_json::to_vec(&log);
b.bytes = json.len() as u64;
let mut wr = Vec::with_capacity(1024);
@@ -1160,7 +1160,7 @@ fn bench_serializer_vec(b: &mut Bencher) {
b.iter(|| {
wr.clear();
- let mut serializer = json::Serializer::new(wr.by_ref());
+ let mut serializer = serde_json::Serializer::new(wr.by_ref());
log.serialize(&mut serializer).unwrap();
let _json = serializer.into_inner();
});
@@ -1169,7 +1169,7 @@ fn bench_serializer_vec(b: &mut Bencher) {
#[bench]
fn bench_serializer_slice(b: &mut Bencher) {
let log = Log::new();
- let json = json::to_vec(&log);
+ let json = serde_json::to_vec(&log);
b.bytes = json.len() as u64;
let mut buf = [0; 1024];
@@ -1178,7 +1178,7 @@ fn bench_serializer_slice(b: &mut Bencher) {
for item in buf.iter_mut(){ *item = 0; }
let mut wr = &mut buf[..];
- let mut serializer = json::Serializer::new(wr.by_ref());
+ let mut serializer = serde_json::Serializer::new(wr.by_ref());
log.serialize(&mut serializer).unwrap();
let _json = serializer.into_inner();
});
@@ -1191,7 +1191,7 @@ fn test_serializer_my_mem_writer0() {
let mut wr = MyMemWriter0::with_capacity(1024);
{
- let mut serializer = json::Serializer::new(wr.by_ref());
+ let mut serializer = serde_json::Serializer::new(wr.by_ref());
log.serialize(&mut serializer).unwrap();
let _json = serializer.into_inner();
}
@@ -1202,7 +1202,7 @@ fn test_serializer_my_mem_writer0() {
#[bench]
fn bench_serializer_my_mem_writer0(b: &mut Bencher) {
let log = Log::new();
- let json = json::to_vec(&log);
+ let json = serde_json::to_vec(&log);
b.bytes = json.len() as u64;
let mut wr = MyMemWriter0::with_capacity(1024);
@@ -1210,7 +1210,7 @@ fn bench_serializer_my_mem_writer0(b: &mut Bencher) {
b.iter(|| {
wr.buf.clear();
- let mut serializer = json::Serializer::new(wr.by_ref());
+ let mut serializer = serde_json::Serializer::new(wr.by_ref());
log.serialize(&mut serializer).unwrap();
let _json = serializer.into_inner();
});
@@ -1223,7 +1223,7 @@ fn test_serializer_my_mem_writer1() {
let mut wr = MyMemWriter1::with_capacity(1024);
{
- let mut serializer = json::Serializer::new(wr.by_ref());
+ let mut serializer = serde_json::Serializer::new(wr.by_ref());
log.serialize(&mut serializer).unwrap();
let _json = serializer.into_inner();
}
@@ -1234,7 +1234,7 @@ fn test_serializer_my_mem_writer1() {
#[bench]
fn bench_serializer_my_mem_writer1(b: &mut Bencher) {
let log = Log::new();
- let json = json::to_vec(&log);
+ let json = serde_json::to_vec(&log);
b.bytes = json.len() as u64;
let mut wr = MyMemWriter1::with_capacity(1024);
@@ -1242,7 +1242,7 @@ fn bench_serializer_my_mem_writer1(b: &mut Bencher) {
b.iter(|| {
wr.buf.clear();
- let mut serializer = json::Serializer::new(wr.by_ref());
+ let mut serializer = serde_json::Serializer::new(wr.by_ref());
log.serialize(&mut serializer).unwrap();
let _json = serializer.into_inner();
});
@@ -1593,6 +1593,6 @@ fn bench_deserializer(b: &mut Bencher) {
b.bytes = JSON_STR.len() as u64;
b.iter(|| {
- let _log: Log = json::from_str(JSON_STR).unwrap();
+ let _log: Log = serde_json::from_str(JSON_STR).unwrap();
});
}
diff --git a/serde_tests/benches/bench_struct.rs b/serde_tests/benches/bench_struct.rs
index fd52097b9..6c76eaef2 100644
--- a/serde_tests/benches/bench_struct.rs
+++ b/serde_tests/benches/bench_struct.rs
@@ -398,7 +398,10 @@ mod deserializer {
}
}
- fn visit_named_map<V>(&mut self, name: &str, mut visitor: V) -> Result<V::Value, Error>
+ fn visit_struct<V>(&mut self,
+ name: &str,
+ _fields: &'static [&'static str],
+ mut visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
match self.stack.pop() {
diff --git a/serde_tests/tests/test.rs b/serde_tests/tests/test.rs
index 732c14329..933c6b850 100644
--- a/serde_tests/tests/test.rs
+++ b/serde_tests/tests/test.rs
@@ -1,3 +1,4 @@
extern crate serde;
+extern crate serde_json;
include!(concat!(env!("OUT_DIR"), "/test.rs"));
diff --git a/serde_tests/tests/test_annotations.rs b/serde_tests/tests/test_annotations.rs
index 37746ae5b..9a21e0bf7 100644
--- a/serde_tests/tests/test_annotations.rs
+++ b/serde_tests/tests/test_annotations.rs
@@ -1,4 +1,4 @@
-use serde::json;
+use serde_json;
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Default {
@@ -33,30 +33,30 @@ enum SerEnum<A> {
#[test]
fn test_default() {
- let deserialized_value: Default = json::from_str(&"{\"a1\":1,\"a2\":2}").unwrap();
+ let deserialized_value: Default = serde_json::from_str(&"{\"a1\":1,\"a2\":2}").unwrap();
assert_eq!(deserialized_value, Default { a1: 1, a2: 2 });
- let deserialized_value: Default = json::from_str(&"{\"a1\":1}").unwrap();
+ let deserialized_value: Default = serde_json::from_str(&"{\"a1\":1}").unwrap();
assert_eq!(deserialized_value, Default { a1: 1, a2: 0 });
}
#[test]
fn test_rename() {
let value = Rename { a1: 1, a2: 2 };
- let serialized_value = json::to_string(&value).unwrap();
+ let serialized_value = serde_json::to_string(&value).unwrap();
assert_eq!(serialized_value, "{\"a1\":1,\"a3\":2}");
- let deserialized_value: Rename = json::from_str(&serialized_value).unwrap();
+ let deserialized_value: Rename = serde_json::from_str(&serialized_value).unwrap();
assert_eq!(value, deserialized_value);
}
#[test]
fn test_format_rename() {
let value = FormatRename { a1: 1, a2: 2 };
- let serialized_value = json::to_string(&value).unwrap();
+ let serialized_value = serde_json::to_string(&value).unwrap();
assert_eq!(serialized_value, "{\"a1\":1,\"a5\":2}");
- let deserialized_value = json::from_str("{\"a1\":1,\"a5\":2}").unwrap();
+ let deserialized_value = serde_json::from_str("{\"a1\":1,\"a5\":2}").unwrap();
assert_eq!(value, deserialized_value);
}
@@ -64,10 +64,10 @@ fn test_format_rename() {
fn test_enum_format_rename() {
let s1 = String::new();
let value = SerEnum::Map { a: 0i8, b: s1 };
- let serialized_value = json::to_string(&value).unwrap();
+ let serialized_value = serde_json::to_string(&value).unwrap();
let ans = "{\"Map\":{\"a\":0,\"d\":\"\"}}";
assert_eq!(serialized_value, ans);
- let deserialized_value = json::from_str(ans).unwrap();
+ let deserialized_value = serde_json::from_str(ans).unwrap();
assert_eq!(value, deserialized_value);
}
diff --git a/serde_tests/tests/test_bytes.rs b/serde_tests/tests/test_bytes.rs
index a72cf1ae2..3ca97285a 100644
--- a/serde_tests/tests/test_bytes.rs
+++ b/serde_tests/tests/test_bytes.rs
@@ -1,7 +1,7 @@
use serde;
use serde::Serialize;
use serde::bytes::{ByteBuf, Bytes};
-use serde::json;
+use serde_json;
///////////////////////////////////////////////////////////////////////////////
@@ -144,11 +144,11 @@ impl serde::Deserializer for BytesDeserializer {
fn test_bytes_ser_json() {
let buf = vec![];
let bytes = Bytes::from(&buf);
- assert_eq!(json::to_string(&bytes).unwrap(), "[]".to_string());
+ assert_eq!(serde_json::to_string(&bytes).unwrap(), "[]".to_string());
let buf = vec![1, 2, 3];
let bytes = Bytes::from(&buf);
- assert_eq!(json::to_string(&bytes).unwrap(), "[1,2,3]".to_string());
+ assert_eq!(serde_json::to_string(&bytes).unwrap(), "[1,2,3]".to_string());
}
#[test]
@@ -167,10 +167,10 @@ fn test_bytes_ser_bytes() {
#[test]
fn test_byte_buf_ser_json() {
let bytes = ByteBuf::new();
- assert_eq!(json::to_string(&bytes).unwrap(), "[]".to_string());
+ assert_eq!(serde_json::to_string(&bytes).unwrap(), "[]".to_string());
let bytes = ByteBuf::from(vec![1, 2, 3]);
- assert_eq!(json::to_string(&bytes).unwrap(), "[1,2,3]".to_string());
+ assert_eq!(serde_json::to_string(&bytes).unwrap(), "[1,2,3]".to_string());
}
#[test]
@@ -189,11 +189,11 @@ fn test_byte_buf_ser_bytes() {
#[test]
fn test_byte_buf_de_json() {
let bytes = ByteBuf::new();
- let v: ByteBuf = json::from_str("[]").unwrap();
+ let v: ByteBuf = serde_json::from_str("[]").unwrap();
assert_eq!(v, bytes);
let bytes = ByteBuf::from(vec![1, 2, 3]);
- let v: ByteBuf = json::from_str("[1, 2, 3]").unwrap();
+ let v: ByteBuf = serde_json::from_str("[1, 2, 3]").unwrap();
assert_eq!(v, bytes);
}
diff --git a/serde_tests/tests/test_de.rs b/serde_tests/tests/test_de.rs
index 7e1f2d986..9b789c84b 100644
--- a/serde_tests/tests/test_de.rs
+++ b/serde_tests/tests/test_de.rs
@@ -161,7 +161,7 @@ impl Deserializer for TokenDeserializer {
}
}
- fn visit_named_unit<V>(&mut self, name: &str, visitor: V) -> Result<V::Value, Error>
+ fn visit_unit_struct<V>(&mut self, name: &str, visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
match self.tokens.peek() {
@@ -178,7 +178,7 @@ impl Deserializer for TokenDeserializer {
}
}
- fn visit_named_seq<V>(&mut self, name: &str, visitor: V) -> Result<V::Value, Error>
+ fn visit_tuple_struct<V>(&mut self, name: &str, visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
match self.tokens.peek() {
@@ -195,7 +195,10 @@ impl Deserializer for TokenDeserializer {
}
}
- fn visit_named_map<V>(&mut self, name: &str, visitor: V) -> Result<V::Value, Error>
+ fn visit_struct<V>(&mut self,
+ name: &str,
+ _fields: &'static [&'static str],
+ visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
match self.tokens.peek() {
@@ -324,7 +327,9 @@ impl<'a> de::VariantVisitor for TokenDeserializerVariantVisitor<'a> {
de::Deserializer::visit(self.de, visitor)
}
- fn visit_map<V>(&mut self, visitor: V) -> Result<V::Value, Error>
+ fn visit_map<V>(&mut self,
+ _fields: &'static [&'static str],
+ visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
de::Deserializer::visit(self.de, visitor)
@@ -334,13 +339,13 @@ impl<'a> de::VariantVisitor for TokenDeserializerVariantVisitor<'a> {
//////////////////////////////////////////////////////////////////////////
#[derive(Copy, Clone, PartialEq, Debug, Deserialize)]
-struct NamedUnit;
+struct UnitStruct;
#[derive(PartialEq, Debug, Deserialize)]
-struct NamedSeq(i32, i32, i32);
+struct TupleStruct(i32, i32, i32);
#[derive(PartialEq, Debug, Deserialize)]
-struct NamedMap {
+struct Struct {
a: i32,
b: i32,
c: i32,
@@ -486,6 +491,26 @@ declare_tests! {
Token::I32(1),
],
}
+ test_result {
+ Ok::<i32, i32>(0) => vec![
+ Token::EnumStart("Result"),
+ Token::Str("Ok"),
+ Token::SeqStart(1),
+ Token::SeqSep,
+ Token::I32(0),
+ Token::SeqEnd,
+ Token::EnumEnd,
+ ],
+ Err::<i32, i32>(1) => vec![
+ Token::EnumStart("Result"),
+ Token::Str("Err"),
+ Token::SeqStart(1),
+ Token::SeqSep,
+ Token::I32(1),
+ Token::SeqEnd,
+ Token::EnumEnd,
+ ],
+ }
test_unit {
() => vec![Token::Unit],
() => vec![
@@ -498,19 +523,19 @@ declare_tests! {
Token::SeqEnd,
],
}
- test_named_unit {
- NamedUnit => vec![Token::Unit],
- NamedUnit => vec![
- Token::Name("NamedUnit"),
+ test_unit_struct {
+ UnitStruct => vec![Token::Unit],
+ UnitStruct => vec![
+ Token::Name("UnitStruct"),
Token::Unit,
],
- NamedUnit => vec![
+ UnitStruct => vec![
Token::SeqStart(0),
Token::SeqEnd,
],
}
- test_named_seq {
- NamedSeq(1, 2, 3) => vec![
+ test_tuple_struct {
+ TupleStruct(1, 2, 3) => vec![
Token::SeqStart(3),
Token::SeqSep,
Token::I32(1),
@@ -522,8 +547,8 @@ declare_tests! {
Token::I32(3),
Token::SeqEnd,
],
- NamedSeq(1, 2, 3) => vec![
- Token::Name("NamedSeq"),
+ TupleStruct(1, 2, 3) => vec![
+ Token::Name("TupleStruct"),
Token::SeqStart(3),
Token::SeqSep,
Token::I32(1),
@@ -818,8 +843,8 @@ declare_tests! {
Token::MapEnd,
],
}
- test_named_map {
- NamedMap { a: 1, b: 2, c: 3 } => vec![
+ test_struct {
+ Struct { a: 1, b: 2, c: 3 } => vec![
Token::MapStart(3),
Token::MapSep,
Token::Str("a"),
@@ -834,8 +859,8 @@ declare_tests! {
Token::I32(3),
Token::MapEnd,
],
- NamedMap { a: 1, b: 2, c: 3 } => vec![
- Token::Name("NamedMap"),
+ Struct { a: 1, b: 2, c: 3 } => vec![
+ Token::Name("Struct"),
Token::MapStart(3),
Token::MapSep,
Token::Str("a"),
diff --git a/serde_tests/tests/test_json.rs b/serde_tests/tests/test_json.rs
index c29f82865..931527e97 100644
--- a/serde_tests/tests/test_json.rs
+++ b/serde_tests/tests/test_json.rs
@@ -1,10 +1,11 @@
-use std::fmt::Debug;
use std::collections::BTreeMap;
+use std::fmt::Debug;
+use std::marker::PhantomData;
use serde::de;
use serde::ser;
-use serde::json::{
+use serde_json::{
self,
Value,
from_str,
@@ -12,7 +13,7 @@ use serde::json::{
to_value,
};
-use serde::json::error::{Error, ErrorCode};
+use serde_json::error::{Error, ErrorCode};
macro_rules! treemap {
($($k:expr => $v:expr),*) => ({
@@ -48,11 +49,11 @@ fn test_encode_ok<T>(errors: &[(T, &str)])
for &(ref value, out) in errors {
let out = out.to_string();
- let s = json::to_string(value).unwrap();
+ let s = serde_json::to_string(value).unwrap();
assert_eq!(s, out);
let v = to_value(&value);
- let s = json::to_string(&v).unwrap();
+ let s = serde_json::to_string(&v).unwrap();
assert_eq!(s, out);
}
}
@@ -63,11 +64,11 @@ fn test_pretty_encode_ok<T>(errors: &[(T, &str)])
for &(ref value, out) in errors {
let out = out.to_string();
- let s = json::to_string_pretty(value).unwrap();
+ let s = serde_json::to_string_pretty(value).unwrap();
assert_eq!(s, out);
let v = to_value(&value);
- let s = json::to_string_pretty(&v).unwrap();
+ let s = serde_json::to_string_pretty(&v).unwrap();
assert_eq!(s, out);
}
}
@@ -891,7 +892,7 @@ fn test_parse_struct() {
Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
]
},
- )
+ ),
]);
let v: Outer = from_str("{}").unwrap();
@@ -902,6 +903,22 @@ fn test_parse_struct() {
inner: vec![],
}
);
+
+ let v: Outer = from_str(
+ "[
+ [
+ [ null, 2, [\"abc\", \"xyz\"] ]
+ ]
+ ]").unwrap();
+
+ assert_eq!(
+ v,
+ Outer {
+ inner: vec![
+ Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
+ ],
+ }
+ );
}
#[test]
@@ -934,7 +951,7 @@ fn test_parse_enum_errors() {
("{\"unknown\":[]}", Error::SyntaxError(ErrorCode::UnknownField("unknown".to_string()), 1, 11)),
("{\"Dog\":{}}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 9)),
("{\"Frog\":{}}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 10)),
- ("{\"Cat\":[]}", Error::SyntaxError(ErrorCode::ExpectedSomeValue, 1, 9)),
+ ("{\"Cat\":[]}", Error::SyntaxError(ErrorCode::EOFWhileParsingValue, 1, 9)),
]);
}
@@ -1064,7 +1081,7 @@ fn test_missing_fmt_renamed_field() {
#[test]
fn test_find_path() {
- let obj: Value = json::from_str(r#"{"x": {"a": 1}, "y": 2}"#).unwrap();
+ let obj: Value = serde_json::from_str(r#"{"x": {"a": 1}, "y": 2}"#).unwrap();
assert!(obj.find_path(&["x", "a"]).unwrap() == &Value::U64(1));
assert!(obj.find_path(&["y"]).unwrap() == &Value::U64(2));
@@ -1073,9 +1090,180 @@ fn test_find_path() {
#[test]
fn test_lookup() {
- let obj: Value = json::from_str(r#"{"x": {"a": 1}, "y": 2}"#).unwrap();
+ let obj: Value = serde_json::from_str(r#"{"x": {"a": 1}, "y": 2}"#).unwrap();
assert!(obj.lookup("x.a").unwrap() == &Value::U64(1));
assert!(obj.lookup("y").unwrap() == &Value::U64(2));
assert!(obj.lookup("z").is_none());
}
+
+#[test]
+fn test_serialize_seq_with_no_len() {
+ #[derive(Clone, Debug, PartialEq)]
+ struct MyVec<T>(Vec<T>);
+
+ impl<T> ser::Serialize for MyVec<T>
+ where T: ser::Serialize,
+ {
+ #[inline]
+ fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ where S: ser::Serializer,
+ {
+ serializer.visit_seq(ser::impls::SeqIteratorVisitor::new(self.0.iter(), None))
+ }
+ }
+
+ struct Visitor<T> {
+ marker: PhantomData<MyVec<T>>,
+ }
+
+ impl<T> de::Visitor for Visitor<T>
+ where T: de::Deserialize,
+ {
+ type Value = MyVec<T>;
+
+ #[inline]
+ fn visit_unit<E>(&mut self) -> Result<MyVec<T>, E>
+ where E: de::Error,
+ {
+ Ok(MyVec(Vec::new()))
+ }
+
+ #[inline]
+ fn visit_seq<V>(&mut self, mut visitor: V) -> Result<MyVec<T>, V::Error>
+ where V: de::SeqVisitor,
+ {
+ let mut values = Vec::new();
+
+ while let Some(value) = try!(visitor.visit()) {
+ values.push(value);
+ }
+
+ try!(visitor.end());
+
+ Ok(MyVec(values))
+ }
+ }
+
+ impl<T> de::Deserialize for MyVec<T>
+ where T: de::Deserialize,
+ {
+ fn deserialize<D>(deserializer: &mut D) -> Result<MyVec<T>, D::Error>
+ where D: de::Deserializer,
+ {
+ deserializer.visit_map(Visitor { marker: PhantomData })
+ }
+ }
+
+ let mut vec = Vec::new();
+ vec.push(MyVec(Vec::new()));
+ vec.push(MyVec(Vec::new()));
+ let vec: MyVec<MyVec<u32>> = MyVec(vec);
+
+ test_encode_ok(&[
+ (
+ vec.clone(),
+ "[[],[]]",
+ ),
+ ]);
+
+ let s = serde_json::to_string_pretty(&vec).unwrap();
+ assert_eq!(
+ s,
+ concat!(
+ "[\n",
+ " [\n",
+ " ],\n",
+ " [\n",
+ " ]\n",
+ "]"
+ )
+ );
+}
+
+#[test]
+fn test_serialize_map_with_no_len() {
+ #[derive(Clone, Debug, PartialEq)]
+ struct Map<K, V>(BTreeMap<K, V>);
+
+ impl<K, V> ser::Serialize for Map<K, V>
+ where K: ser::Serialize + Ord,
+ V: ser::Serialize,
+ {
+ #[inline]
+ fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ where S: ser::Serializer,
+ {
+ serializer.visit_map(ser::impls::MapIteratorVisitor::new(self.0.iter(), None))
+ }
+ }
+
+ struct Visitor<K, V> {
+ marker: PhantomData<Map<K, V>>,
+ }
+
+ impl<K, V> de::Visitor for Visitor<K, V>
+ where K: de::Deserialize + Eq + Ord,
+ V: de::Deserialize,
+ {
+ type Value = Map<K, V>;
+
+ #[inline]
+ fn visit_unit<E>(&mut self) -> Result<Map<K, V>, E>
+ where E: de::Error,
+ {
+ Ok(Map(BTreeMap::new()))
+ }
+
+ #[inline]
+ fn visit_map<Visitor>(&mut self, mut visitor: Visitor) -> Result<Map<K, V>, Visitor::Error>
+ where Visitor: de::MapVisitor,
+ {
+ let mut values = BTreeMap::new();
+
+ while let Some((key, value)) = try!(visitor.visit()) {
+ values.insert(key, value);
+ }
+
+ try!(visitor.end());
+
+ Ok(Map(values))
+ }
+ }
+
+ impl<K, V> de::Deserialize for Map<K, V>
+ where K: de::Deserialize + Eq + Ord,
+ V: de::Deserialize,
+ {
+ fn deserialize<D>(deserializer: &mut D) -> Result<Map<K, V>, D::Error>
+ where D: de::Deserializer,
+ {
+ deserializer.visit_map(Visitor { marker: PhantomData })
+ }
+ }
+
+ let mut map = BTreeMap::new();
+ map.insert("a", Map(BTreeMap::new()));
+ map.insert("b", Map(BTreeMap::new()));
+ let map: Map<_, Map<u32, u32>> = Map(map);
+
+ test_encode_ok(&[
+ (
+ map.clone(),
+ "{\"a\":{},\"b\":{}}",
+ ),
+ ]);
+
+ let s = serde_json::to_string_pretty(&map).unwrap();
+ assert_eq!(
+ s,
+ concat!(
+ "{\n",
+ " \"a\": {\n",
+ " },\n",
+ " \"b\": {\n",
+ " }\n",
+ "}"
+ )
+ );
+}
diff --git a/serde_tests/tests/test_json_builder.rs b/serde_tests/tests/test_json_builder.rs
index f17dd70ae..55fcff08e 100644
--- a/serde_tests/tests/test_json_builder.rs
+++ b/serde_tests/tests/test_json_builder.rs
@@ -1,7 +1,7 @@
use std::collections::BTreeMap;
-use serde::json::value::Value;
-use serde::json::builder::{ArrayBuilder, ObjectBuilder};
+use serde_json::value::Value;
+use serde_json::builder::{ArrayBuilder, ObjectBuilder};
#[test]
fn test_array_builder() {
diff --git a/serde_tests/tests/test_macros.rs b/serde_tests/tests/test_macros.rs
index 524147bf7..d7af98557 100644
--- a/serde_tests/tests/test_macros.rs
+++ b/serde_tests/tests/test_macros.rs
@@ -1,5 +1,5 @@
use std::collections::BTreeMap;
-use serde::json::{self, Value};
+use serde_json::{self, Value};
macro_rules! btreemap {
() => {
@@ -136,19 +136,19 @@ fn test_named_unit() {
let named_unit = NamedUnit;
assert_eq!(
- json::to_string(&named_unit).unwrap(),
+ serde_json::to_string(&named_unit).unwrap(),
"null".to_string()
);
assert_eq!(
- json::to_value(&named_unit),
+ serde_json::to_value(&named_unit),
Value::Null
);
- let v: NamedUnit = json::from_str("null").unwrap();
+ let v: NamedUnit = serde_json::from_str("null").unwrap();
assert_eq!(v, named_unit);
- let v: NamedUnit = json::from_value(Value::Null).unwrap();
+ let v: NamedUnit = serde_json::from_value(Value::Null).unwrap();
assert_eq!(v, named_unit);
}
@@ -160,25 +160,25 @@ fn test_ser_named_tuple() {
let named_tuple = SerNamedTuple(&a, &mut b, c);
assert_eq!(
- json::to_string(&named_tuple).unwrap(),
+ serde_json::to_string(&named_tuple).unwrap(),
"[5,6,7]"
);
assert_eq!(
- json::to_value(&named_tuple),
+ serde_json::to_value(&named_tuple),
Value::Array(vec![Value::U64(5), Value::U64(6), Value::U64(7)])
);
}
#[test]
fn test_de_named_tuple() {
- let v: DeNamedTuple<i32, i32, i32> = json::from_str("[1,2,3]").unwrap();
+ let v: DeNamedTuple<i32, i32, i32> = serde_json::from_str("[1,2,3]").unwrap();
assert_eq!(
v,
DeNamedTuple(1, 2, 3)
);
- let v: Value = json::from_str("[1,2,3]").unwrap();
+ let v: Value = serde_json::from_str("[1,2,3]").unwrap();
assert_eq!(
v,
Value::Array(vec![
@@ -201,12 +201,12 @@ fn test_ser_named_map() {
};
assert_eq!(
- json::to_string(&named_map).unwrap(),
+ serde_json::to_string(&named_map).unwrap(),
"{\"a\":5,\"b\":6,\"c\":7}"
);
assert_eq!(
- json::to_value(&named_map),
+ serde_json::to_value(&named_map),
Value::Object(btreemap![
"a".to_string() => Value::U64(5),
"b".to_string() => Value::U64(6),
@@ -223,12 +223,12 @@ fn test_de_named_map() {
c: 7,
};
- let v2: DeNamedMap<i32, i32, i32> = json::from_str(
+ let v2: DeNamedMap<i32, i32, i32> = serde_json::from_str(
"{\"a\":5,\"b\":6,\"c\":7}"
).unwrap();
assert_eq!(v, v2);
- let v2 = json::from_value(Value::Object(btreemap![
+ let v2 = serde_json::from_value(Value::Object(btreemap![
"a".to_string() => Value::U64(5),
"b".to_string() => Value::U64(6),
"c".to_string() => Value::U64(7)
@@ -239,12 +239,12 @@ fn test_de_named_map() {
#[test]
fn test_ser_enum_unit() {
assert_eq!(
- json::to_string(&SerEnum::Unit::<u32, u32, u32>).unwrap(),
+ serde_json::to_string(&SerEnum::Unit::<u32, u32, u32>).unwrap(),
"{\"Unit\":[]}"
);
assert_eq!(
- json::to_value(&SerEnum::Unit::<u32, u32, u32>),
+ serde_json::to_value(&SerEnum::Unit::<u32, u32, u32>),
Value::Object(btreemap!(
"Unit".to_string() => Value::Array(vec![]))
)
@@ -261,7 +261,7 @@ fn test_ser_enum_seq() {
//let f = 6;
assert_eq!(
- json::to_string(&SerEnum::Seq(
+ serde_json::to_string(&SerEnum::Seq(
a,
b,
&c,
@@ -273,7 +273,7 @@ fn test_ser_enum_seq() {
);
assert_eq!(
- json::to_value(&SerEnum::Seq(
+ serde_json::to_value(&SerEnum::Seq(
a,
b,
&c,
@@ -304,7 +304,7 @@ fn test_ser_enum_map() {
//let f = 6;
assert_eq!(
- json::to_string(&SerEnum::Map {
+ serde_json::to_string(&SerEnum::Map {
a: a,
b: b,
c: &c,
@@ -316,7 +316,7 @@ fn test_ser_enum_map() {
);
assert_eq!(
- json::to_value(&SerEnum::Map {
+ serde_json::to_value(&SerEnum::Map {
a: a,
b: b,
c: &c,
@@ -339,13 +339,13 @@ fn test_ser_enum_map() {
#[test]
fn test_de_enum_unit() {
- let v: DeEnum<_, _, _> = json::from_str("{\"Unit\":[]}").unwrap();
+ let v: DeEnum<_, _, _> = serde_json::from_str("{\"Unit\":[]}").unwrap();
assert_eq!(
v,
DeEnum::Unit::<u32, u32, u32>
);
- let v: DeEnum<_, _, _> = json::from_value(Value::Object(btreemap!(
+ let v: DeEnum<_, _, _> = serde_json::from_value(Value::Object(btreemap!(
"Unit".to_string() => Value::Array(vec![]))
)).unwrap();
assert_eq!(
@@ -363,7 +363,7 @@ fn test_de_enum_seq() {
let e = 5;
//let f = 6;
- let v: DeEnum<_, _, _> = json::from_str("{\"Seq\":[1,2,3,5]}").unwrap();
+ let v: DeEnum<_, _, _> = serde_json::from_str("{\"Seq\":[1,2,3,5]}").unwrap();
assert_eq!(
v,
DeEnum::Seq(
@@ -376,7 +376,7 @@ fn test_de_enum_seq() {
)
);
- let v: DeEnum<_, _, _> = json::from_value(Value::Object(btreemap!(
+ let v: DeEnum<_, _, _> = serde_json::from_value(Value::Object(btreemap!(
"Seq".to_string() => Value::Array(vec![
Value::U64(1),
Value::U64(2),
@@ -408,7 +408,7 @@ fn test_de_enum_map() {
let e = 5;
//let f = 6;
- let v: DeEnum<_, _, _> = json::from_str(
+ let v: DeEnum<_, _, _> = serde_json::from_str(
"{\"Map\":{\"a\":1,\"b\":2,\"c\":3,\"e\":5}}"
).unwrap();
assert_eq!(
@@ -423,7 +423,7 @@ fn test_de_enum_map() {
}
);
- let v: DeEnum<_, _, _> = json::from_value(Value::Object(btreemap!(
+ let v: DeEnum<_, _, _> = serde_json::from_value(Value::Object(btreemap!(
"Map".to_string() => Value::Object(btreemap![
"a".to_string() => Value::U64(1),
"b".to_string() => Value::U64(2),
@@ -452,26 +452,26 @@ fn test_lifetimes() {
let value = 5;
let lifetime = Lifetimes::LifetimeSeq(&value);
assert_eq!(
- json::to_string(&lifetime).unwrap(),
+ serde_json::to_string(&lifetime).unwrap(),
"{\"LifetimeSeq\":[5]}"
);
let lifetime = Lifetimes::NoLifetimeSeq(5);
assert_eq!(
- json::to_string(&lifetime).unwrap(),
+ serde_json::to_string(&lifetime).unwrap(),
"{\"NoLifetimeSeq\":[5]}"
);
let value = 5;
let lifetime = Lifetimes::LifetimeMap { a: &value };
assert_eq!(
- json::to_string(&lifetime).unwrap(),
+ serde_json::to_string(&lifetime).unwrap(),
"{\"LifetimeMap\":{\"a\":5}}"
);
let lifetime = Lifetimes::NoLifetimeMap { a: 5 };
assert_eq!(
- json::to_string(&lifetime).unwrap(),
+ serde_json::to_string(&lifetime).unwrap(),
"{\"NoLifetimeMap\":{\"a\":5}}"
);
}
diff --git a/serde_tests/tests/test_ser.rs b/serde_tests/tests/test_ser.rs
index 27644f450..950b5b828 100644
--- a/serde_tests/tests/test_ser.rs
+++ b/serde_tests/tests/test_ser.rs
@@ -24,17 +24,17 @@ pub enum Token<'a> {
Option(bool),
Unit,
- NamedUnit(&'a str),
+ UnitStruct(&'a str),
EnumUnit(&'a str, &'a str),
SeqStart(Option<usize>),
- NamedSeqStart(&'a str, Option<usize>),
+ TupleStructStart(&'a str, Option<usize>),
EnumSeqStart(&'a str, &'a str, Option<usize>),
SeqSep,
SeqEnd,
MapStart(Option<usize>),
- NamedMapStart(&'a str, Option<usize>),
+ StructStart(&'a str, Option<usize>),
EnumMapStart(&'a str, &'a str, Option<usize>),
MapSep,
MapEnd,
@@ -80,13 +80,20 @@ impl<'a> Serializer for AssertSerializer<'a> {
Ok(())
}
- fn visit_named_unit(&mut self, name: &str) -> Result<(), ()> {
- assert_eq!(self.iter.next().unwrap(), Token::NamedUnit(name));
+ fn visit_unit_struct(&mut self, name: &str) -> Result<(), ()> {
+ assert_eq!(self.iter.next().unwrap(), Token::UnitStruct(name));
Ok(())
}
- fn visit_enum_unit(&mut self, name: &str, variant: &str) -> Result<(), ()> {
- assert_eq!(self.iter.next().unwrap(), Token::EnumUnit(name, variant));
+ fn visit_enum_unit(&mut self,
+ name: &str,
+ _variant_index: usize,
+ variant: &str) -> Result<(), ()> {
+ assert_eq!(
+ self.iter.next().unwrap(),
+ Token::EnumUnit(name, variant)
+ );
+
Ok(())
}
@@ -188,25 +195,32 @@ impl<'a> Serializer for AssertSerializer<'a> {
self.visit_sequence(visitor)
}
- fn visit_named_seq<V>(&mut self, name: &str, visitor: V) -> Result<(), ()>
+ fn visit_tuple_struct<V>(&mut self, name: &str, visitor: V) -> Result<(), ()>
where V: SeqVisitor
{
let len = visitor.len();
- assert_eq!(self.iter.next().unwrap(), Token::NamedSeqStart(name, len));
+ assert_eq!(
+ self.iter.next().unwrap(),
+ Token::TupleStructStart(name, len)
+ );
self.visit_sequence(visitor)
}
fn visit_enum_seq<V>(&mut self,
name: &str,
+ _variant_index: usize,
variant: &str,
visitor: V) -> Result<(), ()>
where V: SeqVisitor
{
let len = visitor.len();
- assert_eq!(self.iter.next().unwrap(), Token::EnumSeqStart(name, variant, len));
+ assert_eq!(
+ self.iter.next().unwrap(),
+ Token::EnumSeqStart(name, variant, len)
+ );
self.visit_sequence(visitor)
}
@@ -228,22 +242,32 @@ impl<'a> Serializer for AssertSerializer<'a> {
self.visit_mapping(visitor)
}
- fn visit_named_map<V>(&mut self, name: &str, visitor: V) -> Result<(), ()>
+ fn visit_struct<V>(&mut self, name: &str, visitor: V) -> Result<(), ()>
where V: MapVisitor
{
let len = visitor.len();
- assert_eq!(self.iter.next().unwrap(), Token::NamedMapStart(name, len));
+ assert_eq!(
+ self.iter.next().unwrap(),
+ Token::StructStart(name, len)
+ );
self.visit_mapping(visitor)
}
- fn visit_enum_map<V>(&mut self, name: &str, variant: &str, visitor: V) -> Result<(), ()>
+ fn visit_enum_map<V>(&mut self,
+ name: &str,
+ _variant_index: usize,
+ variant: &str,
+ visitor: V) -> Result<(), ()>
where V: MapVisitor
{
let len = visitor.len();
- assert_eq!(self.iter.next().unwrap(), Token::EnumMapStart(name, variant, len));
+ assert_eq!(
+ self.iter.next().unwrap(),
+ Token::EnumMapStart(name, variant, len)
+ );
self.visit_mapping(visitor)
}
@@ -262,13 +286,13 @@ impl<'a> Serializer for AssertSerializer<'a> {
//////////////////////////////////////////////////////////////////////////
#[derive(Serialize)]
-struct NamedUnit;
+struct UnitStruct;
#[derive(Serialize)]
-struct NamedSeq(i32, i32, i32);
+struct TupleStruct(i32, i32, i32);
#[derive(Serialize)]
-struct NamedMap {
+struct Struct {
a: i32,
b: i32,
c: i32,
@@ -356,6 +380,20 @@ declare_tests! {
Token::I32(1),
],
}
+ test_result {
+ Ok::<i32, i32>(0) => vec![
+ Token::EnumSeqStart("Result", "Ok", Some(1)),
+ Token::SeqSep,
+ Token::I32(0),
+ Token::SeqEnd,
+ ],
+ Err::<i32, i32>(1) => vec![
+ Token::EnumSeqStart("Result", "Err", Some(1)),
+ Token::SeqSep,
+ Token::I32(1),
+ Token::SeqEnd,
+ ],
+ }
test_slice {
&[0][..0] => vec![
Token::SeqStart(Some(0)),
@@ -480,12 +518,12 @@ declare_tests! {
Token::MapEnd,
],
}
- test_named_unit {
- NamedUnit => vec![Token::NamedUnit("NamedUnit")],
+ test_unit_struct {
+ UnitStruct => vec![Token::UnitStruct("UnitStruct")],
}
- test_named_seq {
- NamedSeq(1, 2, 3) => vec![
- Token::NamedSeqStart("NamedSeq", Some(3)),
+ test_tuple_struct {
+ TupleStruct(1, 2, 3) => vec![
+ Token::TupleStructStart("TupleStruct", Some(3)),
Token::SeqSep,
Token::I32(1),
@@ -497,9 +535,9 @@ declare_tests! {
Token::SeqEnd,
],
}
- test_named_map {
- NamedMap { a: 1, b: 2, c: 3 } => vec![
- Token::NamedMapStart("NamedMap", Some(3)),
+ test_struct {
+ Struct { a: 1, b: 2, c: 3 } => vec![
+ Token::StructStart("Struct", Some(3)),
Token::MapSep,
Token::Str("a"),
Token::I32(1),
| [
"101"
] | serde-rs__serde-114 | Incorrect JSON is generated when serializing an empty map with no up-front size provided
It'll generate things like `{"foo":{}"bar":{}}` (note no comma between `{}` and `"bar"`), which causes errors in deserialization. Supplying up-front sizes to all maps in the serialization code works around the problem.
| 0.4 | b2754c2c3bb9cae4ae7dc1d4ce5aa1275dc45dd4 | diff --git a/README.md b/README.md
index b79648b20..624054f85 100644
--- a/README.md
+++ b/README.md
@@ -39,7 +39,7 @@ struct Point {
```
Serde bundles a high performance JSON serializer and deserializer,
-[serde::json](http://serde-rs.github.io/serde/serde/json/index.html),
+[serde_json](http://serde-rs.github.io/serde/serde_json/index.html),
which comes with the helper functions
[to_string](http://serde-rs.github.io/serde/serde/json/ser/fn.to_string.html)
and
@@ -47,7 +47,7 @@ and
that make it easy to go to and from JSON:
```rust
-use serde::json;
+use serde_json;
...
@@ -59,7 +59,7 @@ println!("{}", serialized_point); // prints: {"x":1,"y":2}
let deserialize_point: Point = json::from_str(&serialized_point).unwrap();
```
-[serde::json](http://serde-rs.github.io/serde/serde/json/index.html) also
+[serde_json](http://serde-rs.github.io/serde/serde_json/index.html) also
supports a generic
[Value](http://serde-rs.github.io/serde/serde/json/value/enum.Value.html)
type, which can represent any JSON value. Also, any
@@ -187,7 +187,7 @@ impl serde::Serialize for Point {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
- serializer.visit_named_map("Point", PointMapVisitor {
+ serializer.visit_struct("Point", PointMapVisitor {
value: self,
state: 0,
})
@@ -383,7 +383,7 @@ impl serde::Deserialize for Point {
fn deserialize<D>(deserializer: &mut D) -> Result<Point, D::Error>
where D: serde::de::Deserializer
{
- deserializer.visit_named_map("Point", PointVisitor)
+ deserializer.visit_struct("Point", PointVisitor)
}
}
diff --git a/serde/Cargo.toml b/serde/Cargo.toml
index f47a913bd..0c6d7cbda 100644
--- a/serde/Cargo.toml
+++ b/serde/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde"
-version = "0.4.3"
+version = "0.5.0"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "A generic serialization/deserialization framework"
diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 390d60fb1..d00e483db 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -571,6 +571,15 @@ macro_rules! tuple_impls {
marker: PhantomData<($($name,)+)>,
}
+ impl<
+ $($name: Deserialize,)+
+ > $visitor<$($name,)+> {
+ fn new() -> Self {
+ $visitor { marker: PhantomData }
+ }
+ }
+
+
impl<
$($name: Deserialize,)+
> Visitor for $visitor<$($name,)+> {
@@ -601,7 +610,7 @@ macro_rules! tuple_impls {
fn deserialize<D>(deserializer: &mut D) -> Result<($($name,)+), D::Error>
where D: Deserializer,
{
- deserializer.visit_tuple($visitor { marker: PhantomData })
+ deserializer.visit_tuple($visitor::new())
}
}
)+
@@ -849,126 +858,75 @@ impl<T> Deserialize for NonZero<T> where T: Deserialize + PartialEq + Zeroable +
///////////////////////////////////////////////////////////////////////////////
+
impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
fn deserialize<D>(deserializer: &mut D) -> Result<Result<T, E>, D::Error>
where D: Deserializer {
enum Field {
- Field0,
- Field1,
+ Ok,
+ Err,
}
impl Deserialize for Field {
#[inline]
fn deserialize<D>(deserializer: &mut D) -> Result<Field, D::Error>
- where D: Deserializer {
- struct FieldVisitor<D> {
- phantom: PhantomData<D>,
- }
+ where D: Deserializer
+ {
+ struct FieldVisitor;
- impl<D> ::de::Visitor for FieldVisitor<D> where D: Deserializer {
+ impl ::de::Visitor for FieldVisitor {
type Value = Field;
fn visit_str<E>(&mut self, value: &str) -> Result<Field, E> where E: Error {
match value {
- "Ok" => Ok(Field::Field0),
- "Err" => Ok(Field::Field1),
+ "Ok" => Ok(Field::Ok),
+ "Err" => Ok(Field::Err),
_ => Err(Error::unknown_field_error(value)),
}
}
fn visit_bytes<E>(&mut self, value: &[u8]) -> Result<Field, E> where E: Error {
- match str::from_utf8(value) {
- Ok(s) => self.visit_str(s),
- _ => Err(Error::syntax_error()),
+ match value {
+ b"Ok" => Ok(Field::Ok),
+ b"Err" => Ok(Field::Err),
+ _ => {
+ match str::from_utf8(value) {
+ Ok(value) => Err(Error::unknown_field_error(value)),
+ Err(_) => Err(Error::syntax_error()),
+ }
+ }
}
}
}
- deserializer.visit(FieldVisitor::<D> {
- phantom: PhantomData,
- })
+ deserializer.visit(FieldVisitor)
}
}
- struct Visitor<D, T, E>(PhantomData<D>, PhantomData<T>, PhantomData<E>)
- where D: Deserializer, T: Deserialize, E: Deserialize;
+ struct Visitor<T, E>(PhantomData<Result<T, E>>);
- impl<D, T, E> EnumVisitor for Visitor<D, T, E> where D: Deserializer,
- T: Deserialize,
- E: Deserialize {
+ impl<T, E> EnumVisitor for Visitor<T, E>
+ where T: Deserialize,
+ E: Deserialize
+ {
type Value = Result<T, E>;
fn visit<V>(&mut self, mut visitor: V) -> Result<Result<T, E>, V::Error>
- where V: VariantVisitor {
- match match visitor.visit_variant() {
- Ok(val) => val,
- Err(err) => return Err(From::from(err)),
- } {
- Field::Field0 => {
- struct Visitor<D, T, E>(PhantomData<D>, PhantomData<T>, PhantomData<E>)
- where D: Deserializer,
- T: Deserialize,
- E: Deserialize;
- impl <D, T, E> ::de::Visitor for Visitor<D, T, E> where D: Deserializer,
- T: Deserialize,
- E: Deserialize {
- type Value = Result<T, E>;
-
- fn visit_seq<V>(&mut self, mut visitor: V)
- -> Result<Result<T, E>, V::Error> where V: SeqVisitor {
- let field0 = match match visitor.visit() {
- Ok(val) => val,
- Err(err) => return Err(From::from(err)),
- } {
- Some(value) => value,
- None => return Err(Error::end_of_stream_error()),
- };
- match visitor.end() {
- Ok(val) => val,
- Err(err) => return Err(From::from(err)),
- };
- Ok(Result::Ok(field0))
- }
- }
- visitor.visit_seq(Visitor::<D, T, E>(PhantomData,
- PhantomData,
- PhantomData))
+ where V: VariantVisitor
+ {
+ match try!(visitor.visit_variant()) {
+ Field::Ok => {
+ let (value,) = try!(visitor.visit_seq(TupleVisitor1::new()));
+ Ok(Ok(value))
}
- Field::Field1 => {
- struct Visitor<D, T, E>(PhantomData<D>, PhantomData<T>, PhantomData<E>)
- where D: Deserializer,
- T: Deserialize,
- E: Deserialize;
- impl <D, T, E> ::de::Visitor for Visitor<D, T, E> where D: Deserializer,
- T: Deserialize,
- E: Deserialize {
- type Value = Result<T, E>;
-
- fn visit_seq<V>(&mut self, mut visitor: V)
- -> Result<Result<T, E>, V::Error> where V: SeqVisitor {
- let field0 = match match visitor.visit() {
- Ok(val) => val,
- Err(err) => return Err(From::from(err)),
- } {
- Some(value) => value,
- None => return Err(Error::end_of_stream_error()),
- };
- match visitor.end() {
- Ok(val) => val,
- Err(err) => return Err(From::from(err)),
- };
- Ok(Result::Err(field0))
- }
- }
- visitor.visit_seq(Visitor::<D, T, E>(PhantomData,
- PhantomData,
- PhantomData))
+ Field::Err => {
+ let (value,) = try!(visitor.visit_seq(TupleVisitor1::new()));
+ Ok(Err(value))
}
}
}
}
- deserializer.visit_enum("Result",
- Visitor::<D, T, E>(PhantomData, PhantomData, PhantomData))
+ deserializer.visit_enum("Result", Visitor(PhantomData))
}
}
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index 253be30e7..5484a7b7c 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -211,25 +211,28 @@ pub trait Deserializer {
/// This method hints that the `Deserialize` type is expecting a named unit. This allows
/// deserializers to a named unit that aren't tagged as a named unit.
#[inline]
- fn visit_named_unit<V>(&mut self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
+ fn visit_unit_struct<V>(&mut self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor,
{
- self.visit(visitor)
+ self.visit_unit(visitor)
}
- /// This method hints that the `Deserialize` type is expecting a named sequence.
- /// This allows deserializers to parse sequences that aren't tagged as sequences.
+ /// This method hints that the `Deserialize` type is expecting a tuple struct. This allows
+ /// deserializers to parse sequences that aren't tagged as sequences.
#[inline]
- fn visit_named_seq<V>(&mut self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
+ fn visit_tuple_struct<V>(&mut self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor,
{
- self.visit_seq(visitor)
+ self.visit_tuple(visitor)
}
- /// This method hints that the `Deserialize` type is expecting a named map. This allows
+ /// This method hints that the `Deserialize` type is expecting a struct. This allows
/// deserializers to parse sequences that aren't tagged as maps.
#[inline]
- fn visit_named_map<V>(&mut self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
+ fn visit_struct<V>(&mut self,
+ _name: &str,
+ _fields: &'static [&'static str],
+ visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor,
{
self.visit_map(visitor)
@@ -241,7 +244,7 @@ pub trait Deserializer {
fn visit_tuple<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor,
{
- self.visit(visitor)
+ self.visit_seq(visitor)
}
/// This method hints that the `Deserialize` type is expecting an enum value. This allows
@@ -261,7 +264,7 @@ pub trait Deserializer {
fn visit_bytes<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor,
{
- self.visit(visitor)
+ self.visit_seq(visitor)
}
/// Specify a format string for the deserializer.
@@ -386,7 +389,7 @@ pub trait Visitor {
}
#[inline]
- fn visit_named_unit<E>(&mut self, _name: &str) -> Result<Self::Value, E>
+ fn visit_unit_struct<E>(&mut self, _name: &str) -> Result<Self::Value, E>
where E: Error,
{
self.visit_unit()
@@ -576,7 +579,9 @@ pub trait VariantVisitor {
}
/// `visit_map` is called when deserializing a struct-like variant.
- fn visit_map<V>(&mut self, _visitor: V) -> Result<V::Value, Self::Error>
+ fn visit_map<V>(&mut self,
+ _fields: &'static [&'static str],
+ _visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor
{
Err(Error::syntax_error())
@@ -602,10 +607,12 @@ impl<'a, T> VariantVisitor for &'a mut T where T: VariantVisitor {
(**self).visit_seq(visitor)
}
- fn visit_map<V>(&mut self, visitor: V) -> Result<V::Value, T::Error>
+ fn visit_map<V>(&mut self,
+ fields: &'static [&'static str],
+ visitor: V) -> Result<V::Value, T::Error>
where V: Visitor,
{
- (**self).visit_map(visitor)
+ (**self).visit_map(fields, visitor)
}
}
diff --git a/serde/src/lib.rs b/serde/src/lib.rs
index 92d86c788..b573c5b9c 100644
--- a/serde/src/lib.rs
+++ b/serde/src/lib.rs
@@ -22,5 +22,4 @@ pub use de::{Deserialize, Deserializer, Error};
pub mod bytes;
pub mod de;
pub mod iter;
-pub mod json;
pub mod ser;
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index 245ffdeca..a8efe18a9 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -15,7 +15,6 @@ use std::collections::vec_map::VecMap;
use std::hash::Hash;
#[cfg(feature = "nightly")]
use std::iter;
-use std::marker::PhantomData;
#[cfg(feature = "nightly")]
use std::num;
#[cfg(feature = "nightly")]
@@ -612,28 +611,17 @@ impl<'a, T: ?Sized> Serialize for Cow<'a, T> where T: Serialize + ToOwned, {
impl<T, E> Serialize for Result<T, E> where T: Serialize, E: Serialize {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer {
match *self {
- Result::Ok(ref field0) => {
- struct Visitor<'a, T, E> where T: Serialize + 'a, E: Serialize + 'a {
- state: usize,
- value: (&'a T,),
- _structure_ty: PhantomData<&'a Result<T, E>>,
- }
+ Result::Ok(ref value) => {
+ struct Visitor<'a, T: 'a>(Option<&'a T>);
- impl<'a, T, E> SeqVisitor for Visitor<'a, T, E> where T: Serialize + 'a,
- E: Serialize + 'a {
+ impl<'a, T> SeqVisitor for Visitor<'a, T> where T: Serialize + 'a {
#[inline]
fn visit<S>(&mut self, serializer: &mut S) -> Result<Option<()>, S::Error>
- where S: Serializer {
- match self.state {
- 0 => {
- self.state += 1;
- let v = match serializer.visit_seq_elt(&self.value.0) {
- Ok(val) => val,
- Err(err) => return Err(From::from(err)),
- };
- Ok(Some(v))
- }
- _ => Ok(None),
+ where S: Serializer
+ {
+ match self.0.take() {
+ Some(value) => Ok(Some(try!(serializer.visit_seq_elt(value)))),
+ None => Ok(None),
}
}
@@ -643,37 +631,18 @@ impl<T, E> Serialize for Result<T, E> where T: Serialize, E: Serialize {
}
}
- let field0: &T = field0;
- let data: PhantomData<&Result<&T,E>> = PhantomData;
- let visitor = Visitor {
- value: (&field0,),
- state: 0,
- _structure_ty: data
- };
- serializer.visit_enum_seq("Result", "Ok", visitor)
+ serializer.visit_enum_seq("Result", 0, "Ok", Visitor(Some(value)))
}
- Result::Err(ref field0) => {
- struct Visitor<'a, T, E> where T: Serialize + 'a, E: Serialize + 'a {
- state: usize,
- value: (&'a E,),
- _structure_ty: PhantomData<&'a Result<T, E>>,
- }
+ Result::Err(ref value) => {
+ struct Visitor<'a, E: 'a>(Option<&'a E>);
- impl<'a, T, E> SeqVisitor for Visitor<'a, T, E> where T: Serialize + 'a,
- E: Serialize + 'a {
+ impl<'a, E> SeqVisitor for Visitor<'a, E> where E: Serialize + 'a {
#[inline]
fn visit<S>(&mut self, serializer: &mut S) -> Result<Option<()>, S::Error>
where S: Serializer {
- match self.state {
- 0 => {
- self.state += 1;
- let v = match serializer.visit_seq_elt(&self.value.0) {
- Ok(val) => val,
- Err(err) => return Err(From::from(err)),
- };
- Ok(Some(v))
- }
- _ => Ok(None),
+ match self.0.take() {
+ Some(value) => Ok(Some(try!(serializer.visit_seq_elt(value)))),
+ None => Ok(None),
}
}
@@ -683,14 +652,7 @@ impl<T, E> Serialize for Result<T, E> where T: Serialize, E: Serialize {
}
}
- let field0: &E = field0;
- let data: PhantomData<&Result<T,&E>> = PhantomData;
- let visitor = Visitor {
- value: (&field0,),
- state: 0,
- _structure_ty: data
- };
- serializer.visit_enum_seq("Result", "Err", visitor)
+ serializer.visit_enum_seq("Result", 1, "Err", Visitor(Some(value)))
}
}
}
diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs
index 89f180426..d816dc35a 100644
--- a/serde/src/ser/mod.rs
+++ b/serde/src/ser/mod.rs
@@ -113,13 +113,14 @@ pub trait Serializer {
fn visit_unit(&mut self) -> Result<(), Self::Error>;
#[inline]
- fn visit_named_unit(&mut self, _name: &str) -> Result<(), Self::Error> {
+ fn visit_unit_struct(&mut self, _name: &str) -> Result<(), Self::Error> {
self.visit_unit()
}
#[inline]
fn visit_enum_unit(&mut self,
_name: &str,
+ _variant_index: usize,
_variant: &str) -> Result<(), Self::Error> {
self.visit_unit()
}
@@ -150,7 +151,7 @@ pub trait Serializer {
}
#[inline]
- fn visit_named_seq<V>(&mut self,
+ fn visit_tuple_struct<V>(&mut self,
_name: &'static str,
visitor: V) -> Result<(), Self::Error>
where V: SeqVisitor,
@@ -159,7 +160,7 @@ pub trait Serializer {
}
#[inline]
- fn visit_named_seq_elt<T>(&mut self, value: T) -> Result<(), Self::Error>
+ fn visit_tuple_struct_elt<T>(&mut self, value: T) -> Result<(), Self::Error>
where T: Serialize
{
self.visit_tuple_elt(value)
@@ -168,18 +169,19 @@ pub trait Serializer {
#[inline]
fn visit_enum_seq<V>(&mut self,
_name: &'static str,
- _variant: &'static str,
+ _variant_index: usize,
+ variant: &'static str,
visitor: V) -> Result<(), Self::Error>
where V: SeqVisitor,
{
- self.visit_tuple(visitor)
+ self.visit_tuple_struct(variant, visitor)
}
#[inline]
fn visit_enum_seq_elt<T>(&mut self, value: T) -> Result<(), Self::Error>
where T: Serialize
{
- self.visit_tuple_elt(value)
+ self.visit_tuple_struct_elt(value)
}
fn visit_map<V>(&mut self, visitor: V) -> Result<(), Self::Error>
@@ -190,7 +192,7 @@ pub trait Serializer {
V: Serialize;
#[inline]
- fn visit_named_map<V>(&mut self,
+ fn visit_struct<V>(&mut self,
_name: &'static str,
visitor: V) -> Result<(), Self::Error>
where V: MapVisitor,
@@ -199,7 +201,7 @@ pub trait Serializer {
}
#[inline]
- fn visit_named_map_elt<K, V>(&mut self, key: K, value: V) -> Result<(), Self::Error>
+ fn visit_struct_elt<K, V>(&mut self, key: K, value: V) -> Result<(), Self::Error>
where K: Serialize,
V: Serialize,
{
@@ -209,11 +211,12 @@ pub trait Serializer {
#[inline]
fn visit_enum_map<V>(&mut self,
_name: &'static str,
+ _variant_index: usize,
variant: &'static str,
visitor: V) -> Result<(), Self::Error>
where V: MapVisitor,
{
- self.visit_named_map(variant, visitor)
+ self.visit_struct(variant, visitor)
}
#[inline]
@@ -221,7 +224,7 @@ pub trait Serializer {
where K: Serialize,
V: Serialize,
{
- self.visit_named_map_elt(key, value)
+ self.visit_struct_elt(key, value)
}
/// Specify a format string for the serializer.
diff --git a/serde_codegen/Cargo.toml b/serde_codegen/Cargo.toml
index ec39afd38..08c685202 100644
--- a/serde_codegen/Cargo.toml
+++ b/serde_codegen/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_codegen"
-version = "0.4.3"
+version = "0.5.0"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Macros to auto-generate implementations for the serde framework"
diff --git a/serde_codegen/src/attr.rs b/serde_codegen/src/attr.rs
index 8d04b0680..9f08969df 100644
--- a/serde_codegen/src/attr.rs
+++ b/serde_codegen/src/attr.rs
@@ -21,7 +21,6 @@ pub struct FieldAttrs {
}
impl FieldAttrs {
-
/// Create a FieldAttr with a single default field name
pub fn new(default_value: bool, name: P<ast::Expr>) -> FieldAttrs {
FieldAttrs {
@@ -35,7 +34,7 @@ impl FieldAttrs {
default_value: bool,
default_name: P<ast::Expr>,
formats: HashMap<P<ast::Expr>, P<ast::Expr>>,
- ) -> FieldAttrs {
+ ) -> FieldAttrs {
FieldAttrs {
names: FieldNames::Format {
formats: formats,
diff --git a/serde_codegen/src/de.rs b/serde_codegen/src/de.rs
index 9d256a512..3f949df00 100644
--- a/serde_codegen/src/de.rs
+++ b/serde_codegen/src/de.rs
@@ -190,11 +190,25 @@ fn deserialize_visitor(
(
builder.item().tuple_struct("__Visitor")
.generics().with(trait_generics.clone()).build()
- .with_tys(
- trait_generics.ty_params.iter().map(|ty_param| {
- builder.ty().phantom_data().id(ty_param.ident)
- })
- )
+ .with_tys({
+ let lifetimes = trait_generics.lifetimes.iter()
+ .map(|lifetime_def| {
+ builder.ty()
+ .phantom_data()
+ .ref_().lifetime(lifetime_def.lifetime.name)
+ .ty()
+ .unit()
+ });
+
+ let ty_params = trait_generics.ty_params.iter()
+ .map(|ty_param| {
+ builder.ty()
+ .phantom_data()
+ .id(ty_param.ident)
+ });
+
+ lifetimes.chain(ty_params)
+ })
.build(),
builder.ty().path()
.segment("__Visitor").with_generics(trait_generics.clone()).build()
@@ -204,11 +218,11 @@ fn deserialize_visitor(
.with_tys(forward_tys)
.with_tys(placeholders)
.build().build()
- .with_args(
- trait_generics.ty_params.iter().map(|_| {
- builder.expr().phantom_data()
- })
- )
+ .with_args({
+ let len = trait_generics.lifetimes.len() + trait_generics.ty_params.len();
+
+ (0 .. len).map(|_| builder.expr().phantom_data())
+ })
.build(),
trait_generics,
)
@@ -260,7 +274,7 @@ fn deserialize_unit_struct(
}
}
- deserializer.visit_named_unit($type_name, __Visitor)
+ deserializer.visit_unit_struct($type_name, __Visitor)
})
}
@@ -304,7 +318,7 @@ fn deserialize_tuple_struct(
}
}
- deserializer.visit_named_seq($type_name, $visitor_expr)
+ deserializer.visit_tuple_struct($type_name, $visitor_expr)
})
}
@@ -342,6 +356,51 @@ fn deserialize_seq(
})
}
+fn deserialize_struct_as_seq(
+ cx: &ExtCtxt,
+ builder: &aster::AstBuilder,
+ struct_path: ast::Path,
+ struct_def: &StructDef,
+) -> P<ast::Expr> {
+ let let_values: Vec<P<ast::Stmt>> = (0 .. struct_def.fields.len())
+ .map(|i| {
+ let name = builder.id(format!("__field{}", i));
+ quote_stmt!(cx,
+ let $name = match try!(visitor.visit()) {
+ Some(value) => { value },
+ None => {
+ return Err(::serde::de::Error::end_of_stream_error());
+ }
+ };
+ ).unwrap()
+ })
+ .collect();
+
+ let result = builder.expr().struct_path(struct_path)
+ .with_id_exprs(
+ struct_def.fields.iter()
+ .enumerate()
+ .map(|(i, field)| {
+ (
+ match field.node.kind {
+ ast::NamedField(name, _) => name.clone(),
+ ast::UnnamedField(_) => panic!("struct contains unnamed fields"),
+ },
+ builder.expr().id(format!("__field{}", i)),
+ )
+ })
+ )
+ .build();
+
+ quote_expr!(cx, {
+ $let_values
+
+ try!(visitor.end());
+
+ Ok($result)
+ })
+}
+
fn deserialize_struct(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
@@ -352,19 +411,27 @@ fn deserialize_struct(
) -> P<ast::Expr> {
let where_clause = &impl_generics.where_clause;
- let (visitor_item, visitor_ty, visitor_expr, visitor_generics) =
- deserialize_visitor(
- builder,
- &impl_generics,
- vec![deserializer_ty_param(builder)],
- vec![deserializer_ty_arg(builder)],
- );
+ let (visitor_item, visitor_ty, visitor_expr, visitor_generics) = deserialize_visitor(
+ builder,
+ &impl_generics,
+ vec![deserializer_ty_param(builder)],
+ vec![deserializer_ty_arg(builder)],
+ );
- let (field_visitor, visit_map_expr) = deserialize_struct_visitor(
+ let type_path = builder.path().id(type_ident).build();
+
+ let visit_seq_expr = deserialize_struct_as_seq(
+ cx,
+ builder,
+ type_path.clone(),
+ struct_def
+ );
+
+ let (field_visitor, fields_stmt, visit_map_expr) = deserialize_struct_visitor(
cx,
builder,
struct_def,
- builder.path().id(type_ident).build(),
+ type_path.clone()
);
let type_name = builder.expr().str(type_ident);
@@ -377,6 +444,13 @@ fn deserialize_struct(
impl $visitor_generics ::serde::de::Visitor for $visitor_ty $where_clause {
type Value = $ty;
+ #[inline]
+ fn visit_seq<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<$ty, __V::Error>
+ where __V: ::serde::de::SeqVisitor,
+ {
+ $visit_seq_expr
+ }
+
#[inline]
fn visit_map<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<$ty, __V::Error>
where __V: ::serde::de::MapVisitor,
@@ -385,7 +459,9 @@ fn deserialize_struct(
}
}
- deserializer.visit_named_map($type_name, $visitor_expr)
+ $fields_stmt
+
+ deserializer.visit_struct($type_name, FIELDS, $visitor_expr)
})
}
@@ -558,11 +634,23 @@ fn deserialize_struct_variant(
) -> P<ast::Expr> {
let where_clause = &generics.where_clause;
- let (field_visitor, field_expr) = deserialize_struct_visitor(
+ let type_path = builder.path()
+ .id(type_ident)
+ .id(variant_ident)
+ .build();
+
+ let visit_seq_expr = deserialize_struct_as_seq(
+ cx,
+ builder,
+ type_path.clone(),
+ struct_def
+ );
+
+ let (field_visitor, fields_stmt, field_expr) = deserialize_struct_visitor(
cx,
builder,
struct_def,
- builder.path().id(type_ident).id(variant_ident).build(),
+ type_path
);
let (visitor_item, visitor_ty, visitor_expr, visitor_generics) =
@@ -581,6 +669,14 @@ fn deserialize_struct_variant(
impl $visitor_generics ::serde::de::Visitor for $visitor_ty $where_clause {
type Value = $ty;
+ #[inline]
+ fn visit_seq<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<$ty, __V::Error>
+ where __V: ::serde::de::SeqVisitor,
+ {
+ $visit_seq_expr
+ }
+
+ #[inline]
fn visit_map<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<$ty, __V::Error>
where __V: ::serde::de::MapVisitor,
{
@@ -588,7 +684,9 @@ fn deserialize_struct_variant(
}
}
- visitor.visit_map($visitor_expr)
+ $fields_stmt
+
+ visitor.visit_map(FIELDS, $visitor_expr)
})
}
@@ -612,6 +710,20 @@ fn deserialize_field_visitor(
)
.build();
+ let index_field_arms: Vec<_> = field_idents.iter()
+ .enumerate()
+ .map(|(field_index, field_ident)| {
+ quote_arm!(cx, $field_index => { Ok(__Field::$field_ident) })
+ })
+ .collect();
+
+ let index_body = quote_expr!(cx,
+ match value {
+ $index_field_arms
+ _ => { Err(::serde::de::Error::syntax_error()) }
+ }
+ );
+
// A set of all the formats that have specialized field attributes
let formats = field_attrs.iter()
.fold(HashSet::new(), |mut set, field_expr| {
@@ -628,7 +740,7 @@ fn deserialize_field_visitor(
})
.collect();
- let body = if formats.is_empty() {
+ let str_body = if formats.is_empty() {
// No formats specific attributes, so no match on format required
quote_expr!(cx,
match value {
@@ -636,7 +748,7 @@ fn deserialize_field_visitor(
_ => { Err(::serde::de::Error::unknown_field_error(value)) }
})
} else {
- let field_arms : Vec<_> = formats.iter()
+ let field_arms: Vec<_> = formats.iter()
.map(|fmt| {
field_idents.iter()
.zip(field_attrs.iter())
@@ -648,7 +760,7 @@ fn deserialize_field_visitor(
})
.collect();
- let fmt_matches : Vec<_> = formats.iter()
+ let fmt_matches: Vec<_> = formats.iter()
.zip(field_arms.iter())
.map(|(ref fmt, ref arms)| {
quote_arm!(cx, $fmt => {
@@ -662,13 +774,14 @@ fn deserialize_field_visitor(
.collect();
quote_expr!(cx,
- match __D::format() {
- $fmt_matches
- _ => match value {
- $default_field_arms
- _ => { Err(::serde::de::Error::unknown_field_error(value)) }
- }
- })
+ match __D::format() {
+ $fmt_matches
+ _ => match value {
+ $default_field_arms
+ _ => { Err(::serde::de::Error::unknown_field_error(value)) }
+ }
+ }
+ )
};
let impl_item = quote_item!(cx,
@@ -688,10 +801,16 @@ fn deserialize_field_visitor(
{
type Value = __Field;
+ fn visit_usize<E>(&mut self, value: usize) -> ::std::result::Result<__Field, E>
+ where E: ::serde::de::Error,
+ {
+ $index_body
+ }
+
fn visit_str<E>(&mut self, value: &str) -> ::std::result::Result<__Field, E>
where E: ::serde::de::Error,
{
- $body
+ $str_body
}
fn visit_bytes<E>(&mut self, value: &[u8]) -> ::std::result::Result<__Field, E>
@@ -705,8 +824,7 @@ fn deserialize_field_visitor(
}
}
- deserializer.visit(
- __FieldVisitor::<D>{ phantom: PhantomData })
+ deserializer.visit(__FieldVisitor::<D>{ phantom: PhantomData })
}
}
).unwrap();
@@ -719,7 +837,7 @@ fn deserialize_struct_visitor(
builder: &aster::AstBuilder,
struct_def: &ast::StructDef,
struct_path: ast::Path,
-) -> (Vec<P<ast::Item>>, P<ast::Expr>) {
+) -> (Vec<P<ast::Item>>, P<ast::Stmt>, P<ast::Expr>) {
let field_visitor = deserialize_field_visitor(
cx,
builder,
@@ -733,7 +851,23 @@ fn deserialize_struct_visitor(
struct_def,
);
- (field_visitor, visit_map_expr)
+ let fields_expr = builder.expr().addr_of().slice()
+ .with_exprs(
+ struct_def.fields.iter()
+ .map(|field| {
+ match field.node.kind {
+ ast::NamedField(name, _) => builder.expr().str(name),
+ ast::UnnamedField(_) => panic!("struct contains unnamed fields"),
+ }
+ })
+ )
+ .build();
+
+ let fields_stmt = quote_stmt!(cx,
+ const FIELDS: &'static [&'static str] = $fields_expr;
+ ).unwrap();
+
+ (field_visitor, fields_stmt, visit_map_expr)
}
fn deserialize_map(
diff --git a/serde_codegen/src/ser.rs b/serde_codegen/src/ser.rs
index 656d5f31b..ec8c6ccdc 100644
--- a/serde_codegen/src/ser.rs
+++ b/serde_codegen/src/ser.rs
@@ -169,7 +169,7 @@ fn serialize_unit_struct(
) -> P<ast::Expr> {
let type_name = builder.expr().str(type_ident);
- quote_expr!(cx, serializer.visit_named_unit($type_name))
+ quote_expr!(cx, serializer.visit_unit_struct($type_name))
}
fn serialize_tuple_struct(
@@ -194,7 +194,7 @@ fn serialize_tuple_struct(
quote_expr!(cx, {
$visitor_struct
$visitor_impl
- serializer.visit_named_seq($type_name, Visitor {
+ serializer.visit_tuple_struct($type_name, Visitor {
value: self,
state: 0,
_structure_ty: ::std::marker::PhantomData,
@@ -226,7 +226,7 @@ fn serialize_struct(
quote_expr!(cx, {
$visitor_struct
$visitor_impl
- serializer.visit_named_map($type_name, Visitor {
+ serializer.visit_struct($type_name, Visitor {
value: self,
state: 0,
_structure_ty: ::std::marker::PhantomData,
@@ -243,7 +243,8 @@ fn serialize_item_enum(
enum_def: &ast::EnumDef,
) -> P<ast::Expr> {
let arms: Vec<ast::Arm> = enum_def.variants.iter()
- .map(|variant| {
+ .enumerate()
+ .map(|(variant_index, variant)| {
serialize_variant(
cx,
builder,
@@ -251,6 +252,7 @@ fn serialize_item_enum(
impl_generics,
ty.clone(),
variant,
+ variant_index,
)
})
.collect();
@@ -269,6 +271,7 @@ fn serialize_variant(
generics: &ast::Generics,
ty: P<ast::Ty>,
variant: &ast::Variant,
+ variant_index: usize,
) -> ast::Arm {
let type_name = builder.expr().str(type_ident);
let variant_ident = variant.node.name;
@@ -285,6 +288,7 @@ fn serialize_variant(
::serde::ser::Serializer::visit_enum_unit(
serializer,
$type_name,
+ $variant_index,
$variant_name,
)
}
@@ -304,6 +308,7 @@ fn serialize_variant(
cx,
builder,
type_name,
+ variant_index,
variant_name,
generics,
ty,
@@ -340,6 +345,7 @@ fn serialize_variant(
cx,
builder,
type_name,
+ variant_index,
variant_name,
generics,
ty,
@@ -356,6 +362,7 @@ fn serialize_tuple_variant(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
type_name: P<ast::Expr>,
+ variant_index: usize,
variant_name: P<ast::Expr>,
generics: &ast::Generics,
structure_ty: P<ast::Ty>,
@@ -395,7 +402,7 @@ fn serialize_tuple_variant(
quote_expr!(cx, {
$visitor_struct
$visitor_impl
- serializer.visit_enum_seq($type_name, $variant_name, Visitor {
+ serializer.visit_enum_seq($type_name, $variant_index, $variant_name, Visitor {
value: $value_expr,
state: 0,
_structure_ty: ::std::marker::PhantomData,
@@ -407,6 +414,7 @@ fn serialize_struct_variant(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
type_name: P<ast::Expr>,
+ variant_index: usize,
variant_name: P<ast::Expr>,
generics: &ast::Generics,
structure_ty: P<ast::Ty>,
@@ -451,7 +459,7 @@ fn serialize_struct_variant(
quote_expr!(cx, {
$visitor_struct
$visitor_impl
- serializer.visit_enum_map($type_name, $variant_name, Visitor {
+ serializer.visit_enum_map($type_name, $variant_index, $variant_name, Visitor {
value: $value_expr,
state: 0,
_structure_ty: ::std::marker::PhantomData,
@@ -476,7 +484,7 @@ fn serialize_tuple_struct_visitor(
quote_arm!(cx,
$i => {
self.state += 1;
- let v = try!(serializer.visit_named_seq_elt(&$expr));
+ let v = try!(serializer.visit_tuple_struct_elt(&$expr));
Ok(Some(v))
}
)
@@ -559,7 +567,7 @@ fn serialize_struct_visitor<I>(
Ok(
Some(
try!(
- serializer.visit_named_map_elt(
+ serializer.visit_struct_elt(
$key_expr,
$value_expr,
)
diff --git a/serde_json/Cargo.toml b/serde_json/Cargo.toml
new file mode 100644
index 000000000..dbde52a96
--- /dev/null
+++ b/serde_json/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "serde_json"
+version = "0.5.0"
+authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
+license = "MIT/Apache-2.0"
+description = "A JSON serialization file format"
+repository = "https://github.com/serde-rs/serde"
+documentation = "http://serde-rs.github.io/serde/serde"
+readme = "README.md"
+keywords = ["serialization", "json"]
+
+[dependencies]
+num = "*"
+serde = { version = "*", path = "../serde" }
diff --git a/serde/src/json/builder.rs b/serde_json/src/builder.rs
similarity index 97%
rename from serde/src/json/builder.rs
rename to serde_json/src/builder.rs
index 3db2c4ed9..2743b3d95 100644
--- a/serde/src/json/builder.rs
+++ b/serde_json/src/builder.rs
@@ -10,8 +10,9 @@
use std::collections::BTreeMap;
-use ser::{self, Serialize};
-use json::value::{self, Value};
+use serde::ser::{self, Serialize};
+
+use value::{self, Value};
pub struct ArrayBuilder {
array: Vec<Value>,
diff --git a/serde/src/json/de.rs b/serde_json/src/de.rs
similarity index 99%
rename from serde/src/json/de.rs
rename to serde_json/src/de.rs
index d4e9f47ed..8bb33931d 100644
--- a/serde/src/json/de.rs
+++ b/serde_json/src/de.rs
@@ -3,8 +3,8 @@ use std::i32;
use std::io;
use std::str;
-use de;
-use iter::LineColIterator;
+use serde::de;
+use serde::iter::LineColIterator;
use super::error::{Error, ErrorCode};
@@ -649,7 +649,9 @@ impl<Iter> de::VariantVisitor for Deserializer<Iter>
de::Deserializer::visit(self, visitor)
}
- fn visit_map<V>(&mut self, visitor: V) -> Result<V::Value, Error>
+ fn visit_map<V>(&mut self,
+ _fields: &'static [&'static str],
+ visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
try!(self.parse_object_colon());
diff --git a/serde/src/json/error.rs b/serde_json/src/error.rs
similarity index 99%
rename from serde/src/json/error.rs
rename to serde_json/src/error.rs
index 29570ebd0..171e24590 100644
--- a/serde/src/json/error.rs
+++ b/serde_json/src/error.rs
@@ -2,7 +2,7 @@ use std::error;
use std::fmt;
use std::io;
-use de;
+use serde::de;
/// The errors that can arise while parsing a JSON stream.
#[derive(Clone, PartialEq)]
diff --git a/serde/src/json/mod.rs b/serde_json/src/lib.rs
similarity index 90%
rename from serde/src/json/mod.rs
rename to serde_json/src/lib.rs
index 3a3a35260..2e13f2a42 100644
--- a/serde/src/json/mod.rs
+++ b/serde_json/src/lib.rs
@@ -6,7 +6,7 @@
//! encode structured data in a text format that can be easily read by humans. Its simple syntax
//! and native compatibility with JavaScript have made it a widely used format.
//!
-//! Data types that can be encoded are JavaScript types (see the `serde::json:Value` enum for more
+//! Data types that can be encoded are JavaScript types (see the `serde_json:Value` enum for more
//! details):
//!
//! * `Boolean`: equivalent to rust's `bool`
@@ -16,7 +16,7 @@
//! * `String`: equivalent to rust's `String`
//! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the
//! same array
-//! * `Object`: equivalent to rust's `BTreeMap<String, serde::json::Value>`
+//! * `Object`: equivalent to rust's `BTreeMap<String, serde_json::Value>`
//! * `Null`
//!
//! An object is a series of string keys mapping to values, in `"key": value` format. Arrays are
@@ -48,8 +48,8 @@
//! `serde::Deserialize` trait. Serde provides provides an annotation to automatically generate
//! the code for these traits: `#[derive(Serialize, Deserialize)]`.
//!
-//! The JSON API also provides an enum `serde::json::Value` and a method `to_value` to serialize
-//! objects. A `serde::json::Value` value can be serialized as a string or buffer using the
+//! The JSON API also provides an enum `serde_json::Value` and a method `to_value` to serialize
+//! objects. A `serde_json::Value` value can be serialized as a string or buffer using the
//! functions described above. You can also use the `json::Serializer` object, which implements the
//! `Serializer` trait.
//!
@@ -63,7 +63,7 @@
//!
//! extern crate serde;
//!
-//! use serde::json::{self, Value};
+//! use serde_json::{self, Value};
//!
//! fn main() {
//! let data: Value = json::from_str("{\"foo\": 13, \"bar\": \"baz\"}").unwrap();
@@ -92,6 +92,9 @@
//! }
//! ```
+extern crate num;
+extern crate serde;
+
pub use self::de::{Deserializer, from_str};
pub use self::error::{Error, ErrorCode};
pub use self::ser::{
diff --git a/serde/src/json/ser.rs b/serde_json/src/ser.rs
similarity index 94%
rename from serde/src/json/ser.rs
rename to serde_json/src/ser.rs
index deaace30a..294a7f494 100644
--- a/serde/src/json/ser.rs
+++ b/serde_json/src/ser.rs
@@ -2,7 +2,7 @@ use std::io;
use std::num::FpCategory;
use std::string::FromUtf8Error;
-use ser;
+use serde::ser;
/// A structure for implementing serialization to JSON.
pub struct Serializer<W, F=CompactFormatter> {
@@ -159,7 +159,10 @@ impl<W, F> ser::Serializer for Serializer<W, F>
}
#[inline]
- fn visit_enum_unit(&mut self, _name: &str, variant: &str) -> io::Result<()> {
+ fn visit_enum_unit(&mut self,
+ _name: &str,
+ _variant_index: usize,
+ variant: &str) -> io::Result<()> {
try!(self.formatter.open(&mut self.writer, b'{'));
try!(self.formatter.comma(&mut self.writer, true));
try!(self.visit_str(variant));
@@ -190,7 +193,11 @@ impl<W, F> ser::Serializer for Serializer<W, F>
}
#[inline]
- fn visit_enum_seq<V>(&mut self, _name: &str, variant: &str, visitor: V) -> io::Result<()>
+ fn visit_enum_seq<V>(&mut self,
+ _name: &str,
+ _variant_index: usize,
+ variant: &str,
+ visitor: V) -> io::Result<()>
where V: ser::SeqVisitor,
{
try!(self.formatter.open(&mut self.writer, b'{'));
@@ -206,9 +213,11 @@ impl<W, F> ser::Serializer for Serializer<W, F>
where T: ser::Serialize,
{
try!(self.formatter.comma(&mut self.writer, self.first));
+ try!(value.serialize(self));
+
self.first = false;
- value.serialize(self)
+ Ok(())
}
#[inline]
@@ -232,7 +241,11 @@ impl<W, F> ser::Serializer for Serializer<W, F>
}
#[inline]
- fn visit_enum_map<V>(&mut self, _name: &str, variant: &str, visitor: V) -> io::Result<()>
+ fn visit_enum_map<V>(&mut self,
+ _name: &str,
+ _variant_index: usize,
+ variant: &str,
+ visitor: V) -> io::Result<()>
where V: ser::MapVisitor,
{
try!(self.formatter.open(&mut self.writer, b'{'));
@@ -250,11 +263,14 @@ impl<W, F> ser::Serializer for Serializer<W, F>
V: ser::Serialize,
{
try!(self.formatter.comma(&mut self.writer, self.first));
- self.first = false;
try!(key.serialize(self));
try!(self.formatter.colon(&mut self.writer));
- value.serialize(self)
+ try!(value.serialize(self));
+
+ self.first = false;
+
+ Ok(())
}
#[inline]
diff --git a/serde/src/json/value.rs b/serde_json/src/value.rs
similarity index 96%
rename from serde/src/json/value.rs
rename to serde_json/src/value.rs
index 7006a0e5c..45cb77855 100644
--- a/serde/src/json/value.rs
+++ b/serde_json/src/value.rs
@@ -6,9 +6,10 @@ use std::vec;
use num::NumCast;
-use de;
-use ser;
-use super::error::Error;
+use serde::de;
+use serde::ser;
+
+use error::Error;
#[derive(Clone, PartialEq)]
pub enum Value {
@@ -458,7 +459,10 @@ impl ser::Serializer for Serializer {
}
#[inline]
- fn visit_enum_unit(&mut self, _name: &str, variant: &str) -> Result<(), ()> {
+ fn visit_enum_unit(&mut self,
+ _name: &str,
+ _variant_index: usize,
+ variant: &str) -> Result<(), ()> {
let mut values = BTreeMap::new();
values.insert(variant.to_string(), Value::Array(vec![]));
@@ -489,7 +493,11 @@ impl ser::Serializer for Serializer {
}
#[inline]
- fn visit_enum_seq<V>(&mut self, _name: &str, variant: &str, visitor: V) -> Result<(), ()>
+ fn visit_enum_seq<V>(&mut self,
+ _name: &str,
+ _variant_index: usize,
+ variant: &str,
+ visitor: V) -> Result<(), ()>
where V: ser::SeqVisitor,
{
try!(self.visit_seq(visitor));
@@ -548,7 +556,11 @@ impl ser::Serializer for Serializer {
}
#[inline]
- fn visit_enum_map<V>(&mut self, _name: &str, variant: &str, visitor: V) -> Result<(), ()>
+ fn visit_enum_map<V>(&mut self,
+ _name: &str,
+ _variant_index: usize,
+ variant: &str,
+ visitor: V) -> Result<(), ()>
where V: ser::MapVisitor,
{
try!(self.visit_map(visitor));
@@ -781,7 +793,9 @@ impl<'a> de::VariantVisitor for SeqDeserializer<'a> {
de::Deserializer::visit(self, visitor)
}
- fn visit_map<V>(&mut self, visitor: V) -> Result<V::Value, Error>
+ fn visit_map<V>(&mut self,
+ _fields: &'static [&'static str],
+ visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
de::Deserializer::visit(self, visitor)
@@ -890,7 +904,9 @@ impl<'a> de::VariantVisitor for MapDeserializer<'a> {
de::Deserializer::visit(self, visitor)
}
- fn visit_map<V>(&mut self, visitor: V) -> Result<V::Value, Error>
+ fn visit_map<V>(&mut self,
+ _fields: &'static [&'static str],
+ visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
de::Deserializer::visit(self, visitor)
diff --git a/serde_macros/Cargo.toml b/serde_macros/Cargo.toml
index f9ce2bb2d..fc2d9e406 100644
--- a/serde_macros/Cargo.toml
+++ b/serde_macros/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_macros"
-version = "0.4.4"
+version = "0.5.0"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Macros to auto-generate implementations for the serde framework"
@@ -17,3 +17,4 @@ serde_codegen = { version = "*", path = "../serde_codegen", default-features = f
num = "*"
rustc-serialize = "*"
serde = { version = "*", path = "../serde", features = ["nightly"] }
+serde_json = { version = "*", path = "../serde_json" }
diff --git a/serde_macros/benches/bench.rs b/serde_macros/benches/bench.rs
index 519c189f8..514edc488 100644
--- a/serde_macros/benches/bench.rs
+++ b/serde_macros/benches/bench.rs
@@ -4,6 +4,7 @@
extern crate num;
extern crate rustc_serialize;
extern crate serde;
+extern crate serde_json;
extern crate test;
include!("../../serde_tests/benches/bench.rs.in");
diff --git a/serde_macros/examples/json.rs b/serde_macros/examples/json.rs
index 3da197dfe..50f5d1992 100644
--- a/serde_macros/examples/json.rs
+++ b/serde_macros/examples/json.rs
@@ -2,9 +2,9 @@
#![plugin(serde_macros)]
extern crate serde;
+extern crate serde_json;
use std::collections::BTreeMap;
-use serde::json;
// Creating serializable types with serde is quite simple with `serde_macros`. It implements a
// syntax extension that automatically generates the necessary serde trait implementations.
@@ -18,7 +18,7 @@ fn main() {
let point = Point { x: 5, y: 6 };
// Serializing to JSON is pretty simple by using the `to_string` method:
- let serialized_point = json::to_string(&point).unwrap();
+ let serialized_point = serde_json::to_string(&point).unwrap();
println!("{}", serialized_point);
// prints:
@@ -26,7 +26,7 @@ fn main() {
// {"x":5,"y":6}
// There is also support for pretty printing using `to_string_pretty`:
- let serialized_point = json::to_string_pretty(&point).unwrap();
+ let serialized_point = serde_json::to_string_pretty(&point).unwrap();
println!("{}", serialized_point);
// prints:
@@ -37,7 +37,7 @@ fn main() {
// }
// Values can also be deserialized with the same style using `from_str`:
- let deserialized_point: Point = json::from_str(&serialized_point).unwrap();
+ let deserialized_point: Point = serde_json::from_str(&serialized_point).unwrap();
println!("{:?}", deserialized_point);
// prints:
@@ -46,16 +46,18 @@ fn main() {
// `Point`s aren't the only type that can be serialized to. Because `Point` members have the
// same type, they can be also serialized into a map. Also,
- let deserialized_map: BTreeMap<String, i64> = json::from_str(&serialized_point).unwrap();
+ let deserialized_map: BTreeMap<String, i64> =
+ serde_json::from_str(&serialized_point).unwrap();
println!("{:?}", deserialized_map);
// prints:
//
// {"x": 5, "y": 6}
- // If you need to accept arbitrary data, you can also deserialize into `json::Value`, which
- // can represent all JSON values.
- let deserialized_value: json::Value = json::from_str(&serialized_point).unwrap();
+ // If you need to accept arbitrary data, you can also deserialize into `serde_json::Value`,
+ // which can represent all JSON values.
+ let deserialized_value: serde_json::Value =
+ serde_json::from_str(&serialized_point).unwrap();
println!("{:?}", deserialized_value);
// prints:
| serde-rs/serde | 2015-07-22T15:55:06Z | b2754c2c3bb9cae4ae7dc1d4ce5aa1275dc45dd4 | |
111 | diff --git a/serde_tests/tests/test_bytes.rs b/serde_tests/tests/test_bytes.rs
index 3ca97285a..65c466a38 100644
--- a/serde_tests/tests/test_bytes.rs
+++ b/serde_tests/tests/test_bytes.rs
@@ -39,6 +39,15 @@ impl serde::Serializer for BytesSerializer {
Err(Error)
}
+ fn visit_enum_simple<T>(&mut self,
+ _name: &str,
+ _variant: &str,
+ _value: T,
+ ) -> Result<(), Error>
+ {
+ Err(Error)
+ }
+
fn visit_bool(&mut self, _v: bool) -> Result<(), Error> {
Err(Error)
}
diff --git a/serde_tests/tests/test_json.rs b/serde_tests/tests/test_json.rs
index 931527e97..14345a289 100644
--- a/serde_tests/tests/test_json.rs
+++ b/serde_tests/tests/test_json.rs
@@ -28,7 +28,7 @@ enum Animal {
Dog,
Frog(String, Vec<isize>),
Cat { age: usize, name: String },
-
+ AntHive(Vec<String>),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -534,6 +534,10 @@ fn test_write_enum() {
Animal::Cat { age: 5, name: "Kate".to_string() },
"{\"Cat\":{\"age\":5,\"name\":\"Kate\"}}"
),
+ (
+ Animal::AntHive(vec!["Bob".to_string(), "Stuart".to_string()]),
+ "{\"AntHive\":[\"Bob\",\"Stuart\"]}",
+ ),
]);
test_pretty_encode_ok(&[
@@ -976,6 +980,10 @@ fn test_parse_enum() {
" { \"Cat\" : { \"age\" : 5 , \"name\" : \"Kate\" } } ",
Animal::Cat { age: 5, name: "Kate".to_string() },
),
+ (
+ " { \"AntHive\" : [\"Bob\", \"Stuart\"] } ",
+ Animal::AntHive(vec!["Bob".to_string(), "Stuart".to_string()]),
+ ),
]);
test_parse_ok(vec![
diff --git a/serde_tests/tests/test_macros.rs b/serde_tests/tests/test_macros.rs
index 3c41ca4c7..c36e086ef 100644
--- a/serde_tests/tests/test_macros.rs
+++ b/serde_tests/tests/test_macros.rs
@@ -473,13 +473,13 @@ fn test_lifetimes() {
let lifetime = Lifetimes::LifetimeSeq(&value);
assert_eq!(
serde_json::to_string(&lifetime).unwrap(),
- "{\"LifetimeSeq\":[5]}"
+ "{\"LifetimeSeq\":5}"
);
let lifetime = Lifetimes::NoLifetimeSeq(5);
assert_eq!(
serde_json::to_string(&lifetime).unwrap(),
- "{\"NoLifetimeSeq\":[5]}"
+ "{\"NoLifetimeSeq\":5}"
);
let value = 5;
@@ -515,8 +515,8 @@ fn test_generic() {
declare_tests!(
GenericStruct<u32> : GenericStruct { x: 5 } => "{\"x\":5}",
GenericTupleStruct<u32> : GenericTupleStruct(5) => "[5]",
- GenericEnumSeq<u32, u32> : GenericEnumSeq::Ok(5) => "{\"Ok\":[5]}",
- GenericEnumSeq<u32, u32> : GenericEnumSeq::Err(5) => "{\"Err\":[5]}",
+ GenericEnumSeq<u32, u32> : GenericEnumSeq::Ok(5) => "{\"Ok\":5}",
+ GenericEnumSeq<u32, u32> : GenericEnumSeq::Err(5) => "{\"Err\":5}",
GenericEnumMap<u32, u32> : GenericEnumMap::Ok { x: 5 } => "{\"Ok\":{\"x\":5}}",
GenericEnumMap<u32, u32> : GenericEnumMap::Err { x: 5 } => "{\"Err\":{\"x\":5}}",
);
diff --git a/serde_tests/tests/test_ser.rs b/serde_tests/tests/test_ser.rs
index 950b5b828..62627fba1 100644
--- a/serde_tests/tests/test_ser.rs
+++ b/serde_tests/tests/test_ser.rs
@@ -27,6 +27,8 @@ pub enum Token<'a> {
UnitStruct(&'a str),
EnumUnit(&'a str, &'a str),
+ EnumSimple(&'a str, &'a str),
+
SeqStart(Option<usize>),
TupleStructStart(&'a str, Option<usize>),
EnumSeqStart(&'a str, &'a str, Option<usize>),
@@ -80,6 +82,17 @@ impl<'a> Serializer for AssertSerializer<'a> {
Ok(())
}
+ fn visit_enum_simple<T>(&mut self,
+ name: &str,
+ variant: &str,
+ value: T,
+ ) -> Result<(), ()>
+ where T: Serialize,
+ {
+ assert_eq!(self.iter.next(), Some(Token::EnumSimple(name, variant)));
+ value.serialize(self)
+ }
+
fn visit_unit_struct(&mut self, name: &str) -> Result<(), ()> {
assert_eq!(self.iter.next().unwrap(), Token::UnitStruct(name));
Ok(())
@@ -301,6 +314,7 @@ struct Struct {
#[derive(Serialize)]
enum Enum {
Unit,
+ One(i32),
Seq(i32, i32),
Map { a: i32, b: i32 },
}
@@ -554,6 +568,7 @@ declare_tests! {
}
test_enum {
Enum::Unit => vec![Token::EnumUnit("Enum", "Unit")],
+ Enum::One(42) => vec![Token::EnumSimple("Enum", "One"), Token::I32(42)],
Enum::Seq(1, 2) => vec![
Token::EnumSeqStart("Enum", "Seq", Some(2)),
Token::SeqSep,
| [
"104"
] | serde-rs__serde-111 | Enum-Tuple-Variant with single element should not be a sequence
``` rust
#[Deserialize]
enum A {
B(i32),
C(Vec<i32>),
}
```
The json for this requires additional square brackets for another array layer.
``` json
{"C":[[5, 6, 7]]}
or
{"B":[42]}
```
Unit variants are already handles specially. I propose to also handle single element variants specially, so the following would be legal:
``` json
{"C":[5, 6, 7]}
or
{"B":42}
```
Anyone that wishes to have the previous behavior, could use an explicit tuple.
``` rust
#[Deserialize]
enum A {
B((i32,)),
C((Vec<i32>,)),
}
```
Alternatively deserialization might accept both, but that might be more of a mess than it's worth
| 0.5 | 447d08bd9121b871ab6d646bdeba66321a948194 | diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index 5484a7b7c..2f3c6a301 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -571,6 +571,11 @@ pub trait VariantVisitor {
Err(Error::syntax_error())
}
+ /// `visit_simple` is called when deserializing a variant with a single value.
+ fn visit_simple<T: Deserialize>(&mut self) -> Result<T, Self::Error> {
+ Err(Error::syntax_error())
+ }
+
/// `visit_seq` is called when deserializing a tuple-like variant.
fn visit_seq<V>(&mut self, _visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor
@@ -601,6 +606,10 @@ impl<'a, T> VariantVisitor for &'a mut T where T: VariantVisitor {
(**self).visit_unit()
}
+ fn visit_simple<D: Deserialize>(&mut self) -> Result<D, T::Error> {
+ (**self).visit_simple()
+ }
+
fn visit_seq<V>(&mut self, visitor: V) -> Result<V::Value, T::Error>
where V: Visitor,
{
diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs
index d816dc35a..4484d344d 100644
--- a/serde/src/ser/mod.rs
+++ b/serde/src/ser/mod.rs
@@ -125,6 +125,14 @@ pub trait Serializer {
self.visit_unit()
}
+ #[inline]
+ fn visit_enum_simple<T>(&mut self,
+ _name: &str,
+ _variant: &str,
+ _value: T,
+ ) -> Result<(), Self::Error>
+ where T: Serialize;
+
fn visit_none(&mut self) -> Result<(), Self::Error>;
fn visit_some<V>(&mut self, value: V) -> Result<(), Self::Error>
diff --git a/serde_codegen/src/de.rs b/serde_codegen/src/de.rs
index 3f949df00..90f7d7ff6 100644
--- a/serde_codegen/src/de.rs
+++ b/serde_codegen/src/de.rs
@@ -555,6 +555,12 @@ fn deserialize_variant(
Ok($type_ident::$variant_ident)
})
}
+ ast::TupleVariantKind(ref args) if args.len() == 1 => {
+ quote_expr!(cx, {
+ let val = try!(visitor.visit_simple());
+ Ok($type_ident::$variant_ident(val))
+ })
+ }
ast::TupleVariantKind(ref args) => {
deserialize_tuple_variant(
cx,
diff --git a/serde_codegen/src/ser.rs b/serde_codegen/src/ser.rs
index 8c74e1199..fb48eb25e 100644
--- a/serde_codegen/src/ser.rs
+++ b/serde_codegen/src/ser.rs
@@ -296,7 +296,25 @@ fn serialize_variant(
)
}
)
- }
+ },
+ ast::TupleVariantKind(ref args) if args.len() == 1 => {
+ let field = builder.id("__simple_value");
+ let field = builder.pat().ref_id(field);
+ let pat = builder.pat().enum_()
+ .id(type_ident).id(variant_ident).build()
+ .with_pats(Some(field).into_iter())
+ .build();
+ quote_arm!(cx,
+ $pat => {
+ ::serde::ser::Serializer::visit_enum_simple(
+ serializer,
+ $type_name,
+ $variant_name,
+ __simple_value,
+ )
+ }
+ )
+ },
ast::TupleVariantKind(ref args) => {
let fields: Vec<ast::Ident> = (0 .. args.len())
.map(|i| builder.id(format!("__field{}", i)))
diff --git a/serde_json/src/de.rs b/serde_json/src/de.rs
index 8bb33931d..efdd53df8 100644
--- a/serde_json/src/de.rs
+++ b/serde_json/src/de.rs
@@ -632,20 +632,22 @@ impl<Iter> de::VariantVisitor for Deserializer<Iter>
fn visit_variant<V>(&mut self) -> Result<V, Error>
where V: de::Deserialize
{
- de::Deserialize::deserialize(self)
+ let val = try!(de::Deserialize::deserialize(self));
+ try!(self.parse_object_colon());
+ Ok(val)
}
fn visit_unit(&mut self) -> Result<(), Error> {
- try!(self.parse_object_colon());
+ de::Deserialize::deserialize(self)
+ }
+ fn visit_simple<T: de::Deserialize>(&mut self) -> Result<T, Error> {
de::Deserialize::deserialize(self)
}
fn visit_seq<V>(&mut self, visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
- try!(self.parse_object_colon());
-
de::Deserializer::visit(self, visitor)
}
@@ -654,8 +656,6 @@ impl<Iter> de::VariantVisitor for Deserializer<Iter>
visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
- try!(self.parse_object_colon());
-
de::Deserializer::visit(self, visitor)
}
}
diff --git a/serde_json/src/lib.rs b/serde_json/src/lib.rs
index 2e13f2a42..3032db9c2 100644
--- a/serde_json/src/lib.rs
+++ b/serde_json/src/lib.rs
@@ -61,12 +61,12 @@
//! //#![feature(custom_derive, plugin)]
//! //#![plugin(serde_macros)]
//!
-//! extern crate serde;
+//! extern crate serde_json;
//!
-//! use serde_json::{self, Value};
+//! use serde_json::Value;
//!
//! fn main() {
-//! let data: Value = json::from_str("{\"foo\": 13, \"bar\": \"baz\"}").unwrap();
+//! let data: Value = serde_json::from_str("{\"foo\": 13, \"bar\": \"baz\"}").unwrap();
//! println!("data: {:?}", data);
//! // data: {"bar":"baz","foo":13}
//! println!("object? {}", data.is_object());
diff --git a/serde_json/src/ser.rs b/serde_json/src/ser.rs
index 294a7f494..b7f5b2d81 100644
--- a/serde_json/src/ser.rs
+++ b/serde_json/src/ser.rs
@@ -171,6 +171,22 @@ impl<W, F> ser::Serializer for Serializer<W, F>
self.formatter.close(&mut self.writer, b'}')
}
+ #[inline]
+ fn visit_enum_simple<T>(&mut self,
+ _name: &str,
+ variant: &str,
+ value: T,
+ ) -> io::Result<()>
+ where T: ser::Serialize,
+ {
+ try!(self.formatter.open(&mut self.writer, b'{'));
+ try!(self.formatter.comma(&mut self.writer, true));
+ try!(self.visit_str(variant));
+ try!(self.formatter.colon(&mut self.writer));
+ try!(value.serialize(self));
+ self.formatter.close(&mut self.writer, b'}')
+ }
+
#[inline]
fn visit_seq<V>(&mut self, mut visitor: V) -> io::Result<()>
where V: ser::SeqVisitor,
diff --git a/serde_json/src/value.rs b/serde_json/src/value.rs
index 45cb77855..f01dfe1d6 100644
--- a/serde_json/src/value.rs
+++ b/serde_json/src/value.rs
@@ -471,6 +471,22 @@ impl ser::Serializer for Serializer {
Ok(())
}
+ #[inline]
+ fn visit_enum_simple<T>(&mut self,
+ _name: &str,
+ variant: &str,
+ value: T,
+ ) -> Result<(), ()>
+ where T: ser::Serialize,
+ {
+ let mut values = BTreeMap::new();
+ values.insert(variant.to_string(), to_value(&value));
+
+ self.state.push(State::Value(Value::Object(values)));
+
+ Ok(())
+ }
+
#[inline]
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<(), ()>
where V: ser::SeqVisitor,
@@ -687,33 +703,19 @@ impl de::Deserializer for Deserializer {
let mut iter = value.into_iter();
- let value = match iter.next() {
- Some((variant, Value::Array(fields))) => {
- self.value = Some(Value::String(variant));
-
- let len = fields.len();
- try!(visitor.visit(SeqDeserializer {
- de: self,
- iter: fields.into_iter(),
- len: len,
- }))
- }
- Some((variant, Value::Object(fields))) => {
- let len = fields.len();
- try!(visitor.visit(MapDeserializer {
- de: self,
- iter: fields.into_iter(),
- value: Some(Value::String(variant)),
- len: len,
- }))
- }
- Some(_) => { return Err(de::Error::syntax_error()); }
- None => { return Err(de::Error::syntax_error()); }
+ let (variant, value) = match iter.next() {
+ Some(v) => v,
+ None => return Err(de::Error::syntax_error()),
};
+ // enums are encoded in json as maps with a single key:value pair
match iter.next() {
Some(_) => Err(de::Error::syntax_error()),
- None => Ok(value)
+ None => visitor.visit(VariantDeserializer {
+ de: self,
+ val: Some(value),
+ variant: Some(Value::String(variant)),
+ }),
}
}
@@ -723,6 +725,67 @@ impl de::Deserializer for Deserializer {
}
}
+struct VariantDeserializer<'a> {
+ de: &'a mut Deserializer,
+ val: Option<Value>,
+ variant: Option<Value>,
+}
+
+impl<'a> de::VariantVisitor for VariantDeserializer<'a> {
+ type Error = Error;
+
+ fn visit_variant<V>(&mut self) -> Result<V, Error>
+ where V: de::Deserialize,
+ {
+ de::Deserialize::deserialize(&mut Deserializer::new(self.variant.take().unwrap()))
+ }
+
+ fn visit_unit(&mut self) -> Result<(), Error>
+ {
+ de::Deserialize::deserialize(&mut Deserializer::new(self.val.take().unwrap()))
+ }
+
+ fn visit_simple<D: de::Deserialize>(&mut self) -> Result<D, Error>
+ {
+ de::Deserialize::deserialize(&mut Deserializer::new(self.val.take().unwrap()))
+ }
+
+ fn visit_seq<V>(&mut self, visitor: V) -> Result<V::Value, Error>
+ where V: de::Visitor,
+ {
+ if let Value::Array(fields) = self.val.take().unwrap() {
+ de::Deserializer::visit(
+ &mut SeqDeserializer {
+ de: self.de,
+ len: fields.len(),
+ iter: fields.into_iter(),
+ },
+ visitor,
+ )
+ } else {
+ Err(de::Error::syntax_error())
+ }
+ }
+
+ fn visit_map<V>(&mut self, _fields: &'static[&'static str], visitor: V) -> Result<V::Value, Error>
+ where V: de::Visitor,
+ {
+ if let Value::Object(fields) = self.val.take().unwrap() {
+ de::Deserializer::visit(
+ &mut MapDeserializer {
+ de: self.de,
+ len: fields.len(),
+ iter: fields.into_iter(),
+ value: None,
+ },
+ visitor,
+ )
+ } else {
+ Err(de::Error::syntax_error())
+ }
+ }
+}
+
struct SeqDeserializer<'a> {
de: &'a mut Deserializer,
iter: vec::IntoIter<Value>,
@@ -773,35 +836,6 @@ impl<'a> de::SeqVisitor for SeqDeserializer<'a> {
}
}
-impl<'a> de::VariantVisitor for SeqDeserializer<'a> {
- type Error = Error;
-
- fn visit_variant<V>(&mut self) -> Result<V, Error>
- where V: de::Deserialize,
- {
- de::Deserialize::deserialize(self.de)
- }
-
- fn visit_unit(&mut self) -> Result<(), Error>
- {
- de::Deserialize::deserialize(self)
- }
-
- fn visit_seq<V>(&mut self, visitor: V) -> Result<V::Value, Error>
- where V: de::Visitor,
- {
- de::Deserializer::visit(self, visitor)
- }
-
- fn visit_map<V>(&mut self,
- _fields: &'static [&'static str],
- visitor: V) -> Result<V::Value, Error>
- where V: de::Visitor,
- {
- de::Deserializer::visit(self, visitor)
- }
-}
-
struct MapDeserializer<'a> {
de: &'a mut Deserializer,
iter: btree_map::IntoIter<String, Value>,
@@ -884,35 +918,6 @@ impl<'a> de::Deserializer for MapDeserializer<'a> {
}
}
-impl<'a> de::VariantVisitor for MapDeserializer<'a> {
- type Error = Error;
-
- fn visit_variant<V>(&mut self) -> Result<V, Error>
- where V: de::Deserialize,
- {
- self.de.value = self.value.take();
- de::Deserialize::deserialize(self.de)
- }
-
- fn visit_unit(&mut self) -> Result<(), Error> {
- de::Deserialize::deserialize(self)
- }
-
- fn visit_seq<V>(&mut self, visitor: V) -> Result<V::Value, Error>
- where V: de::Visitor,
- {
- de::Deserializer::visit(self, visitor)
- }
-
- fn visit_map<V>(&mut self,
- _fields: &'static [&'static str],
- visitor: V) -> Result<V::Value, Error>
- where V: de::Visitor,
- {
- de::Deserializer::visit(self, visitor)
- }
-}
-
/// Shortcut function to encode a `T` into a JSON `Value`
pub fn to_value<T>(value: &T) -> Value
where T: ser::Serialize
| serde-rs/serde | 2015-07-17T13:23:12Z | The use-case is the pandoc ast
http://hackage.haskell.org/package/pandoc-types-1.12.4.4/docs/Text-Pandoc-Definition.html
That is interesting, because "normal" single element variants serialize directly as their inner type.
O_o, i need to investigate further then... maybe a newtype might come to my rescue
My claim isn't true, it was in a faulty version I wrote some time ago. Sorry for the rush.
| 7b773ac08880adece2f1bd809efcbd5828b23293 |
80 | diff --git a/serde_tests/tests/test_json.rs b/serde_tests/tests/test_json.rs
index 58f118dac..c29f82865 100644
--- a/serde_tests/tests/test_json.rs
+++ b/serde_tests/tests/test_json.rs
@@ -703,6 +703,7 @@ fn test_parse_number_errors() {
("1e+", Error::SyntaxError(ErrorCode::InvalidNumber, 1, 3)),
("1a", Error::SyntaxError(ErrorCode::TrailingCharacters, 1, 2)),
("777777777777777777777777777", Error::SyntaxError(ErrorCode::InvalidNumber, 1, 20)),
+ ("1e777777777777777777777777777", Error::SyntaxError(ErrorCode::InvalidNumber, 1, 22)),
]);
}
| [
"77"
] | serde-rs__serde-80 | Integer overflow when parsing JSON scientific notation number
This is a different issue from #75
### Code
``` rust
#![feature(plugin)]
#![plugin(afl_coverage_plugin)]
extern crate afl_coverage;
extern crate serde;
use std::io::{self, Read, Cursor};
use serde::json::{self, Value};
fn main() {
let mut input = String::new();
let result = io::stdin().read_to_string(&mut input);
if result.is_ok() {
if let Ok(j) = json::from_str::<json::Value>(&input) {
let _ = json::to_string(&j);
}
}
}
```
### Input
```
[7E-7777777777]
```
### Crash
```
root@vultr:~/afl-staging-area2# cargo run < outputs/crashes/id\:000008*
Running `target/debug/afl-staging-area2`
thread '<main>' panicked at 'arithmetic operation overflowed', /root/serde/serde/src/json/de.rs:270
An unknown error occurred
To learn more, run the command again with --verbose.
```
This bug was found using https://github.com/kmcallister/afl.rs 👍
| 0.4 | 81d617bd936b15a24db7d800bb92d6d0bafc9ed6 | diff --git a/serde/src/json/de.rs b/serde/src/json/de.rs
index 1d0bc8d94..a5ec279bb 100644
--- a/serde/src/json/de.rs
+++ b/serde/src/json/de.rs
@@ -249,7 +249,7 @@ impl<Iter> Deserializer<Iter>
fn parse_exponent(&mut self, mut res: f64) -> Result<f64, Error> {
try!(self.bump());
- let mut exp = 0;
+ let mut exp: u64 = 0;
let mut neg_exp = false;
if self.ch_is(b'+') {
@@ -267,8 +267,16 @@ impl<Iter> Deserializer<Iter>
while !self.eof() {
match self.ch_or_null() {
c @ b'0' ... b'9' => {
- exp *= 10;
- exp += (c as i32) - (b'0' as i32);
+ macro_rules! try_or_invalid {
+ ($e: expr) => {
+ match $e {
+ Some(v) => v,
+ None => { return Err(self.error(ErrorCode::InvalidNumber)); }
+ }
+ }
+ }
+ exp = try_or_invalid!(exp.checked_mul(10));
+ exp = try_or_invalid!(exp.checked_add((c as u64) - (b'0' as u64)));
try!(self.bump());
}
@@ -276,7 +284,7 @@ impl<Iter> Deserializer<Iter>
}
}
- let exp: f64 = 10_f64.powi(exp);
+ let exp: f64 = 10_f64.powf(exp as f64);
if neg_exp {
res /= exp;
} else {
| serde-rs/serde | 2015-05-20T14:35:12Z | b2754c2c3bb9cae4ae7dc1d4ce5aa1275dc45dd4 | |
64 | diff --git a/tests/test_json.rs b/tests/test_json.rs
index 2135f0c5d..ba45d9747 100644
--- a/tests/test_json.rs
+++ b/tests/test_json.rs
@@ -1,4 +1,4 @@
-#![feature(custom_derive, plugin, test)]
+#![feature(custom_derive, plugin, test, custom_attribute)]
#![plugin(serde_macros)]
extern crate test;
@@ -1019,3 +1019,26 @@ fn test_missing_field() {
))).unwrap();
assert_eq!(value, Foo { x: Some(5) });
}
+
+#[test]
+fn test_missing_renamed_field() {
+ #[derive(Debug, PartialEq, Deserialize)]
+ struct Foo {
+ #[serde(rename_deserialize="y")]
+ x: Option<u32>,
+ }
+
+ let value: Foo = from_str("{}").unwrap();
+ assert_eq!(value, Foo { x: None });
+
+ let value: Foo = from_str("{\"y\": 5}").unwrap();
+ assert_eq!(value, Foo { x: Some(5) });
+
+ let value: Foo = from_value(Value::Object(treemap!())).unwrap();
+ assert_eq!(value, Foo { x: None });
+
+ let value: Foo = from_value(Value::Object(treemap!(
+ "y".to_string() => Value::I64(5)
+ ))).unwrap();
+ assert_eq!(value, Foo { x: Some(5) });
+}
| [
"63"
] | serde-rs__serde-64 | MapVisitor::missing_field gets the original field name, not the renamed name
Deserializing the following struct calls `missing_field` with `field=="myval"` instead of `field=="blubber"`
``` rust
struct Test {
#[serde(rename="blubber")]
myval: String,
}
```
| null | ed1b476a22aed23674e81b326a706eac64178de0 | diff --git a/serde_macros/src/de.rs b/serde_macros/src/de.rs
index a47ad0abc..14716bf0f 100644
--- a/serde_macros/src/de.rs
+++ b/serde_macros/src/de.rs
@@ -639,9 +639,11 @@ fn deserialize_map(
let extract_values: Vec<P<ast::Stmt>> = field_names.iter()
.zip(struct_def.fields.iter())
.map(|(field_name, field)| {
- let name_str = match field.node.kind {
- ast::NamedField(name, _) => builder.expr().str(name),
- ast::UnnamedField(_) => panic!("struct contains unnamed fields"),
+ let rename = field::field_rename(field, &field::Direction::Deserialize);
+ let name_str = match (rename, field.node.kind) {
+ (Some(rename), _) => builder.expr().build_lit(P(rename.clone())),
+ (None, ast::NamedField(name, _)) => builder.expr().str(name),
+ (None, ast::UnnamedField(_)) => panic!("struct contains unnamed fields"),
};
let missing_expr = if field::default_value(field) {
diff --git a/serde_macros/src/field.rs b/serde_macros/src/field.rs
index baa79009f..c35e694ba 100644
--- a/serde_macros/src/field.rs
+++ b/serde_macros/src/field.rs
@@ -10,7 +10,7 @@ pub enum Direction {
Deserialize,
}
-fn field_rename<'a>(
+pub fn field_rename<'a>(
field: &'a ast::StructField,
direction: &Direction,
) -> Option<&'a ast::Lit> {
| serde-rs/serde | 2015-04-23T14:44:58Z | 8cb6607e827717136a819caa44d8e43702724883 | |
1,656 | diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index 16628efd6..025d87b09 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -889,11 +889,37 @@ declare_tests! {
Path::new("/usr/local/lib") => &[
Token::BorrowedStr("/usr/local/lib"),
],
+ Path::new("/usr/local/lib") => &[
+ Token::BorrowedBytes(b"/usr/local/lib"),
+ ],
}
test_path_buf {
PathBuf::from("/usr/local/lib") => &[
+ Token::Str("/usr/local/lib"),
+ ],
+ PathBuf::from("/usr/local/lib") => &[
+ Token::String("/usr/local/lib"),
+ ],
+ PathBuf::from("/usr/local/lib") => &[
+ Token::Bytes(b"/usr/local/lib"),
+ ],
+ PathBuf::from("/usr/local/lib") => &[
+ Token::ByteBuf(b"/usr/local/lib"),
+ ],
+ }
+ test_boxed_path {
+ PathBuf::from("/usr/local/lib").into_boxed_path() => &[
+ Token::Str("/usr/local/lib"),
+ ],
+ PathBuf::from("/usr/local/lib").into_boxed_path() => &[
Token::String("/usr/local/lib"),
],
+ PathBuf::from("/usr/local/lib").into_boxed_path() => &[
+ Token::Bytes(b"/usr/local/lib"),
+ ],
+ PathBuf::from("/usr/local/lib").into_boxed_path() => &[
+ Token::ByteBuf(b"/usr/local/lib"),
+ ],
}
test_cstring {
CString::new("abc").unwrap() => &[
| [
"1633"
] | serde-rs__serde-1656 | Support deserializing Box<Path>
I've tried to derive `Deserialize` for a `Rc<Path>` field, which fails.
If I understand the code correctly, it's missing a
```
forwarded_impl!((), Box<Path>, PathBuf::into_boxed_path);
```
so the `Rc<Path>` forwards to `Box<Path>` forwards to `PathBuf`.
| 1.10 | cf314185558f92fecc4f81ea98b3648967bfc8ea | diff --git a/serde/build.rs b/serde/build.rs
index e36ed62f5..a78b6d79a 100644
--- a/serde/build.rs
+++ b/serde/build.rs
@@ -29,8 +29,9 @@ fn main() {
println!("cargo:rustc-cfg=core_reverse");
}
- // CString::into_boxed_c_str stabilized in Rust 1.20:
+ // CString::into_boxed_c_str and PathBuf::into_boxed_path stabilized in Rust 1.20:
// https://doc.rust-lang.org/std/ffi/struct.CString.html#method.into_boxed_c_str
+ // https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.into_boxed_path
if minor >= 20 {
println!("cargo:rustc-cfg=de_boxed_c_str");
}
diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index e96314809..cffe05900 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -1580,6 +1580,24 @@ impl<'de> Visitor<'de> for PathBufVisitor {
{
Ok(From::from(v))
}
+
+ fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
+ where
+ E: Error,
+ {
+ str::from_utf8(v)
+ .map(From::from)
+ .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
+ }
+
+ fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
+ where
+ E: Error,
+ {
+ String::from_utf8(v)
+ .map(From::from)
+ .map_err(|e| Error::invalid_value(Unexpected::Bytes(&e.into_bytes()), &self))
+ }
}
#[cfg(feature = "std")]
@@ -1592,6 +1610,9 @@ impl<'de> Deserialize<'de> for PathBuf {
}
}
+#[cfg(all(feature = "std", de_boxed_c_str))]
+forwarded_impl!((), Box<Path>, PathBuf::into_boxed_path);
+
////////////////////////////////////////////////////////////////////////////////
// If this were outside of the serde crate, it would just use:
| serde-rs/serde | 2019-10-22T20:59:50Z | Thanks, I would accept a PR to fix this. | 099fa25b86524f07d86852ea2de071e8dd2a653f |
1,622 | diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index 3946865b8..16628efd6 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -104,6 +104,9 @@ struct StructSkipAllDenyUnknown {
a: i32,
}
+#[derive(Default, PartialEq, Debug)]
+struct NotDeserializable;
+
#[derive(PartialEq, Debug, Deserialize)]
enum Enum {
#[allow(dead_code)]
@@ -117,6 +120,7 @@ enum Enum {
b: i32,
c: i32,
},
+ SimpleWithSkipped(#[serde(skip_deserializing)] NotDeserializable),
}
#[derive(PartialEq, Debug, Deserialize)]
@@ -728,6 +732,11 @@ declare_tests! {
Token::I32(1),
],
}
+ test_enum_simple_with_skipped {
+ Enum::SimpleWithSkipped(NotDeserializable) => &[
+ Token::UnitVariant { name: "Enum", variant: "SimpleWithSkipped" },
+ ],
+ }
test_enum_seq {
Enum::Seq(1, 2, 3) => &[
Token::TupleVariant { name: "Enum", variant: "Seq", len: 3 },
@@ -1217,13 +1226,13 @@ declare_error_tests! {
&[
Token::UnitVariant { name: "Enum", variant: "Foo" },
],
- "unknown variant `Foo`, expected one of `Unit`, `Simple`, `Seq`, `Map`",
+ "unknown variant `Foo`, expected one of `Unit`, `Simple`, `Seq`, `Map`, `SimpleWithSkipped`",
}
test_enum_skipped_variant<Enum> {
&[
Token::UnitVariant { name: "Enum", variant: "Skipped" },
],
- "unknown variant `Skipped`, expected one of `Unit`, `Simple`, `Seq`, `Map`",
+ "unknown variant `Skipped`, expected one of `Unit`, `Simple`, `Seq`, `Map`, `SimpleWithSkipped`",
}
test_enum_skip_all<EnumSkipAll> {
&[
@@ -1254,10 +1263,10 @@ declare_error_tests! {
test_enum_out_of_range<Enum> {
&[
Token::Enum { name: "Enum" },
- Token::U32(4),
+ Token::U32(5),
Token::Unit,
],
- "invalid value: integer `4`, expected variant index 0 <= i < 4",
+ "invalid value: integer `5`, expected variant index 0 <= i < 5",
}
test_short_tuple<(u8, u8, u8)> {
&[
diff --git a/test_suite/tests/test_ser.rs b/test_suite/tests/test_ser.rs
index 719e987d8..68293f5a1 100644
--- a/test_suite/tests/test_ser.rs
+++ b/test_suite/tests/test_ser.rs
@@ -44,6 +44,9 @@ struct Struct {
c: i32,
}
+#[derive(PartialEq, Debug)]
+struct NotSerializable;
+
#[derive(Serialize, PartialEq, Debug)]
enum Enum {
Unit,
@@ -64,6 +67,7 @@ enum Enum {
_a: i32,
_b: i32,
},
+ OneWithSkipped(#[serde(skip_serializing)] NotSerializable),
}
//////////////////////////////////////////////////////////////////////////
@@ -326,6 +330,7 @@ declare_tests! {
Token::I32(2),
Token::StructVariantEnd,
],
+ Enum::OneWithSkipped(NotSerializable) => &[Token::UnitVariant {name: "Enum", variant: "OneWithSkipped" }],
}
test_box {
Box::new(0i32) => &[Token::I32(0)],
| [
"1396"
] | serde-rs__serde-1622 | #[serde(skip)] in tuple enum variants silently ignored
```rust
#[macro_use]
extern crate serde_derive; // 1.0.78
extern crate serde; // 1.0.78
struct S;
#[derive(Serialize)]
enum E {
V(#[serde(skip)] S),
}
```
```
error[E0277]: the trait bound `S: serde::Serialize` is not satisfied
--> src/lib.rs:7:10
|
7 | #[derive(Serialize)]
| ^^^^^^^^^ the trait `serde::Serialize` is not implemented for `S`
|
= note: required by `serde::Serializer::serialize_newtype_variant`
error: aborting due to previous error
```
[Playground](https://play.rust-lang.org/?gist=52468306cc60f55fd62d11eba4a1ca45&version=stable&mode=debug&edition=2015)
The attribute should either work (thus serializing like `enum E { V() }` or give an error/warning that it has no meaning in this position.
| 1.0 | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index acc6dfb70..d54309c85 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -1689,6 +1689,24 @@ fn deserialize_externally_tagged_variant(
}
}
Style::Newtype => {
+ if variant.fields[0].attrs.skip_deserializing() {
+ let this = ¶ms.this;
+ let let_default = match variant.fields[0].attrs.default() {
+ attr::Default::Default => quote!(
+ _serde::export::Default::default()
+ ),
+ attr::Default::Path(ref path) => quote!(
+ #path()
+ ),
+ attr::Default::None => unimplemented!(),
+ };
+
+
+ return quote_block! {
+ try!(_serde::de::VariantAccess::unit_variant(__variant));
+ _serde::export::Ok(#this::#variant_ident(#let_default))
+ };
+ }
deserialize_externally_tagged_newtype_variant(variant_ident, params, &variant.fields[0])
}
Style::Tuple => {
@@ -1839,6 +1857,21 @@ fn deserialize_untagged_newtype_variant(
let field_ty = field.ty;
match field.attrs.deserialize_with() {
None => {
+ if field.attrs.skip_deserializing() {
+ let let_default = match field.attrs.default() {
+ attr::Default::Default => quote!(
+ _serde::export::Default::default()
+ ),
+ attr::Default::Path(ref path) => quote!(
+ #path()
+ ),
+ attr::Default::None => unimplemented!(),
+ };
+
+ return quote_expr! {
+ _serde::export::Ok(#this::#variant_ident(#let_default))
+ };
+ }
let span = field.original.span();
let func = quote_spanned!(span=> <#field_ty as _serde::Deserialize>::deserialize);
quote_expr! {
diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index 57caaaff5..e79b8e7eb 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -522,6 +522,16 @@ fn serialize_externally_tagged_variant(
}
Style::Newtype => {
let field = &variant.fields[0];
+ if field.attrs.skip_serializing() {
+ return quote_expr! {
+ _serde::Serializer::serialize_unit_variant(
+ __serializer,
+ #type_name,
+ #variant_index,
+ #variant_name,
+ )
+ }
+ }
let mut field_expr = quote!(__field0);
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr);
@@ -598,6 +608,15 @@ fn serialize_internally_tagged_variant(
}
Style::Newtype => {
let field = &variant.fields[0];
+ if field.attrs.skip_serializing() {
+ return quote_block! {
+ let mut __struct = try!(_serde::Serializer::serialize_struct(
+ __serializer, #type_name, 1));
+ try!(_serde::ser::SerializeStruct::serialize_field(
+ &mut __struct, #tag, #variant_name));
+ _serde::ser::SerializeStruct::end(__struct)
+ };
+ }
let mut field_expr = quote!(__field0);
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr);
@@ -658,6 +677,15 @@ fn serialize_adjacently_tagged_variant(
}
Style::Newtype => {
let field = &variant.fields[0];
+ if field.attrs.skip_serializing() {
+ return quote_block! {
+ let mut __struct = try!(_serde::Serializer::serialize_struct(
+ __serializer, #type_name, 1));
+ try!(_serde::ser::SerializeStruct::serialize_field(
+ &mut __struct, #tag, #variant_name));
+ _serde::ser::SerializeStruct::end(__struct)
+ };
+ }
let mut field_expr = quote!(__field0);
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr);
@@ -761,6 +789,11 @@ fn serialize_untagged_variant(
}
Style::Newtype => {
let field = &variant.fields[0];
+ if field.attrs.skip_serializing() {
+ return quote_expr! {
+ _serde::Serializer::serialize_unit(__serializer)
+ };
+ }
let mut field_expr = quote!(__field0);
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr);
| serde-rs/serde | 2019-09-07T09:28:37Z | Just ran into this today. Changing the variant into
```rust
enum E {
V { #[serde(skip)] v: S }
}
```
makes it work as expected. I think should just work instead of an error. This is likely a bug.
This also applies to tuple structs (e.g. `struct Ignore(#[serde(skip)] Foo);`).
Might be related to why `#[serde(default)]` is also ignored: https://github.com/serde-rs/serde/issues/1418. | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,572 | diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index 90e0f3951..c970b8de8 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -9,6 +9,7 @@ use std::num::Wrapping;
use std::ops::Bound;
use std::path::{Path, PathBuf};
use std::rc::{Rc, Weak as RcWeak};
+use std::sync::atomic;
use std::sync::{Arc, Weak as ArcWeak};
use std::time::{Duration, UNIX_EPOCH};
@@ -1140,6 +1141,81 @@ fn test_never_type() {
);
}
+macro_rules! assert_de_tokens_atomic {
+ ($ty:ty, $val:expr, $tokens:expr) => {
+ let mut de = serde_test::Deserializer::new($tokens);
+ match <$ty>::deserialize(&mut de) {
+ Ok(v) => {
+ let loaded = v.load(atomic::Ordering::SeqCst);
+ assert_eq!($val, loaded);
+ },
+ Err(e) => panic!("tokens failed to deserialize: {}", e)
+ };
+ if de.remaining() > 0 {
+ panic!("{} remaining tokens", de.remaining());
+ }
+ }
+}
+
+#[test]
+fn test_atomics() {
+ assert_de_tokens_atomic!(
+ atomic::AtomicBool,
+ true,
+ &[Token::Bool(true)]
+ );
+ assert_de_tokens_atomic!(
+ atomic::AtomicI8,
+ -127,
+ &[Token::I8(-127i8)]
+ );
+ assert_de_tokens_atomic!(
+ atomic::AtomicI16,
+ -510,
+ &[Token::I16(-510i16)]
+ );
+ assert_de_tokens_atomic!(
+ atomic::AtomicI32,
+ -131072,
+ &[Token::I32(-131072i32)]
+ );
+ assert_de_tokens_atomic!(
+ atomic::AtomicI64,
+ -8589934592,
+ &[Token::I64(-8589934592)]
+ );
+ assert_de_tokens_atomic!(
+ atomic::AtomicIsize,
+ -131072isize,
+ &[Token::I32(-131072)]
+ );
+ assert_de_tokens_atomic!(
+ atomic::AtomicU8,
+ 127,
+ &[Token::U8(127u8)]
+ );
+ assert_de_tokens_atomic!(
+ atomic::AtomicU16,
+ 510u16,
+ &[Token::U16(510u16)]
+ );
+ assert_de_tokens_atomic!(
+ atomic::AtomicU32,
+ 131072u32,
+ &[Token::U32(131072u32)]
+ );
+ assert_de_tokens_atomic!(
+ atomic::AtomicU64,
+ 8589934592u64,
+ &[Token::U64(8589934592)]
+ );
+ assert_de_tokens_atomic!(
+ atomic::AtomicUsize,
+ 131072usize,
+ &[Token::U32(131072)]
+ );
+}
+
declare_error_tests! {
test_unknown_field<StructDenyUnknown> {
&[
diff --git a/test_suite/tests/test_ser.rs b/test_suite/tests/test_ser.rs
index 55be98004..88e349ae2 100644
--- a/test_suite/tests/test_ser.rs
+++ b/test_suite/tests/test_ser.rs
@@ -10,6 +10,7 @@ use std::ops::Bound;
use std::path::{Path, PathBuf};
use std::rc::{Rc, Weak as RcWeak};
use std::sync::{Arc, Weak as ArcWeak};
+use std::sync::atomic;
use std::time::{Duration, UNIX_EPOCH};
#[cfg(unix)]
@@ -483,6 +484,20 @@ declare_tests! {
Token::Str("1a"),
],
}
+ test_atomic {
+ atomic::AtomicBool::new(false) => &[Token::Bool(false)],
+ atomic::AtomicBool::new(true) => &[Token::Bool(true)],
+ atomic::AtomicI8::new(63i8) => &[Token::I8(63i8)],
+ atomic::AtomicI16::new(-318i16) => &[Token::I16(-318i16)],
+ atomic::AtomicI32::new(65792i32) => &[Token::I32(65792i32)],
+ atomic::AtomicI64::new(-4295032832i64) => &[Token::I64(-4295032832i64)],
+ atomic::AtomicIsize::new(-65792isize) => &[Token::I64(-65792i64)],
+ atomic::AtomicU8::new(192u8) => &[Token::U8(192u8)],
+ atomic::AtomicU16::new(510u16) => &[Token::U16(510u16)],
+ atomic::AtomicU32::new(131072u32) => &[Token::U32(131072u32)],
+ atomic::AtomicU64::new(12884901888u64) => &[Token::U64(12884901888u64)],
+ atomic::AtomicUsize::new(655360usize) => &[Token::U64(655360u64)],
+ }
}
declare_tests! {
| [
"1496"
] | serde-rs__serde-1572 | Support for atomics data types?
Hi,
it seems like there is no Serialize support for atomic data type: https://doc.rust-lang.org/core/sync/atomic/index.html
Is there any reason for this?
A first implementation would be to simply load them using `Ordering::Relaxed` and that should be quite enough.
| 1.0 | ce89adecc12b909e32548b1b929d443d62647029 | diff --git a/serde/build.rs b/serde/build.rs
index e27e2f34f..ae0f98690 100644
--- a/serde/build.rs
+++ b/serde/build.rs
@@ -68,6 +68,10 @@ fn main() {
if minor >= 28 {
println!("cargo:rustc-cfg=num_nonzero");
}
+
+ if minor >= 34 {
+ println!("cargo:rustc-cfg=std_integer_atomics");
+ }
}
fn rustc_minor_version() -> Option<u32> {
diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 1d4c31878..0a28c43ed 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -2543,3 +2543,56 @@ where
Deserialize::deserialize(deserializer).map(Wrapping)
}
}
+
+#[cfg(all(feature="std", std_integer_atomics))]
+use std::sync::atomic;
+
+
+#[cfg(all(feature="std", std_integer_atomics))]
+macro_rules! atomic_impl {
+ ($ty:path, $primitive:ident) => {
+ impl<'de> Deserialize<'de> for $ty
+ {
+ #[inline]
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where D: Deserializer<'de>
+ {
+ let val = $primitive::deserialize(deserializer)?;
+ Ok(Self::new(val))
+ }
+ }
+ }
+}
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicBool, bool);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicI8, i8);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicI16, i16);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicI32, i32);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicI64, i64);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicIsize, isize);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicU8, u8);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicU16, u16);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicU32, u32);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicU64, u64);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicUsize, usize);
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index fb0449a75..59b54117f 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -839,3 +839,55 @@ where
self.0.serialize(serializer)
}
}
+
+////////////////////////////////////////////////////////////////////////////////
+#[cfg(all(feature="std", std_integer_atomics))]
+use std::sync::atomic;
+
+#[cfg(all(feature="std", std_integer_atomics))]
+macro_rules! atomic_impl {
+ ($ty:path, $method:ident $($cast:tt)*) => {
+ impl Serialize for $ty {
+ #[inline]
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.$method(self.load(atomic::Ordering::SeqCst) $($cast)*)
+ }
+ }
+ }
+}
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicBool, serialize_bool);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicI8, serialize_i8);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicI16, serialize_i16);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicI32, serialize_i32);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicI64, serialize_i64);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicIsize, serialize_i64 as i64);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicU8, serialize_u8);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicU16, serialize_u16);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicU32, serialize_u32);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicU64, serialize_u64);
+
+#[cfg(all(feature="std", std_integer_atomics))]
+atomic_impl!(atomic::AtomicUsize, serialize_u64 as u64);
| serde-rs/serde | 2019-07-12T01:19:39Z | I would prefer to match Debug which uses Ordering::SeqCst.
https://github.com/rust-lang/rust/blob/1.33.0/src/libcore/sync/atomic.rs#L1137-L1141
I would be prepared to consider a PR adding impls that use SeqCst.
SeqCst is the strongest guarantee possible. This is ok and maybe even desiderable in debugging code, but I am not sure is desiderable on production code.
What is your take on this?
Do you believe performance won't be a concern? I am not sure of the performance characteristics of serde (never used) so I am really asking a little more feedback on your thoughts!
Cheers
If someone observes serialization of atomics as a bottleneck, they can use a `serialize_with` attribute to substitute in a Serialize impl with a weaker guarantee. SeqCst is a safe default with the least surprises and frequently no different performance.
I am not sure if I got the time to do this anyway, I don't believe in the next few weeks at the very least.
If anybody wants to jump on it feel free to just implement it! | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,559 | diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index f1f7739d0..90e0f3951 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -124,6 +124,19 @@ enum EnumOther {
Other,
}
+#[derive(PartialEq, Debug)]
+struct IgnoredAny;
+
+impl<'de> Deserialize<'de> for IgnoredAny {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ serde::de::IgnoredAny::deserialize(deserializer)?;
+ Ok(IgnoredAny)
+ }
+}
+
//////////////////////////////////////////////////////////////////////////
macro_rules! declare_tests {
@@ -929,6 +942,21 @@ declare_tests! {
Token::SeqEnd,
],
}
+ test_ignored_any {
+ IgnoredAny => &[
+ Token::Str("s"),
+ ],
+ IgnoredAny => &[
+ Token::Seq { len: Some(1) },
+ Token::Bool(true),
+ Token::SeqEnd,
+ ],
+ IgnoredAny => &[
+ Token::Enum { name: "E" },
+ Token::Str("Rust"),
+ Token::Unit,
+ ],
+ }
}
declare_tests! {
diff --git a/test_suite/tests/test_ignored_any.rs b/test_suite/tests/test_ignored_any.rs
new file mode 100644
index 000000000..921cdfc79
--- /dev/null
+++ b/test_suite/tests/test_ignored_any.rs
@@ -0,0 +1,104 @@
+use serde::de::value::{Error, MapDeserializer, SeqDeserializer};
+use serde::de::{
+ DeserializeSeed, EnumAccess, IgnoredAny, IntoDeserializer, VariantAccess, Visitor,
+};
+use serde::{forward_to_deserialize_any, Deserialize, Deserializer};
+
+#[derive(PartialEq, Debug, Deserialize)]
+enum Target {
+ Unit,
+ Newtype(i32),
+ Tuple(i32, i32),
+ Struct { a: i32 },
+}
+
+struct Enum(&'static str);
+
+impl<'de> Deserializer<'de> for Enum {
+ type Error = Error;
+
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_enum(self)
+ }
+
+ forward_to_deserialize_any! {
+ bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
+ bytes byte_buf option unit unit_struct newtype_struct seq tuple
+ tuple_struct map struct enum identifier ignored_any
+ }
+}
+
+impl<'de> EnumAccess<'de> for Enum {
+ type Error = Error;
+ type Variant = Self;
+
+ fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
+ where
+ V: DeserializeSeed<'de>,
+ {
+ let v = seed.deserialize(self.0.into_deserializer())?;
+ Ok((v, self))
+ }
+}
+
+impl<'de> VariantAccess<'de> for Enum {
+ type Error = Error;
+
+ fn unit_variant(self) -> Result<(), Self::Error> {
+ Ok(())
+ }
+
+ fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
+ where
+ T: DeserializeSeed<'de>,
+ {
+ seed.deserialize(10i32.into_deserializer())
+ }
+
+ fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
+ where
+ V: Visitor<'de>,
+ {
+ let seq = SeqDeserializer::new(vec![1i32, 2].into_iter());
+ visitor.visit_seq(seq)
+ }
+
+ fn struct_variant<V>(
+ self,
+ _fields: &'static [&'static str],
+ visitor: V,
+ ) -> Result<V::Value, Self::Error>
+ where
+ V: Visitor<'de>,
+ {
+ let map = MapDeserializer::new(vec![("a", 10i32)].into_iter());
+ visitor.visit_map(map)
+ }
+}
+
+#[test]
+fn test_deserialize_enum() {
+ // First just make sure the Deserializer impl works
+ assert_eq!(Target::Unit, Target::deserialize(Enum("Unit")).unwrap());
+ assert_eq!(
+ Target::Newtype(10),
+ Target::deserialize(Enum("Newtype")).unwrap()
+ );
+ assert_eq!(
+ Target::Tuple(1, 2),
+ Target::deserialize(Enum("Tuple")).unwrap()
+ );
+ assert_eq!(
+ Target::Struct { a: 10 },
+ Target::deserialize(Enum("Struct")).unwrap()
+ );
+
+ // Now try IgnoredAny
+ IgnoredAny::deserialize(Enum("Unit")).unwrap();
+ IgnoredAny::deserialize(Enum("Newtype")).unwrap();
+ IgnoredAny::deserialize(Enum("Tuple")).unwrap();
+ IgnoredAny::deserialize(Enum("Struct")).unwrap();
+}
| [
"1558"
] | serde-rs__serde-1559 | IgnoredAny doesn't handle enums, leading to a confusing error message
If IgnoredAny gets an enum, serde outputs the error message "invalid type: enum, expected anything at all", which doesn't make much sense. This is because IgnoredAny doesn't have a visit_enum impl. I think the intent might make sense if IgnoredAny doesn't know how to deserialize the enum. But "expected anything at all" doesn't really make sense as an error when an enum is clearly something.
| 1.0 | 4cb13b33e069c4e65f1dd66224b328928b5d9b1e | diff --git a/serde/src/de/ignored_any.rs b/serde/src/de/ignored_any.rs
index 855d68e1a..68a644e0d 100644
--- a/serde/src/de/ignored_any.rs
+++ b/serde/src/de/ignored_any.rs
@@ -1,6 +1,8 @@
use lib::*;
-use de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor};
+use de::{
+ Deserialize, Deserializer, EnumAccess, Error, MapAccess, SeqAccess, VariantAccess, Visitor,
+};
/// An efficient way of discarding data from a deserializer.
///
@@ -205,6 +207,13 @@ impl<'de> Visitor<'de> for IgnoredAny {
let _ = bytes;
Ok(IgnoredAny)
}
+
+ fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
+ where
+ A: EnumAccess<'de>,
+ {
+ data.variant::<IgnoredAny>()?.1.newtype_variant()
+ }
}
impl<'de> Deserialize<'de> for IgnoredAny {
| serde-rs/serde | 2019-06-27T17:32:56Z | Actually, after thinking about it, I think this is always buggy behavior. If you agree I'd be happy to open a quick PR. | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,521 | diff --git a/test_suite/Cargo.toml b/test_suite/Cargo.toml
index 4e793cb54..dbc8578bd 100644
--- a/test_suite/Cargo.toml
+++ b/test_suite/Cargo.toml
@@ -7,14 +7,12 @@ publish = false
[features]
unstable = ["serde/unstable"]
-compiletest = ["compiletest_rs"]
[dev-dependencies]
fnv = "1.0"
rustc-serialize = "0.3.16"
+select-rustc = "0.1"
serde = { path = "../serde", features = ["rc", "derive"] }
serde_derive = { path = "../serde_derive", features = ["deserialize_in_place"] }
serde_test = { path = "../serde_test" }
-
-[dependencies]
-compiletest_rs = { version = "0.3", optional = true, features = ["stable"] }
+trybuild = "1.0"
diff --git a/test_suite/deps/Cargo.toml b/test_suite/deps/Cargo.toml
deleted file mode 100644
index fbe2f2cda..000000000
--- a/test_suite/deps/Cargo.toml
+++ /dev/null
@@ -1,11 +0,0 @@
-[package]
-name = "serde_test_suite_deps"
-version = "0.0.0"
-authors = ["David Tolnay <dtolnay@gmail.com>"]
-publish = false
-
-[workspace]
-
-[dependencies]
-serde = { path = "../../serde" }
-serde_derive = { path = "../../serde_derive" }
diff --git a/test_suite/deps/src/lib.rs b/test_suite/deps/src/lib.rs
deleted file mode 100644
index e63ee9d43..000000000
--- a/test_suite/deps/src/lib.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-#![feature(/*=============================================]
-#![=== Serde test suite requires a nightly compiler. ===]
-#![====================================================*/)]
diff --git a/test_suite/tests/compiletest.rs b/test_suite/tests/compiletest.rs
index 1b70621f7..214d43678 100644
--- a/test_suite/tests/compiletest.rs
+++ b/test_suite/tests/compiletest.rs
@@ -1,21 +1,6 @@
-#![cfg(feature = "compiletest")]
-
-use compiletest_rs as compiletest;
-
+#[rustc::attr(not(nightly), ignore)]
#[test]
fn ui() {
- compiletest::run_tests(&compiletest::Config {
- mode: compiletest::common::Mode::Ui,
- src_base: std::path::PathBuf::from("tests/ui"),
- target_rustcflags: Some(String::from(
- "\
- --edition=2018 \
- -L deps/target/debug/deps \
- -Z unstable-options \
- --extern serde_derive \
- ",
- )),
- build_base: std::path::PathBuf::from("../target/ui"),
- ..Default::default()
- });
+ let t = trybuild::TestCases::new();
+ t.compile_fail("tests/ui/**/*.rs");
}
diff --git a/test_suite/tests/ui/borrow/bad_lifetimes.stderr b/test_suite/tests/ui/borrow/bad_lifetimes.stderr
index 1adc34a59..5b2984977 100644
--- a/test_suite/tests/ui/borrow/bad_lifetimes.stderr
+++ b/test_suite/tests/ui/borrow/bad_lifetimes.stderr
@@ -3,6 +3,3 @@ error: failed to parse borrowed lifetimes: "zzz"
|
5 | #[serde(borrow = "zzz")]
| ^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/borrow/duplicate_lifetime.stderr b/test_suite/tests/ui/borrow/duplicate_lifetime.stderr
index 57c9690a5..f9916fd02 100644
--- a/test_suite/tests/ui/borrow/duplicate_lifetime.stderr
+++ b/test_suite/tests/ui/borrow/duplicate_lifetime.stderr
@@ -3,6 +3,3 @@ error: duplicate borrowed lifetime `'a`
|
5 | #[serde(borrow = "'a + 'a")]
| ^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/borrow/duplicate_variant.stderr b/test_suite/tests/ui/borrow/duplicate_variant.stderr
index 7ff995a67..bae8e5fde 100644
--- a/test_suite/tests/ui/borrow/duplicate_variant.stderr
+++ b/test_suite/tests/ui/borrow/duplicate_variant.stderr
@@ -3,6 +3,3 @@ error: duplicate serde attribute `borrow`
|
8 | #[serde(borrow)]
| ^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/borrow/empty_lifetimes.stderr b/test_suite/tests/ui/borrow/empty_lifetimes.stderr
index 01d79b3ba..2d6f042cd 100644
--- a/test_suite/tests/ui/borrow/empty_lifetimes.stderr
+++ b/test_suite/tests/ui/borrow/empty_lifetimes.stderr
@@ -3,6 +3,3 @@ error: at least one lifetime must be borrowed
|
5 | #[serde(borrow = "")]
| ^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/borrow/no_lifetimes.stderr b/test_suite/tests/ui/borrow/no_lifetimes.stderr
index 04bcc852e..52601e975 100644
--- a/test_suite/tests/ui/borrow/no_lifetimes.stderr
+++ b/test_suite/tests/ui/borrow/no_lifetimes.stderr
@@ -4,6 +4,3 @@ error: field `s` has no lifetimes to borrow
5 | / #[serde(borrow)]
6 | | s: String,
| |_____________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/borrow/struct_variant.stderr b/test_suite/tests/ui/borrow/struct_variant.stderr
index 758e6343e..5624d2077 100644
--- a/test_suite/tests/ui/borrow/struct_variant.stderr
+++ b/test_suite/tests/ui/borrow/struct_variant.stderr
@@ -4,6 +4,3 @@ error: #[serde(borrow)] may only be used on newtype variants
8 | / #[serde(borrow)]
9 | | S { s: Str<'a> },
| |____________________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/borrow/wrong_lifetime.stderr b/test_suite/tests/ui/borrow/wrong_lifetime.stderr
index 356595520..f282e124e 100644
--- a/test_suite/tests/ui/borrow/wrong_lifetime.stderr
+++ b/test_suite/tests/ui/borrow/wrong_lifetime.stderr
@@ -4,6 +4,3 @@ error: field `s` does not have lifetime 'b
5 | / #[serde(borrow = "'b")]
6 | | s: &'a str,
| |______________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/conflict/adjacent-tag.stderr b/test_suite/tests/ui/conflict/adjacent-tag.stderr
index 6045f5f56..ad4967958 100644
--- a/test_suite/tests/ui/conflict/adjacent-tag.stderr
+++ b/test_suite/tests/ui/conflict/adjacent-tag.stderr
@@ -7,6 +7,3 @@ error: enum tags `conflict` for type and content conflict with each other
7 | | B,
8 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/conflict/flatten-newtype-struct.stderr b/test_suite/tests/ui/conflict/flatten-newtype-struct.stderr
index 86e9501aa..aeacefb9c 100644
--- a/test_suite/tests/ui/conflict/flatten-newtype-struct.stderr
+++ b/test_suite/tests/ui/conflict/flatten-newtype-struct.stderr
@@ -3,6 +3,3 @@ error: #[serde(flatten)] cannot be used on newtype structs
|
6 | struct Foo(#[serde(flatten)] HashMap<String, String>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/conflict/flatten-tuple-struct.stderr b/test_suite/tests/ui/conflict/flatten-tuple-struct.stderr
index ecdb987cd..e1999344c 100644
--- a/test_suite/tests/ui/conflict/flatten-tuple-struct.stderr
+++ b/test_suite/tests/ui/conflict/flatten-tuple-struct.stderr
@@ -3,6 +3,3 @@ error: #[serde(flatten)] cannot be used on tuple structs
|
6 | struct Foo(u32, #[serde(flatten)] HashMap<String, String>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/conflict/internal-tag-alias.stderr b/test_suite/tests/ui/conflict/internal-tag-alias.stderr
index 2fcaa18d4..7a57f427c 100644
--- a/test_suite/tests/ui/conflict/internal-tag-alias.stderr
+++ b/test_suite/tests/ui/conflict/internal-tag-alias.stderr
@@ -9,6 +9,3 @@ error: variant field name `conflict` conflicts with internal tag
9 | | },
10 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/conflict/internal-tag.stderr b/test_suite/tests/ui/conflict/internal-tag.stderr
index d98c3874f..f1ae4579a 100644
--- a/test_suite/tests/ui/conflict/internal-tag.stderr
+++ b/test_suite/tests/ui/conflict/internal-tag.stderr
@@ -9,6 +9,3 @@ error: variant field name `conflict` conflicts with internal tag
9 | | },
10 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/default-attribute/enum.stderr b/test_suite/tests/ui/default-attribute/enum.stderr
index 9f2a26180..a3b7a0277 100644
--- a/test_suite/tests/ui/default-attribute/enum.stderr
+++ b/test_suite/tests/ui/default-attribute/enum.stderr
@@ -3,6 +3,3 @@ error: #[serde(default)] can only be used on structs with named fields
|
5 | enum E {
| ^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/default-attribute/enum_path.stderr b/test_suite/tests/ui/default-attribute/enum_path.stderr
index 9a9a8ecbb..c6523c9ec 100644
--- a/test_suite/tests/ui/default-attribute/enum_path.stderr
+++ b/test_suite/tests/ui/default-attribute/enum_path.stderr
@@ -3,6 +3,3 @@ error: #[serde(default = "...")] can only be used on structs with named fields
|
5 | enum E {
| ^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/default-attribute/nameless_struct_fields.stderr b/test_suite/tests/ui/default-attribute/nameless_struct_fields.stderr
index 3e8d07087..3557946a2 100644
--- a/test_suite/tests/ui/default-attribute/nameless_struct_fields.stderr
+++ b/test_suite/tests/ui/default-attribute/nameless_struct_fields.stderr
@@ -3,6 +3,3 @@ error: #[serde(default)] can only be used on structs with named fields
|
5 | struct T(u8, u8);
| ^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/default-attribute/nameless_struct_fields_path.stderr b/test_suite/tests/ui/default-attribute/nameless_struct_fields_path.stderr
index 9197807b0..db5fa4b8d 100644
--- a/test_suite/tests/ui/default-attribute/nameless_struct_fields_path.stderr
+++ b/test_suite/tests/ui/default-attribute/nameless_struct_fields_path.stderr
@@ -3,6 +3,3 @@ error: #[serde(default = "...")] can only be used on structs with named fields
|
5 | struct T(u8, u8);
| ^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/duplicate-attribute/rename-and-ser.stderr b/test_suite/tests/ui/duplicate-attribute/rename-and-ser.stderr
index 74f730fd3..34ecd735c 100644
--- a/test_suite/tests/ui/duplicate-attribute/rename-and-ser.stderr
+++ b/test_suite/tests/ui/duplicate-attribute/rename-and-ser.stderr
@@ -3,6 +3,3 @@ error: unknown serde field attribute `serialize`
|
5 | #[serde(rename = "x", serialize = "y")]
| ^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/duplicate-attribute/rename-ser-rename-ser.stderr b/test_suite/tests/ui/duplicate-attribute/rename-ser-rename-ser.stderr
index 04e67b13e..979f97385 100644
--- a/test_suite/tests/ui/duplicate-attribute/rename-ser-rename-ser.stderr
+++ b/test_suite/tests/ui/duplicate-attribute/rename-ser-rename-ser.stderr
@@ -3,6 +3,3 @@ error: duplicate serde attribute `rename`
|
5 | #[serde(rename(serialize = "x"), rename(serialize = "y"))]
| ^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/duplicate-attribute/rename-ser-rename.stderr b/test_suite/tests/ui/duplicate-attribute/rename-ser-rename.stderr
index d9cb3650b..866b2372f 100644
--- a/test_suite/tests/ui/duplicate-attribute/rename-ser-rename.stderr
+++ b/test_suite/tests/ui/duplicate-attribute/rename-ser-rename.stderr
@@ -3,6 +3,3 @@ error: duplicate serde attribute `rename`
|
6 | #[serde(rename = "y")]
| ^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/duplicate-attribute/rename-ser-ser.stderr b/test_suite/tests/ui/duplicate-attribute/rename-ser-ser.stderr
index c5526c710..e6e3b3843 100644
--- a/test_suite/tests/ui/duplicate-attribute/rename-ser-ser.stderr
+++ b/test_suite/tests/ui/duplicate-attribute/rename-ser-ser.stderr
@@ -3,6 +3,3 @@ error: duplicate serde attribute `rename`
|
5 | #[serde(rename(serialize = "x", serialize = "y"))]
| ^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/duplicate-attribute/two-rename-ser.stderr b/test_suite/tests/ui/duplicate-attribute/two-rename-ser.stderr
index 3934ac9d9..9973b4a87 100644
--- a/test_suite/tests/ui/duplicate-attribute/two-rename-ser.stderr
+++ b/test_suite/tests/ui/duplicate-attribute/two-rename-ser.stderr
@@ -3,6 +3,3 @@ error: duplicate serde attribute `rename`
|
6 | #[serde(rename(serialize = "y"))]
| ^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/duplicate-attribute/with-and-serialize-with.stderr b/test_suite/tests/ui/duplicate-attribute/with-and-serialize-with.stderr
index 27e3a0bf6..62e29d574 100644
--- a/test_suite/tests/ui/duplicate-attribute/with-and-serialize-with.stderr
+++ b/test_suite/tests/ui/duplicate-attribute/with-and-serialize-with.stderr
@@ -3,6 +3,3 @@ error: duplicate serde attribute `serialize_with`
|
5 | #[serde(with = "w", serialize_with = "s")]
| ^^^^^^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/enum-representation/content-no-tag.stderr b/test_suite/tests/ui/enum-representation/content-no-tag.stderr
index ad7186e57..ea3602816 100644
--- a/test_suite/tests/ui/enum-representation/content-no-tag.stderr
+++ b/test_suite/tests/ui/enum-representation/content-no-tag.stderr
@@ -3,6 +3,3 @@ error: #[serde(tag = "...", content = "...")] must be used together
|
4 | #[serde(content = "c")]
| ^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/enum-representation/internal-tuple-variant.stderr b/test_suite/tests/ui/enum-representation/internal-tuple-variant.stderr
index 8d133689d..cbe2cf851 100644
--- a/test_suite/tests/ui/enum-representation/internal-tuple-variant.stderr
+++ b/test_suite/tests/ui/enum-representation/internal-tuple-variant.stderr
@@ -3,6 +3,3 @@ error: #[serde(tag = "...")] cannot be used with tuple variants
|
6 | Tuple(u8, u8),
| ^^^^^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/enum-representation/untagged-and-adjacent.stderr b/test_suite/tests/ui/enum-representation/untagged-and-adjacent.stderr
index 367a55fe5..9f42b51b3 100644
--- a/test_suite/tests/ui/enum-representation/untagged-and-adjacent.stderr
+++ b/test_suite/tests/ui/enum-representation/untagged-and-adjacent.stderr
@@ -15,6 +15,3 @@ error: untagged enum cannot have #[serde(tag = "...", content = "...")]
|
5 | #[serde(tag = "t", content = "c")]
| ^^^^^^^
-
-error: aborting due to 3 previous errors
-
diff --git a/test_suite/tests/ui/enum-representation/untagged-and-content.stderr b/test_suite/tests/ui/enum-representation/untagged-and-content.stderr
index 847579ac9..467d6c27a 100644
--- a/test_suite/tests/ui/enum-representation/untagged-and-content.stderr
+++ b/test_suite/tests/ui/enum-representation/untagged-and-content.stderr
@@ -9,6 +9,3 @@ error: untagged enum cannot have #[serde(content = "...")]
|
5 | #[serde(content = "c")]
| ^^^^^^^
-
-error: aborting due to 2 previous errors
-
diff --git a/test_suite/tests/ui/enum-representation/untagged-and-internal.stderr b/test_suite/tests/ui/enum-representation/untagged-and-internal.stderr
index 2bb43502c..78fed3dab 100644
--- a/test_suite/tests/ui/enum-representation/untagged-and-internal.stderr
+++ b/test_suite/tests/ui/enum-representation/untagged-and-internal.stderr
@@ -9,6 +9,3 @@ error: enum cannot be both untagged and internally tagged
|
5 | #[serde(tag = "type")]
| ^^^
-
-error: aborting due to 2 previous errors
-
diff --git a/test_suite/tests/ui/enum-representation/untagged-struct.stderr b/test_suite/tests/ui/enum-representation/untagged-struct.stderr
index 49f77bc62..8a065d9b0 100644
--- a/test_suite/tests/ui/enum-representation/untagged-struct.stderr
+++ b/test_suite/tests/ui/enum-representation/untagged-struct.stderr
@@ -3,6 +3,3 @@ error: #[serde(untagged)] can only be used on enums
|
5 | struct S;
| ^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/expected-string/boolean.stderr b/test_suite/tests/ui/expected-string/boolean.stderr
index 4396e4b15..f14bc7e65 100644
--- a/test_suite/tests/ui/expected-string/boolean.stderr
+++ b/test_suite/tests/ui/expected-string/boolean.stderr
@@ -3,6 +3,3 @@ error: expected serde rename attribute to be a string: `rename = "..."`
|
5 | #[serde(rename = true)]
| ^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/expected-string/byte_character.stderr b/test_suite/tests/ui/expected-string/byte_character.stderr
index 3ebf6f275..3b801dcb2 100644
--- a/test_suite/tests/ui/expected-string/byte_character.stderr
+++ b/test_suite/tests/ui/expected-string/byte_character.stderr
@@ -3,6 +3,3 @@ error: expected serde rename attribute to be a string: `rename = "..."`
|
5 | #[serde(rename = b'a')]
| ^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/expected-string/byte_string.stderr b/test_suite/tests/ui/expected-string/byte_string.stderr
index 7b5be122f..a16b0b92a 100644
--- a/test_suite/tests/ui/expected-string/byte_string.stderr
+++ b/test_suite/tests/ui/expected-string/byte_string.stderr
@@ -3,6 +3,3 @@ error: expected serde rename attribute to be a string: `rename = "..."`
|
5 | #[serde(rename = b"byte string")]
| ^^^^^^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/expected-string/character.stderr b/test_suite/tests/ui/expected-string/character.stderr
index ff6849115..4524c07fa 100644
--- a/test_suite/tests/ui/expected-string/character.stderr
+++ b/test_suite/tests/ui/expected-string/character.stderr
@@ -3,6 +3,3 @@ error: expected serde rename attribute to be a string: `rename = "..."`
|
5 | #[serde(rename = 'a')]
| ^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/expected-string/float.stderr b/test_suite/tests/ui/expected-string/float.stderr
index a8106cb68..f8c78c466 100644
--- a/test_suite/tests/ui/expected-string/float.stderr
+++ b/test_suite/tests/ui/expected-string/float.stderr
@@ -3,6 +3,3 @@ error: expected serde rename attribute to be a string: `rename = "..."`
|
5 | #[serde(rename = 3.14)]
| ^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/expected-string/integer.stderr b/test_suite/tests/ui/expected-string/integer.stderr
index cce9ebaeb..0d26e6087 100644
--- a/test_suite/tests/ui/expected-string/integer.stderr
+++ b/test_suite/tests/ui/expected-string/integer.stderr
@@ -3,6 +3,3 @@ error: expected serde rename attribute to be a string: `rename = "..."`
|
5 | #[serde(rename = 100)]
| ^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/identifier/both.stderr b/test_suite/tests/ui/identifier/both.stderr
index c26741753..7cc3e86ea 100644
--- a/test_suite/tests/ui/identifier/both.stderr
+++ b/test_suite/tests/ui/identifier/both.stderr
@@ -9,6 +9,3 @@ error: #[serde(field_identifier)] and #[serde(variant_identifier)] cannot both b
|
4 | #[serde(field_identifier, variant_identifier)]
| ^^^^^^^^^^^^^^^^^^
-
-error: aborting due to 2 previous errors
-
diff --git a/test_suite/tests/ui/identifier/field_struct.stderr b/test_suite/tests/ui/identifier/field_struct.stderr
index 49013343f..c87dd3bd5 100644
--- a/test_suite/tests/ui/identifier/field_struct.stderr
+++ b/test_suite/tests/ui/identifier/field_struct.stderr
@@ -3,6 +3,3 @@ error: #[serde(field_identifier)] can only be used on an enum
|
5 | struct S;
| ^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/identifier/field_tuple.stderr b/test_suite/tests/ui/identifier/field_tuple.stderr
index 2710d0b8c..5c2465a9d 100644
--- a/test_suite/tests/ui/identifier/field_tuple.stderr
+++ b/test_suite/tests/ui/identifier/field_tuple.stderr
@@ -3,6 +3,3 @@ error: #[serde(field_identifier)] may only contain unit variants
|
7 | B(u8, u8),
| ^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/identifier/newtype_not_last.stderr b/test_suite/tests/ui/identifier/newtype_not_last.stderr
index 3a30c9a90..d4af4203c 100644
--- a/test_suite/tests/ui/identifier/newtype_not_last.stderr
+++ b/test_suite/tests/ui/identifier/newtype_not_last.stderr
@@ -3,6 +3,3 @@ error: `Other` must be the last variant
|
7 | Other(String),
| ^^^^^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/identifier/not_unit.stderr b/test_suite/tests/ui/identifier/not_unit.stderr
index 26b7e0a7b..612bfc630 100644
--- a/test_suite/tests/ui/identifier/not_unit.stderr
+++ b/test_suite/tests/ui/identifier/not_unit.stderr
@@ -4,6 +4,3 @@ error: #[serde(other)] must be on a unit variant
7 | / #[serde(other)]
8 | | Other(u8, u8),
| |_________________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/identifier/other_not_last.stderr b/test_suite/tests/ui/identifier/other_not_last.stderr
index a470f48fa..4a0525d67 100644
--- a/test_suite/tests/ui/identifier/other_not_last.stderr
+++ b/test_suite/tests/ui/identifier/other_not_last.stderr
@@ -4,6 +4,3 @@ error: #[serde(other)] must be on the last variant
7 | / #[serde(other)]
8 | | Other,
| |_________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/identifier/other_untagged.stderr b/test_suite/tests/ui/identifier/other_untagged.stderr
index f6068adef..ddcf7b5a2 100644
--- a/test_suite/tests/ui/identifier/other_untagged.stderr
+++ b/test_suite/tests/ui/identifier/other_untagged.stderr
@@ -4,6 +4,3 @@ error: #[serde(other)] cannot appear on untagged enum
6 | / #[serde(other)]
7 | | Other,
| |_________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/identifier/other_variant.stderr b/test_suite/tests/ui/identifier/other_variant.stderr
index 900a71a03..d9089d7f0 100644
--- a/test_suite/tests/ui/identifier/other_variant.stderr
+++ b/test_suite/tests/ui/identifier/other_variant.stderr
@@ -4,6 +4,3 @@ error: #[serde(other)] may not be used on a variant identifier
6 | / #[serde(other)]
7 | | Other,
| |_________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/identifier/variant_struct.stderr b/test_suite/tests/ui/identifier/variant_struct.stderr
index d4760ddbc..ba8ed0672 100644
--- a/test_suite/tests/ui/identifier/variant_struct.stderr
+++ b/test_suite/tests/ui/identifier/variant_struct.stderr
@@ -3,6 +3,3 @@ error: #[serde(variant_identifier)] can only be used on an enum
|
5 | struct S;
| ^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/identifier/variant_tuple.stderr b/test_suite/tests/ui/identifier/variant_tuple.stderr
index ba25c76ff..9fb0a7fb3 100644
--- a/test_suite/tests/ui/identifier/variant_tuple.stderr
+++ b/test_suite/tests/ui/identifier/variant_tuple.stderr
@@ -3,6 +3,3 @@ error: #[serde(variant_identifier)] may only contain unit variants
|
7 | B(u8, u8),
| ^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/malformed/bound.stderr b/test_suite/tests/ui/malformed/bound.stderr
index 6f65801c4..59537de1d 100644
--- a/test_suite/tests/ui/malformed/bound.stderr
+++ b/test_suite/tests/ui/malformed/bound.stderr
@@ -3,6 +3,3 @@ error: malformed bound attribute, expected `bound(serialize = ..., deserialize =
|
5 | #[serde(bound(unknown))]
| ^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/malformed/rename.stderr b/test_suite/tests/ui/malformed/rename.stderr
index 104bfba59..a2e244f56 100644
--- a/test_suite/tests/ui/malformed/rename.stderr
+++ b/test_suite/tests/ui/malformed/rename.stderr
@@ -3,6 +3,3 @@ error: malformed rename attribute, expected `rename(serialize = ..., deserialize
|
5 | #[serde(rename(unknown))]
| ^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/precondition/deserialize_de_lifetime.stderr b/test_suite/tests/ui/precondition/deserialize_de_lifetime.stderr
index 7cb0c1b82..642f3f1c8 100644
--- a/test_suite/tests/ui/precondition/deserialize_de_lifetime.stderr
+++ b/test_suite/tests/ui/precondition/deserialize_de_lifetime.stderr
@@ -3,6 +3,3 @@ error: cannot deserialize when there is a lifetime parameter called 'de
|
4 | struct S<'de> {
| ^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/precondition/deserialize_dst.stderr b/test_suite/tests/ui/precondition/deserialize_dst.stderr
index f037310b9..923864561 100644
--- a/test_suite/tests/ui/precondition/deserialize_dst.stderr
+++ b/test_suite/tests/ui/precondition/deserialize_dst.stderr
@@ -6,6 +6,3 @@ error: cannot deserialize a dynamically sized struct
6 | | slice: [u8],
7 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/precondition/serialize_field_identifier.stderr b/test_suite/tests/ui/precondition/serialize_field_identifier.stderr
index bd102f368..9b59f4f84 100644
--- a/test_suite/tests/ui/precondition/serialize_field_identifier.stderr
+++ b/test_suite/tests/ui/precondition/serialize_field_identifier.stderr
@@ -7,6 +7,3 @@ error: field identifiers cannot be serialized
7 | | B,
8 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/precondition/serialize_variant_identifier.stderr b/test_suite/tests/ui/precondition/serialize_variant_identifier.stderr
index 244a4f2ca..4641f35fd 100644
--- a/test_suite/tests/ui/precondition/serialize_variant_identifier.stderr
+++ b/test_suite/tests/ui/precondition/serialize_variant_identifier.stderr
@@ -7,6 +7,3 @@ error: variant identifiers cannot be serialized
7 | | B,
8 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/remote/bad_getter.stderr b/test_suite/tests/ui/remote/bad_getter.stderr
index 955a6caf4..871509269 100644
--- a/test_suite/tests/ui/remote/bad_getter.stderr
+++ b/test_suite/tests/ui/remote/bad_getter.stderr
@@ -3,6 +3,3 @@ error: failed to parse path: "~~~"
|
12 | #[serde(getter = "~~~")]
| ^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/remote/bad_remote.stderr b/test_suite/tests/ui/remote/bad_remote.stderr
index e275d14ad..dc985564c 100644
--- a/test_suite/tests/ui/remote/bad_remote.stderr
+++ b/test_suite/tests/ui/remote/bad_remote.stderr
@@ -3,6 +3,3 @@ error: failed to parse path: "~~~"
|
10 | #[serde(remote = "~~~")]
| ^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/remote/enum_getter.stderr b/test_suite/tests/ui/remote/enum_getter.stderr
index 14ffc9a4a..77edefc57 100644
--- a/test_suite/tests/ui/remote/enum_getter.stderr
+++ b/test_suite/tests/ui/remote/enum_getter.stderr
@@ -9,6 +9,3 @@ error: #[serde(getter = "...")] is not allowed in an enum
15 | | },
16 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/remote/missing_field.stderr b/test_suite/tests/ui/remote/missing_field.stderr
index d79fb380d..e3566253e 100644
--- a/test_suite/tests/ui/remote/missing_field.stderr
+++ b/test_suite/tests/ui/remote/missing_field.stderr
@@ -4,6 +4,4 @@ error[E0063]: missing field `b` in initializer of `remote::S`
11 | #[serde(remote = "remote::S")]
| ^^^^^^^^^^^ missing `b`
-error: aborting due to previous error
-
For more information about this error, try `rustc --explain E0063`.
diff --git a/test_suite/tests/ui/remote/nonremote_getter.stderr b/test_suite/tests/ui/remote/nonremote_getter.stderr
index 446f523cd..60d6d48ed 100644
--- a/test_suite/tests/ui/remote/nonremote_getter.stderr
+++ b/test_suite/tests/ui/remote/nonremote_getter.stderr
@@ -6,6 +6,3 @@ error: #[serde(getter = "...")] can only be used in structs that have #[serde(re
6 | | a: u8,
7 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/remote/unknown_field.stderr b/test_suite/tests/ui/remote/unknown_field.stderr
index 03b367e53..6a8d11ba0 100644
--- a/test_suite/tests/ui/remote/unknown_field.stderr
+++ b/test_suite/tests/ui/remote/unknown_field.stderr
@@ -10,7 +10,5 @@ error[E0560]: struct `remote::S` has no field named `b`
12 | b: u8,
| ^ help: a field with a similar name exists: `a`
-error: aborting due to 2 previous errors
-
Some errors have detailed explanations: E0560, E0609.
For more information about an error, try `rustc --explain E0560`.
diff --git a/test_suite/tests/ui/remote/wrong_de.stderr b/test_suite/tests/ui/remote/wrong_de.stderr
index 9c95ee614..85281862b 100644
--- a/test_suite/tests/ui/remote/wrong_de.stderr
+++ b/test_suite/tests/ui/remote/wrong_de.stderr
@@ -3,11 +3,5 @@ error[E0308]: mismatched types
|
7 | #[derive(Deserialize)]
| ^^^^^^^^^^^ expected u16, found u8
-help: you can cast an `u8` to `u16`, which will zero-extend the source value
- |
-7 | #[derive(Deserialize.into())]
- | ^^^^^^^^^^^^^^^^^^
-
-error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
diff --git a/test_suite/tests/ui/remote/wrong_getter.stderr b/test_suite/tests/ui/remote/wrong_getter.stderr
index 4c1614051..177933666 100644
--- a/test_suite/tests/ui/remote/wrong_getter.stderr
+++ b/test_suite/tests/ui/remote/wrong_getter.stderr
@@ -7,6 +7,4 @@ error[E0308]: mismatched types
= note: expected type `&u8`
found type `&u16`
-error: aborting due to previous error
-
For more information about this error, try `rustc --explain E0308`.
diff --git a/test_suite/tests/ui/remote/wrong_ser.stderr b/test_suite/tests/ui/remote/wrong_ser.stderr
index 76a35f4ed..547409256 100644
--- a/test_suite/tests/ui/remote/wrong_ser.stderr
+++ b/test_suite/tests/ui/remote/wrong_ser.stderr
@@ -7,6 +7,4 @@ error[E0308]: mismatched types
= note: expected type `&u8`
found type `&u16`
-error: aborting due to previous error
-
For more information about this error, try `rustc --explain E0308`.
diff --git a/test_suite/tests/ui/rename/container_unknown_rename_rule.stderr b/test_suite/tests/ui/rename/container_unknown_rename_rule.stderr
index 6728b612f..728d71ca2 100644
--- a/test_suite/tests/ui/rename/container_unknown_rename_rule.stderr
+++ b/test_suite/tests/ui/rename/container_unknown_rename_rule.stderr
@@ -3,6 +3,3 @@ error: unknown rename rule for #[serde(rename_all = "abc")]
|
4 | #[serde(rename_all = "abc")]
| ^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/rename/variant_unknown_rename_rule.stderr b/test_suite/tests/ui/rename/variant_unknown_rename_rule.stderr
index f31e1abe7..7a52f37a8 100644
--- a/test_suite/tests/ui/rename/variant_unknown_rename_rule.stderr
+++ b/test_suite/tests/ui/rename/variant_unknown_rename_rule.stderr
@@ -3,6 +3,3 @@ error: unknown rename rule for #[serde(rename_all = "abc")]
|
5 | #[serde(rename_all = "abc")]
| ^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/struct-representation/internally-tagged-tuple.stderr b/test_suite/tests/ui/struct-representation/internally-tagged-tuple.stderr
index 52b3f77b0..7cf179895 100644
--- a/test_suite/tests/ui/struct-representation/internally-tagged-tuple.stderr
+++ b/test_suite/tests/ui/struct-representation/internally-tagged-tuple.stderr
@@ -3,6 +3,3 @@ error: #[serde(tag = "...")] can only be used on enums and structs with named fi
|
5 | struct S(u8, u8);
| ^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/struct-representation/internally-tagged-unit.stderr b/test_suite/tests/ui/struct-representation/internally-tagged-unit.stderr
index 31fca0004..47b4de8ab 100644
--- a/test_suite/tests/ui/struct-representation/internally-tagged-unit.stderr
+++ b/test_suite/tests/ui/struct-representation/internally-tagged-unit.stderr
@@ -3,6 +3,3 @@ error: #[serde(tag = "...")] can only be used on enums and structs with named fi
|
3 | #[derive(Serialize)]
| ^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/transparent/at_most_one.stderr b/test_suite/tests/ui/transparent/at_most_one.stderr
index dcdbfa9b2..b6a234c01 100644
--- a/test_suite/tests/ui/transparent/at_most_one.stderr
+++ b/test_suite/tests/ui/transparent/at_most_one.stderr
@@ -7,6 +7,3 @@ error: #[serde(transparent)] requires struct to have at most one transparent fie
7 | | b: u8,
8 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/transparent/de_at_least_one.stderr b/test_suite/tests/ui/transparent/de_at_least_one.stderr
index aa9d4ea75..42a02c0b7 100644
--- a/test_suite/tests/ui/transparent/de_at_least_one.stderr
+++ b/test_suite/tests/ui/transparent/de_at_least_one.stderr
@@ -9,6 +9,3 @@ error: #[serde(transparent)] requires at least one field that is neither skipped
9 | | b: u8,
10 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/transparent/enum.stderr b/test_suite/tests/ui/transparent/enum.stderr
index d1ee11ad1..2181fa8ba 100644
--- a/test_suite/tests/ui/transparent/enum.stderr
+++ b/test_suite/tests/ui/transparent/enum.stderr
@@ -4,6 +4,3 @@ error: #[serde(transparent)] is not allowed on an enum
4 | / #[serde(transparent)]
5 | | enum E {}
| |_________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/transparent/ser_at_least_one.stderr b/test_suite/tests/ui/transparent/ser_at_least_one.stderr
index bf1b9a203..6e1c01b54 100644
--- a/test_suite/tests/ui/transparent/ser_at_least_one.stderr
+++ b/test_suite/tests/ui/transparent/ser_at_least_one.stderr
@@ -7,6 +7,3 @@ error: #[serde(transparent)] requires at least one field that is not skipped
7 | | a: u8,
8 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/transparent/unit_struct.stderr b/test_suite/tests/ui/transparent/unit_struct.stderr
index 82956cf36..d6371efac 100644
--- a/test_suite/tests/ui/transparent/unit_struct.stderr
+++ b/test_suite/tests/ui/transparent/unit_struct.stderr
@@ -4,6 +4,3 @@ error: #[serde(transparent)] is not allowed on a unit struct
4 | / #[serde(transparent)]
5 | | struct S;
| |_________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/transparent/with_from.stderr b/test_suite/tests/ui/transparent/with_from.stderr
index 3fd789b79..fd031d436 100644
--- a/test_suite/tests/ui/transparent/with_from.stderr
+++ b/test_suite/tests/ui/transparent/with_from.stderr
@@ -6,6 +6,3 @@ error: #[serde(transparent)] is not allowed with #[serde(from = "...")]
6 | | a: u8,
7 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/transparent/with_into.stderr b/test_suite/tests/ui/transparent/with_into.stderr
index 816a42768..c8f72a376 100644
--- a/test_suite/tests/ui/transparent/with_into.stderr
+++ b/test_suite/tests/ui/transparent/with_into.stderr
@@ -6,6 +6,3 @@ error: #[serde(transparent)] is not allowed with #[serde(into = "...")]
6 | | a: u8,
7 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/type-attribute/from.stderr b/test_suite/tests/ui/type-attribute/from.stderr
index 06cafcd63..1aae4c4db 100644
--- a/test_suite/tests/ui/type-attribute/from.stderr
+++ b/test_suite/tests/ui/type-attribute/from.stderr
@@ -3,6 +3,3 @@ error: failed to parse type: from = "Option<T"
|
4 | #[serde(from = "Option<T")]
| ^^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/type-attribute/into.stderr b/test_suite/tests/ui/type-attribute/into.stderr
index bcf9569e4..0e9d0fed6 100644
--- a/test_suite/tests/ui/type-attribute/into.stderr
+++ b/test_suite/tests/ui/type-attribute/into.stderr
@@ -3,6 +3,3 @@ error: failed to parse type: into = "Option<T"
|
4 | #[serde(into = "Option<T")]
| ^^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/unexpected-literal/container.stderr b/test_suite/tests/ui/unexpected-literal/container.stderr
index bf2ab2f02..4d0c687c2 100644
--- a/test_suite/tests/ui/unexpected-literal/container.stderr
+++ b/test_suite/tests/ui/unexpected-literal/container.stderr
@@ -3,6 +3,3 @@ error: unexpected literal in serde container attribute
|
4 | #[serde("literal")]
| ^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/unexpected-literal/field.stderr b/test_suite/tests/ui/unexpected-literal/field.stderr
index 57954031e..3895a660f 100644
--- a/test_suite/tests/ui/unexpected-literal/field.stderr
+++ b/test_suite/tests/ui/unexpected-literal/field.stderr
@@ -3,6 +3,3 @@ error: unexpected literal in serde field attribute
|
5 | #[serde("literal")]
| ^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/unexpected-literal/variant.stderr b/test_suite/tests/ui/unexpected-literal/variant.stderr
index 6c4904b07..b7b2165c5 100644
--- a/test_suite/tests/ui/unexpected-literal/variant.stderr
+++ b/test_suite/tests/ui/unexpected-literal/variant.stderr
@@ -3,6 +3,3 @@ error: unexpected literal in serde variant attribute
|
5 | #[serde("literal")]
| ^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/unknown-attribute/container.stderr b/test_suite/tests/ui/unknown-attribute/container.stderr
index dbb589c1b..402a1b603 100644
--- a/test_suite/tests/ui/unknown-attribute/container.stderr
+++ b/test_suite/tests/ui/unknown-attribute/container.stderr
@@ -3,6 +3,3 @@ error: unknown serde container attribute `abc`
|
4 | #[serde(abc = "xyz")]
| ^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/unknown-attribute/field.stderr b/test_suite/tests/ui/unknown-attribute/field.stderr
index d95e280ba..b13754a36 100644
--- a/test_suite/tests/ui/unknown-attribute/field.stderr
+++ b/test_suite/tests/ui/unknown-attribute/field.stderr
@@ -3,6 +3,3 @@ error: unknown serde field attribute `abc`
|
5 | #[serde(abc = "xyz")]
| ^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/unknown-attribute/variant.stderr b/test_suite/tests/ui/unknown-attribute/variant.stderr
index a3d586075..64254f857 100644
--- a/test_suite/tests/ui/unknown-attribute/variant.stderr
+++ b/test_suite/tests/ui/unknown-attribute/variant.stderr
@@ -3,6 +3,3 @@ error: unknown serde variant attribute `abc`
|
5 | #[serde(abc = "xyz")]
| ^^^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/unsupported/union_de.stderr b/test_suite/tests/ui/unsupported/union_de.stderr
index 4f674e0d3..b7892d490 100644
--- a/test_suite/tests/ui/unsupported/union_de.stderr
+++ b/test_suite/tests/ui/unsupported/union_de.stderr
@@ -6,6 +6,3 @@ error: Serde does not support derive for unions
6 | | y: (),
7 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/unsupported/union_ser.stderr b/test_suite/tests/ui/unsupported/union_ser.stderr
index 9535cc8ee..78d87c71e 100644
--- a/test_suite/tests/ui/unsupported/union_ser.stderr
+++ b/test_suite/tests/ui/unsupported/union_ser.stderr
@@ -6,6 +6,3 @@ error: Serde does not support derive for unions
6 | | y: (),
7 | | }
| |_^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/update-references.sh b/test_suite/tests/ui/update-references.sh
deleted file mode 100755
index 725943295..000000000
--- a/test_suite/tests/ui/update-references.sh
+++ /dev/null
@@ -1,38 +0,0 @@
-#!/bin/bash
-#
-# Copyright 2015 The Rust Project Developers. See the COPYRIGHT
-# file at the top-level directory of this distribution and at
-# http://rust-lang.org/COPYRIGHT.
-#
-# 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.
-
-# A script to update the references for particular tests. The idea is
-# that you do a run, which will generate files in the build directory
-# containing the (normalized) actual output of the compiler. This
-# script will then copy that output and replace the "expected output"
-# files. You can then commit the changes.
-#
-# If you find yourself manually editing a foo.stderr file, you're
-# doing it wrong.
-
-cd "$(dirname "${BASH_SOURCE[0]}")"
-BUILD_DIR="../../../target/ui"
-
-for testcase in */*.rs; do
- STDERR_NAME="${testcase/%.rs/.stderr}"
- STDOUT_NAME="${testcase/%.rs/.stdout}"
- if [ -f "$BUILD_DIR/$STDOUT_NAME" ] && \
- ! (diff "$BUILD_DIR/$STDOUT_NAME" "$STDOUT_NAME" >& /dev/null); then
- echo "updating $STDOUT_NAME"
- cp "$BUILD_DIR/$STDOUT_NAME" "$STDOUT_NAME"
- fi
- if [ -f "$BUILD_DIR/$STDERR_NAME" ] && \
- ! (diff "$BUILD_DIR/$STDERR_NAME" "$STDERR_NAME" >& /dev/null); then
- echo "updating $STDERR_NAME"
- cp "$BUILD_DIR/$STDERR_NAME" "$STDERR_NAME"
- fi
-done
diff --git a/test_suite/tests/ui/with-variant/skip_de_newtype_field.stderr b/test_suite/tests/ui/with-variant/skip_de_newtype_field.stderr
index 1b5f15cd0..d3ff8c6e8 100644
--- a/test_suite/tests/ui/with-variant/skip_de_newtype_field.stderr
+++ b/test_suite/tests/ui/with-variant/skip_de_newtype_field.stderr
@@ -4,6 +4,3 @@ error: variant `Newtype` cannot have both #[serde(deserialize_with)] and a field
5 | / #[serde(deserialize_with = "deserialize_some_newtype_variant")]
6 | | Newtype(#[serde(skip_deserializing)] String),
| |________________________________________________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/with-variant/skip_de_struct_field.stderr b/test_suite/tests/ui/with-variant/skip_de_struct_field.stderr
index 7b3649c60..ee7e37918 100644
--- a/test_suite/tests/ui/with-variant/skip_de_struct_field.stderr
+++ b/test_suite/tests/ui/with-variant/skip_de_struct_field.stderr
@@ -8,6 +8,3 @@ error: variant `Struct` cannot have both #[serde(deserialize_with)] and a field
9 | | f2: u8,
10 | | },
| |_____^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/with-variant/skip_de_tuple_field.stderr b/test_suite/tests/ui/with-variant/skip_de_tuple_field.stderr
index 5c3e44e18..f2cc90e80 100644
--- a/test_suite/tests/ui/with-variant/skip_de_tuple_field.stderr
+++ b/test_suite/tests/ui/with-variant/skip_de_tuple_field.stderr
@@ -4,6 +4,3 @@ error: variant `Tuple` cannot have both #[serde(deserialize_with)] and a field #
5 | / #[serde(deserialize_with = "deserialize_some_other_variant")]
6 | | Tuple(#[serde(skip_deserializing)] String, u8),
| |__________________________________________________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/with-variant/skip_de_whole_variant.stderr b/test_suite/tests/ui/with-variant/skip_de_whole_variant.stderr
index 2d5ac0643..8f1be1632 100644
--- a/test_suite/tests/ui/with-variant/skip_de_whole_variant.stderr
+++ b/test_suite/tests/ui/with-variant/skip_de_whole_variant.stderr
@@ -5,6 +5,3 @@ error: variant `Unit` cannot have both #[serde(deserialize_with)] and #[serde(sk
6 | | #[serde(skip_deserializing)]
7 | | Unit,
| |________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/with-variant/skip_ser_newtype_field.stderr b/test_suite/tests/ui/with-variant/skip_ser_newtype_field.stderr
index 3298c5272..5741bc4fc 100644
--- a/test_suite/tests/ui/with-variant/skip_ser_newtype_field.stderr
+++ b/test_suite/tests/ui/with-variant/skip_ser_newtype_field.stderr
@@ -4,6 +4,3 @@ error: variant `Newtype` cannot have both #[serde(serialize_with)] and a field #
5 | / #[serde(serialize_with = "serialize_some_newtype_variant")]
6 | | Newtype(#[serde(skip_serializing)] String),
| |______________________________________________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/with-variant/skip_ser_newtype_field_if.stderr b/test_suite/tests/ui/with-variant/skip_ser_newtype_field_if.stderr
index 09c7ba431..8103680f6 100644
--- a/test_suite/tests/ui/with-variant/skip_ser_newtype_field_if.stderr
+++ b/test_suite/tests/ui/with-variant/skip_ser_newtype_field_if.stderr
@@ -4,6 +4,3 @@ error: variant `Newtype` cannot have both #[serde(serialize_with)] and a field #
5 | / #[serde(serialize_with = "serialize_some_newtype_variant")]
6 | | Newtype(#[serde(skip_serializing_if = "always")] String),
| |____________________________________________________________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/with-variant/skip_ser_struct_field.stderr b/test_suite/tests/ui/with-variant/skip_ser_struct_field.stderr
index fca04c58f..5b1e2301a 100644
--- a/test_suite/tests/ui/with-variant/skip_ser_struct_field.stderr
+++ b/test_suite/tests/ui/with-variant/skip_ser_struct_field.stderr
@@ -8,6 +8,3 @@ error: variant `Struct` cannot have both #[serde(serialize_with)] and a field `f
9 | | f2: u8,
10 | | },
| |_____^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/with-variant/skip_ser_struct_field_if.stderr b/test_suite/tests/ui/with-variant/skip_ser_struct_field_if.stderr
index a999665ac..4fc89d6a5 100644
--- a/test_suite/tests/ui/with-variant/skip_ser_struct_field_if.stderr
+++ b/test_suite/tests/ui/with-variant/skip_ser_struct_field_if.stderr
@@ -8,6 +8,3 @@ error: variant `Struct` cannot have both #[serde(serialize_with)] and a field `f
9 | | f2: u8,
10 | | },
| |_____^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/with-variant/skip_ser_tuple_field.stderr b/test_suite/tests/ui/with-variant/skip_ser_tuple_field.stderr
index 828c4aaab..4ea2dda59 100644
--- a/test_suite/tests/ui/with-variant/skip_ser_tuple_field.stderr
+++ b/test_suite/tests/ui/with-variant/skip_ser_tuple_field.stderr
@@ -4,6 +4,3 @@ error: variant `Tuple` cannot have both #[serde(serialize_with)] and a field #0
5 | / #[serde(serialize_with = "serialize_some_other_variant")]
6 | | Tuple(#[serde(skip_serializing)] String, u8),
| |________________________________________________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/with-variant/skip_ser_tuple_field_if.stderr b/test_suite/tests/ui/with-variant/skip_ser_tuple_field_if.stderr
index f83801157..1f8a81493 100644
--- a/test_suite/tests/ui/with-variant/skip_ser_tuple_field_if.stderr
+++ b/test_suite/tests/ui/with-variant/skip_ser_tuple_field_if.stderr
@@ -4,6 +4,3 @@ error: variant `Tuple` cannot have both #[serde(serialize_with)] and a field #0
5 | / #[serde(serialize_with = "serialize_some_other_variant")]
6 | | Tuple(#[serde(skip_serializing_if = "always")] String, u8),
| |______________________________________________________________^
-
-error: aborting due to previous error
-
diff --git a/test_suite/tests/ui/with-variant/skip_ser_whole_variant.stderr b/test_suite/tests/ui/with-variant/skip_ser_whole_variant.stderr
index 5b3f74774..20decdc43 100644
--- a/test_suite/tests/ui/with-variant/skip_ser_whole_variant.stderr
+++ b/test_suite/tests/ui/with-variant/skip_ser_whole_variant.stderr
@@ -5,6 +5,3 @@ error: variant `Unit` cannot have both #[serde(serialize_with)] and #[serde(skip
6 | | #[serde(skip_serializing)]
7 | | Unit,
| |________^
-
-error: aborting due to previous error
-
| [
"1513"
] | serde-rs__serde-1521 | Re-enable compile-fail tests
Disabled temporarily in #1512 due to libserde now appearing in the nightly sysroot and causing a conflict. We will need to figure out how else to run these tests.
| 1.0 | 28ce892617573d8da6d86bcb8a504aa1d8097b07 | diff --git a/.travis.yml b/.travis.yml
index f0e62b81e..7a2a44a42 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -26,8 +26,6 @@ matrix:
- cargo build --no-default-features --features alloc
- cargo build --no-default-features --features rc,alloc
- cargo test --features derive,rc,unstable
- - cd "${TRAVIS_BUILD_DIR}/test_suite/deps"
- - cargo build
- cd "${TRAVIS_BUILD_DIR}/test_suite"
- cargo test --features unstable
- cd "${TRAVIS_BUILD_DIR}/test_suite/no_std"
diff --git a/appveyor.yml b/appveyor.yml
index 1f99a9607..9fccc8dac 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -35,7 +35,5 @@ for:
- cargo build --no-default-features --features alloc
- cargo build --no-default-features --features rc,alloc
- cargo test --features derive,rc,unstable
- - cd %APPVEYOR_BUILD_FOLDER%\test_suite\deps
- - cargo build
- cd %APPVEYOR_BUILD_FOLDER%\test_suite
- cargo test --features unstable
| serde-rs/serde | 2019-05-06T16:59:53Z | I think the solution will involve factoring out the test runner from https://github.com/dtolnay/proc-macro-workshop and dropping compiletest_rs in favor of that. It is a more robust approach based on Cargo rather than direct rustc invocations. I have found that it works very reliably and in particular would not have this class of problem.
Upstream issue: https://github.com/dtolnay/proc-macro-workshop/issues/14
Here's the clippy workaround: https://github.com/rust-lang/rust-clippy/pull/4017 | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,499 | diff --git a/test_suite/tests/test_serde_path.rs b/test_suite/tests/test_serde_path.rs
new file mode 100644
index 000000000..4de436733
--- /dev/null
+++ b/test_suite/tests/test_serde_path.rs
@@ -0,0 +1,39 @@
+#[test]
+fn test_gen_custom_serde() {
+ #[derive(serde::Serialize, serde::Deserialize)]
+ #[serde(crate = "fake_serde")]
+ struct Foo;
+
+ // Would be overlapping if serde::Serialize were implemented
+ impl AssertNotSerdeSerialize for Foo {}
+ // Would be overlapping if serde::Deserialize were implemented
+ impl<'a> AssertNotSerdeDeserialize<'a> for Foo {}
+
+ fake_serde::assert::<Foo>();
+}
+
+mod fake_serde {
+ pub use serde::*;
+
+ pub fn assert<T>()
+ where
+ T: Serialize,
+ T: for<'a> Deserialize<'a>,
+ {}
+
+ pub trait Serialize {
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>;
+ }
+
+ pub trait Deserialize<'a>: Sized {
+ fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error>;
+ }
+}
+
+trait AssertNotSerdeSerialize {}
+
+impl<T: serde::Serialize> AssertNotSerdeSerialize for T {}
+
+trait AssertNotSerdeDeserialize<'a> {}
+
+impl<'a, T: serde::Deserialize<'a>> AssertNotSerdeDeserialize<'a> for T {}
| [
"1487"
] | serde-rs__serde-1499 | Allow specifying `serde` path and avoid injecting `extern crate serde as _serde`.
[tower-web](https://github.com/carllerche/tower-web/) provides a `#[derive(Response)]` macro. This macro is a shim on top of serde's `derive(Serialize)`. It works by catching HTTP specific attributes and leaving any serde attributes. It then generates a "shadow" version of the struct that has the actual `derive(Serialize)`.
The problem is that the user must add `serde` to their `Cargo.toml` even if they do not interact with any serde APIs directly.
`tower-web` re-exports `serde` in the crate. I propose to have a serde attribute that allows specifying the path to `serde`. If this attribute is set, the `extern crate serde as _serde` is omitted.
[This](https://gist.github.com/carllerche/6e2351e1c3f968792cb898c08a726d96) gist illustrates the problem. `hello.rs` is very basic. I also included the expanded code.
In short, I would like [this](https://gist.github.com/carllerche/6e2351e1c3f968792cb898c08a726d96#file-hello-expanded-rs-L70) line omitted and all references to `_serde` replaced with `__tw::codegen::serde`.
One way to expose the API is as an attribute:
```rust
#[derive(Serialize)]
#[serde(serde_path = "__tw::codegen::serde")]
struct Routes {
// ....
}
```
If you like this strategy, I could attempt a PR.
| 1.0 | 295730ba1e8ccfb58afad836ea4907b951698aae | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 7fa1030b1..df76ec631 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -27,15 +27,16 @@ pub fn expand_derive_deserialize(input: &syn::DeriveInput) -> Result<TokenStream
let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(¶ms);
let body = Stmts(deserialize_body(&cont, ¶ms));
let delife = params.borrowed.de_lifetime();
+ let serde = cont.attrs.serde_path();
let impl_block = if let Some(remote) = cont.attrs.remote() {
let vis = &input.vis;
let used = pretend::pretend_used(&cont);
quote! {
impl #de_impl_generics #ident #ty_generics #where_clause {
- #vis fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<#remote #ty_generics, __D::Error>
+ #vis fn deserialize<__D>(__deserializer: __D) -> #serde::export::Result<#remote #ty_generics, __D::Error>
where
- __D: _serde::Deserializer<#delife>,
+ __D: #serde::Deserializer<#delife>,
{
#used
#body
@@ -47,10 +48,10 @@ pub fn expand_derive_deserialize(input: &syn::DeriveInput) -> Result<TokenStream
quote! {
#[automatically_derived]
- impl #de_impl_generics _serde::Deserialize<#delife> for #ident #ty_generics #where_clause {
- fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error>
+ impl #de_impl_generics #serde::Deserialize<#delife> for #ident #ty_generics #where_clause {
+ fn deserialize<__D>(__deserializer: __D) -> #serde::export::Result<Self, __D::Error>
where
- __D: _serde::Deserializer<#delife>,
+ __D: #serde::Deserializer<#delife>,
{
#body
}
@@ -60,7 +61,7 @@ pub fn expand_derive_deserialize(input: &syn::DeriveInput) -> Result<TokenStream
}
};
- Ok(dummy::wrap_in_const("DESERIALIZE", ident, impl_block))
+ Ok(dummy::wrap_in_const(cont.attrs.custom_serde_path(), "DESERIALIZE", ident, impl_block))
}
fn precondition(cx: &Ctxt, cont: &Container) {
diff --git a/serde_derive/src/dummy.rs b/serde_derive/src/dummy.rs
index c265f03ea..a4e0e038b 100644
--- a/serde_derive/src/dummy.rs
+++ b/serde_derive/src/dummy.rs
@@ -1,8 +1,9 @@
use proc_macro2::{Ident, Span, TokenStream};
+use syn;
use try;
-pub fn wrap_in_const(trait_: &str, ty: &Ident, code: TokenStream) -> TokenStream {
+pub fn wrap_in_const(serde_path: Option<&syn::Path>, trait_: &str, ty: &Ident, code: TokenStream) -> TokenStream {
let try_replacement = try::replacement();
let dummy_const = Ident::new(
@@ -10,13 +11,21 @@ pub fn wrap_in_const(trait_: &str, ty: &Ident, code: TokenStream) -> TokenStream
Span::call_site(),
);
- quote! {
- #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
- const #dummy_const: () = {
+ let use_serde = serde_path.map(|path| {
+ quote!(use #path as _serde;)
+ }).unwrap_or_else(|| {
+ quote! {
#[allow(unknown_lints)]
#[cfg_attr(feature = "cargo-clippy", allow(useless_attribute))]
#[allow(rust_2018_idioms)]
extern crate serde as _serde;
+ }
+ });
+
+ quote! {
+ #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
+ const #dummy_const: () = {
+ #use_serde
#try_replacement
#code
};
diff --git a/serde_derive/src/internals/attr.rs b/serde_derive/src/internals/attr.rs
index b95d490f2..db763e22c 100644
--- a/serde_derive/src/internals/attr.rs
+++ b/serde_derive/src/internals/attr.rs
@@ -1,6 +1,7 @@
use internals::Ctxt;
use proc_macro2::{Group, Span, TokenStream, TokenTree};
use quote::ToTokens;
+use std::borrow::Cow;
use std::collections::BTreeSet;
use std::str::FromStr;
use syn;
@@ -218,6 +219,7 @@ pub struct Container {
remote: Option<syn::Path>,
identifier: Identifier,
has_flatten: bool,
+ serde_path: Option<syn::Path>,
}
/// Styles of representing an enum.
@@ -298,6 +300,7 @@ impl Container {
let mut remote = Attr::none(cx, "remote");
let mut field_identifier = BoolAttr::none(cx, "field_identifier");
let mut variant_identifier = BoolAttr::none(cx, "variant_identifier");
+ let mut serde_path = Attr::none(cx, "crate");
for meta_items in item.attrs.iter().filter_map(get_serde_meta_items) {
for meta_item in meta_items {
@@ -582,6 +585,13 @@ impl Container {
variant_identifier.set_true(word);
}
+ // Parse `#[serde(crate = "foo")]`
+ Meta(NameValue(ref m)) if m.ident == "crate" => {
+ if let Ok(path) = parse_lit_into_path(cx, &m.ident, &m.lit) {
+ serde_path.set(&m.ident, path)
+ }
+ }
+
Meta(ref meta_item) => {
cx.error_spanned_by(
meta_item.name(),
@@ -613,6 +623,7 @@ impl Container {
remote: remote.get(),
identifier: decide_identifier(cx, item, field_identifier, variant_identifier),
has_flatten: false,
+ serde_path: serde_path.get(),
}
}
@@ -671,6 +682,16 @@ impl Container {
pub fn mark_has_flatten(&mut self) {
self.has_flatten = true;
}
+
+ pub fn custom_serde_path(&self) -> Option<&syn::Path> {
+ self.serde_path.as_ref()
+ }
+
+ pub fn serde_path(&self) -> Cow<syn::Path> {
+ self.custom_serde_path()
+ .map(Cow::Borrowed)
+ .unwrap_or_else(|| Cow::Owned(parse_quote!(_serde)))
+ }
}
fn decide_tag(
diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index 4d1f680db..d5c83bc64 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -22,15 +22,16 @@ pub fn expand_derive_serialize(input: &syn::DeriveInput) -> Result<TokenStream,
let params = Parameters::new(&cont);
let (impl_generics, ty_generics, where_clause) = params.generics.split_for_impl();
let body = Stmts(serialize_body(&cont, ¶ms));
+ let serde = cont.attrs.serde_path();
let impl_block = if let Some(remote) = cont.attrs.remote() {
let vis = &input.vis;
let used = pretend::pretend_used(&cont);
quote! {
impl #impl_generics #ident #ty_generics #where_clause {
- #vis fn serialize<__S>(__self: &#remote #ty_generics, __serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error>
+ #vis fn serialize<__S>(__self: &#remote #ty_generics, __serializer: __S) -> #serde::export::Result<__S::Ok, __S::Error>
where
- __S: _serde::Serializer,
+ __S: #serde::Serializer,
{
#used
#body
@@ -40,10 +41,10 @@ pub fn expand_derive_serialize(input: &syn::DeriveInput) -> Result<TokenStream,
} else {
quote! {
#[automatically_derived]
- impl #impl_generics _serde::Serialize for #ident #ty_generics #where_clause {
- fn serialize<__S>(&self, __serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error>
+ impl #impl_generics #serde::Serialize for #ident #ty_generics #where_clause {
+ fn serialize<__S>(&self, __serializer: __S) -> #serde::export::Result<__S::Ok, __S::Error>
where
- __S: _serde::Serializer,
+ __S: #serde::Serializer,
{
#body
}
@@ -51,7 +52,7 @@ pub fn expand_derive_serialize(input: &syn::DeriveInput) -> Result<TokenStream,
}
};
- Ok(dummy::wrap_in_const("SERIALIZE", ident, impl_block))
+ Ok(dummy::wrap_in_const(cont.attrs.custom_serde_path(), "SERIALIZE", ident, impl_block))
}
fn precondition(cx: &Ctxt, cont: &Container) {
| serde-rs/serde | 2019-03-18T21:21:21Z | Seems reasonable. Please send a PR.
You will need to decide whether the given path is a `use` path or a relative path i.e. whether the expanded code is:
```rust
use __tw::codegen::serde;
impl serde::Serialize for T
```
or this:
```rust
impl __tw::codegen::serde::Serialize for T
```
Those would have different behavior in 2015 edition.
I'm pretty sure `use` doesn't work in the anon const scope thing. Since tower-web generates in a const scope, it cannot do option 1.
My thought is that whatever is set in `#[serde(serde_path = "__tw::codegen::serde")]` is used verbatim in the generated code. i.e. option 2.
Do you have thoughts on this? Also, do you have thoughts on what the attr should be?
Gentle ping :)
When you are +1 on the path, I can try to put together a PR (since it will probably be non-trivial, I'm hoping to get approval on the direction first).
Thanks for the reminder. I would accept a PR for option 2 using:
```rust
#[serde(crate = "__tw::codegen::serde")]
```
as the attribute. | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,474 | diff --git a/test_suite/tests/test_macros.rs b/test_suite/tests/test_macros.rs
index 280f00439..dd9591370 100644
--- a/test_suite/tests/test_macros.rs
+++ b/test_suite/tests/test_macros.rs
@@ -1424,6 +1424,48 @@ fn test_internally_tagged_braced_struct_with_zero_fields() {
);
}
+#[test]
+fn test_internally_tagged_struct_with_flattened_field() {
+ #[derive(Debug, PartialEq, Serialize, Deserialize)]
+ #[serde(tag="tag_struct")]
+ pub struct Struct {
+ #[serde(flatten)]
+ pub flat: Enum
+ }
+
+ #[derive(Debug, PartialEq, Serialize, Deserialize)]
+ #[serde(tag="tag_enum", content="content")]
+ pub enum Enum {
+ A(u64),
+ }
+
+ assert_tokens(
+ &Struct{flat: Enum::A(0)},
+ &[
+ Token::Map { len: None },
+ Token::Str("tag_struct"),
+ Token::Str("Struct"),
+ Token::Str("tag_enum"),
+ Token::Str("A"),
+ Token::Str("content"),
+ Token::U64(0),
+ Token::MapEnd
+ ]
+ );
+
+ assert_de_tokens(
+ &Struct{flat: Enum::A(0)},
+ &[
+ Token::Map { len: None },
+ Token::Str("tag_enum"),
+ Token::Str("A"),
+ Token::Str("content"),
+ Token::U64(0),
+ Token::MapEnd
+ ]
+ );
+}
+
#[test]
fn test_enum_in_untagged_enum() {
#[derive(Debug, PartialEq, Serialize, Deserialize)]
| [
"1468"
] | serde-rs__serde-1474 | Marking a struct field as flattened makes the struct ignore its tag
If I define a struct with a tag and add a field with the "flatten" attribute to this struct. The structs's tag seems to be ignored.
```rust
extern crate serde; // 1.0.84
#[macro_use]
extern crate serde_derive; // 1.0.84
#[macro_use]
extern crate serde_json; // 1.0.34
#[derive(Serialize, Debug)]
#[serde(tag="type")]
pub struct Program {
#[serde(flatten)]
pub body: ProgramType
}
#[derive(Serialize, Debug)]
#[serde(tag="sourceType", content="body")]
pub enum ProgramType {
#[serde(rename="script")]
Script(u64),
}
fn main() {
let p = Program{body: ProgramType::Script(0)};
// This assert fails, output:
// left: `Object({"body": Number(0), "sourceType": String("script")})`,
// right: `Object({"body": Number(0), "sourceType": String("script"), "type": String("Program")})`
assert_eq!(serde_json::to_value(p).unwrap(),
json!({"type": "Program", "sourceType": "script", "body": 0}))
}
```
| 1.0 | c8e39594357bdecb9dfee889dbdfced735033469 | diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index 1dacdc05a..e87ddee80 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -289,37 +289,41 @@ fn serialize_struct(params: &Parameters, fields: &[Field], cattrs: &attr::Contai
}
}
+fn serialize_struct_tag_field(
+ cattrs: &attr::Container,
+ struct_trait: &StructTrait,
+) -> TokenStream {
+ match *cattrs.tag() {
+ attr::TagType::Internal { ref tag } => {
+ let type_name = cattrs.name().serialize_name();
+ let func = struct_trait.serialize_field(Span::call_site());
+ quote! {
+ try!(#func(&mut __serde_state, #tag, #type_name));
+ }
+ }
+ _ => quote!{}
+ }
+}
+
fn serialize_struct_as_struct(
params: &Parameters,
fields: &[Field],
cattrs: &attr::Container,
) -> Fragment {
- let mut serialize_fields =
+ let serialize_fields =
serialize_struct_visitor(fields, params, false, &StructTrait::SerializeStruct);
let type_name = cattrs.name().serialize_name();
- let additional_field_count: usize = match *cattrs.tag() {
- attr::TagType::Internal { ref tag } => {
- let func = StructTrait::SerializeStruct.serialize_field(Span::call_site());
- serialize_fields.insert(
- 0,
- quote! {
- try!(#func(&mut __serde_state, #tag, #type_name));
- },
- );
-
- 1
- }
- _ => 0,
- };
+ let tag_field = serialize_struct_tag_field(cattrs, &StructTrait::SerializeStruct);
+ let tag_field_exists = !tag_field.is_empty();
let mut serialized_fields = fields
.iter()
.filter(|&field| !field.attrs.skip_serializing())
.peekable();
- let let_mut = mut_if(serialized_fields.peek().is_some() || additional_field_count > 0);
+ let let_mut = mut_if(serialized_fields.peek().is_some() || tag_field_exists);
let len = serialized_fields
.map(|field| match field.attrs.skip_serializing_if() {
@@ -330,12 +334,13 @@ fn serialize_struct_as_struct(
}
})
.fold(
- quote!(#additional_field_count),
+ quote!(#tag_field_exists as usize),
|sum, expr| quote!(#sum + #expr),
);
quote_block! {
let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct(__serializer, #type_name, #len));
+ #tag_field
#(#serialize_fields)*
_serde::ser::SerializeStruct::end(__serde_state)
}
@@ -349,12 +354,15 @@ fn serialize_struct_as_map(
let serialize_fields =
serialize_struct_visitor(fields, params, false, &StructTrait::SerializeMap);
+ let tag_field = serialize_struct_tag_field(cattrs, &StructTrait::SerializeMap);
+ let tag_field_exists = !tag_field.is_empty();
+
let mut serialized_fields = fields
.iter()
.filter(|&field| !field.attrs.skip_serializing())
.peekable();
- let let_mut = mut_if(serialized_fields.peek().is_some());
+ let let_mut = mut_if(serialized_fields.peek().is_some() || tag_field_exists);
let len = if cattrs.has_flatten() {
quote!(_serde::export::None)
@@ -367,12 +375,16 @@ fn serialize_struct_as_map(
quote!(if #path(#field_expr) { 0 } else { 1 })
}
})
- .fold(quote!(0), |sum, expr| quote!(#sum + #expr));
+ .fold(
+ quote!(#tag_field_exists as usize),
+ |sum, expr| quote!(#sum + #expr)
+ );
quote!(_serde::export::Some(#len))
};
quote_block! {
let #let_mut __serde_state = try!(_serde::Serializer::serialize_map(__serializer, #len));
+ #tag_field
#(#serialize_fields)*
_serde::ser::SerializeMap::end(__serde_state)
}
| serde-rs/serde | 2019-02-03T01:17:53Z | Thanks! This looks like a bug. Would you be interested in sending a PR to fix it?
Sure. I implemented the tagged structs in the first place so I guess it's only fair if I have to do the bug fixing :D But it might take a few days. | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,390 | diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index 0df7fd69f..60bd0b413 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -272,7 +272,7 @@ declare_tests! {
0f32 => &[Token::F32(0.)],
0f64 => &[Token::F64(0.)],
}
- #[cfg(not(target_arch = "wasm32"))]
+ #[cfg(not(any(target_arch = "asmjs", target_arch = "wasm32")))]
test_small_int_to_128 {
1i128 => &[Token::I8(1)],
1i128 => &[Token::I16(1)],
diff --git a/test_suite/tests/test_ser.rs b/test_suite/tests/test_ser.rs
index 231b6ee7c..81129540f 100644
--- a/test_suite/tests/test_ser.rs
+++ b/test_suite/tests/test_ser.rs
@@ -618,7 +618,7 @@ fn test_enum_skipped() {
);
}
-#[cfg(not(target_arch = "wasm32"))]
+#[cfg(not(any(target_arch = "asmjs", target_arch = "wasm32")))]
#[test]
fn test_integer128() {
assert_ser_tokens_error(&1i128, &[], "i128 is not supported");
diff --git a/test_suite/tests/test_value.rs b/test_suite/tests/test_value.rs
index d351ed540..180e72f28 100644
--- a/test_suite/tests/test_value.rs
+++ b/test_suite/tests/test_value.rs
@@ -26,7 +26,7 @@ fn test_u32_to_enum() {
assert_eq!(E::B, e);
}
-#[cfg(not(target_arch = "wasm32"))]
+#[cfg(not(any(target_arch = "asmjs", target_arch = "wasm32")))]
#[test]
fn test_integer128() {
let de_u128 = IntoDeserializer::<value::Error>::into_deserializer(1u128);
| [
"1366"
] | serde-rs__serde-1390 | Set up CI build on Emscripten target
@koute do you know of any existing projects that test every commit on Emscripten? I would have liked to catch #1365 in CI. Is it as simple as just passing a `--target` to Cargo? Does that only let us test cross-compilation or is there a way to run our test suite as well?
| 1.0 | 2cf10a600370b987a35136d21216d5dc29f7ecba | diff --git a/travis.sh b/travis.sh
index 11c9556f5..9002e3e5c 100755
--- a/travis.sh
+++ b/travis.sh
@@ -53,6 +53,7 @@ elif [ -n "${EMSCRIPTEN}" ]; then
chmod +x ~/.cargo/bin/cargo-web
cd "$DIR/test_suite"
+ cargo web test --target=asmjs-unknown-emscripten --nodejs
cargo web test --target=wasm32-unknown-emscripten --nodejs
else
CHANNEL=nightly
| serde-rs/serde | 2018-09-15T22:15:44Z | > @koute do you know of any existing projects that test every commit on Emscripten?
Yes! My [stdweb](https://github.com/koute/stdweb) does. (: In fact, this is how I caught this - suddenly my builds on stable started failing, and after more thorough investigation the culprit was the newest version of `serde_json` which switched to `ryu`.
> Is it as simple as just passing a --target to Cargo? Does that only let us test cross-compilation or is there a way to run our test suite as well?
Mostly, yes, however you need to manually install Emscripten (`rustup` doesn't install it for you) and manually run the test file yourself (or set a runner in `.cargo/config`). I don't know if that's still the case though, but there was also a bug where after a fresh installation of Emscripten you had to "warm" it up (basically the first compilation after installing Emscripten produces no artifacts but no error is generated).
You can either do it manually, or you can use my [cargo-web](https://github.com/koute/cargo-web) to automate it. It will automatically install the target through `rustup`, download Emscripten for you and work around the post install bug.
Basically, you can run this on Travis to install a precompiled binary of `cargo-web`:
```
CARGO_WEB_RELEASE=$(curl -L -s -H 'Accept: application/json' https://github.com/koute/cargo-web/releases/latest)
CARGO_WEB_VERSION=$(echo $CARGO_WEB_RELEASE | sed -e 's/.*"tag_name":"\([^"]*\)".*/\1/')
CARGO_WEB_URL="https://github.com/koute/cargo-web/releases/download/$CARGO_WEB_VERSION/cargo-web-x86_64-unknown-linux-gnu.gz"
echo "Downloading cargo-web from: $CARGO_WEB_URL"
curl -L $CARGO_WEB_URL | gzip -d > cargo-web
chmod +x cargo-web
mkdir -p ~/.cargo/bin
mv cargo-web ~/.cargo/bin
```
And then simply:
```
# Install Node.js
nvm install 9
# Run the tests.
cargo web test --target=asmjs-unknown-emscripten --nodejs
cargo web test --target=wasm32-unknown-emscripten --nodejs
```
(By default it runs the tests in a headless Chromium, but that's not necessary for projects which aren't strictly Web-related so `--nodejs` will make it run through Node.js.)
Amazing! Thanks, we'll get this set up and stop breaking your builds.
I couldn't get asmjs working because of
```console
error[E0463]: can't find crate for `proc_macro`
--> /home/travis/.cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-0.4.16/src/lib.rs:53:1
|
53 | extern crate proc_macro;
| ^^^^^^^^^^^^^^^^^^^^^^^^ can't find crate
```
but I added a wasm32-unknown-emscripten builder in #1373.
@dtolnay It cannot find the `proc_macro` crate on the `asmjs-unknown-emscripten` as `proc_macro` seems to not be shipped by Rust for that target. (Which does make sense.)
If you remove `proc-macro2 = "0.4"` from the `[dev-dependencies]` of `serde_test_suite` then the `asmjs-unknown-unknown` will work. (Although you'd still need to extend the `#[cfg]`s in `tests/test_de.rs` `tests/test_ser.rs` and `tests/test_value.rs` to also handle `asmjs`, as they currently only match `wasm32`.) | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,380 | diff --git a/test_suite/tests/test_annotations.rs b/test_suite/tests/test_annotations.rs
index 87eda5015..bf8af8052 100644
--- a/test_suite/tests/test_annotations.rs
+++ b/test_suite/tests/test_annotations.rs
@@ -12,9 +12,11 @@
extern crate serde_derive;
extern crate serde;
-use self::serde::de::{self, Unexpected};
+use self::serde::de::{self, Visitor, MapAccess, Unexpected};
use self::serde::{Deserialize, Deserializer, Serialize, Serializer};
+
use std::collections::{BTreeMap, HashMap};
+use std::fmt;
use std::marker::PhantomData;
extern crate serde_test;
@@ -2311,3 +2313,66 @@ fn test_flattened_internally_tagged_unit_enum_with_unknown_fields() {
],
);
}
+
+#[test]
+fn test_flatten_any_after_flatten_struct() {
+ #[derive(PartialEq, Debug)]
+ struct Any;
+
+ impl<'de> Deserialize<'de> for Any {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ struct AnyVisitor;
+
+ impl<'de> Visitor<'de> for AnyVisitor {
+ type Value = Any;
+
+ fn expecting(&self, _formatter: &mut fmt::Formatter) -> fmt::Result {
+ unimplemented!()
+ }
+
+ fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
+ where
+ M: MapAccess<'de>,
+ {
+ while let Some((Any, Any)) = map.next_entry()? {}
+ Ok(Any)
+ }
+ }
+
+ deserializer.deserialize_any(AnyVisitor)
+ }
+ }
+
+ #[derive(Deserialize, PartialEq, Debug)]
+ struct Outer {
+ #[serde(flatten)]
+ inner: Inner,
+ #[serde(flatten)]
+ extra: Any,
+ }
+
+ #[derive(Deserialize, PartialEq, Debug)]
+ struct Inner {
+ inner: i32,
+ }
+
+ let s = Outer {
+ inner: Inner {
+ inner: 0,
+ },
+ extra: Any,
+ };
+
+ assert_de_tokens(
+ &s,
+ &[
+ Token::Map { len: None },
+ Token::Str("inner"),
+ Token::I32(0),
+ Token::MapEnd,
+ ],
+ );
+}
| [
"1379"
] | serde-rs__serde-1380 | Serde panics when flattening struct and Value
When trying to deserialize a struct which contains another struct with the `#[serde(flatten)]` annotation and a field with the `#[serde(flatten)]` annotation and the type `toml::Value` (same with `serde_yaml` or `serde_json`), serde will panic.
A minimal example for reproducing this:
```rust
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate toml;
#[derive(Debug, Deserialize)]
struct Test {
text: Option<String>,
#[serde(flatten)]
settings: Settings,
#[serde(flatten)]
extra: toml::Value,
}
#[derive(Debug, Deserialize)]
struct Settings {
width: Option<u8>,
}
fn main() {
let file = "text = \"test\"\nwidth = 8";
let test: Test = toml::from_str(file).unwrap();
}
```
[playground](https://play.rust-lang.org/?gist=b5fd8d4d24cd319f76c3fa439c36ca8d&version=stable&mode=debug&edition=2015)
This will result in the following error:
```
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value'
```
| 1.0 | 108cca687c7851973cc6cb1ad06de620ab8fae4d | diff --git a/serde/src/private/de.rs b/serde/src/private/de.rs
index 51c7035a3..4b0f2c4c2 100644
--- a/serde/src/private/de.rs
+++ b/serde/src/private/de.rs
@@ -2916,18 +2916,17 @@ where
where
T: DeserializeSeed<'de>,
{
- match self.iter.next() {
- Some(item) => {
+ while let Some(item) = self.iter.next() {
+ if let Some((ref key, ref content)) = *item {
// Do not take(), instead borrow this entry. The internally tagged
// enum does its own buffering so we can't tell whether this entry
// is going to be consumed. Borrowing here leaves the entry
// available for later flattened fields.
- let (ref key, ref content) = *item.as_ref().unwrap();
self.pending = Some(content);
- seed.deserialize(ContentRefDeserializer::new(key)).map(Some)
+ return seed.deserialize(ContentRefDeserializer::new(key)).map(Some);
}
- None => Ok(None),
}
+ Ok(None)
}
fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
| serde-rs/serde | 2018-09-08T23:56:07Z | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 | |
1,373 | diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index 95b419e26..4897abd05 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -156,8 +156,12 @@ macro_rules! declare_tests {
)+
};
- ($($name:ident { $($value:expr => $tokens:expr,)+ })+) => {
+ ($(
+ $(#[$cfg:meta])*
+ $name:ident { $($value:expr => $tokens:expr,)+ }
+ )+) => {
$(
+ $(#[$cfg])*
#[test]
fn $name() {
$(
@@ -260,6 +264,7 @@ declare_tests! {
0f32 => &[Token::F32(0.)],
0f64 => &[Token::F64(0.)],
}
+ #[cfg(not(target_arch = "wasm32"))]
test_small_int_to_128 {
1i128 => &[Token::I8(1)],
1i128 => &[Token::I16(1)],
diff --git a/test_suite/tests/test_ser.rs b/test_suite/tests/test_ser.rs
index 086029b56..231b6ee7c 100644
--- a/test_suite/tests/test_ser.rs
+++ b/test_suite/tests/test_ser.rs
@@ -618,6 +618,7 @@ fn test_enum_skipped() {
);
}
+#[cfg(not(target_arch = "wasm32"))]
#[test]
fn test_integer128() {
assert_ser_tokens_error(&1i128, &[], "i128 is not supported");
diff --git a/test_suite/tests/test_value.rs b/test_suite/tests/test_value.rs
index d2d9e67c0..d351ed540 100644
--- a/test_suite/tests/test_value.rs
+++ b/test_suite/tests/test_value.rs
@@ -26,6 +26,7 @@ fn test_u32_to_enum() {
assert_eq!(E::B, e);
}
+#[cfg(not(target_arch = "wasm32"))]
#[test]
fn test_integer128() {
let de_u128 = IntoDeserializer::<value::Error>::into_deserializer(1u128);
| [
"1366"
] | serde-rs__serde-1373 | Set up CI build on Emscripten target
@koute do you know of any existing projects that test every commit on Emscripten? I would have liked to catch #1365 in CI. Is it as simple as just passing a `--target` to Cargo? Does that only let us test cross-compilation or is there a way to run our test suite as well?
| 1.0 | d23a40c1bbd938830126db65ef83b99a8c64467e | diff --git a/.travis.yml b/.travis.yml
index 87d36ff77..9124ebbbf 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -18,5 +18,8 @@ matrix:
include:
- rust: nightly
env: CLIPPY=true
+ - rust: nightly
+ env: EMSCRIPTEN=true
+ script: nvm install 9 && ./travis.sh
script: ./travis.sh
diff --git a/travis.sh b/travis.sh
index 8626e3e66..55b795084 100755
--- a/travis.sh
+++ b/travis.sh
@@ -42,6 +42,18 @@ if [ -n "${CLIPPY}" ]; then
cd "$DIR/test_suite/no_std"
cargo clippy -- -Dclippy
+elif [ -n "${EMSCRIPTEN}" ]; then
+ CARGO_WEB_RELEASE=$(curl -L -s -H 'Accept: application/json' https://github.com/koute/cargo-web/releases/latest)
+ CARGO_WEB_VERSION=$(echo "${CARGO_WEB_RELEASE}" | sed -e 's/.*"tag_name":"\([^"]*\)".*/\1/')
+ CARGO_WEB_URL="https://github.com/koute/cargo-web/releases/download/${CARGO_WEB_VERSION}/cargo-web-x86_64-unknown-linux-gnu.gz"
+
+ mkdir -p ~/.cargo/bin
+ echo "Downloading cargo-web from: ${CARGO_WEB_URL}"
+ curl -L "${CARGO_WEB_URL}" | gzip -d > ~/.cargo/bin/cargo-web
+ chmod +x ~/.cargo/bin/cargo-web
+
+ cd "$DIR/test_suite"
+ cargo web test --target=wasm32-unknown-emscripten --nodejs
else
CHANNEL=nightly
cd "$DIR"
| serde-rs/serde | 2018-09-02T19:34:54Z | > @koute do you know of any existing projects that test every commit on Emscripten?
Yes! My [stdweb](https://github.com/koute/stdweb) does. (: In fact, this is how I caught this - suddenly my builds on stable started failing, and after more thorough investigation the culprit was the newest version of `serde_json` which switched to `ryu`.
> Is it as simple as just passing a --target to Cargo? Does that only let us test cross-compilation or is there a way to run our test suite as well?
Mostly, yes, however you need to manually install Emscripten (`rustup` doesn't install it for you) and manually run the test file yourself (or set a runner in `.cargo/config`). I don't know if that's still the case though, but there was also a bug where after a fresh installation of Emscripten you had to "warm" it up (basically the first compilation after installing Emscripten produces no artifacts but no error is generated).
You can either do it manually, or you can use my [cargo-web](https://github.com/koute/cargo-web) to automate it. It will automatically install the target through `rustup`, download Emscripten for you and work around the post install bug.
Basically, you can run this on Travis to install a precompiled binary of `cargo-web`:
```
CARGO_WEB_RELEASE=$(curl -L -s -H 'Accept: application/json' https://github.com/koute/cargo-web/releases/latest)
CARGO_WEB_VERSION=$(echo $CARGO_WEB_RELEASE | sed -e 's/.*"tag_name":"\([^"]*\)".*/\1/')
CARGO_WEB_URL="https://github.com/koute/cargo-web/releases/download/$CARGO_WEB_VERSION/cargo-web-x86_64-unknown-linux-gnu.gz"
echo "Downloading cargo-web from: $CARGO_WEB_URL"
curl -L $CARGO_WEB_URL | gzip -d > cargo-web
chmod +x cargo-web
mkdir -p ~/.cargo/bin
mv cargo-web ~/.cargo/bin
```
And then simply:
```
# Install Node.js
nvm install 9
# Run the tests.
cargo web test --target=asmjs-unknown-emscripten --nodejs
cargo web test --target=wasm32-unknown-emscripten --nodejs
```
(By default it runs the tests in a headless Chromium, but that's not necessary for projects which aren't strictly Web-related so `--nodejs` will make it run through Node.js.)
Amazing! Thanks, we'll get this set up and stop breaking your builds. | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
739 | diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index 8bdfdcee0..138ed0cd9 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -47,91 +47,29 @@ impl<I> Deserializer<I>
}
}
- fn visit_seq<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
+ fn visit_seq<V>(&mut self, len: Option<usize>, sep: Token<'static>, end: Token<'static>, visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
let value = try!(visitor.visit_seq(DeserializerSeqVisitor {
de: self,
len: len,
+ sep: sep,
+ end: end.clone(),
}));
- try!(self.expect_token(Token::SeqEnd));
+ try!(self.expect_token(end));
Ok(value)
}
- fn visit_array<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
- {
- let value = try!(visitor.visit_seq(DeserializerArrayVisitor {
- de: self,
- len: len,
- }));
- try!(self.expect_token(Token::SeqEnd));
- Ok(value)
- }
-
- fn visit_tuple<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
- {
- let value = try!(visitor.visit_seq(DeserializerTupleVisitor {
- de: self,
- len: len,
- }));
- try!(self.expect_token(Token::TupleEnd));
- Ok(value)
- }
-
- fn visit_tuple_struct<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
- {
- let value = try!(visitor.visit_seq(DeserializerTupleStructVisitor {
- de: self,
- len: len,
- }));
- try!(self.expect_token(Token::TupleStructEnd));
- Ok(value)
- }
-
- fn visit_variant_seq<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
- {
- let value = try!(visitor.visit_seq(DeserializerVariantSeqVisitor {
- de: self,
- len: len,
- }));
- try!(self.expect_token(Token::EnumSeqEnd));
- Ok(value)
- }
-
- fn visit_map<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
+ fn visit_map<V>(&mut self, len: Option<usize>, sep: Token<'static>, end: Token<'static>, visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
let value = try!(visitor.visit_map(DeserializerMapVisitor {
de: self,
len: len,
+ sep: sep,
+ end: end.clone(),
}));
- try!(self.expect_token(Token::MapEnd));
- Ok(value)
- }
-
- fn visit_struct<V>(&mut self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
- {
- let value = try!(visitor.visit_map(DeserializerStructVisitor {
- de: self,
- len: fields.len(),
- }));
- try!(self.expect_token(Token::StructEnd));
- Ok(value)
- }
-
- fn visit_variant_map<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
- {
- let value = try!(visitor.visit_map(DeserializerVariantMapVisitor {
- de: self,
- len: len,
- }));
- try!(self.expect_token(Token::EnumMapEnd));
+ try!(self.expect_token(end));
Ok(value)
}
}
@@ -141,89 +79,9 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
{
type Error = Error;
- fn deserialize_seq<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_struct_field<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_map<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_unit<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_bytes<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_byte_buf<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_ignored_any<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_string<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_str<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_char<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_i64<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_i32<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_i16<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_i8<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_u64<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_u32<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_u16<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_u8<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_f32<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_f64<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_bool<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
+ forward_to_deserialize! {
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit
+ seq bytes byte_buf map struct_field ignored_any
}
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
@@ -251,16 +109,22 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
Some(Token::Unit) => visitor.visit_unit(),
Some(Token::UnitStruct(_name)) => visitor.visit_unit(),
Some(Token::SeqStart(len)) => {
- self.visit_seq(len, visitor)
+ self.visit_seq(len, Token::SeqSep, Token::SeqEnd, visitor)
}
- Some(Token::SeqArrayStart(len))| Some(Token::TupleStructStart(_, len)) => {
- self.visit_seq(Some(len), visitor)
+ Some(Token::SeqArrayStart(len)) => {
+ self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
+ }
+ Some(Token::TupleStart(len)) => {
+ self.visit_seq(Some(len), Token::TupleSep, Token::TupleEnd, visitor)
+ }
+ Some(Token::TupleStructStart(_, len)) => {
+ self.visit_seq(Some(len), Token::TupleStructSep, Token::TupleStructEnd, visitor)
}
Some(Token::MapStart(len)) => {
- self.visit_map(len, visitor)
+ self.visit_map(len, Token::MapSep, Token::MapEnd, visitor)
}
Some(Token::StructStart(_, len)) => {
- self.visit_map(Some(len), visitor)
+ self.visit_map(Some(len), Token::StructSep, Token::StructEnd, visitor)
}
Some(token) => Err(Error::UnexpectedToken(token)),
None => Err(Error::EndOfTokens),
@@ -360,7 +224,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
match self.tokens.peek() {
Some(&Token::SeqArrayStart(_)) => {
self.tokens.next();
- self.visit_array(len, visitor)
+ self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
}
Some(_) => self.deserialize(visitor),
None => Err(Error::EndOfTokens),
@@ -379,19 +243,19 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
}
Some(&Token::SeqStart(_)) => {
self.tokens.next();
- self.visit_seq(Some(len), visitor)
+ self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
}
Some(&Token::SeqArrayStart(_)) => {
self.tokens.next();
- self.visit_array(len, visitor)
+ self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
}
Some(&Token::TupleStart(_)) => {
self.tokens.next();
- self.visit_tuple(len, visitor)
+ self.visit_seq(Some(len), Token::TupleSep, Token::TupleEnd, visitor)
}
Some(&Token::TupleStructStart(_, _)) => {
self.tokens.next();
- self.visit_tuple_struct(len, visitor)
+ self.visit_seq(Some(len), Token::TupleStructSep, Token::TupleStructEnd, visitor)
}
Some(_) => self.deserialize(visitor),
None => Err(Error::EndOfTokens),
@@ -419,20 +283,20 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
}
Some(&Token::SeqStart(_)) => {
self.tokens.next();
- self.visit_seq(Some(len), visitor)
+ self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
}
Some(&Token::SeqArrayStart(_)) => {
self.tokens.next();
- self.visit_array(len, visitor)
+ self.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
}
Some(&Token::TupleStart(_)) => {
self.tokens.next();
- self.visit_tuple(len, visitor)
+ self.visit_seq(Some(len), Token::TupleSep, Token::TupleEnd, visitor)
}
Some(&Token::TupleStructStart(n, _)) => {
self.tokens.next();
if name == n {
- self.visit_tuple_struct(len, visitor)
+ self.visit_seq(Some(len), Token::TupleStructSep, Token::TupleStructEnd, visitor)
} else {
Err(Error::InvalidName(n))
}
@@ -452,14 +316,14 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
Some(&Token::StructStart(n, _)) => {
self.tokens.next();
if name == n {
- self.visit_struct(fields, visitor)
+ self.visit_map(Some(fields.len()), Token::StructSep, Token::StructEnd, visitor)
} else {
Err(Error::InvalidName(n))
}
}
Some(&Token::MapStart(_)) => {
self.tokens.next();
- self.visit_map(Some(fields.len()), visitor)
+ self.visit_map(Some(fields.len()), Token::MapSep, Token::MapEnd, visitor)
}
Some(_) => self.deserialize(visitor),
None => Err(Error::EndOfTokens),
@@ -472,6 +336,8 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
struct DeserializerSeqVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
de: &'a mut Deserializer<I>,
len: Option<usize>,
+ sep: Token<'static>,
+ end: Token<'static>,
}
impl<'a, I> SeqVisitor for DeserializerSeqVisitor<'a, I>
@@ -482,158 +348,15 @@ impl<'a, I> SeqVisitor for DeserializerSeqVisitor<'a, I>
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
where T: DeserializeSeed,
{
- match self.de.tokens.peek() {
- Some(&Token::SeqSep) => {
- self.de.tokens.next();
- self.len = self.len.map(|len| len - 1);
- seed.deserialize(&mut *self.de).map(Some)
- }
- Some(&Token::SeqEnd) => Ok(None),
- Some(_) => {
- let token = self.de.tokens.next().unwrap();
- Err(Error::UnexpectedToken(token))
- }
- None => Err(Error::EndOfTokens),
+ if self.de.tokens.peek() == Some(&self.end) {
+ return Ok(None);
}
- }
-
- fn size_hint(&self) -> (usize, Option<usize>) {
- let len = self.len.unwrap_or(0);
- (len, self.len)
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-struct DeserializerArrayVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
- de: &'a mut Deserializer<I>,
- len: usize,
-}
-
-impl<'a, I> SeqVisitor for DeserializerArrayVisitor<'a, I>
- where I: Iterator<Item=Token<'static>>,
-{
- type Error = Error;
-
- fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
- where T: DeserializeSeed,
- {
- match self.de.tokens.peek() {
- Some(&Token::SeqSep) => {
- self.de.tokens.next();
- self.len -= 1;
+ match self.de.tokens.next() {
+ Some(ref token) if *token == self.sep => {
+ self.len = self.len.map(|len| len.saturating_sub(1));
seed.deserialize(&mut *self.de).map(Some)
}
- Some(&Token::SeqEnd) => Ok(None),
- Some(_) => {
- let token = self.de.tokens.next().unwrap();
- Err(Error::UnexpectedToken(token))
- }
- None => Err(Error::EndOfTokens),
- }
- }
-
- fn size_hint(&self) -> (usize, Option<usize>) {
- (self.len, Some(self.len))
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-struct DeserializerTupleVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
- de: &'a mut Deserializer<I>,
- len: usize,
-}
-
-impl<'a, I> SeqVisitor for DeserializerTupleVisitor<'a, I>
- where I: Iterator<Item=Token<'static>>,
-{
- type Error = Error;
-
- fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
- where T: DeserializeSeed,
- {
- match self.de.tokens.peek() {
- Some(&Token::TupleSep) => {
- self.de.tokens.next();
- self.len -= 1;
- seed.deserialize(&mut *self.de).map(Some)
- }
- Some(&Token::TupleEnd) => Ok(None),
- Some(_) => {
- let token = self.de.tokens.next().unwrap();
- Err(Error::UnexpectedToken(token))
- }
- None => Err(Error::EndOfTokens),
- }
- }
-
- fn size_hint(&self) -> (usize, Option<usize>) {
- (self.len, Some(self.len))
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-struct DeserializerTupleStructVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
- de: &'a mut Deserializer<I>,
- len: usize,
-}
-
-impl<'a, I> SeqVisitor for DeserializerTupleStructVisitor<'a, I>
- where I: Iterator<Item=Token<'static>>,
-{
- type Error = Error;
-
- fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
- where T: DeserializeSeed,
- {
- match self.de.tokens.peek() {
- Some(&Token::TupleStructSep) => {
- self.de.tokens.next();
- self.len -= 1;
- seed.deserialize(&mut *self.de).map(Some)
- }
- Some(&Token::TupleStructEnd) => Ok(None),
- Some(_) => {
- let token = self.de.tokens.next().unwrap();
- Err(Error::UnexpectedToken(token))
- }
- None => Err(Error::EndOfTokens),
- }
- }
-
- fn size_hint(&self) -> (usize, Option<usize>) {
- (self.len, Some(self.len))
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-
-struct DeserializerVariantSeqVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
- de: &'a mut Deserializer<I>,
- len: Option<usize>,
-}
-
-impl<'a, I> SeqVisitor for DeserializerVariantSeqVisitor<'a, I>
- where I: Iterator<Item=Token<'static>>,
-{
- type Error = Error;
-
- fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
- where T: DeserializeSeed,
- {
- match self.de.tokens.peek() {
- Some(&Token::EnumSeqSep) => {
- self.de.tokens.next();
- self.len = self.len.map(|len| len - 1);
- seed.deserialize(&mut *self.de).map(Some)
- }
- Some(&Token::EnumSeqEnd) => Ok(None),
- Some(_) => {
- let token = self.de.tokens.next().unwrap();
- Err(Error::UnexpectedToken(token))
- }
+ Some(other) => Err(Error::UnexpectedToken(other)),
None => Err(Error::EndOfTokens),
}
}
@@ -649,6 +372,8 @@ impl<'a, I> SeqVisitor for DeserializerVariantSeqVisitor<'a, I>
struct DeserializerMapVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
de: &'a mut Deserializer<I>,
len: Option<usize>,
+ sep: Token<'static>,
+ end: Token<'static>,
}
impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
@@ -659,17 +384,15 @@ impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
where K: DeserializeSeed,
{
- match self.de.tokens.peek() {
- Some(&Token::MapSep) => {
- self.de.tokens.next();
- self.len = self.len.map(|len| if len > 0 { len - 1} else { 0 });
+ if self.de.tokens.peek() == Some(&self.end) {
+ return Ok(None);
+ }
+ match self.de.tokens.next() {
+ Some(ref token) if *token == self.sep => {
+ self.len = self.len.map(|len| len.saturating_sub(1));
seed.deserialize(&mut *self.de).map(Some)
}
- Some(&Token::MapEnd) => Ok(None),
- Some(_) => {
- let token = self.de.tokens.next().unwrap();
- Err(Error::UnexpectedToken(token))
- }
+ Some(other) => Err(Error::UnexpectedToken(other)),
None => Err(Error::EndOfTokens),
}
}
@@ -688,47 +411,6 @@ impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
//////////////////////////////////////////////////////////////////////////
-struct DeserializerStructVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
- de: &'a mut Deserializer<I>,
- len: usize,
-}
-
-impl<'a, I> MapVisitor for DeserializerStructVisitor<'a, I>
- where I: Iterator<Item=Token<'static>>,
-{
- type Error = Error;
-
- fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
- where K: DeserializeSeed,
- {
- match self.de.tokens.peek() {
- Some(&Token::StructSep) => {
- self.de.tokens.next();
- self.len = self.len.saturating_sub(1);
- seed.deserialize(&mut *self.de).map(Some)
- }
- Some(&Token::StructEnd) => Ok(None),
- Some(_) => {
- let token = self.de.tokens.next().unwrap();
- Err(Error::UnexpectedToken(token))
- }
- None => Err(Error::EndOfTokens),
- }
- }
-
- fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
- where V: DeserializeSeed,
- {
- seed.deserialize(&mut *self.de)
- }
-
- fn size_hint(&self) -> (usize, Option<usize>) {
- (self.len, Some(self.len))
- }
-}
-
-//////////////////////////////////////////////////////////////////////////
-
struct DeserializerEnumVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
de: &'a mut Deserializer<I>,
}
@@ -803,7 +485,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
let token = self.de.tokens.next().unwrap();
if len == enum_len {
- self.de.visit_variant_seq(Some(len), visitor)
+ self.de.visit_seq(Some(len), Token::EnumSeqSep, Token::EnumSeqEnd, visitor)
} else {
Err(Error::UnexpectedToken(token))
}
@@ -812,7 +494,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
let token = self.de.tokens.next().unwrap();
if len == enum_len {
- self.de.visit_seq(Some(len), visitor)
+ self.de.visit_seq(Some(len), Token::SeqSep, Token::SeqEnd, visitor)
} else {
Err(Error::UnexpectedToken(token))
}
@@ -834,7 +516,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
let token = self.de.tokens.next().unwrap();
if fields.len() == enum_len {
- self.de.visit_variant_map(Some(fields.len()), visitor)
+ self.de.visit_map(Some(fields.len()), Token::EnumMapSep, Token::EnumMapEnd, visitor)
} else {
Err(Error::UnexpectedToken(token))
}
@@ -843,7 +525,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
let token = self.de.tokens.next().unwrap();
if fields.len() == enum_len {
- self.de.visit_map(Some(fields.len()), visitor)
+ self.de.visit_map(Some(fields.len()), Token::MapSep, Token::MapEnd, visitor)
} else {
Err(Error::UnexpectedToken(token))
}
@@ -855,45 +537,3 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
}
}
}
-
-//////////////////////////////////////////////////////////////////////////
-
-struct DeserializerVariantMapVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
- de: &'a mut Deserializer<I>,
- len: Option<usize>,
-}
-
-impl<'a, I> MapVisitor for DeserializerVariantMapVisitor<'a, I>
- where I: Iterator<Item=Token<'static>>,
-{
- type Error = Error;
-
- fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
- where K: DeserializeSeed,
- {
- match self.de.tokens.peek() {
- Some(&Token::EnumMapSep) => {
- self.de.tokens.next();
- self.len = self.len.map(|len| if len > 0 { len - 1} else { 0 });
- seed.deserialize(&mut *self.de).map(Some)
- }
- Some(&Token::EnumMapEnd) => Ok(None),
- Some(_) => {
- let token = self.de.tokens.next().unwrap();
- Err(Error::UnexpectedToken(token))
- }
- None => Err(Error::EndOfTokens),
- }
- }
-
- fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
- where V: DeserializeSeed,
- {
- seed.deserialize(&mut *self.de)
- }
-
- fn size_hint(&self) -> (usize, Option<usize>) {
- let len = self.len.unwrap_or(0);
- (len, self.len)
- }
-}
diff --git a/serde_test/src/lib.rs b/serde_test/src/lib.rs
index 945262c02..53f966f67 100644
--- a/serde_test/src/lib.rs
+++ b/serde_test/src/lib.rs
@@ -1,3 +1,4 @@
+#[macro_use]
extern crate serde;
mod assert;
diff --git a/test_suite/tests/compile-fail/enum-representation/internal-tuple-variant.rs b/test_suite/tests/compile-fail/enum-representation/internal-tuple-variant.rs
new file mode 100644
index 000000000..950e8d027
--- /dev/null
+++ b/test_suite/tests/compile-fail/enum-representation/internal-tuple-variant.rs
@@ -0,0 +1,10 @@
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
+#[serde(tag = "type")] //~^ HELP: #[serde(tag = "...")] cannot be used with tuple variants
+enum E {
+ Tuple(u8, u8),
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/enum-representation/internally-tagged-struct.rs b/test_suite/tests/compile-fail/enum-representation/internally-tagged-struct.rs
new file mode 100644
index 000000000..358dfde45
--- /dev/null
+++ b/test_suite/tests/compile-fail/enum-representation/internally-tagged-struct.rs
@@ -0,0 +1,8 @@
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
+#[serde(tag = "type")] //~^ HELP: #[serde(tag = "...")] can only be used on enums
+struct S;
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/enum-representation/untagged-and-internal.rs b/test_suite/tests/compile-fail/enum-representation/untagged-and-internal.rs
new file mode 100644
index 000000000..7442679c5
--- /dev/null
+++ b/test_suite/tests/compile-fail/enum-representation/untagged-and-internal.rs
@@ -0,0 +1,12 @@
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
+#[serde(untagged)]
+#[serde(tag = "type")] //~^^ HELP: enum cannot be both untagged and internally tagged
+enum E {
+ A(u8),
+ B(String),
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/enum-representation/untagged-struct.rs b/test_suite/tests/compile-fail/enum-representation/untagged-struct.rs
new file mode 100644
index 000000000..611f8416a
--- /dev/null
+++ b/test_suite/tests/compile-fail/enum-representation/untagged-struct.rs
@@ -0,0 +1,8 @@
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
+#[serde(untagged)] //~^ HELP: #[serde(untagged)] can only be used on enums
+struct S;
+
+fn main() {}
diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index b748bb125..6ae92129d 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -225,7 +225,7 @@ declare_tests! {
],
() => &[
Token::TupleStructStart("Anything", 0),
- Token::SeqEnd,
+ Token::TupleStructEnd,
],
}
test_unit_struct {
@@ -330,7 +330,7 @@ declare_tests! {
],
BTreeSet::<isize>::new() => &[
Token::TupleStructStart("Anything", 0),
- Token::SeqEnd,
+ Token::TupleStructEnd,
],
}
test_hashset {
@@ -358,7 +358,7 @@ declare_tests! {
],
HashSet::<isize>::new() => &[
Token::TupleStructStart("Anything", 0),
- Token::SeqEnd,
+ Token::TupleStructEnd,
],
hashset![FnvHasher @ 1, 2, 3] => &[
Token::SeqStart(Some(3)),
@@ -408,7 +408,7 @@ declare_tests! {
],
Vec::<isize>::new() => &[
Token::TupleStructStart("Anything", 0),
- Token::SeqEnd,
+ Token::TupleStructEnd,
],
}
test_array {
@@ -472,7 +472,7 @@ declare_tests! {
],
[0; 0] => &[
Token::TupleStructStart("Anything", 0),
- Token::SeqEnd,
+ Token::TupleStructEnd,
],
}
test_tuple {
@@ -564,7 +564,7 @@ declare_tests! {
],
BTreeMap::<isize, isize>::new() => &[
Token::StructStart("Anything", 0),
- Token::MapEnd,
+ Token::StructEnd,
],
}
test_hashmap {
@@ -618,7 +618,7 @@ declare_tests! {
],
HashMap::<isize, isize>::new() => &[
Token::StructStart("Anything", 0),
- Token::MapEnd,
+ Token::StructEnd,
],
hashmap![FnvHasher @ 1 => 2, 3 => 4] => &[
Token::MapStart(Some(2)),
diff --git a/test_suite/tests/test_macros.rs b/test_suite/tests/test_macros.rs
index 6e5e1d823..21185412b 100644
--- a/test_suite/tests/test_macros.rs
+++ b/test_suite/tests/test_macros.rs
@@ -1,11 +1,14 @@
extern crate serde_test;
use self::serde_test::{
+ Error,
Token,
assert_tokens,
assert_ser_tokens,
assert_de_tokens,
+ assert_de_tokens_error,
};
+use std::collections::BTreeMap;
use std::marker::PhantomData;
// That tests that the derived Serialize implementation doesn't trigger
@@ -625,3 +628,256 @@ fn test_enum_state_field() {
]
);
}
+
+#[test]
+fn test_untagged_enum() {
+ #[derive(Debug, PartialEq, Serialize, Deserialize)]
+ #[serde(untagged)]
+ enum Untagged {
+ A {
+ a: u8,
+ },
+ B {
+ b: u8,
+ },
+ C,
+ D(u8),
+ E(String),
+ F(u8, u8),
+ }
+
+ assert_tokens(
+ &Untagged::A { a: 1 },
+ &[
+ Token::StructStart("Untagged", 1),
+
+ Token::StructSep,
+ Token::Str("a"),
+ Token::U8(1),
+
+ Token::StructEnd,
+ ]
+ );
+
+ assert_tokens(
+ &Untagged::B { b: 2 },
+ &[
+ Token::StructStart("Untagged", 1),
+
+ Token::StructSep,
+ Token::Str("b"),
+ Token::U8(2),
+
+ Token::StructEnd,
+ ]
+ );
+
+ assert_tokens(
+ &Untagged::C,
+ &[
+ Token::Unit,
+ ]
+ );
+
+ assert_tokens(
+ &Untagged::D(4),
+ &[
+ Token::U8(4),
+ ]
+ );
+ assert_tokens(
+ &Untagged::E("e".to_owned()),
+ &[
+ Token::Str("e"),
+ ]
+ );
+
+ assert_tokens(
+ &Untagged::F(1, 2),
+ &[
+ Token::TupleStart(2),
+
+ Token::TupleSep,
+ Token::U8(1),
+
+ Token::TupleSep,
+ Token::U8(2),
+
+ Token::TupleEnd,
+ ]
+ );
+
+ assert_de_tokens_error::<Untagged>(
+ &[
+ Token::Option(false),
+ ],
+ Error::Message("data did not match any variant of untagged enum Untagged".to_owned()),
+ );
+
+ assert_de_tokens_error::<Untagged>(
+ &[
+ Token::TupleStart(1),
+
+ Token::TupleSep,
+ Token::U8(1),
+
+ Token::TupleEnd,
+ ],
+ Error::Message("data did not match any variant of untagged enum Untagged".to_owned()),
+ );
+
+ assert_de_tokens_error::<Untagged>(
+ &[
+ Token::TupleStart(3),
+
+ Token::TupleSep,
+ Token::U8(1),
+
+ Token::TupleSep,
+ Token::U8(2),
+
+ Token::TupleSep,
+ Token::U8(3),
+
+ Token::TupleEnd,
+ ],
+ Error::Message("data did not match any variant of untagged enum Untagged".to_owned()),
+ );
+}
+
+#[test]
+fn test_internally_tagged_enum() {
+ #[derive(Debug, PartialEq, Serialize, Deserialize)]
+ struct Newtype(BTreeMap<String, String>);
+
+ #[derive(Debug, PartialEq, Serialize, Deserialize)]
+ struct Struct {
+ f: u8,
+ }
+
+ #[derive(Debug, PartialEq, Serialize, Deserialize)]
+ #[serde(tag = "type")]
+ enum InternallyTagged {
+ A {
+ a: u8,
+ },
+ B {
+ b: u8,
+ },
+ C,
+ D(BTreeMap<String, String>),
+ E(Newtype),
+ F(Struct),
+ }
+
+ assert_tokens(
+ &InternallyTagged::A { a: 1 },
+ &[
+ Token::StructStart("InternallyTagged", 2),
+
+ Token::StructSep,
+ Token::Str("type"),
+ Token::Str("A"),
+
+ Token::StructSep,
+ Token::Str("a"),
+ Token::U8(1),
+
+ Token::StructEnd,
+ ]
+ );
+
+ assert_tokens(
+ &InternallyTagged::B { b: 2 },
+ &[
+ Token::StructStart("InternallyTagged", 2),
+
+ Token::StructSep,
+ Token::Str("type"),
+ Token::Str("B"),
+
+ Token::StructSep,
+ Token::Str("b"),
+ Token::U8(2),
+
+ Token::StructEnd,
+ ]
+ );
+
+ assert_tokens(
+ &InternallyTagged::C,
+ &[
+ Token::StructStart("InternallyTagged", 1),
+
+ Token::StructSep,
+ Token::Str("type"),
+ Token::Str("C"),
+
+ Token::StructEnd,
+ ]
+ );
+
+ assert_tokens(
+ &InternallyTagged::D(BTreeMap::new()),
+ &[
+ Token::MapStart(Some(1)),
+
+ Token::MapSep,
+ Token::Str("type"),
+ Token::Str("D"),
+
+ Token::MapEnd,
+ ]
+ );
+
+ assert_tokens(
+ &InternallyTagged::E(Newtype(BTreeMap::new())),
+ &[
+ Token::MapStart(Some(1)),
+
+ Token::MapSep,
+ Token::Str("type"),
+ Token::Str("E"),
+
+ Token::MapEnd,
+ ]
+ );
+
+ assert_tokens(
+ &InternallyTagged::F(Struct { f: 6 }),
+ &[
+ Token::StructStart("Struct", 2),
+
+ Token::StructSep,
+ Token::Str("type"),
+ Token::Str("F"),
+
+ Token::StructSep,
+ Token::Str("f"),
+ Token::U8(6),
+
+ Token::StructEnd,
+ ]
+ );
+
+ assert_de_tokens_error::<InternallyTagged>(
+ &[
+ Token::MapStart(Some(0)),
+ Token::MapEnd,
+ ],
+ Error::Message("missing field `type`".to_owned()),
+ );
+
+ assert_de_tokens_error::<InternallyTagged>(
+ &[
+ Token::MapStart(Some(1)),
+
+ Token::MapSep,
+ Token::Str("type"),
+ Token::Str("Z"),
+
+ Token::MapEnd,
+ ],
+ Error::Message("unknown variant `Z`, expected one of `A`, `B`, `C`, `D`, `E`, `F`".to_owned()),
+ );
+}
| [
"415"
] | serde-rs__serde-739 | Is it possible to handle tagged enums?
``` rust
#[derive(Serialize, Deserialize, Debug)]
enum Motion {
Column(i32),
Line(i32),
}
#[derive(Serialize, Deserialize, Debug)]
enum Command {
Move(Motion),
Delete(Motion),
Input(String),
}
fn main() {
let cmd = Command::Move(Motion::Column(1));
let cmd_str = serde_json::to_string(&cmd).unwrap();
println!("result: {}", cmd_str);
}
```
this will get result like this:
``` json
{
"Move": {
"Column": 1
}
}
```
Is it possible to make it be:
``` json
{
"type": "Move",
"content": {
"type": "Column",
"content": 1
}
}
```
| 0.9 | faaa4945790646aa89cd03baf4fc04fd190e8146 | diff --git a/serde/src/de/content.rs b/serde/src/de/content.rs
new file mode 100644
index 000000000..fa8875c89
--- /dev/null
+++ b/serde/src/de/content.rs
@@ -0,0 +1,743 @@
+// This module is doc(hidden) and nothing here should be used outside of
+// generated code.
+//
+// We will iterate on the implementation for a few releases and only have to
+// worry about backward compatibility for the `untagged` and `tag` attributes
+// rather than for this entire mechanism.
+//
+// This issue is tracking making some of this stuff public:
+// https://github.com/serde-rs/serde/issues/741
+
+#![doc(hidden)]
+
+use core::fmt;
+use core::marker::PhantomData;
+
+#[cfg(all(not(feature = "std"), feature = "collections"))]
+use collections::{String, Vec};
+
+#[cfg(all(feature = "alloc", not(feature = "std")))]
+use alloc::boxed::Box;
+
+use de::{
+ self,
+ Deserialize,
+ DeserializeSeed,
+ Deserializer,
+ Visitor,
+ SeqVisitor,
+ MapVisitor,
+ EnumVisitor,
+};
+
+/// Used from generated code to buffer the contents of the Deserializer when
+/// deserializing untagged enums and internally tagged enums.
+///
+/// Not public API. Use serde-value instead.
+#[derive(Debug)]
+pub enum Content<E> {
+ // Don't mind the PhantomData, just need to use E somewhere.
+ Bool(bool, PhantomData<E>),
+
+ U8(u8),
+ U16(u16),
+ U32(u32),
+ U64(u64),
+
+ I8(i8),
+ I16(i16),
+ I32(i32),
+ I64(i64),
+
+ F32(f32),
+ F64(f64),
+
+ Char(char),
+ String(String),
+ Bytes(Vec<u8>),
+
+ None,
+ Some(Box<Content<E>>),
+
+ Unit,
+ Newtype(Box<Content<E>>),
+ Seq(Vec<Content<E>>),
+ Map(Vec<(Content<E>, Content<E>)>),
+}
+
+impl<E> Deserialize for Content<E> {
+ fn deserialize<D: Deserializer>(deserializer: D) -> Result<Self, D::Error> {
+ // Untagged and internally tagged enums are only supported in
+ // self-describing formats.
+ deserializer.deserialize(ContentVisitor::new())
+ }
+}
+
+struct ContentVisitor<E> {
+ err: PhantomData<E>,
+}
+
+impl<E> ContentVisitor<E> {
+ fn new() -> Self {
+ ContentVisitor {
+ err: PhantomData,
+ }
+ }
+}
+
+impl<E> Visitor for ContentVisitor<E> {
+ type Value = Content<E>;
+
+ fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ fmt.write_str("any value")
+ }
+
+ fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::Bool(value, PhantomData))
+ }
+
+ fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::I8(value))
+ }
+
+ fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::I16(value))
+ }
+
+ fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::I32(value))
+ }
+
+ fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::I64(value))
+ }
+
+ fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::U8(value))
+ }
+
+ fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::U16(value))
+ }
+
+ fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::U32(value))
+ }
+
+ fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::U64(value))
+ }
+
+ fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::F32(value))
+ }
+
+ fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::F64(value))
+ }
+
+ fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::Char(value))
+ }
+
+ fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::String(value.into()))
+ }
+
+ fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::String(value))
+ }
+
+ fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::Bytes(value.into()))
+ }
+
+ fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::Bytes(value))
+ }
+
+ fn visit_unit<F>(self) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::Unit)
+ }
+
+ fn visit_none<F>(self) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ Ok(Content::None)
+ }
+
+ fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
+ where D: Deserializer
+ {
+ Deserialize::deserialize(deserializer).map(|v| Content::Some(Box::new(v)))
+ }
+
+ fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
+ where D: Deserializer
+ {
+ Deserialize::deserialize(deserializer).map(|v| Content::Newtype(Box::new(v)))
+ }
+
+ fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
+ where V: SeqVisitor
+ {
+ let mut vec = Vec::with_capacity(visitor.size_hint().0);
+ while let Some(e) = try!(visitor.visit()) {
+ vec.push(e);
+ }
+ Ok(Content::Seq(vec))
+ }
+
+ fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
+ where V: MapVisitor
+ {
+ let mut vec = Vec::with_capacity(visitor.size_hint().0);
+ while let Some(kv) = try!(visitor.visit()) {
+ vec.push(kv);
+ }
+ Ok(Content::Map(vec))
+ }
+
+ fn visit_enum<V>(self, _visitor: V) -> Result<Self::Value, V::Error>
+ where V: EnumVisitor
+ {
+ Err(de::Error::custom("untagged and internally tagged enums do not support enum input"))
+ }
+}
+
+/// This is the type of the map keys in an internally tagged enum.
+///
+/// Not public API.
+pub enum TagOrContent<E> {
+ Tag,
+ Content(Content<E>),
+}
+
+struct TagOrContentVisitor<E> {
+ name: &'static str,
+ err: PhantomData<E>,
+}
+
+impl<E> TagOrContentVisitor<E> {
+ fn new(name: &'static str) -> Self {
+ TagOrContentVisitor {
+ name: name,
+ err: PhantomData,
+ }
+ }
+}
+
+impl<E> DeserializeSeed for TagOrContentVisitor<E> {
+ type Value = TagOrContent<E>;
+
+ fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
+ where D: Deserializer
+ {
+ // Internally tagged enums are only supported in self-describing
+ // formats.
+ deserializer.deserialize(self)
+ }
+}
+
+impl<E> Visitor for TagOrContentVisitor<E> {
+ type Value = TagOrContent<E>;
+
+ fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ write!(fmt, "a type tag `{}` or any other value", self.name)
+ }
+
+ fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ ContentVisitor::new().visit_bool(value).map(TagOrContent::Content)
+ }
+
+ fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ ContentVisitor::new().visit_i8(value).map(TagOrContent::Content)
+ }
+
+ fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ ContentVisitor::new().visit_i16(value).map(TagOrContent::Content)
+ }
+
+ fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ ContentVisitor::new().visit_i32(value).map(TagOrContent::Content)
+ }
+
+ fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ ContentVisitor::new().visit_i64(value).map(TagOrContent::Content)
+ }
+
+ fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ ContentVisitor::new().visit_u8(value).map(TagOrContent::Content)
+ }
+
+ fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ ContentVisitor::new().visit_u16(value).map(TagOrContent::Content)
+ }
+
+ fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ ContentVisitor::new().visit_u32(value).map(TagOrContent::Content)
+ }
+
+ fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ ContentVisitor::new().visit_u64(value).map(TagOrContent::Content)
+ }
+
+ fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ ContentVisitor::new().visit_f32(value).map(TagOrContent::Content)
+ }
+
+ fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ ContentVisitor::new().visit_f64(value).map(TagOrContent::Content)
+ }
+
+ fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ ContentVisitor::new().visit_char(value).map(TagOrContent::Content)
+ }
+
+ fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ if value == self.name {
+ Ok(TagOrContent::Tag)
+ } else {
+ ContentVisitor::new().visit_str(value).map(TagOrContent::Content)
+ }
+ }
+
+ fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ if value == self.name {
+ Ok(TagOrContent::Tag)
+ } else {
+ ContentVisitor::new().visit_string(value).map(TagOrContent::Content)
+ }
+ }
+
+ fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ if value == self.name.as_bytes() {
+ Ok(TagOrContent::Tag)
+ } else {
+ ContentVisitor::new().visit_bytes(value).map(TagOrContent::Content)
+ }
+ }
+
+ fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ if value == self.name.as_bytes() {
+ Ok(TagOrContent::Tag)
+ } else {
+ ContentVisitor::new().visit_byte_buf(value).map(TagOrContent::Content)
+ }
+ }
+
+ fn visit_unit<F>(self) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ ContentVisitor::new().visit_unit().map(TagOrContent::Content)
+ }
+
+ fn visit_none<F>(self) -> Result<Self::Value, F>
+ where F: de::Error
+ {
+ ContentVisitor::new().visit_none().map(TagOrContent::Content)
+ }
+
+ fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
+ where D: Deserializer
+ {
+ ContentVisitor::new().visit_some(deserializer).map(TagOrContent::Content)
+ }
+
+ fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
+ where D: Deserializer
+ {
+ ContentVisitor::new().visit_newtype_struct(deserializer).map(TagOrContent::Content)
+ }
+
+ fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error>
+ where V: SeqVisitor
+ {
+ ContentVisitor::new().visit_seq(visitor).map(TagOrContent::Content)
+ }
+
+ fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error>
+ where V: MapVisitor
+ {
+ ContentVisitor::new().visit_map(visitor).map(TagOrContent::Content)
+ }
+
+ fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error>
+ where V: EnumVisitor
+ {
+ ContentVisitor::new().visit_enum(visitor).map(TagOrContent::Content)
+ }
+}
+
+/// Used by generated code to deserialize an internally tagged enum.
+///
+/// Not public API.
+pub struct TaggedContent<T, E> {
+ pub tag: T,
+ pub content: Content<E>,
+}
+
+/// Not public API.
+pub struct TaggedContentVisitor<T, E> {
+ tag_name: &'static str,
+ tag: PhantomData<T>,
+ err: PhantomData<E>,
+}
+
+impl<T, E> TaggedContentVisitor<T, E> {
+ /// Visitor for the content of an internally tagged enum with the given tag
+ /// name.
+ pub fn new(name: &'static str) -> Self {
+ TaggedContentVisitor {
+ tag_name: name,
+ tag: PhantomData,
+ err: PhantomData,
+ }
+ }
+}
+
+impl<T, E> DeserializeSeed for TaggedContentVisitor<T, E>
+ where T: Deserialize
+{
+ type Value = TaggedContent<T, E>;
+
+ fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
+ where D: Deserializer
+ {
+ // Internally tagged enums are only supported in self-describing
+ // formats.
+ deserializer.deserialize(self)
+ }
+}
+
+impl<T, E> Visitor for TaggedContentVisitor<T, E>
+ where T: Deserialize
+{
+ type Value = TaggedContent<T, E>;
+
+ fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ fmt.write_str("any value")
+ }
+
+ fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
+ where V: MapVisitor
+ {
+ let mut tag = None;
+ let mut vec = Vec::with_capacity(visitor.size_hint().0);
+ while let Some(k) = try!(visitor.visit_key_seed(TagOrContentVisitor::new(self.tag_name))) {
+ match k {
+ TagOrContent::Tag => {
+ if tag.is_some() {
+ return Err(de::Error::duplicate_field(self.tag_name));
+ }
+ tag = Some(try!(visitor.visit_value()));
+ }
+ TagOrContent::Content(k) => {
+ let v = try!(visitor.visit_value());
+ vec.push((k, v));
+ }
+ }
+ }
+ match tag {
+ None => {
+ Err(de::Error::missing_field(self.tag_name))
+ }
+ Some(tag) => {
+ Ok(TaggedContent {
+ tag: tag,
+ content: Content::Map(vec),
+ })
+ }
+ }
+ }
+}
+
+/// Used when deserializing an internally tagged enum because the content will
+/// be used exactly once.
+impl<E> Deserializer for Content<E>
+ where E: de::Error
+{
+ type Error = E;
+
+ fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ where V: Visitor
+ {
+ match self {
+ Content::Bool(v, _) => visitor.visit_bool(v),
+ Content::U8(v) => visitor.visit_u8(v),
+ Content::U16(v) => visitor.visit_u16(v),
+ Content::U32(v) => visitor.visit_u32(v),
+ Content::U64(v) => visitor.visit_u64(v),
+ Content::I8(v) => visitor.visit_i8(v),
+ Content::I16(v) => visitor.visit_i16(v),
+ Content::I32(v) => visitor.visit_i32(v),
+ Content::I64(v) => visitor.visit_i64(v),
+ Content::F32(v) => visitor.visit_f32(v),
+ Content::F64(v) => visitor.visit_f64(v),
+ Content::Char(v) => visitor.visit_char(v),
+ Content::String(v) => visitor.visit_string(v),
+ Content::Unit => visitor.visit_unit(),
+ Content::None => visitor.visit_none(),
+ Content::Some(v) => visitor.visit_some(*v),
+ Content::Newtype(v) => visitor.visit_newtype_struct(*v),
+ Content::Seq(v) => {
+ let seq = v.into_iter();
+ let mut seq_visitor = de::value::SeqDeserializer::new(seq);
+ let value = try!(visitor.visit_seq(&mut seq_visitor));
+ try!(seq_visitor.end());
+ Ok(value)
+ },
+ Content::Map(v) => {
+ let map = v.into_iter();
+ let mut map_visitor = de::value::MapDeserializer::new(map);
+ let value = try!(visitor.visit_map(&mut map_visitor));
+ try!(map_visitor.end());
+ Ok(value)
+ },
+ Content::Bytes(v) => visitor.visit_byte_buf(v),
+ }
+ }
+
+ fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ where V: Visitor
+ {
+ match self {
+ Content::None => visitor.visit_none(),
+ Content::Some(v) => visitor.visit_some(*v),
+ Content::Unit => visitor.visit_unit(),
+ _ => visitor.visit_some(self)
+ }
+ }
+
+ fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
+ where V: Visitor
+ {
+ visitor.visit_newtype_struct(self)
+ }
+
+ forward_to_deserialize! {
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
+ seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
+ struct_field tuple enum ignored_any
+ }
+}
+
+impl<E> de::value::ValueDeserializer<E> for Content<E>
+ where E: de::Error
+{
+ type Deserializer = Self;
+
+ fn into_deserializer(self) -> Self {
+ self
+ }
+}
+
+/// Used when deserializing an untagged enum because the content may need to be
+/// used more than once.
+impl<'a, E> Deserializer for &'a Content<E>
+ where E: de::Error
+{
+ type Error = E;
+
+ fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ where V: Visitor
+ {
+ match *self {
+ Content::Bool(v, _) => visitor.visit_bool(v),
+ Content::U8(v) => visitor.visit_u8(v),
+ Content::U16(v) => visitor.visit_u16(v),
+ Content::U32(v) => visitor.visit_u32(v),
+ Content::U64(v) => visitor.visit_u64(v),
+ Content::I8(v) => visitor.visit_i8(v),
+ Content::I16(v) => visitor.visit_i16(v),
+ Content::I32(v) => visitor.visit_i32(v),
+ Content::I64(v) => visitor.visit_i64(v),
+ Content::F32(v) => visitor.visit_f32(v),
+ Content::F64(v) => visitor.visit_f64(v),
+ Content::Char(v) => visitor.visit_char(v),
+ Content::String(ref v) => visitor.visit_str(v),
+ Content::Unit => visitor.visit_unit(),
+ Content::None => visitor.visit_none(),
+ Content::Some(ref v) => visitor.visit_some(&**v),
+ Content::Newtype(ref v) => visitor.visit_newtype_struct(&**v),
+ Content::Seq(ref v) => {
+ let seq = v.into_iter();
+ let mut seq_visitor = de::value::SeqDeserializer::new(seq);
+ let value = try!(visitor.visit_seq(&mut seq_visitor));
+ try!(seq_visitor.end());
+ Ok(value)
+ },
+ Content::Map(ref v) => {
+ let map = v.into_iter().map(|&(ref k, ref v)| (k, v));
+ let mut map_visitor = de::value::MapDeserializer::new(map);
+ let value = try!(visitor.visit_map(&mut map_visitor));
+ try!(map_visitor.end());
+ Ok(value)
+ },
+ Content::Bytes(ref v) => visitor.visit_bytes(v),
+ }
+ }
+
+ fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ where V: Visitor
+ {
+ match *self {
+ Content::None => visitor.visit_none(),
+ Content::Some(ref v) => visitor.visit_some(&**v),
+ Content::Unit => visitor.visit_unit(),
+ _ => visitor.visit_some(self)
+ }
+ }
+
+ fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
+ where V: Visitor
+ {
+ visitor.visit_newtype_struct(self)
+ }
+
+ forward_to_deserialize! {
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
+ seq_fixed_size bytes byte_buf map unit_struct tuple_struct struct
+ struct_field tuple enum ignored_any
+ }
+}
+
+impl<'a, E> de::value::ValueDeserializer<E> for &'a Content<E>
+ where E: de::Error
+{
+ type Deserializer = Self;
+
+ fn into_deserializer(self) -> Self {
+ self
+ }
+}
+
+/// Visitor for deserializing an internally tagged unit variant.
+///
+/// Not public API.
+pub struct InternallyTaggedUnitVisitor<'a> {
+ type_name: &'a str,
+ variant_name: &'a str,
+}
+
+impl<'a> InternallyTaggedUnitVisitor<'a> {
+ /// Not public API.
+ pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
+ InternallyTaggedUnitVisitor {
+ type_name: type_name,
+ variant_name: variant_name,
+ }
+ }
+}
+
+impl<'a> Visitor for InternallyTaggedUnitVisitor<'a> {
+ type Value = ();
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name)
+ }
+
+ fn visit_map<V>(self, _: V) -> Result<(), V::Error>
+ where V: MapVisitor
+ {
+ Ok(())
+ }
+}
+
+/// Visitor for deserializing an untagged unit variant.
+///
+/// Not public API.
+pub struct UntaggedUnitVisitor<'a> {
+ type_name: &'a str,
+ variant_name: &'a str,
+}
+
+impl<'a> UntaggedUnitVisitor<'a> {
+ /// Not public API.
+ pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
+ UntaggedUnitVisitor {
+ type_name: type_name,
+ variant_name: variant_name,
+ }
+ }
+}
+
+impl<'a> Visitor for UntaggedUnitVisitor<'a> {
+ type Value = ();
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ write!(formatter, "unit variant {}::{}", self.type_name, self.variant_name)
+ }
+
+ fn visit_unit<E>(self) -> Result<(), E>
+ where E: de::Error
+ {
+ Ok(())
+ }
+}
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index ce86ce1ea..8471c9953 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -115,6 +115,8 @@ mod from_primitive;
// Helpers used by generated code. Not public API.
#[doc(hidden)]
pub mod private;
+#[cfg(any(feature = "std", feature = "collections"))]
+mod content;
///////////////////////////////////////////////////////////////////////////////
diff --git a/serde/src/de/private.rs b/serde/src/de/private.rs
index 1ff206cdb..750eecdc8 100644
--- a/serde/src/de/private.rs
+++ b/serde/src/de/private.rs
@@ -2,6 +2,14 @@ use core::marker::PhantomData;
use de::{Deserialize, Deserializer, Error, Visitor};
+#[cfg(any(feature = "std", feature = "collections"))]
+pub use de::content::{
+ Content,
+ TaggedContentVisitor,
+ InternallyTaggedUnitVisitor,
+ UntaggedUnitVisitor,
+};
+
/// If the missing field is of type `Option<T>` then treat is as `None`,
/// otherwise it is an error.
pub fn missing_field<V, E>(field: &'static str) -> Result<V, E>
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 32b69d5ff..85d152678 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -428,7 +428,9 @@ impl<I, E> SeqDeserializer<I, E>
}
}
- fn end(&mut self) -> Result<(), E> {
+ /// Check for remaining elements after passing a `SeqDeserializer` to
+ /// `Visitor::visit_seq`.
+ pub fn end(mut self) -> Result<(), E> {
let mut remaining = 0;
while self.iter.next().is_some() {
remaining += 1;
@@ -610,17 +612,9 @@ impl<I, E> MapDeserializer<I, E>
}
}
- fn next_pair(&mut self) -> Option<(<I::Item as private::Pair>::First, <I::Item as private::Pair>::Second)> {
- match self.iter.next() {
- Some(kv) => {
- self.count += 1;
- Some(private::Pair::split(kv))
- }
- None => None,
- }
- }
-
- fn end(&mut self) -> Result<(), E> {
+ /// Check for remaining elements after passing a `MapDeserializer` to
+ /// `Visitor::visit_map`.
+ pub fn end(mut self) -> Result<(), E> {
let mut remaining = 0;
while self.iter.next().is_some() {
remaining += 1;
@@ -633,6 +627,16 @@ impl<I, E> MapDeserializer<I, E>
Err(de::Error::invalid_length(self.count + remaining, &ExpectedInMap(self.count)))
}
}
+
+ fn next_pair(&mut self) -> Option<(<I::Item as private::Pair>::First, <I::Item as private::Pair>::Second)> {
+ match self.iter.next() {
+ Some(kv) => {
+ self.count += 1;
+ Some(private::Pair::split(kv))
+ }
+ None => None,
+ }
+ }
}
impl<I, E> de::Deserializer for MapDeserializer<I, E>
diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs
index a18346cec..42ccd169d 100644
--- a/serde/src/ser/mod.rs
+++ b/serde/src/ser/mod.rs
@@ -106,6 +106,10 @@ use core::fmt::Display;
mod impls;
mod impossible;
+// Helpers used by generated code. Not public API.
+#[doc(hidden)]
+pub mod private;
+
pub use self::impossible::Impossible;
///////////////////////////////////////////////////////////////////////////////
diff --git a/serde/src/ser/private.rs b/serde/src/ser/private.rs
new file mode 100644
index 000000000..9d17ec789
--- /dev/null
+++ b/serde/src/ser/private.rs
@@ -0,0 +1,235 @@
+use core::fmt::{self, Display};
+
+use ser::{self, Serialize, Serializer, SerializeMap, SerializeStruct};
+
+/// Not public API.
+pub fn serialize_tagged_newtype<S, T>(
+ serializer: S,
+ type_ident: &'static str,
+ variant_ident: &'static str,
+ tag: &'static str,
+ variant_name: &'static str,
+ value: T,
+) -> Result<S::Ok, S::Error>
+ where S: Serializer,
+ T: Serialize
+{
+ value.serialize(TaggedSerializer {
+ type_ident: type_ident,
+ variant_ident: variant_ident,
+ tag: tag,
+ variant_name: variant_name,
+ delegate: serializer,
+ })
+}
+
+struct TaggedSerializer<S> {
+ type_ident: &'static str,
+ variant_ident: &'static str,
+ tag: &'static str,
+ variant_name: &'static str,
+ delegate: S,
+}
+
+enum Unsupported {
+ Boolean,
+ Integer,
+ Float,
+ Char,
+ String,
+ ByteArray,
+ Optional,
+ Unit,
+ UnitStruct,
+ Sequence,
+ Tuple,
+ TupleStruct,
+ Enum,
+}
+
+impl Display for Unsupported {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ match *self {
+ Unsupported::Boolean => formatter.write_str("a boolean"),
+ Unsupported::Integer => formatter.write_str("an integer"),
+ Unsupported::Float => formatter.write_str("a float"),
+ Unsupported::Char => formatter.write_str("a char"),
+ Unsupported::String => formatter.write_str("a string"),
+ Unsupported::ByteArray => formatter.write_str("a byte array"),
+ Unsupported::Optional => formatter.write_str("an optional"),
+ Unsupported::Unit => formatter.write_str("unit"),
+ Unsupported::UnitStruct => formatter.write_str("a unit struct"),
+ Unsupported::Sequence => formatter.write_str("a sequence"),
+ Unsupported::Tuple => formatter.write_str("a tuple"),
+ Unsupported::TupleStruct => formatter.write_str("a tuple struct"),
+ Unsupported::Enum => formatter.write_str("an enum"),
+ }
+ }
+}
+
+struct Error {
+ type_ident: &'static str,
+ variant_ident: &'static str,
+ ty: Unsupported,
+}
+
+impl Display for Error {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ write!(formatter,
+ "cannot serialize tagged newtype variant {}::{} containing {}",
+ self.type_ident, self.variant_ident, self.ty)
+ }
+}
+
+impl<S> TaggedSerializer<S>
+ where S: Serializer
+{
+ fn bad_type(self, what: Unsupported) -> S::Error {
+ ser::Error::custom(Error {
+ type_ident: self.type_ident,
+ variant_ident: self.variant_ident,
+ ty: what,
+ })
+ }
+}
+
+impl<S> Serializer for TaggedSerializer<S>
+ where S: Serializer
+{
+ type Ok = S::Ok;
+ type Error = S::Error;
+
+ type SerializeSeq = S::SerializeSeq;
+ type SerializeTuple = S::SerializeTuple;
+ type SerializeTupleStruct = S::SerializeTupleStruct;
+ type SerializeTupleVariant = S::SerializeTupleVariant;
+ type SerializeMap = S::SerializeMap;
+ type SerializeStruct = S::SerializeStruct;
+ type SerializeStructVariant = S::SerializeStructVariant;
+
+ fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Boolean))
+ }
+
+ fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Integer))
+ }
+
+ fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Integer))
+ }
+
+ fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Integer))
+ }
+
+ fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Integer))
+ }
+
+ fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Integer))
+ }
+
+ fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Integer))
+ }
+
+ fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Integer))
+ }
+
+ fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Integer))
+ }
+
+ fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Float))
+ }
+
+ fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Float))
+ }
+
+ fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Char))
+ }
+
+ fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::String))
+ }
+
+ fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::ByteArray))
+ }
+
+ fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Optional))
+ }
+
+ fn serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error>
+ where T: Serialize
+ {
+ Err(self.bad_type(Unsupported::Optional))
+ }
+
+ fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Unit))
+ }
+
+ fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::UnitStruct))
+ }
+
+ fn serialize_unit_variant(self, _: &'static str, _: usize, _: &'static str) -> Result<Self::Ok, Self::Error> {
+ Err(self.bad_type(Unsupported::Enum))
+ }
+
+ fn serialize_newtype_struct<T: ?Sized>(self, _: &'static str, value: &T) -> Result<Self::Ok, Self::Error>
+ where T: Serialize
+ {
+ value.serialize(self)
+ }
+
+ fn serialize_newtype_variant<T: ?Sized>(self, _: &'static str, _: usize, _: &'static str, _: &T) -> Result<Self::Ok, Self::Error>
+ where T: Serialize
+ {
+ Err(self.bad_type(Unsupported::Enum))
+ }
+
+ fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
+ Err(self.bad_type(Unsupported::Sequence))
+ }
+
+ fn serialize_seq_fixed_size(self, _: usize) -> Result<Self::SerializeSeq, Self::Error> {
+ Err(self.bad_type(Unsupported::Sequence))
+ }
+
+ fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
+ Err(self.bad_type(Unsupported::Tuple))
+ }
+
+ fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Result<Self::SerializeTupleStruct, Self::Error> {
+ Err(self.bad_type(Unsupported::TupleStruct))
+ }
+
+ fn serialize_tuple_variant(self, _: &'static str, _: usize, _: &'static str, _: usize) -> Result<Self::SerializeTupleVariant, Self::Error> {
+ Err(self.bad_type(Unsupported::Enum))
+ }
+
+ fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
+ let mut map = try!(self.delegate.serialize_map(len.map(|len| len + 1)));
+ try!(map.serialize_entry(self.tag, self.variant_name));
+ Ok(map)
+ }
+
+ fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct, Self::Error> {
+ let mut state = try!(self.delegate.serialize_struct(name, len + 1));
+ try!(state.serialize_field(self.tag, self.variant_name));
+ Ok(state)
+ }
+
+ fn serialize_struct_variant(self, _: &'static str, _: usize, _: &'static str, _: usize) -> Result<Self::SerializeStructVariant, Self::Error> {
+ Err(self.bad_type(Unsupported::Enum))
+ }
+}
diff --git a/serde_codegen_internals/src/attr.rs b/serde_codegen_internals/src/attr.rs
index 575dad5ab..97fa4650b 100644
--- a/serde_codegen_internals/src/attr.rs
+++ b/serde_codegen_internals/src/attr.rs
@@ -92,6 +92,32 @@ pub struct Item {
deny_unknown_fields: bool,
ser_bound: Option<Vec<syn::WherePredicate>>,
de_bound: Option<Vec<syn::WherePredicate>>,
+ tag: EnumTag,
+}
+
+/// Styles of representing an enum.
+#[derive(Debug)]
+pub enum EnumTag {
+ /// The default.
+ ///
+ /// ```json
+ /// {"variant1": {"key1": "value1", "key2": "value2"}}
+ /// ```
+ External,
+
+ /// `#[serde(tag = "type")]`
+ ///
+ /// ```json
+ /// {"type": "variant1", "key1": "value1", "key2": "value2"}
+ /// ```
+ Internal(String),
+
+ /// `#[serde(untagged)]`
+ ///
+ /// ```json
+ /// {"key1": "value1", "key2": "value2"}
+ /// ```
+ None,
}
impl Item {
@@ -102,6 +128,8 @@ impl Item {
let mut deny_unknown_fields = BoolAttr::none(cx, "deny_unknown_fields");
let mut ser_bound = Attr::none(cx, "bound");
let mut de_bound = Attr::none(cx, "bound");
+ let mut untagged = BoolAttr::none(cx, "untagged");
+ let mut internal_tag = Attr::none(cx, "tag");
for meta_items in item.attrs.iter().filter_map(get_serde_meta_items) {
for meta_item in meta_items {
@@ -143,6 +171,32 @@ impl Item {
}
}
+ // Parse `#[serde(untagged)]`
+ MetaItem(Word(ref name)) if name == "untagged" => {
+ match item.body {
+ syn::Body::Enum(_) => {
+ untagged.set_true();
+ }
+ syn::Body::Struct(_) => {
+ cx.error("#[serde(untagged)] can only be used on enums")
+ }
+ }
+ }
+
+ // Parse `#[serde(tag = "type")]`
+ MetaItem(NameValue(ref name, ref lit)) if name == "tag" => {
+ if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) {
+ match item.body {
+ syn::Body::Enum(_) => {
+ internal_tag.set(s);
+ }
+ syn::Body::Struct(_) => {
+ cx.error("#[serde(tag = \"...\")] can only be used on enums")
+ }
+ }
+ }
+ }
+
MetaItem(ref meta_item) => {
cx.error(format!("unknown serde container attribute `{}`",
meta_item.name()));
@@ -155,6 +209,32 @@ impl Item {
}
}
+ let tag = match (untagged.get(), internal_tag.get()) {
+ (false, None) => EnumTag::External,
+ (true, None) => EnumTag::None,
+ (false, Some(tag)) => {
+ // Check that there are no tuple variants.
+ if let syn::Body::Enum(ref variants) = item.body {
+ for variant in variants {
+ match variant.data {
+ syn::VariantData::Struct(_) | syn::VariantData::Unit => {}
+ syn::VariantData::Tuple(ref fields) => {
+ if fields.len() != 1 {
+ cx.error("#[serde(tag = \"...\")] cannot be used with tuple variants");
+ break;
+ }
+ }
+ }
+ }
+ }
+ EnumTag::Internal(tag)
+ }
+ (true, Some(_)) => {
+ cx.error("enum cannot be both untagged and internally tagged");
+ EnumTag::External // doesn't matter, will error
+ }
+ };
+
Item {
name: Name {
serialize: ser_name.get().unwrap_or_else(|| item.ident.to_string()),
@@ -163,6 +243,7 @@ impl Item {
deny_unknown_fields: deny_unknown_fields.get(),
ser_bound: ser_bound.get(),
de_bound: de_bound.get(),
+ tag: tag,
}
}
@@ -181,6 +262,10 @@ impl Item {
pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
self.de_bound.as_ref().map(|vec| &vec[..])
}
+
+ pub fn tag(&self) -> &EnumTag {
+ &self.tag
+ }
}
/// Represents variant attribute information
diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 3d7b5d1f0..b72d78ad4 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -110,7 +110,8 @@ fn deserialize_body(
impl_generics,
ty,
fields,
- &item.attrs)
+ &item.attrs,
+ None)
}
Body::Struct(Style::Tuple, ref fields) |
Body::Struct(Style::Newtype, ref fields) => {
@@ -124,7 +125,8 @@ fn deserialize_body(
impl_generics,
ty,
fields,
- &item.attrs)
+ &item.attrs,
+ None)
}
Body::Struct(Style::Unit, _) => {
deserialize_unit_struct(
@@ -238,6 +240,7 @@ fn deserialize_tuple(
ty: syn::Ty,
fields: &[Field],
item_attrs: &attr::Item,
+ deserializer: Option<Tokens>,
) -> Tokens {
let where_clause = &impl_generics.where_clause;
@@ -274,7 +277,9 @@ fn deserialize_tuple(
false,
);
- let dispatch = if is_enum {
+ let dispatch = if let Some(deserializer) = deserializer {
+ quote!(_serde::Deserializer::deserialize(#deserializer, #visitor_expr))
+ } else if is_enum {
quote!(_serde::de::VariantVisitor::visit_tuple(visitor, #nfields, #visitor_expr))
} else if nfields == 1 {
let type_name = item_attrs.name().deserialize_name();
@@ -424,7 +429,11 @@ fn deserialize_struct(
ty: syn::Ty,
fields: &[Field],
item_attrs: &attr::Item,
+ deserializer: Option<Tokens>,
) -> Tokens {
+ let is_enum = variant_ident.is_some();
+ let is_untagged = deserializer.is_some();
+
let where_clause = &impl_generics.where_clause;
let (visitor_item, visitor_ty, visitor_expr) = deserialize_visitor(impl_generics);
@@ -454,8 +463,11 @@ fn deserialize_struct(
item_attrs,
);
- let is_enum = variant_ident.is_some();
- let dispatch = if is_enum {
+ let dispatch = if let Some(deserializer) = deserializer {
+ quote! {
+ _serde::Deserializer::deserialize(#deserializer, #visitor_expr)
+ }
+ } else if is_enum {
quote! {
_serde::de::VariantVisitor::visit_struct(visitor, FIELDS, #visitor_expr)
}
@@ -473,6 +485,20 @@ fn deserialize_struct(
quote!(mut visitor)
};
+ let visit_seq = if is_untagged {
+ // untagged struct variants do not get a visit_seq method
+ None
+ } else {
+ Some(quote! {
+ #[inline]
+ fn visit_seq<__V>(self, #visitor_var: __V) -> _serde::export::Result<#ty, __V::Error>
+ where __V: _serde::de::SeqVisitor
+ {
+ #visit_seq
+ }
+ })
+ };
+
quote!({
#field_visitor
@@ -485,12 +511,7 @@ fn deserialize_struct(
_serde::export::fmt::Formatter::write_str(formatter, #expecting)
}
- #[inline]
- fn visit_seq<__V>(self, #visitor_var: __V) -> _serde::export::Result<#ty, __V::Error>
- where __V: _serde::de::SeqVisitor
- {
- #visit_seq
- }
+ #visit_seq
#[inline]
fn visit_map<__V>(self, mut visitor: __V) -> _serde::export::Result<#ty, __V::Error>
@@ -512,6 +533,45 @@ fn deserialize_item_enum(
ty: syn::Ty,
variants: &[Variant],
item_attrs: &attr::Item
+) -> Tokens {
+ match *item_attrs.tag() {
+ attr::EnumTag::External => {
+ deserialize_externally_tagged_enum(
+ type_ident,
+ impl_generics,
+ ty,
+ variants,
+ item_attrs,
+ )
+ }
+ attr::EnumTag::Internal(ref tag) => {
+ deserialize_internally_tagged_enum(
+ type_ident,
+ impl_generics,
+ ty,
+ variants,
+ item_attrs,
+ tag,
+ )
+ }
+ attr::EnumTag::None => {
+ deserialize_untagged_enum(
+ type_ident,
+ impl_generics,
+ ty,
+ variants,
+ item_attrs,
+ )
+ }
+ }
+}
+
+fn deserialize_externally_tagged_enum(
+ type_ident: &syn::Ident,
+ impl_generics: &syn::Generics,
+ ty: syn::Ty,
+ variants: &[Variant],
+ item_attrs: &attr::Item,
) -> Tokens {
let where_clause = &impl_generics.where_clause;
@@ -545,7 +605,7 @@ fn deserialize_item_enum(
.map(|(i, variant)| {
let variant_name = field_i(i);
- let block = deserialize_variant(
+ let block = deserialize_externally_tagged_variant(
type_ident,
impl_generics,
ty.clone(),
@@ -604,7 +664,111 @@ fn deserialize_item_enum(
})
}
-fn deserialize_variant(
+fn deserialize_internally_tagged_enum(
+ type_ident: &syn::Ident,
+ impl_generics: &syn::Generics,
+ ty: syn::Ty,
+ variants: &[Variant],
+ item_attrs: &attr::Item,
+ tag: &str,
+) -> Tokens {
+ let variant_names_idents: Vec<_> = variants.iter()
+ .enumerate()
+ .filter(|&(_, variant)| !variant.attrs.skip_deserializing())
+ .map(|(i, variant)| (variant.attrs.name().deserialize_name(), field_i(i)))
+ .collect();
+
+ let variants_stmt = {
+ let variant_names = variant_names_idents.iter().map(|&(ref name, _)| name);
+ quote! {
+ const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ];
+ }
+ };
+
+ let variant_visitor = deserialize_field_visitor(
+ variant_names_idents,
+ item_attrs,
+ true,
+ );
+
+ // Match arms to extract a variant from a string
+ let variant_arms = variants.iter()
+ .enumerate()
+ .filter(|&(_, variant)| !variant.attrs.skip_deserializing())
+ .map(|(i, variant)| {
+ let variant_name = field_i(i);
+
+ let block = deserialize_internally_tagged_variant(
+ type_ident,
+ impl_generics,
+ ty.clone(),
+ variant,
+ item_attrs,
+ quote!(_tagged.content),
+ );
+
+ quote! {
+ __Field::#variant_name => #block
+ }
+ });
+
+ quote!({
+ #variant_visitor
+
+ #variants_stmt
+
+ let _tagged = try!(_serde::Deserializer::deserialize(
+ deserializer,
+ _serde::de::private::TaggedContentVisitor::<__Field, __D::Error>::new(#tag)));
+
+ match _tagged.tag {
+ #(#variant_arms)*
+ }
+ })
+}
+
+fn deserialize_untagged_enum(
+ type_ident: &syn::Ident,
+ impl_generics: &syn::Generics,
+ ty: syn::Ty,
+ variants: &[Variant],
+ item_attrs: &attr::Item,
+) -> Tokens {
+ let attempts = variants.iter()
+ .filter(|variant| !variant.attrs.skip_deserializing())
+ .map(|variant| {
+ deserialize_untagged_variant(
+ type_ident,
+ impl_generics,
+ ty.clone(),
+ variant,
+ item_attrs,
+ quote!(&_content),
+ )
+ });
+
+ // TODO this message could be better by saving the errors from the failed
+ // attempts. The heuristic used by TOML was to count the number of fields
+ // processed before an error, and use the error that happened after the
+ // largest number of fields. I'm not sure I like that. Maybe it would be
+ // better to save all the errors and combine them into one message that
+ // explains why none of the variants matched.
+ let fallthrough_msg = format!("data did not match any variant of untagged enum {}", type_ident);
+
+ quote!({
+ let _content = try!(<_serde::de::private::Content<__D::Error> as _serde::Deserialize>::deserialize(deserializer));
+
+ #(
+ if let _serde::export::Ok(ok) = #attempts {
+ return _serde::export::Ok(ok);
+ }
+ )*
+
+ _serde::export::Err(_serde::de::Error::custom(#fallthrough_msg))
+ })
+}
+
+fn deserialize_externally_tagged_variant(
type_ident: &syn::Ident,
generics: &syn::Generics,
ty: syn::Ty,
@@ -621,7 +785,7 @@ fn deserialize_variant(
})
}
Style::Newtype => {
- deserialize_newtype_variant(
+ deserialize_externally_tagged_newtype_variant(
type_ident,
variant_ident,
generics,
@@ -636,6 +800,7 @@ fn deserialize_variant(
ty,
&variant.fields,
item_attrs,
+ None,
)
}
Style::Struct => {
@@ -646,22 +811,115 @@ fn deserialize_variant(
ty,
&variant.fields,
item_attrs,
+ None,
+ )
+ }
+ }
+}
+
+fn deserialize_internally_tagged_variant(
+ type_ident: &syn::Ident,
+ generics: &syn::Generics,
+ ty: syn::Ty,
+ variant: &Variant,
+ item_attrs: &attr::Item,
+ deserializer: Tokens,
+) -> Tokens {
+ let variant_ident = &variant.ident;
+
+ match variant.style {
+ Style::Unit => {
+ let type_name = type_ident.as_ref();
+ let variant_name = variant.ident.as_ref();
+ quote!({
+ try!(_serde::Deserializer::deserialize(#deserializer, _serde::de::private::InternallyTaggedUnitVisitor::new(#type_name, #variant_name)));
+ _serde::export::Ok(#type_ident::#variant_ident)
+ })
+ }
+ Style::Newtype | Style::Struct => {
+ deserialize_untagged_variant(
+ type_ident,
+ generics,
+ ty,
+ variant,
+ item_attrs,
+ deserializer,
)
}
+ Style::Tuple => unreachable!("checked in serde_codegen_internals"),
}
}
-fn deserialize_newtype_variant(
+fn deserialize_untagged_variant(
+ type_ident: &syn::Ident,
+ generics: &syn::Generics,
+ ty: syn::Ty,
+ variant: &Variant,
+ item_attrs: &attr::Item,
+ deserializer: Tokens,
+) -> Tokens {
+ let variant_ident = &variant.ident;
+
+ match variant.style {
+ Style::Unit => {
+ let type_name = type_ident.as_ref();
+ let variant_name = variant.ident.as_ref();
+ quote! {
+ _serde::export::Result::map(
+ _serde::Deserializer::deserialize(
+ #deserializer,
+ _serde::de::private::UntaggedUnitVisitor::new(#type_name, #variant_name)
+ ),
+ |()| #type_ident::#variant_ident)
+ }
+ }
+ Style::Newtype => {
+ deserialize_untagged_newtype_variant(
+ type_ident,
+ variant_ident,
+ generics,
+ &variant.fields[0],
+ deserializer,
+ )
+ }
+ Style::Tuple => {
+ deserialize_tuple(
+ type_ident,
+ Some(variant_ident),
+ generics,
+ ty,
+ &variant.fields,
+ item_attrs,
+ Some(deserializer),
+ )
+ }
+ Style::Struct => {
+ deserialize_struct(
+ type_ident,
+ Some(variant_ident),
+ generics,
+ ty,
+ &variant.fields,
+ item_attrs,
+ Some(deserializer),
+ )
+ }
+ }
+}
+
+fn deserialize_externally_tagged_newtype_variant(
type_ident: &syn::Ident,
variant_ident: &syn::Ident,
impl_generics: &syn::Generics,
field: &Field,
) -> Tokens {
- let visit = match field.attrs.deserialize_with() {
+ match field.attrs.deserialize_with() {
None => {
let field_ty = &field.ty;
quote! {
- try!(_serde::de::VariantVisitor::visit_newtype::<#field_ty>(visitor))
+ _serde::export::Result::map(
+ _serde::de::VariantVisitor::visit_newtype::<#field_ty>(visitor),
+ #type_ident::#variant_ident),
}
}
Some(path) => {
@@ -670,12 +928,41 @@ fn deserialize_newtype_variant(
quote!({
#wrapper
#wrapper_impl
- try!(_serde::de::VariantVisitor::visit_newtype::<#wrapper_ty>(visitor)).value
+ _serde::export::Result::map(
+ _serde::de::VariantVisitor::visit_newtype::<#wrapper_ty>(visitor),
+ |_wrapper| #type_ident::#variant_ident(_wrapper.value))
+ })
+ }
+ }
+}
+
+fn deserialize_untagged_newtype_variant(
+ type_ident: &syn::Ident,
+ variant_ident: &syn::Ident,
+ impl_generics: &syn::Generics,
+ field: &Field,
+ deserializer: Tokens,
+) -> Tokens {
+ match field.attrs.deserialize_with() {
+ None => {
+ let field_ty = &field.ty;
+ quote!({
+ _serde::export::Result::map(
+ <#field_ty as _serde::Deserialize>::deserialize(#deserializer),
+ #type_ident::#variant_ident)
+ })
+ }
+ Some(path) => {
+ let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
+ type_ident, impl_generics, field.ty, path);
+ quote!({
+ #wrapper
+ #wrapper_impl
+ _serde::export::Result::map(
+ <#wrapper_ty as _serde::Deserialize>::deserialize(#deserializer),
+ |_wrapper| #type_ident::#variant_ident(_wrapper.value))
})
}
- };
- quote! {
- _serde::export::Ok(#type_ident::#variant_ident(#visit)),
}
}
diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index 6478de411..52c86c7e7 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -251,14 +251,11 @@ fn serialize_variant(
variant_index: usize,
item_attrs: &attr::Item,
) -> Tokens {
- let type_name = item_attrs.name().serialize_name();
-
let variant_ident = variant.ident.clone();
- let variant_name = variant.attrs.name().serialize_name();
if variant.attrs.skip_serializing() {
let skipped_msg = format!("the enum variant {}::{} cannot be serialized",
- type_ident, variant_ident);
+ type_ident, variant_ident);
let skipped_err = quote! {
_serde::export::Err(_serde::ser::Error::custom(#skipped_msg))
};
@@ -271,140 +268,351 @@ fn serialize_variant(
#type_ident::#variant_ident #fields_pat => #skipped_err,
}
} else { // variant wasn't skipped
- match variant.style {
+ let case = match variant.style {
Style::Unit => {
quote! {
- #type_ident::#variant_ident =>
- _serde::Serializer::serialize_unit_variant(
- _serializer,
- #type_name,
- #variant_index,
- #variant_name,
- ),
+ #type_ident::#variant_ident
}
- },
+ }
Style::Newtype => {
- let block = serialize_newtype_variant(
- type_name,
- variant_index,
- variant_name,
- ty,
- generics,
- &variant.fields[0],
- );
-
quote! {
- #type_ident::#variant_ident(ref __simple_value) => #block,
+ #type_ident::#variant_ident(ref __simple_value)
}
- },
+ }
Style::Tuple => {
let field_names = (0 .. variant.fields.len())
.map(|i| Ident::new(format!("__field{}", i)));
-
- let block = serialize_tuple_variant(
- type_name,
- variant_index,
- variant_name,
- generics,
- ty,
- &variant.fields,
- );
-
quote! {
- #type_ident::#variant_ident(#(ref #field_names),*) => { #block }
+ #type_ident::#variant_ident(#(ref #field_names),*)
}
}
Style::Struct => {
let fields = variant.fields.iter()
.map(|f| f.ident.clone().expect("struct variant has unnamed fields"));
+ quote! {
+ #type_ident::#variant_ident { #(ref #fields),* }
+ }
+ }
+ };
- let block = serialize_struct_variant(
+ let body = match *item_attrs.tag() {
+ attr::EnumTag::External => {
+ serialize_externally_tagged_variant(
+ generics,
+ ty,
+ variant,
variant_index,
- variant_name,
+ item_attrs,
+ )
+ }
+ attr::EnumTag::Internal(ref tag) => {
+ serialize_internally_tagged_variant(
+ type_ident.as_ref(),
+ variant_ident.as_ref(),
generics,
ty,
- &variant.fields,
+ variant,
item_attrs,
- );
-
- quote! {
- #type_ident::#variant_ident { #(ref #fields),* } => { #block }
- }
+ tag,
+ )
+ }
+ attr::EnumTag::None => {
+ serialize_untagged_variant(
+ generics,
+ ty,
+ variant,
+ item_attrs,
+ )
}
+ };
+
+ quote! {
+ #case => #body
}
}
}
-fn serialize_newtype_variant(
- type_name: String,
+fn serialize_externally_tagged_variant(
+ generics: &syn::Generics,
+ ty: syn::Ty,
+ variant: &Variant,
variant_index: usize,
- variant_name: String,
- item_ty: syn::Ty,
+ item_attrs: &attr::Item,
+) -> Tokens {
+ let type_name = item_attrs.name().serialize_name();
+ let variant_name = variant.attrs.name().serialize_name();
+
+ match variant.style {
+ Style::Unit => {
+ quote! {
+ _serde::Serializer::serialize_unit_variant(
+ _serializer,
+ #type_name,
+ #variant_index,
+ #variant_name,
+ ),
+ }
+ }
+ Style::Newtype => {
+ let field = &variant.fields[0];
+ let mut field_expr = quote!(__simple_value);
+ if let Some(path) = field.attrs.serialize_with() {
+ field_expr = wrap_serialize_with(
+ &ty, generics, field.ty, path, field_expr);
+ }
+
+ quote! {
+ _serde::Serializer::serialize_newtype_variant(
+ _serializer,
+ #type_name,
+ #variant_index,
+ #variant_name,
+ #field_expr,
+ ),
+ }
+ }
+ Style::Tuple => {
+ let block = serialize_tuple_variant(
+ TupleVariant::ExternallyTagged {
+ type_name: type_name,
+ variant_index: variant_index,
+ variant_name: variant_name,
+ },
+ generics,
+ ty,
+ &variant.fields,
+ );
+
+ quote! {
+ { #block }
+ }
+ }
+ Style::Struct => {
+ let block = serialize_struct_variant(
+ StructVariant::ExternallyTagged {
+ variant_index: variant_index,
+ variant_name: variant_name,
+ },
+ generics,
+ ty,
+ &variant.fields,
+ item_attrs,
+ );
+
+ quote! {
+ { #block }
+ }
+ }
+ }
+}
+
+fn serialize_internally_tagged_variant(
+ type_ident: &str,
+ variant_ident: &str,
generics: &syn::Generics,
- field: &Field,
+ ty: syn::Ty,
+ variant: &Variant,
+ item_attrs: &attr::Item,
+ tag: &str,
) -> Tokens {
- let mut field_expr = quote!(__simple_value);
- if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(
- &item_ty, generics, field.ty, path, field_expr);
+ let type_name = item_attrs.name().serialize_name();
+ let variant_name = variant.attrs.name().serialize_name();
+
+ match variant.style {
+ Style::Unit => {
+ quote!({
+ let mut __struct = try!(_serde::Serializer::serialize_struct(
+ _serializer, #type_name, 1));
+ try!(_serde::ser::SerializeStruct::serialize_field(
+ &mut __struct, #tag, #variant_name));
+ _serde::ser::SerializeStruct::end(__struct)
+ })
+ }
+ Style::Newtype => {
+ let field = &variant.fields[0];
+ let mut field_expr = quote!(__simple_value);
+ if let Some(path) = field.attrs.serialize_with() {
+ field_expr = wrap_serialize_with(
+ &ty, generics, field.ty, path, field_expr);
+ }
+
+ quote! {
+ _serde::ser::private::serialize_tagged_newtype(
+ _serializer,
+ #type_ident,
+ #variant_ident,
+ #tag,
+ #variant_name,
+ #field_expr,
+ ),
+ }
+ }
+ Style::Struct => {
+ let block = serialize_struct_variant(
+ StructVariant::InternallyTagged {
+ tag: tag,
+ variant_name: variant_name,
+ },
+ generics,
+ ty,
+ &variant.fields,
+ item_attrs,
+ );
+
+ quote! {
+ { #block }
+ }
+ }
+ Style::Tuple => unreachable!("checked in serde_codegen_internals"),
}
+}
- quote! {
- _serde::Serializer::serialize_newtype_variant(
- _serializer,
- #type_name,
- #variant_index,
- #variant_name,
- #field_expr,
- )
+fn serialize_untagged_variant(
+ generics: &syn::Generics,
+ ty: syn::Ty,
+ variant: &Variant,
+ item_attrs: &attr::Item,
+) -> Tokens {
+ match variant.style {
+ Style::Unit => {
+ quote! {
+ _serde::Serializer::serialize_unit(_serializer),
+ }
+ }
+ Style::Newtype => {
+ let field = &variant.fields[0];
+ let mut field_expr = quote!(__simple_value);
+ if let Some(path) = field.attrs.serialize_with() {
+ field_expr = wrap_serialize_with(
+ &ty, generics, field.ty, path, field_expr);
+ }
+
+ quote! {
+ _serde::Serialize::serialize(#field_expr, _serializer),
+ }
+ }
+ Style::Tuple => {
+ let block = serialize_tuple_variant(
+ TupleVariant::Untagged,
+ generics,
+ ty,
+ &variant.fields,
+ );
+
+ quote! {
+ { #block }
+ }
+ }
+ Style::Struct => {
+ let block = serialize_struct_variant(
+ StructVariant::Untagged,
+ generics,
+ ty,
+ &variant.fields,
+ item_attrs,
+ );
+
+ quote! {
+ { #block }
+ }
+ }
}
}
+enum TupleVariant {
+ ExternallyTagged {
+ type_name: String,
+ variant_index: usize,
+ variant_name: String,
+ },
+ Untagged,
+}
+
fn serialize_tuple_variant(
- type_name: String,
- variant_index: usize,
- variant_name: String,
+ context: TupleVariant,
generics: &syn::Generics,
structure_ty: syn::Ty,
fields: &[Field],
) -> Tokens {
+ let method = match context {
+ TupleVariant::ExternallyTagged{..} => {
+ quote!(_serde::ser::SerializeTupleVariant::serialize_field)
+ }
+ TupleVariant::Untagged => {
+ quote!(_serde::ser::SerializeTuple::serialize_element)
+ }
+ };
+
let serialize_stmts = serialize_tuple_struct_visitor(
structure_ty,
fields,
generics,
true,
- quote!(_serde::ser::SerializeTupleVariant::serialize_field),
+ method,
);
let len = serialize_stmts.len();
let let_mut = mut_if(len > 0);
- quote! {
- let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple_variant(
- _serializer,
- #type_name,
- #variant_index,
- #variant_name,
- #len));
- #(#serialize_stmts)*
- _serde::ser::SerializeTupleVariant::end(__serde_state)
+ match context {
+ TupleVariant::ExternallyTagged { type_name, variant_index, variant_name } => {
+ quote! {
+ let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple_variant(
+ _serializer,
+ #type_name,
+ #variant_index,
+ #variant_name,
+ #len));
+ #(#serialize_stmts)*
+ _serde::ser::SerializeTupleVariant::end(__serde_state)
+ }
+ }
+ TupleVariant::Untagged => {
+ quote! {
+ let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple(
+ _serializer,
+ #len));
+ #(#serialize_stmts)*
+ _serde::ser::SerializeTuple::end(__serde_state)
+ }
+ }
}
}
-fn serialize_struct_variant(
- variant_index: usize,
- variant_name: String,
+enum StructVariant<'a> {
+ ExternallyTagged {
+ variant_index: usize,
+ variant_name: String,
+ },
+ InternallyTagged {
+ tag: &'a str,
+ variant_name: String,
+ },
+ Untagged,
+}
+
+fn serialize_struct_variant<'a>(
+ context: StructVariant<'a>,
generics: &syn::Generics,
ty: syn::Ty,
fields: &[Field],
item_attrs: &attr::Item,
) -> Tokens {
+ let method = match context {
+ StructVariant::ExternallyTagged{..} => {
+ quote!(_serde::ser::SerializeStructVariant::serialize_field)
+ }
+ StructVariant::InternallyTagged{..} | StructVariant::Untagged => {
+ quote!(_serde::ser::SerializeStruct::serialize_field)
+ }
+ };
+
let serialize_fields = serialize_struct_visitor(
ty.clone(),
fields,
generics,
true,
- quote!(_serde::ser::SerializeStructVariant::serialize_field),
+ method,
);
let item_name = item_attrs.name().serialize_name();
@@ -426,16 +634,47 @@ fn serialize_struct_variant(
})
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
- quote! {
- let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct_variant(
- _serializer,
- #item_name,
- #variant_index,
- #variant_name,
- #len,
- ));
- #(#serialize_fields)*
- _serde::ser::SerializeStructVariant::end(__serde_state)
+ match context {
+ StructVariant::ExternallyTagged { variant_index, variant_name } => {
+ quote! {
+ let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct_variant(
+ _serializer,
+ #item_name,
+ #variant_index,
+ #variant_name,
+ #len,
+ ));
+ #(#serialize_fields)*
+ _serde::ser::SerializeStructVariant::end(__serde_state)
+ }
+ }
+ StructVariant::InternallyTagged { tag, variant_name } => {
+ quote! {
+ let mut __serde_state = try!(_serde::Serializer::serialize_struct(
+ _serializer,
+ #item_name,
+ #len + 1,
+ ));
+ try!(_serde::ser::SerializeStruct::serialize_field(
+ &mut __serde_state,
+ #tag,
+ #variant_name,
+ ));
+ #(#serialize_fields)*
+ _serde::ser::SerializeStruct::end(__serde_state)
+ }
+ }
+ StructVariant::Untagged => {
+ quote! {
+ let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct(
+ _serializer,
+ #item_name,
+ #len,
+ ));
+ #(#serialize_fields)*
+ _serde::ser::SerializeStruct::end(__serde_state)
+ }
+ }
}
}
| serde-rs/serde | 2017-02-03T03:01:50Z | Here is one approach. Manually implement Serialize for a `Wrapper<T>` type that contains "type" and "content".
``` rust
#[derive(Serialize)]
struct Wrapper<T> {
#[serde(rename = "type")]
name: String,
content: T,
}
impl<T> Wrapper<T> {
fn new(name: &'static str, content: T) -> Self {
Wrapper {
name: name.to_string(),
content: content,
}
}
}
impl serde::Serialize for Motion {
fn serialize<S>(&self, ser: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
match *self {
Motion::Column(ref i) => Wrapper::new("Column", i).serialize(ser),
Motion::Line(ref i) => Wrapper::new("Line", i).serialize(ser),
}
}
}
impl serde::Serialize for Command {
fn serialize<S>(&self, ser: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
match *self {
Command::Move(ref m) => Wrapper::new("Move", m).serialize(ser),
Command::Delete(ref m) => Wrapper::new("Delete", m).serialize(ser),
Command::Input(ref s) => Wrapper::new("Input", s).serialize(ser),
}
}
}
```
You could use a macro to make this a lot nicer so it becomes just something like:
``` rust
tagged_enum!(Motion {
Column(i32),
Line(i32),
});
```
related discussion: https://github.com/serde-rs/json/issues/67
Here is a complete working solution. For deserialization it uses a `serde_json::Value` to partially deserialize the input, check the "type", then deserialize the "content" into the correct Rust type. It has readable error messages when things go wrong, for example if the input is `{"type":"Bla","content":1}` you get "unrecognized Command type: Bla" and if the input is `{"type":"Move","content":[0]}` you get "bad Move content: [0]".
``` rust
#![feature(plugin, custom_derive)]
#![plugin(serde_macros)]
extern crate serde;
extern crate serde_json as json;
////////////////////////////////////////////////////////////////////////////////
#[derive(Serialize, Deserialize)]
struct Wrapper {
#[serde(rename = "type")]
name: String,
content: json::Value,
}
impl Wrapper {
fn new<T>(name: &'static str, content: T) -> Self
where T: serde::Serialize
{
Wrapper {
name: name.to_string(),
content: json::to_value(&content),
}
}
}
macro_rules! tagged_enum {
($name:ident { $( $variant:ident ( $content:ty ), )* }) => {
#[derive(Debug)]
enum $name {
$(
$variant($content),
)*
}
impl ::serde::Serialize for $name {
fn serialize<S>(&self, ser: &mut S) -> Result<(), S::Error>
where S: ::serde::Serializer
{
match *self {
$(
$name::$variant(ref content) => {
Wrapper::new(stringify!($variant), content)
}
)*
}.serialize(ser)
}
}
impl ::serde::Deserialize for $name {
fn deserialize<D>(des: &mut D) -> Result<Self, D::Error>
where D: ::serde::Deserializer,
{
use ::serde::Error;
let wrapper = try!(Wrapper::deserialize(des));
let str_for_error = wrapper.content.to_string();
match &wrapper.name[..] {
$(
stringify!($variant) => Ok($name::$variant(try!(
json::from_value(wrapper.content)
.map_err(|_| D::Error::custom(format!(
"bad {} content: {}", stringify!($variant), str_for_error)))
))),
)*
other => {
Err(D::Error::custom(format!(
"unrecognized {} type: {}", stringify!($name), other)))
}
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
tagged_enum!(Motion {
Column(i32),
Line(i32),
});
tagged_enum!(Command {
Move(Motion),
Delete(Motion),
Input(String),
});
fn main() {
let cmd = Command::Move(Motion::Column(1));
let cmd_str = json::to_string_pretty(&cmd).unwrap();
println!("serialized command - {}", cmd_str);
let cmd: Command = json::from_str(&cmd_str).unwrap();
println!("deserialized command - {:?}", cmd);
}
```
thank you all, @dtolnay your solution is great.
Any plans of having something like the `tagged_enum!()` above (possibly with a configurable name for the typefield) exposed directly by serde or serde-json? This data layout seems common enough, at least in JSON world.
Yes we need to provide some way to make this easier. https://github.com/serde-rs/json/issues/67 is tracking a similar request. | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 |
738 | diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index 34b5c469f..2f53a00e4 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -8,11 +8,15 @@ use self::serde::de::{Deserialize, Deserializer};
use std::borrow::Cow;
use std::marker::PhantomData;
+use std::result::Result as StdResult;
// Try to trip up the generated code if it fails to use fully qualified paths.
#[allow(dead_code)]
struct Result;
-use std::result::Result as StdResult;
+#[allow(dead_code)]
+struct Ok;
+#[allow(dead_code)]
+struct Err;
//////////////////////////////////////////////////////////////////////////
| [
"737"
] | serde-rs__serde-738 | Generated code is wrong if Ok or Err are redefined
```rust
#[macro_use]
extern crate serde_derive;
struct Ok;
struct Err;
#[derive(Deserialize)]
struct S {
x: ()
}
```
```rust
error: expected function, found `Ok`
--> src/main.rs:7:10
|
7 | #[derive(Deserialize)]
| ^^^^^^^^^^^
|
note: defined here
--> src/main.rs:4:1
|
4 | struct Ok;
| ^^^^^^^^^^
error: expected function, found `Err`
--> src/main.rs:7:10
|
7 | #[derive(Deserialize)]
| ^^^^^^^^^^^
|
note: defined here
--> src/main.rs:5:1
|
5 | struct Err;
| ^^^^^^^^^^^
```
| 0.9 | d9605714395a983649d82b03394ccaa9db596399 | diff --git a/serde/src/export.rs b/serde/src/export.rs
index 61c9ba67c..9c635457e 100644
--- a/serde/src/export.rs
+++ b/serde/src/export.rs
@@ -9,7 +9,8 @@ use collections::borrow::Cow;
pub use core::default::Default;
pub use core::fmt;
pub use core::marker::PhantomData;
-pub use core::result::Result;
+pub use core::option::Option::{self, None, Some};
+pub use core::result::Result::{self, Ok, Err};
#[cfg(any(feature = "collections", feature = "std"))]
pub fn from_utf8_lossy(bytes: &[u8]) -> Cow<str> {
diff --git a/serde/src/lib.rs b/serde/src/lib.rs
index eb07bbbff..f22f167a6 100644
--- a/serde/src/lib.rs
+++ b/serde/src/lib.rs
@@ -79,7 +79,7 @@ extern crate core as actual_core;
#[cfg(feature = "std")]
mod core {
pub use std::{ops, hash, fmt, cmp, marker, mem, i8, i16, i32, i64, u8, u16, u32, u64, isize,
- usize, f32, f64, char, str, num, slice, iter, cell, default, result};
+ usize, f32, f64, char, str, num, slice, iter, cell, default, result, option};
#[cfg(feature = "unstable")]
pub use actual_core::nonzero;
}
diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index f371680e4..3d7b5d1f0 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -209,21 +209,21 @@ fn deserialize_unit_struct(
type Value = #type_ident;
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
- formatter.write_str(#expecting)
+ _serde::export::fmt::Formatter::write_str(formatter, #expecting)
}
#[inline]
fn visit_unit<__E>(self) -> _serde::export::Result<#type_ident, __E>
where __E: _serde::de::Error,
{
- Ok(#type_ident)
+ _serde::export::Ok(#type_ident)
}
#[inline]
fn visit_seq<__V>(self, _: __V) -> _serde::export::Result<#type_ident, __V::Error>
where __V: _serde::de::SeqVisitor,
{
- Ok(#type_ident)
+ _serde::export::Ok(#type_ident)
}
}
@@ -278,10 +278,10 @@ fn deserialize_tuple(
quote!(_serde::de::VariantVisitor::visit_tuple(visitor, #nfields, #visitor_expr))
} else if nfields == 1 {
let type_name = item_attrs.name().deserialize_name();
- quote!(deserializer.deserialize_newtype_struct(#type_name, #visitor_expr))
+ quote!(_serde::Deserializer::deserialize_newtype_struct(deserializer, #type_name, #visitor_expr))
} else {
let type_name = item_attrs.name().deserialize_name();
- quote!(deserializer.deserialize_tuple_struct(#type_name, #nfields, #visitor_expr))
+ quote!(_serde::Deserializer::deserialize_tuple_struct(deserializer, #type_name, #nfields, #visitor_expr))
};
let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing());
@@ -298,7 +298,7 @@ fn deserialize_tuple(
type Value = #ty;
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
- formatter.write_str(#expecting)
+ _serde::export::fmt::Formatter::write_str(formatter, #expecting)
}
#visit_newtype_struct
@@ -341,7 +341,7 @@ fn deserialize_seq(
let visit = match field.attrs.deserialize_with() {
None => {
let field_ty = &field.ty;
- quote!(try!(visitor.visit::<#field_ty>()))
+ quote!(try!(_serde::de::SeqVisitor::visit::<#field_ty>(&mut visitor)))
}
Some(path) => {
let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
@@ -349,7 +349,8 @@ fn deserialize_seq(
quote!({
#wrapper
#wrapper_impl
- try!(visitor.visit::<#wrapper_ty>()).map(|wrap| wrap.value)
+ try!(_serde::de::SeqVisitor::visit::<#wrapper_ty>(&mut visitor))
+ .map(|wrap| wrap.value)
})
}
};
@@ -357,7 +358,7 @@ fn deserialize_seq(
let #var = match #visit {
Some(value) => { value },
None => {
- return Err(_serde::de::Error::invalid_length(#index_in_seq, &#expecting));
+ return _serde::export::Err(_serde::de::Error::invalid_length(#index_in_seq, &#expecting));
}
};
};
@@ -379,7 +380,7 @@ fn deserialize_seq(
quote! {
#(#let_values)*
- Ok(#result)
+ _serde::export::Ok(#result)
}
}
@@ -411,7 +412,7 @@ fn deserialize_newtype_struct(
fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::export::Result<Self::Value, __E::Error>
where __E: _serde::Deserializer,
{
- Ok(#type_path(#value))
+ _serde::export::Ok(#type_path(#value))
}
}
}
@@ -461,7 +462,7 @@ fn deserialize_struct(
} else {
let type_name = item_attrs.name().deserialize_name();
quote! {
- deserializer.deserialize_struct(#type_name, FIELDS, #visitor_expr)
+ _serde::Deserializer::deserialize_struct(deserializer, #type_name, FIELDS, #visitor_expr)
}
};
@@ -481,7 +482,7 @@ fn deserialize_struct(
type Value = #ty;
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
- formatter.write_str(#expecting)
+ _serde::export::fmt::Formatter::write_str(formatter, #expecting)
}
#[inline]
@@ -563,13 +564,14 @@ fn deserialize_item_enum(
// all variants have `#[serde(skip_deserializing)]`.
quote! {
// FIXME: Once we drop support for Rust 1.15:
- // let Err(err) = visitor.visit_variant::<__Field>();
- // Err(err)
- visitor.visit_variant::<__Field>().map(|(impossible, _)| match impossible {})
+ // let _serde::export::Err(err) = _serde::de::EnumVisitor::visit_variant::<__Field>(visitor);
+ // _serde::export::Err(err)
+ _serde::de::EnumVisitor::visit_variant::<__Field>(visitor)
+ .map(|(impossible, _)| match impossible {})
}
} else {
quote! {
- match try!(visitor.visit_variant()) {
+ match try!(_serde::de::EnumVisitor::visit_variant(visitor)) {
#(#variant_arms)*
}
}
@@ -586,7 +588,7 @@ fn deserialize_item_enum(
type Value = #ty;
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
- formatter.write_str(#expecting)
+ _serde::export::fmt::Formatter::write_str(formatter, #expecting)
}
fn visit_enum<__V>(self, visitor: __V) -> _serde::export::Result<#ty, __V::Error>
@@ -598,7 +600,7 @@ fn deserialize_item_enum(
#variants_stmt
- deserializer.deserialize_enum(#type_name, VARIANTS, #visitor_expr)
+ _serde::Deserializer::deserialize_enum(deserializer, #type_name, VARIANTS, #visitor_expr)
})
}
@@ -615,7 +617,7 @@ fn deserialize_variant(
Style::Unit => {
quote!({
try!(_serde::de::VariantVisitor::visit_unit(visitor));
- Ok(#type_ident::#variant_ident)
+ _serde::export::Ok(#type_ident::#variant_ident)
})
}
Style::Newtype => {
@@ -673,7 +675,7 @@ fn deserialize_newtype_variant(
}
};
quote! {
- Ok(#type_ident::#variant_ident(#visit)),
+ _serde::export::Ok(#type_ident::#variant_ident(#visit)),
}
}
@@ -701,9 +703,9 @@ fn deserialize_field_visitor(
{
match value {
#(
- #variant_indices => Ok(__Field::#field_idents),
+ #variant_indices => _serde::export::Ok(__Field::#field_idents),
)*
- _ => Err(_serde::de::Error::invalid_value(
+ _ => _serde::export::Err(_serde::de::Error::invalid_value(
_serde::de::Unexpected::Unsigned(value as u64),
&#fallthrough_msg))
}
@@ -715,15 +717,15 @@ fn deserialize_field_visitor(
let fallthrough_arm = if is_variant {
quote! {
- Err(_serde::de::Error::unknown_variant(value, VARIANTS))
+ _serde::export::Err(_serde::de::Error::unknown_variant(value, VARIANTS))
}
} else if item_attrs.deny_unknown_fields() {
quote! {
- Err(_serde::de::Error::unknown_field(value, FIELDS))
+ _serde::export::Err(_serde::de::Error::unknown_field(value, FIELDS))
}
} else {
quote! {
- Ok(__Field::__ignore)
+ _serde::export::Ok(__Field::__ignore)
}
};
@@ -755,7 +757,7 @@ fn deserialize_field_visitor(
type Value = __Field;
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
- formatter.write_str("field name")
+ _serde::export::fmt::Formatter::write_str(formatter, "field name")
}
#visit_index
@@ -765,7 +767,7 @@ fn deserialize_field_visitor(
{
match value {
#(
- #field_strs => Ok(__Field::#field_idents),
+ #field_strs => _serde::export::Ok(__Field::#field_idents),
)*
_ => #fallthrough_arm
}
@@ -776,7 +778,7 @@ fn deserialize_field_visitor(
{
match value {
#(
- #field_bytes => Ok(__Field::#field_idents),
+ #field_bytes => _serde::export::Ok(__Field::#field_idents),
)*
_ => {
#bytes_to_str
@@ -786,7 +788,7 @@ fn deserialize_field_visitor(
}
}
- deserializer.deserialize_struct_field(__FieldVisitor)
+ _serde::Deserializer::deserialize_struct_field(deserializer, __FieldVisitor)
}
}
}
@@ -848,7 +850,7 @@ fn deserialize_map(
.map(|&(field, ref name)| {
let field_ty = &field.ty;
quote! {
- let mut #name: Option<#field_ty> = None;
+ let mut #name: _serde::export::Option<#field_ty> = _serde::export::None;
}
});
@@ -862,7 +864,7 @@ fn deserialize_map(
None => {
let field_ty = &field.ty;
quote! {
- try!(visitor.visit_value::<#field_ty>())
+ try!(_serde::de::MapVisitor::visit_value::<#field_ty>(&mut visitor))
}
}
Some(path) => {
@@ -871,16 +873,16 @@ fn deserialize_map(
quote!({
#wrapper
#wrapper_impl
- try!(visitor.visit_value::<#wrapper_ty>()).value
+ try!(_serde::de::MapVisitor::visit_value::<#wrapper_ty>(&mut visitor)).value
})
}
};
quote! {
__Field::#name => {
- if #name.is_some() {
- return Err(<__V::Error as _serde::de::Error>::duplicate_field(#deser_name));
+ if _serde::export::Option::is_some(&#name) {
+ return _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#deser_name));
}
- #name = Some(#visit);
+ #name = _serde::export::Some(#visit);
}
}
});
@@ -890,7 +892,7 @@ fn deserialize_map(
None
} else {
Some(quote! {
- _ => { let _ = try!(visitor.visit_value::<_serde::de::impls::IgnoredAny>()); }
+ _ => { let _ = try!(_serde::de::MapVisitor::visit_value::<_serde::de::impls::IgnoredAny>(&mut visitor)); }
})
};
@@ -898,12 +900,13 @@ fn deserialize_map(
let match_keys = if item_attrs.deny_unknown_fields() && all_skipped {
quote! {
// FIXME: Once we drop support for Rust 1.15:
- // let None::<__Field> = try!(visitor.visit_key());
- try!(visitor.visit_key::<__Field>()).map(|impossible| match impossible {});
+ // let _serde::export::None::<__Field> = try!(_serde::de::MapVisitor::visit_key(&mut visitor));
+ try!(_serde::de::MapVisitor::visit_key::<__Field>(&mut visitor))
+ .map(|impossible| match impossible {});
}
} else {
quote! {
- while let Some(key) = try!(visitor.visit_key::<__Field>()) {
+ while let _serde::export::Some(key) = try!(_serde::de::MapVisitor::visit_key::<__Field>(&mut visitor)) {
match key {
#(#value_arms)*
#ignored_arm
@@ -919,8 +922,8 @@ fn deserialize_map(
quote! {
let #name = match #name {
- Some(#name) => #name,
- None => #missing_expr
+ _serde::export::Some(#name) => #name,
+ _serde::export::None => #missing_expr
};
}
});
@@ -943,7 +946,7 @@ fn deserialize_map(
#(#extract_values)*
- Ok(#struct_path { #(#result),* })
+ _serde::export::Ok(#struct_path { #(#result),* })
}
}
@@ -990,7 +993,7 @@ fn wrap_deserialize_with(
where __D: _serde::Deserializer
{
let value = try!(#deserialize_with(__d));
- Ok(__SerdeDeserializeWithStruct {
+ _serde::export::Ok(__SerdeDeserializeWithStruct {
value: value,
phantom: _serde::export::PhantomData,
})
@@ -1021,7 +1024,7 @@ fn expr_is_missing(attrs: &attr::Field) -> Tokens {
}
Some(_) => {
quote! {
- return Err(<__V::Error as _serde::de::Error>::missing_field(#name))
+ return _serde::export::Err(<__V::Error as _serde::de::Error>::missing_field(#name))
}
}
}
diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index f85839e53..6478de411 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -125,7 +125,7 @@ fn serialize_unit_struct(item_attrs: &attr::Item) -> Tokens {
let type_name = item_attrs.name().serialize_name();
quote! {
- _serializer.serialize_unit_struct(#type_name)
+ _serde::Serializer::serialize_unit_struct(_serializer, #type_name)
}
}
@@ -144,7 +144,7 @@ fn serialize_newtype_struct(
}
quote! {
- _serializer.serialize_newtype_struct(#type_name, #field_expr)
+ _serde::Serializer::serialize_newtype_struct(_serializer, #type_name, #field_expr)
}
}
@@ -167,7 +167,7 @@ fn serialize_tuple_struct(
let let_mut = mut_if(len > 0);
quote! {
- let #let_mut __serde_state = try!(_serializer.serialize_tuple_struct(#type_name, #len));
+ let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple_struct(_serializer, #type_name, #len));
#(#serialize_stmts)*
_serde::ser::SerializeTupleStruct::end(__serde_state)
}
@@ -208,7 +208,7 @@ fn serialize_struct(
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
quote! {
- let #let_mut __serde_state = try!(_serializer.serialize_struct(#type_name, #len));
+ let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct(_serializer, #type_name, #len));
#(#serialize_fields)*
_serde::ser::SerializeStruct::end(__serde_state)
}
@@ -260,7 +260,7 @@ fn serialize_variant(
let skipped_msg = format!("the enum variant {}::{} cannot be serialized",
type_ident, variant_ident);
let skipped_err = quote! {
- Err(_serde::ser::Error::custom(#skipped_msg))
+ _serde::export::Err(_serde::ser::Error::custom(#skipped_msg))
};
let fields_pat = match variant.style {
Style::Unit => quote!(),
@@ -380,7 +380,8 @@ fn serialize_tuple_variant(
let let_mut = mut_if(len > 0);
quote! {
- let #let_mut __serde_state = try!(_serializer.serialize_tuple_variant(
+ let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple_variant(
+ _serializer,
#type_name,
#variant_index,
#variant_name,
@@ -426,7 +427,8 @@ fn serialize_struct_variant(
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
quote! {
- let #let_mut __serde_state = try!(_serializer.serialize_struct_variant(
+ let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct_variant(
+ _serializer,
#item_name,
#variant_index,
#variant_name,
@@ -537,7 +539,7 @@ fn wrap_serialize_with(
quote!({
struct __SerializeWith #wrapper_generics #where_clause {
value: &'__a #field_ty,
- phantom: ::std::marker::PhantomData<#item_ty>,
+ phantom: _serde::export::PhantomData<#item_ty>,
}
impl #wrapper_generics _serde::Serialize for #wrapper_ty #where_clause {
@@ -550,7 +552,7 @@ fn wrap_serialize_with(
&__SerializeWith {
value: #value,
- phantom: ::std::marker::PhantomData::<#item_ty>,
+ phantom: _serde::export::PhantomData::<#item_ty>,
}
})
}
| serde-rs/serde | 2017-02-01T20:14:24Z | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 | |
733 | diff --git a/serde_test/Cargo.toml b/serde_test/Cargo.toml
index 94f6a409b..83d90e971 100644
--- a/serde_test/Cargo.toml
+++ b/serde_test/Cargo.toml
@@ -11,11 +11,7 @@ readme = "../README.md"
keywords = ["serde", "serialization"]
include = ["Cargo.toml", "src/**/*.rs"]
-[features]
-unstable-testing = ["clippy"]
-
[dependencies]
-clippy = { version = "0.*", optional = true }
serde = { version = "0.9", path = "../serde" }
[badges]
diff --git a/serde_test/src/lib.rs b/serde_test/src/lib.rs
index 4c9397e60..945262c02 100644
--- a/serde_test/src/lib.rs
+++ b/serde_test/src/lib.rs
@@ -1,6 +1,3 @@
-#![cfg_attr(feature = "clippy", feature(plugin))]
-#![cfg_attr(feature = "clippy", plugin(clippy))]
-
extern crate serde;
mod assert;
diff --git a/test_suite/Cargo.toml b/test_suite/Cargo.toml
index 20039a9c7..86ac863fd 100644
--- a/test_suite/Cargo.toml
+++ b/test_suite/Cargo.toml
@@ -13,11 +13,8 @@ publish = false
[features]
unstable-testing = [
- "clippy",
"compiletest_rs",
"serde/unstable-testing",
- "serde_derive/unstable-testing",
- "serde_test/unstable-testing",
]
[dev-dependencies]
@@ -28,7 +25,6 @@ serde_derive = { path = "../serde_derive" }
serde_test = { path = "../serde_test" }
[dependencies]
-clippy = { version = "0.*", optional = true }
compiletest_rs = { version = "0.2", optional = true }
[[test]]
diff --git a/test_suite/no_std/src/main.rs b/test_suite/no_std/src/main.rs
index 5eae52672..6639b5ccc 100644
--- a/test_suite/no_std/src/main.rs
+++ b/test_suite/no_std/src/main.rs
@@ -21,7 +21,9 @@ pub extern fn rust_eh_unwind_resume() {}
pub extern fn rust_begin_panic(_msg: core::fmt::Arguments,
_file: &'static str,
_line: u32) -> ! {
- loop {}
+ unsafe {
+ libc::abort()
+ }
}
//////////////////////////////////////////////////////////////////////////////
diff --git a/test_suite/tests/test.rs b/test_suite/tests/test.rs
index 7c1b06b53..b83be6366 100644
--- a/test_suite/tests/test.rs
+++ b/test_suite/tests/test.rs
@@ -1,6 +1,3 @@
-#![cfg_attr(feature = "clippy", feature(plugin))]
-#![cfg_attr(feature = "clippy", plugin(clippy))]
-
#![cfg_attr(feature = "unstable-testing", feature(test, non_ascii_idents))]
#[cfg(feature = "unstable-testing")]
| [
"729"
] | serde-rs__serde-733 | Cannot publish serde_derive
```
$ git checkout v0.9.3
HEAD is now at 8624ca6... Release 0.9.3
$ cd serde_derive
$ cargo publish
Updating registry `https://github.com/rust-lang/crates.io-index`
Packaging serde_derive v0.9.3 (file://../serde_derive)
Verifying serde_derive v0.9.3 (file://../serde_derive)
Updating registry `https://github.com/rust-lang/crates.io-index`
error: failed to verify package tarball
Caused by:
cyclic package dependency: package `cargo_metadata v0.1.1` depends on itself
$ cargo tree --features clippy
serde_derive v0.9.3 (file://../serde_derive)
├── clippy v0.0.112
│ ├── cargo_metadata v0.1.1
│ │ ├── serde v0.9.3
│ │ ├── serde_derive v0.9.2
│ │ │ ├── quote v0.3.12
│ │ │ ├── serde_codegen_internals v0.12.0
│ │ │ │ └── syn v0.11.4
│ │ │ │ ├── quote v0.3.12 (*)
│ │ │ │ └── unicode-xid v0.0.4
│ │ │ └── syn v0.11.4 (*)
│ │ └── serde_json v0.9.1
│ │ ├── dtoa v0.3.1
│ │ ├── itoa v0.2.1
│ │ ├── num-traits v0.1.36
│ │ └── serde v0.9.3 (*)
│ └── clippy_lints v0.0.112
│ ├── matches v0.1.4
│ ├── quine-mc_cluskey v0.2.4
│ ├── regex-syntax v0.4.0
│ ├── semver v0.2.3
│ │ └── nom v1.2.4
│ ├── toml v0.2.1
│ │ └── rustc-serialize v0.3.22
│ └── unicode-normalization v0.1.3
├── quote v0.3.12 (*)
├── serde_codegen_internals v0.12.0 (file://../serde_codegen_internals)
│ └── syn v0.11.4 (*)
└── syn v0.11.4 (*)
```
@oli-obk any ideas? Serde_derive depends on clippy which depends on cargo_metadata which depends on serde_derive.
| 0.9 | 74cf80989d06210c9309e82549a51ff6d0b4ed94 | diff --git a/.travis.yml b/.travis.yml
index aca19dc87..c415551ee 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,5 +1,6 @@
sudo: false
language: rust
+cache: cargo
# run builds for all the trains (and more)
rust:
@@ -8,20 +9,16 @@ rust:
- beta
- nightly
+matrix:
+ include:
+ - rust: nightly
+ env: CLIPPY=true
+
before_script:
- pip install 'travis-cargo<0.2' --user
- export PATH=$HOME/.local/bin:$PATH
-script:
- - (cd serde && travis-cargo build)
- - (cd serde && travis-cargo --only beta test)
- - (cd serde && travis-cargo --only nightly test -- --features unstable-testing)
- - (cd serde && travis-cargo build -- --no-default-features)
- - (cd serde && travis-cargo --only nightly build -- --no-default-features --features alloc)
- - (cd serde && travis-cargo --only nightly build -- --no-default-features --features collections)
- - (cd test_suite && travis-cargo --only beta test)
- - (cd test_suite/deps && travis-cargo --only nightly build && cd .. && travis-cargo --only nightly test -- --features unstable-testing)
- - (cd test_suite/no_std && travis-cargo --only nightly build)
+script: sh travis.sh
env:
global:
diff --git a/serde/Cargo.toml b/serde/Cargo.toml
index 2cc5dca4c..357fff3af 100644
--- a/serde/Cargo.toml
+++ b/serde/Cargo.toml
@@ -22,10 +22,7 @@ std = []
unstable = []
alloc = ["unstable"]
collections = ["alloc"]
-unstable-testing = ["clippy", "unstable", "std"]
-
-[dependencies]
-clippy = { version = "0.*", optional = true }
+unstable-testing = ["unstable", "std"]
[dev-dependencies]
serde_derive = "0.9"
diff --git a/serde/src/lib.rs b/serde/src/lib.rs
index efb29411e..eb07bbbff 100644
--- a/serde/src/lib.rs
+++ b/serde/src/lib.rs
@@ -64,9 +64,7 @@
#![cfg_attr(feature = "unstable", feature(nonzero, inclusive_range, zero_one))]
#![cfg_attr(feature = "alloc", feature(alloc))]
#![cfg_attr(feature = "collections", feature(collections, enumset))]
-#![cfg_attr(feature = "clippy", feature(plugin))]
-#![cfg_attr(feature = "clippy", plugin(clippy))]
-#![cfg_attr(feature = "clippy", allow(linkedlist, type_complexity, doc_markdown))]
+#![cfg_attr(feature = "cargo-clippy", allow(linkedlist, type_complexity, doc_markdown))]
#![deny(missing_docs)]
#[cfg(feature = "collections")]
diff --git a/serde_codegen_internals/Cargo.toml b/serde_codegen_internals/Cargo.toml
index 9d9bfb658..36ec99aab 100644
--- a/serde_codegen_internals/Cargo.toml
+++ b/serde_codegen_internals/Cargo.toml
@@ -10,11 +10,7 @@ documentation = "https://docs.serde.rs/serde_codegen_internals/"
keywords = ["serde", "serialization"]
include = ["Cargo.toml", "src/**/*.rs"]
-[features]
-unstable-testing = ["clippy"]
-
[dependencies]
-clippy = { version = "0.*", optional = true }
syn = "0.11"
[badges]
diff --git a/serde_codegen_internals/src/lib.rs b/serde_codegen_internals/src/lib.rs
index 0f37f5fa2..cd998deb9 100644
--- a/serde_codegen_internals/src/lib.rs
+++ b/serde_codegen_internals/src/lib.rs
@@ -1,6 +1,3 @@
-#![cfg_attr(feature = "clippy", plugin(clippy))]
-#![cfg_attr(feature = "clippy", feature(plugin))]
-
extern crate syn;
pub mod ast;
diff --git a/serde_derive/Cargo.toml b/serde_derive/Cargo.toml
index 419cd9624..e3c5f3599 100644
--- a/serde_derive/Cargo.toml
+++ b/serde_derive/Cargo.toml
@@ -12,7 +12,6 @@ include = ["Cargo.toml", "src/**/*.rs"]
[features]
unstable = []
-unstable-testing = ["clippy", "serde_codegen_internals/unstable-testing"]
[badges]
travis-ci = { repository = "serde-rs/serde" }
@@ -22,7 +21,6 @@ name = "serde_derive"
proc-macro = true
[dependencies]
-clippy = { version = "0.*", optional = true }
quote = "0.3.8"
serde_codegen_internals = { version = "=0.12.0", default-features = false, path = "../serde_codegen_internals" }
syn = { version = "0.11", features = ["aster", "visit"] }
diff --git a/serde_derive/src/lib.rs b/serde_derive/src/lib.rs
index cf80dc64f..6e6a8c3af 100644
--- a/serde_derive/src/lib.rs
+++ b/serde_derive/src/lib.rs
@@ -1,7 +1,5 @@
-#![cfg_attr(feature = "clippy", plugin(clippy))]
-#![cfg_attr(feature = "clippy", feature(plugin))]
-#![cfg_attr(feature = "clippy", allow(too_many_arguments))]
-#![cfg_attr(feature = "clippy", allow(used_underscore_binding))]
+#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
+#![cfg_attr(feature = "cargo-clippy", allow(used_underscore_binding))]
// The `quote!` macro requires deep recursion.
#![recursion_limit = "192"]
diff --git a/travis.sh b/travis.sh
new file mode 100644
index 000000000..225869ee7
--- /dev/null
+++ b/travis.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -ev
+if [ "${CLIPPY}" = "true" ]; then
+ if cargo install clippy -f; then
+ (cd serde && cargo clippy --features unstable-testing -- -Dclippy)
+ (cd serde_derive && cargo clippy --features unstable-testing -- -Dclippy)
+ (cd test_suite && cargo clippy --features unstable-testing -- -Dclippy)
+ (cd test_suite/deps && cargo clippy -- -Dclippy)
+ (cd test_suite/no_std && cargo clippy -- -Dclippy)
+ else
+ echo "could not compile clippy, ignoring clippy tests"
+ fi
+else
+ (cd serde && travis-cargo build)
+ (cd serde && travis-cargo --only beta test)
+ (cd serde && travis-cargo --only nightly test -- --features unstable-testing)
+ (cd serde && travis-cargo build -- --no-default-features)
+ (cd serde && travis-cargo --only nightly build -- --no-default-features --features alloc)
+ (cd serde && travis-cargo --only nightly build -- --no-default-features --features collections)
+ (cd test_suite && travis-cargo --only beta test)
+ (cd test_suite/deps && travis-cargo --only nightly build)
+ (cd test_suite travis-cargo --only nightly test -- --features unstable-testing)
+ (cd test_suite/no_std && travis-cargo --only nightly build)
+fi
\ No newline at end of file
| serde-rs/serde | 2017-01-31T08:35:07Z | I got around it by `cargo publish --no-verify` but obviously that is not ideal...
lol I so did not see that one coming.
Can we just move to cargo clippy instead of depending on clippy?
I could even set up clippy testing as a separate travis job, so it wouldn't break our nightly job
> cargo clippy
> separate travis job
Yes let's do both of those! | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 |
721 | diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index fc29ccd94..cb41ab15c 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -225,26 +225,16 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
where __V: de::Visitor {
self.deserialize(visitor)
}
- fn deserialize_usize<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
- fn deserialize_isize<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
- where __V: de::Visitor {
- self.deserialize(visitor)
- }
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
match self.tokens.next() {
Some(Token::Bool(v)) => visitor.visit_bool(v),
- Some(Token::Isize(v)) => visitor.visit_isize(v),
Some(Token::I8(v)) => visitor.visit_i8(v),
Some(Token::I16(v)) => visitor.visit_i16(v),
Some(Token::I32(v)) => visitor.visit_i32(v),
Some(Token::I64(v)) => visitor.visit_i64(v),
- Some(Token::Usize(v)) => visitor.visit_usize(v),
Some(Token::U8(v)) => visitor.visit_u8(v),
Some(Token::U16(v)) => visitor.visit_u16(v),
Some(Token::U32(v)) => visitor.visit_u32(v),
diff --git a/serde_test/src/ser.rs b/serde_test/src/ser.rs
index c97de428e..4327733fb 100644
--- a/serde_test/src/ser.rs
+++ b/serde_test/src/ser.rs
@@ -46,11 +46,6 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
Ok(())
}
- fn serialize_isize(self, v: isize) -> Result<(), Error> {
- assert_eq!(self.tokens.next(), Some(&Token::Isize(v)));
- Ok(())
- }
-
fn serialize_i8(self, v: i8) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::I8(v)));
Ok(())
@@ -71,11 +66,6 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
Ok(())
}
- fn serialize_usize(self, v: usize) -> Result<(), Error> {
- assert_eq!(self.tokens.next(), Some(&Token::Usize(v)));
- Ok(())
- }
-
fn serialize_u8(self, v: u8) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::U8(v)));
Ok(())
diff --git a/serde_test/src/token.rs b/serde_test/src/token.rs
index b8bd23c66..b2d2a6ef2 100644
--- a/serde_test/src/token.rs
+++ b/serde_test/src/token.rs
@@ -1,12 +1,10 @@
#[derive(Clone, PartialEq, Debug)]
pub enum Token<'a> {
Bool(bool),
- Isize(isize),
I8(i8),
I16(i16),
I32(i32),
I64(i64),
- Usize(usize),
U8(u8),
U16(u16),
U32(u32),
diff --git a/testing/tests/test_de.rs b/testing/tests/test_de.rs
index 83c3eabf5..97481b594 100644
--- a/testing/tests/test_de.rs
+++ b/testing/tests/test_de.rs
@@ -155,12 +155,10 @@ declare_tests! {
false => &[Token::Bool(false)],
}
test_isize {
- 0isize => &[Token::Isize(0)],
0isize => &[Token::I8(0)],
0isize => &[Token::I16(0)],
0isize => &[Token::I32(0)],
0isize => &[Token::I64(0)],
- 0isize => &[Token::Usize(0)],
0isize => &[Token::U8(0)],
0isize => &[Token::U16(0)],
0isize => &[Token::U32(0)],
@@ -169,14 +167,12 @@ declare_tests! {
0isize => &[Token::F64(0.)],
}
test_ints {
- 0isize => &[Token::Isize(0)],
0i8 => &[Token::I8(0)],
0i16 => &[Token::I16(0)],
0i32 => &[Token::I32(0)],
0i64 => &[Token::I64(0)],
}
test_uints {
- 0usize => &[Token::Usize(0)],
0u8 => &[Token::U8(0)],
0u16 => &[Token::U16(0)],
0u32 => &[Token::U32(0)],
@@ -777,7 +773,7 @@ declare_tests! {
test_enum_unit_usize {
Enum::Unit => &[
Token::EnumStart("Enum"),
- Token::Usize(0),
+ Token::U32(0),
Token::Unit,
],
}
@@ -935,7 +931,7 @@ declare_error_tests! {
test_enum_out_of_range<Enum> {
&[
Token::EnumStart("Enum"),
- Token::Usize(4),
+ Token::U32(4),
Token::Unit,
],
Error::Message("invalid value: integer `4`, expected variant index 0 <= i < 4".into()),
diff --git a/testing/tests/test_ser.rs b/testing/tests/test_ser.rs
index 4d8e0f0e8..852c57001 100644
--- a/testing/tests/test_ser.rs
+++ b/testing/tests/test_ser.rs
@@ -60,14 +60,12 @@ declare_ser_tests! {
false => &[Token::Bool(false)],
}
test_isizes {
- 0isize => &[Token::Isize(0)],
0i8 => &[Token::I8(0)],
0i16 => &[Token::I16(0)],
0i32 => &[Token::I32(0)],
0i64 => &[Token::I64(0)],
}
test_usizes {
- 0usize => &[Token::Usize(0)],
0u8 => &[Token::U8(0)],
0u16 => &[Token::U16(0)],
0u32 => &[Token::U32(0)],
| [
"718"
] | serde-rs__serde-721 | Remove usize and isize from Serializer, Deserializer, Visitor
Why do we need usize and isize as types in our data model? Can we get away with just the specific bit width types? For the most part data formats just treat these as u64 and i64 right?
| null | 8cb6607e827717136a819caa44d8e43702724883 | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 496e5bb71..d28dba028 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -180,12 +180,10 @@ macro_rules! impl_deserialize_num {
formatter.write_str(stringify!($ty))
}
- impl_deserialize_num_method!($ty, isize, visit_isize, from_isize, Signed, i64);
impl_deserialize_num_method!($ty, i8, visit_i8, from_i8, Signed, i64);
impl_deserialize_num_method!($ty, i16, visit_i16, from_i16, Signed, i64);
impl_deserialize_num_method!($ty, i32, visit_i32, from_i32, Signed, i64);
impl_deserialize_num_method!($ty, i64, visit_i64, from_i64, Signed, i64);
- impl_deserialize_num_method!($ty, usize, visit_usize, from_usize, Unsigned, u64);
impl_deserialize_num_method!($ty, u8, visit_u8, from_u8, Unsigned, u64);
impl_deserialize_num_method!($ty, u16, visit_u16, from_u16, Unsigned, u64);
impl_deserialize_num_method!($ty, u32, visit_u32, from_u32, Unsigned, u64);
@@ -209,12 +207,12 @@ macro_rules! impl_deserialize_num {
}
}
-impl_deserialize_num!(isize, deserialize_isize);
+impl_deserialize_num!(isize, deserialize_i64);
impl_deserialize_num!(i8, deserialize_i8);
impl_deserialize_num!(i16, deserialize_i16);
impl_deserialize_num!(i32, deserialize_i32);
impl_deserialize_num!(i64, deserialize_i64);
-impl_deserialize_num!(usize, deserialize_usize);
+impl_deserialize_num!(usize, deserialize_u64);
impl_deserialize_num!(u8, deserialize_u8);
impl_deserialize_num!(u16, deserialize_u16);
impl_deserialize_num!(u32, deserialize_u32);
@@ -1150,7 +1148,7 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
formatter.write_str("`Ok` or `Err`")
}
- fn visit_usize<E>(self, value: usize) -> Result<Field, E> where E: Error {
+ fn visit_u32<E>(self, value: u32) -> Result<Field, E> where E: Error {
match value {
0 => Ok(Field::Ok),
1 => Ok(Field::Err),
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index e45b20af1..e053b3dfb 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -339,12 +339,12 @@ pub enum Unexpected<'a> {
/// The input contained a boolean value that was not expected.
Bool(bool),
- /// The input contained an unsigned integer `usize`, `u8`, `u16`, `u32` or
- /// `u64` that was not expected.
+ /// The input contained an unsigned integer `u8`, `u16`, `u32` or `u64` that
+ /// was not expected.
Unsigned(u64),
- /// The input contained a signed integer `isize`, `i8`, `i16`, `i32` or
- /// `i64` that was not expected.
+ /// The input contained a signed integer `i8`, `i16`, `i32` or `i64` that
+ /// was not expected.
Signed(i64),
/// The input contained a floating point `f32` or `f64` that was not
@@ -694,7 +694,7 @@ impl<T> DeserializeSeed for PhantomData<T>
/// any data structure supported by Serde.
///
/// The role of this trait is to define the deserialization half of the Serde
-/// data model, which is a way to categorize every Rust data type into one of 30
+/// data model, which is a way to categorize every Rust data type into one of 28
/// possible types. Each method of the `Serializer` trait corresponds to one of
/// the types of the data model.
///
@@ -704,13 +704,13 @@ impl<T> DeserializeSeed for PhantomData<T>
///
/// The types that make up the Serde data model are:
///
-/// - 15 primitive types:
+/// - 12 primitive types:
/// - bool
-/// - isize, i8, i16, i32, i64
-/// - usize, u8, u16, u32, u64
+/// - i8, i16, i32, i64
+/// - u8, u16, u32, u64
/// - f32, f64
/// - char
-/// - string
+/// - string
/// - byte array - [u8]
/// - option
/// - either none or some value
@@ -792,10 +792,6 @@ pub trait Deserializer: Sized {
fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
- /// Hint that the `Deserialize` type is expecting a `usize` value.
- fn deserialize_usize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
/// Hint that the `Deserialize` type is expecting a `u8` value.
fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
@@ -812,10 +808,6 @@ pub trait Deserializer: Sized {
fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
- /// Hint that the `Deserialize` type is expecting an `isize` value.
- fn deserialize_isize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
-
/// Hint that the `Deserialize` type is expecting an `i8` value.
fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
@@ -1030,13 +1022,6 @@ pub trait Visitor: Sized {
Err(Error::invalid_type(Unexpected::Bool(v), &self))
}
- /// Deserialize an `isize` into a `Value`.
- fn visit_isize<E>(self, v: isize) -> Result<Self::Value, E>
- where E: Error,
- {
- self.visit_i64(v as i64)
- }
-
/// Deserialize an `i8` into a `Value`.
fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
where E: Error,
@@ -1065,13 +1050,6 @@ pub trait Visitor: Sized {
Err(Error::invalid_type(Unexpected::Signed(v), &self))
}
- /// Deserialize a `usize` into a `Value`.
- fn visit_usize<E>(self, v: usize) -> Result<Self::Value, E>
- where E: Error,
- {
- self.visit_u64(v as u64)
- }
-
/// Deserialize a `u8` into a `Value`.
fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
where E: Error,
diff --git a/serde/src/de/private.rs b/serde/src/de/private.rs
index 92e71cf86..1ff206cdb 100644
--- a/serde/src/de/private.rs
+++ b/serde/src/de/private.rs
@@ -28,10 +28,9 @@ pub fn missing_field<V, E>(field: &'static str) -> Result<V, E>
}
forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str
- string unit seq seq_fixed_size bytes byte_buf map unit_struct
- newtype_struct tuple_struct struct struct_field tuple enum
- ignored_any
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
+ seq_fixed_size bytes byte_buf map unit_struct newtype_struct
+ tuple_struct struct struct_field tuple enum ignored_any
}
}
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 38f993940..ae5c93afb 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -126,9 +126,9 @@ impl<E> de::Deserializer for UnitDeserializer<E>
type Error = E;
forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any byte_buf
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
+ seq_fixed_size bytes map unit_struct newtype_struct tuple_struct struct
+ struct_field tuple enum ignored_any byte_buf
}
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
@@ -147,7 +147,7 @@ impl<E> de::Deserializer for UnitDeserializer<E>
///////////////////////////////////////////////////////////////////////////////
macro_rules! primitive_deserializer {
- ($ty:ty, $name:ident, $method:ident) => {
+ ($ty:ty, $name:ident, $method:ident $($cast:tt)*) => {
/// A helper deserializer that deserializes a number.
pub struct $name<E>($ty, PhantomData<E>);
@@ -167,16 +167,15 @@ macro_rules! primitive_deserializer {
type Error = E;
forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str
- string unit option seq seq_fixed_size bytes map unit_struct
- newtype_struct tuple_struct struct struct_field tuple enum
- ignored_any byte_buf
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit
+ option seq seq_fixed_size bytes map unit_struct newtype_struct
+ tuple_struct struct struct_field tuple enum ignored_any byte_buf
}
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
- visitor.$method(self.0)
+ visitor.$method(self.0 $($cast)*)
}
}
}
@@ -187,12 +186,12 @@ primitive_deserializer!(i8, I8Deserializer, visit_i8);
primitive_deserializer!(i16, I16Deserializer, visit_i16);
primitive_deserializer!(i32, I32Deserializer, visit_i32);
primitive_deserializer!(i64, I64Deserializer, visit_i64);
-primitive_deserializer!(isize, IsizeDeserializer, visit_isize);
+primitive_deserializer!(isize, IsizeDeserializer, visit_i64 as i64);
primitive_deserializer!(u8, U8Deserializer, visit_u8);
primitive_deserializer!(u16, U16Deserializer, visit_u16);
primitive_deserializer!(u32, U32Deserializer, visit_u32);
primitive_deserializer!(u64, U64Deserializer, visit_u64);
-primitive_deserializer!(usize, UsizeDeserializer, visit_usize);
+primitive_deserializer!(usize, UsizeDeserializer, visit_u64 as u64);
primitive_deserializer!(f32, F32Deserializer, visit_f32);
primitive_deserializer!(f64, F64Deserializer, visit_f64);
primitive_deserializer!(char, CharDeserializer, visit_char);
@@ -233,9 +232,9 @@ impl<'a, E> de::Deserializer for StrDeserializer<'a, E>
}
forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple ignored_any byte_buf
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+ seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
+ struct struct_field tuple ignored_any byte_buf
}
}
@@ -291,9 +290,9 @@ impl<E> de::Deserializer for StringDeserializer<E>
}
forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple ignored_any byte_buf
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+ seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
+ struct struct_field tuple ignored_any byte_buf
}
}
@@ -353,9 +352,9 @@ impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E>
}
forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple ignored_any byte_buf
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+ seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
+ struct struct_field tuple ignored_any byte_buf
}
}
@@ -426,9 +425,9 @@ impl<I, T, E> de::Deserializer for SeqDeserializer<I, E>
}
forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any byte_buf
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+ seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
+ struct struct_field tuple enum ignored_any byte_buf
}
}
@@ -538,9 +537,9 @@ impl<V_, E> de::Deserializer for SeqVisitorDeserializer<V_, E>
}
forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any byte_buf
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+ seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
+ struct struct_field tuple enum ignored_any byte_buf
}
}
@@ -634,9 +633,9 @@ impl<I, E> de::Deserializer for MapDeserializer<I, E>
}
forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option bytes map unit_struct newtype_struct tuple_struct struct
- struct_field tuple enum ignored_any byte_buf
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+ bytes map unit_struct newtype_struct tuple_struct struct struct_field
+ tuple enum ignored_any byte_buf
}
}
@@ -728,9 +727,9 @@ impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E>
type Error = E;
forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option bytes map unit_struct newtype_struct tuple_struct struct
- struct_field tuple enum ignored_any byte_buf
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+ bytes map unit_struct newtype_struct tuple_struct struct struct_field
+ tuple enum ignored_any byte_buf
}
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
@@ -872,9 +871,9 @@ impl<V_, E> de::Deserializer for MapVisitorDeserializer<V_, E>
}
forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any byte_buf
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+ seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
+ struct struct_field tuple enum ignored_any byte_buf
}
}
@@ -905,9 +904,9 @@ impl<'a, E> de::Deserializer for BytesDeserializer<'a, E>
}
forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any byte_buf
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+ seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
+ struct struct_field tuple enum ignored_any byte_buf
}
}
@@ -941,9 +940,9 @@ impl<E> de::Deserializer for ByteBufDeserializer<E>
}
forward_to_deserialize! {
- bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
- unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any byte_buf
+ bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+ seq seq_fixed_size bytes map unit_struct newtype_struct tuple_struct
+ struct struct_field tuple enum ignored_any byte_buf
}
}
diff --git a/serde/src/macros.rs b/serde/src/macros.rs
index 0a8416ac7..8050e8b59 100644
--- a/serde/src/macros.rs
+++ b/serde/src/macros.rs
@@ -32,9 +32,6 @@ macro_rules! forward_to_deserialize_helper {
(bool) => {
forward_to_deserialize_method!{deserialize_bool()}
};
- (usize) => {
- forward_to_deserialize_method!{deserialize_usize()}
- };
(u8) => {
forward_to_deserialize_method!{deserialize_u8()}
};
@@ -47,9 +44,6 @@ macro_rules! forward_to_deserialize_helper {
(u64) => {
forward_to_deserialize_method!{deserialize_u64()}
};
- (isize) => {
- forward_to_deserialize_method!{deserialize_isize()}
- };
(i8) => {
forward_to_deserialize_method!{deserialize_i8()}
};
@@ -154,9 +148,9 @@ macro_rules! forward_to_deserialize_helper {
/// self.deserialize(visitor)
/// }
/// # forward_to_deserialize! {
-/// # usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
-/// # unit option seq seq_fixed_size bytes byte_buf map unit_struct
-/// # newtype_struct tuple_struct struct struct_field tuple enum ignored_any
+/// # u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+/// # seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
+/// # tuple_struct struct struct_field tuple enum ignored_any
/// # }
/// # }
/// # fn main() {}
@@ -181,9 +175,9 @@ macro_rules! forward_to_deserialize_helper {
/// }
///
/// forward_to_deserialize! {
-/// bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str
-/// string unit option seq seq_fixed_size bytes byte_buf map unit_struct
-/// newtype_struct tuple_struct struct struct_field tuple enum ignored_any
+/// bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
+/// seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
+/// tuple_struct struct struct_field tuple enum ignored_any
/// }
/// }
/// # fn main() {}
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index c08f56ecc..5eb36c568 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -74,25 +74,25 @@ use super::Iterator;
///////////////////////////////////////////////////////////////////////////////
macro_rules! impl_visit {
- ($ty:ty, $method:ident) => {
+ ($ty:ty, $method:ident $($cast:tt)*) => {
impl Serialize for $ty {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
- serializer.$method(*self)
+ serializer.$method(*self $($cast)*)
}
}
}
}
impl_visit!(bool, serialize_bool);
-impl_visit!(isize, serialize_isize);
+impl_visit!(isize, serialize_i64 as i64);
impl_visit!(i8, serialize_i8);
impl_visit!(i16, serialize_i16);
impl_visit!(i32, serialize_i32);
impl_visit!(i64, serialize_i64);
-impl_visit!(usize, serialize_usize);
+impl_visit!(usize, serialize_u64 as u64);
impl_visit!(u8, serialize_u8);
impl_visit!(u16, serialize_u16);
impl_visit!(u32, serialize_u32);
diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs
index 1fa471148..e4df61b44 100644
--- a/serde/src/ser/mod.rs
+++ b/serde/src/ser/mod.rs
@@ -179,7 +179,7 @@ pub trait Serialize {
/// data structure supported by Serde.
///
/// The role of this trait is to define the serialization half of the Serde data
-/// model, which is a way to categorize every Rust data structure into one of 30
+/// model, which is a way to categorize every Rust data structure into one of 28
/// possible types. Each method of the `Serializer` trait corresponds to one of
/// the types of the data model.
///
@@ -188,13 +188,13 @@ pub trait Serialize {
///
/// The types that make up the Serde data model are:
///
-/// - 15 primitive types:
+/// - 12 primitive types:
/// - bool
-/// - isize, i8, i16, i32, i64
-/// - usize, u8, u16, u32, u64
+/// - i8, i16, i32, i64
+/// - u8, u16, u32, u64
/// - f32, f64
/// - char
-/// - string
+/// - string
/// - byte array - [u8]
/// - option
/// - either none or some value
@@ -279,13 +279,6 @@ pub trait Serializer {
/// Serialize a `bool` value.
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>;
- /// Serialize an `isize` value.
- ///
- /// If the format does not differentiate between `isize` and `i64`, a
- /// reasonable implementation would be to cast the value to `i64` and
- /// forward to `serialize_i64`.
- fn serialize_isize(self, v: isize) -> Result<Self::Ok, Self::Error>;
-
/// Serialize an `i8` value.
///
/// If the format does not differentiate between `i8` and `i64`, a
@@ -310,13 +303,6 @@ pub trait Serializer {
/// Serialize an `i64` value.
fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>;
- /// Serialize a `usize` value.
- ///
- /// If the format does not differentiate between `usize` and `u64`, a
- /// reasonable implementation would be to cast the value to `u64` and
- /// forward to `serialize_u64`.
- fn serialize_usize(self, v: usize) -> Result<Self::Ok, Self::Error>;
-
/// Serialize a `u8` value.
///
/// If the format does not differentiate between `u8` and `u64`, a
diff --git a/serde_codegen/src/de.rs b/serde_codegen/src/de.rs
index 65f4905c6..e73193b0f 100644
--- a/serde_codegen/src/de.rs
+++ b/serde_codegen/src/de.rs
@@ -692,11 +692,11 @@ fn deserialize_field_visitor(
Some(quote!(__ignore,))
};
- let visit_usize = if is_variant {
- let variant_indices = 0usize..;
+ let visit_index = if is_variant {
+ let variant_indices = 0u32..;
let fallthrough_msg = format!("variant index 0 <= i < {}", fields.len());
Some(quote! {
- fn visit_usize<__E>(self, value: usize) -> _serde::export::Result<__Field, __E>
+ fn visit_u32<__E>(self, value: u32) -> _serde::export::Result<__Field, __E>
where __E: _serde::de::Error
{
match value {
@@ -758,7 +758,7 @@ fn deserialize_field_visitor(
formatter.write_str("field name")
}
- #visit_usize
+ #visit_index
fn visit_str<__E>(self, value: &str) -> _serde::export::Result<__Field, __E>
where __E: _serde::de::Error
| serde-rs/serde | 2017-01-25T17:00:47Z | That would probably be better. Apparently we will never (for reasonable definitions of "never") get a `usize` that is bigger than 64 bits
@oli-obk how would you feel about squeezing this into 0.9?
One thing we still need to settle is the convention for deserializing enum variants by index, which currently uses usize. I guess `visit_u32`? | 8cb6607e827717136a819caa44d8e43702724883 |
716 | diff --git a/serde_derive/no-std-tests/Cargo.toml b/serde_derive/no-std-tests/Cargo.toml
index 432a962c7..ec5de0a34 100644
--- a/serde_derive/no-std-tests/Cargo.toml
+++ b/serde_derive/no-std-tests/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_derive_tests_no_std"
-version = "0.9.0-rc2"
+version = "0.9.0-rc3"
publish = false
[dependencies]
diff --git a/serde_test/Cargo.toml b/serde_test/Cargo.toml
index b4ea1c74e..cee7fe169 100644
--- a/serde_test/Cargo.toml
+++ b/serde_test/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_test"
-version = "0.9.0-rc2"
+version = "0.9.0-rc3"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Token De/Serializer for testing De/Serialize implementations"
@@ -12,4 +12,4 @@ keywords = ["serde", "serialization"]
include = ["Cargo.toml", "src/**/*.rs"]
[dependencies]
-serde = { version = "0.9.0-rc2", path = "../serde" }
+serde = { version = "0.9.0-rc3", path = "../serde" }
diff --git a/serde_test/src/ser.rs b/serde_test/src/ser.rs
index 60c501254..c97de428e 100644
--- a/serde_test/src/ser.rs
+++ b/serde_test/src/ser.rs
@@ -139,20 +139,20 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
Ok(())
}
- fn serialize_newtype_struct<T>(self,
- name: &'static str,
- value: T) -> Result<(), Error>
+ fn serialize_newtype_struct<T: ?Sized>(self,
+ name: &'static str,
+ value: &T) -> Result<(), Error>
where T: Serialize,
{
assert_eq!(self.tokens.next(), Some(&Token::StructNewType(name)));
value.serialize(self)
}
- fn serialize_newtype_variant<T>(self,
- name: &str,
- _variant_index: usize,
- variant: &str,
- value: T) -> Result<(), Error>
+ fn serialize_newtype_variant<T: ?Sized>(self,
+ name: &str,
+ _variant_index: usize,
+ variant: &str,
+ value: &T) -> Result<(), Error>
where T: Serialize,
{
assert_eq!(self.tokens.next(), Some(&Token::EnumNewType(name, variant)));
@@ -164,8 +164,8 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
Ok(())
}
- fn serialize_some<V>(self, value: V) -> Result<(), Error>
- where V: Serialize,
+ fn serialize_some<T: ?Sized>(self, value: &T) -> Result<(), Error>
+ where T: Serialize,
{
assert_eq!(self.tokens.next(), Some(&Token::Option(true)));
value.serialize(self)
@@ -228,7 +228,7 @@ impl<'s, 'a, I> ser::SerializeSeq for &'s mut Serializer<'a, I>
type Ok = ();
type Error = Error;
- fn serialize_element<T>(&mut self, value: T) -> Result<(), Error>
+ fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::SeqSep));
@@ -247,7 +247,7 @@ impl<'s, 'a, I> ser::SerializeTuple for &'s mut Serializer<'a, I>
type Ok = ();
type Error = Error;
- fn serialize_element<T>(&mut self, value: T) -> Result<(), Error>
+ fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::TupleSep));
@@ -266,7 +266,7 @@ impl<'s, 'a, I> ser::SerializeTupleStruct for &'s mut Serializer<'a, I>
type Ok = ();
type Error = Error;
- fn serialize_field<T>(&mut self, value: T) -> Result<(), Error>
+ fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::TupleStructSep));
@@ -285,7 +285,7 @@ impl<'s, 'a, I> ser::SerializeTupleVariant for &'s mut Serializer<'a, I>
type Ok = ();
type Error = Error;
- fn serialize_field<T>(&mut self, value: T) -> Result<(), Error>
+ fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::EnumSeqSep));
@@ -304,12 +304,12 @@ impl<'s, 'a, I> ser::SerializeMap for &'s mut Serializer<'a, I>
type Ok = ();
type Error = Error;
- fn serialize_key<T>(&mut self, key: T) -> Result<(), Self::Error> where T: Serialize {
+ fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error> where T: Serialize {
assert_eq!(self.tokens.next(), Some(&Token::MapSep));
key.serialize(&mut **self)
}
- fn serialize_value<T>(&mut self, value: T) -> Result<(), Self::Error> where T: Serialize {
+ fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize {
value.serialize(&mut **self)
}
@@ -325,7 +325,7 @@ impl<'s, 'a, I> ser::SerializeStruct for &'s mut Serializer<'a, I>
type Ok = ();
type Error = Error;
- fn serialize_field<V>(&mut self, key: &'static str, value: V) -> Result<(), Self::Error> where V: Serialize {
+ fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> where T: Serialize {
assert_eq!(self.tokens.next(), Some(&Token::StructSep));
try!(key.serialize(&mut **self));
value.serialize(&mut **self)
@@ -343,7 +343,7 @@ impl<'s, 'a, I> ser::SerializeStructVariant for &'s mut Serializer<'a, I>
type Ok = ();
type Error = Error;
- fn serialize_field<V>(&mut self, key: &'static str, value: V) -> Result<(), Self::Error> where V: Serialize {
+ fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> where T: Serialize {
assert_eq!(self.tokens.next(), Some(&Token::EnumMapSep));
try!(key.serialize(&mut **self));
value.serialize(&mut **self)
diff --git a/testing/Cargo.toml b/testing/Cargo.toml
index b592a2143..9088a779b 100644
--- a/testing/Cargo.toml
+++ b/testing/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_testing"
-version = "0.9.0-rc2"
+version = "0.9.0-rc3"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "A generic serialization/deserialization framework"
| [
"467"
] | serde-rs__serde-716 | Serializer methods with `T: Serialize` arguments would make more sense as `&T`
From @sfackler in IRC:
> the signatures of methods implies things about how they're expected to be used. If a method takes something by value, I'm going to assume it needs ownership of the value, and I can only find that the "normal" intent is to pass by reference if I find that forwarding implementation buried in the pile of 100 or however many there are in rustdoc
(the forwarding implementation is `impl<'a, T: ?Sized> Serialize for &'a T where T: Serialize`)
| null | b9d865d8e7ee61a0578db0301dd3a933af695019 | diff --git a/serde/Cargo.toml b/serde/Cargo.toml
index a57ff9543..175f0c635 100644
--- a/serde/Cargo.toml
+++ b/serde/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde"
-version = "0.9.0-rc2"
+version = "0.9.0-rc3"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "A generic serialization/deserialization framework"
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index 257893566..734337e95 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -247,7 +247,7 @@ impl<'a, I> Serialize for Iterator<I>
};
let mut seq = try!(serializer.serialize_seq(size));
for e in iter {
- try!(seq.serialize_element(e));
+ try!(seq.serialize_element(&e));
}
seq.end()
}
@@ -263,7 +263,7 @@ macro_rules! serialize_seq {
{
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
for e in self {
- try!(seq.serialize_element(e));
+ try!(seq.serialize_element(&e));
}
seq.end()
}
@@ -331,7 +331,7 @@ impl<A> Serialize for ops::Range<A>
{
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
for e in self.clone() {
- try!(seq.serialize_element(e));
+ try!(seq.serialize_element(&e));
}
seq.end()
}
@@ -348,7 +348,7 @@ impl<A> Serialize for ops::RangeInclusive<A>
{
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
for e in self.clone() {
- try!(seq.serialize_element(e));
+ try!(seq.serialize_element(&e));
}
seq.end()
}
@@ -696,8 +696,8 @@ impl Serialize for Duration {
{
use super::SerializeStruct;
let mut state = try!(serializer.serialize_struct("Duration", 2));
- try!(state.serialize_field("secs", self.as_secs()));
- try!(state.serialize_field("nanos", self.subsec_nanos()));
+ try!(state.serialize_field("secs", &self.as_secs()));
+ try!(state.serialize_field("nanos", &self.subsec_nanos()));
state.end()
}
}
diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs
index 4131f0b2b..f755579dd 100644
--- a/serde/src/ser/mod.rs
+++ b/serde/src/ser/mod.rs
@@ -200,30 +200,30 @@ pub trait Serializer {
/// struct, to be more efficiently serialized than a tuple struct with
/// multiple items. A reasonable implementation would be to forward to
/// `serialize_tuple_struct` or to just serialize the inner value without wrapping.
- fn serialize_newtype_struct<T: Serialize>(
+ fn serialize_newtype_struct<T: ?Sized + Serialize>(
self,
name: &'static str,
- value: T,
+ value: &T,
) -> Result<Self::Ok, Self::Error>;
/// Allows a variant with a single item to be more efficiently serialized
/// than a variant with multiple items. A reasonable implementation would be
/// to forward to `serialize_tuple_variant`.
- fn serialize_newtype_variant<T: Serialize>(
+ fn serialize_newtype_variant<T: ?Sized + Serialize>(
self,
name: &'static str,
variant_index: usize,
variant: &'static str,
- value: T,
+ value: &T,
) -> Result<Self::Ok, Self::Error>;
/// Serializes a `None` value.
fn serialize_none(self) -> Result<Self::Ok, Self::Error>;
/// Serializes a `Some(...)` value.
- fn serialize_some<T: Serialize>(
+ fn serialize_some<T: ?Sized + Serialize>(
self,
- value: T,
+ value: &T,
) -> Result<Self::Ok, Self::Error>;
/// Begins to serialize a sequence. This call must be followed by zero or
@@ -311,7 +311,7 @@ pub trait SerializeSeq {
type Error: Error;
/// Serializes a sequence element.
- fn serialize_element<T: Serialize>(&mut self, value: T) -> Result<(), Self::Error>;
+ fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
/// Finishes serializing a sequence.
fn end(self) -> Result<Self::Ok, Self::Error>;
@@ -327,7 +327,7 @@ pub trait SerializeTuple {
type Error: Error;
/// Serializes a tuple element.
- fn serialize_element<T: Serialize>(&mut self, value: T) -> Result<(), Self::Error>;
+ fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
/// Finishes serializing a tuple.
fn end(self) -> Result<Self::Ok, Self::Error>;
@@ -343,7 +343,7 @@ pub trait SerializeTupleStruct {
type Error: Error;
/// Serializes a tuple struct element.
- fn serialize_field<T: Serialize>(&mut self, value: T) -> Result<(), Self::Error>;
+ fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
/// Finishes serializing a tuple struct.
fn end(self) -> Result<Self::Ok, Self::Error>;
@@ -359,7 +359,7 @@ pub trait SerializeTupleVariant {
type Error: Error;
/// Serializes a tuple variant element.
- fn serialize_field<T: Serialize>(&mut self, value: T) -> Result<(), Self::Error>;
+ fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
/// Finishes serializing a tuple variant.
fn end(self) -> Result<Self::Ok, Self::Error>;
@@ -375,10 +375,10 @@ pub trait SerializeMap {
type Error: Error;
/// Serialize a map key.
- fn serialize_key<T: Serialize>(&mut self, key: T) -> Result<(), Self::Error>;
+ fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), Self::Error>;
/// Serialize a map value.
- fn serialize_value<T: Serialize>(&mut self, value: T) -> Result<(), Self::Error>;
+ fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error>;
/// Finishes serializing a map.
fn end(self) -> Result<Self::Ok, Self::Error>;
@@ -394,7 +394,7 @@ pub trait SerializeStruct {
type Error: Error;
/// Serializes a struct field.
- fn serialize_field<V: Serialize>(&mut self, key: &'static str, value: V) -> Result<(), Self::Error>;
+ fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>;
/// Finishes serializing a struct.
fn end(self) -> Result<Self::Ok, Self::Error>;
@@ -410,7 +410,7 @@ pub trait SerializeStructVariant {
type Error: Error;
/// Serialize a struct variant element.
- fn serialize_field<V: Serialize>(&mut self, key: &'static str, value: V) -> Result<(), Self::Error>;
+ fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>;
/// Finishes serializing a struct variant.
fn end(self) -> Result<Self::Ok, Self::Error>;
diff --git a/serde_codegen/Cargo.toml b/serde_codegen/Cargo.toml
index 6161e373e..a8e5a5414 100644
--- a/serde_codegen/Cargo.toml
+++ b/serde_codegen/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_codegen"
-version = "0.9.0-rc2"
+version = "0.9.0-rc3"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Macros to auto-generate implementations for the serde framework"
diff --git a/serde_codegen/src/ser.rs b/serde_codegen/src/ser.rs
index ae3a6c7fa..c8efe1afa 100644
--- a/serde_codegen/src/ser.rs
+++ b/serde_codegen/src/ser.rs
@@ -548,7 +548,7 @@ fn wrap_serialize_with(
}
}
- __SerializeWith {
+ &__SerializeWith {
value: #value,
phantom: ::std::marker::PhantomData::<#item_ty>,
}
diff --git a/serde_derive/Cargo.toml b/serde_derive/Cargo.toml
index ddc3f62f8..3b3171cb6 100644
--- a/serde_derive/Cargo.toml
+++ b/serde_derive/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_derive"
-version = "0.9.0-rc2"
+version = "0.9.0-rc3"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]"
@@ -15,7 +15,7 @@ name = "serde_derive"
proc-macro = true
[dependencies.serde_codegen]
-version = "=0.9.0-rc2"
+version = "=0.9.0-rc3"
path = "../serde_codegen"
default-features = false
features = ["with-syn"]
@@ -23,5 +23,5 @@ features = ["with-syn"]
[dev-dependencies]
compiletest_rs = "^0.2.0"
fnv = "1.0"
-serde = { version = "0.9.0-rc2", path = "../serde" }
-serde_test = { version = "0.9.0-rc2", path = "../serde_test" }
+serde = { version = "0.9.0-rc3", path = "../serde" }
+serde_test = { version = "0.9.0-rc3", path = "../serde_test" }
| serde-rs/serde | 2017-01-24T00:53:01Z | This was the response in IRC:
> **\<erickt>** It possibly takes things by value because it'll let you potentially serialize some value without a copy
> **\<sfackler>** ah that makes sense
@erickt do you have an example of this? Serialize::serialize is defined on &self so I'm not sure where it would avoid a copy.
The same question applies to `serde_json::to_*`, for example [`to_writer`](https://docs.serde.rs/serde_json/ser/fn.to_writer.html). Those currently take &T which is inconsistent with the Serializer methods taking T.
It would only make sense for serializing to `json::Value` or similar types. It's probably not worth the effort, but strictly more powerful for the future. My slight preference is thus to move everything to by val.
I have tried to implement #571 with a wrapper type, but it's not possible without some `RefCell<Option<T>>` dance, because to iterate over an iterator, you need mutable access to the iterator. If we moved `Serialize::serialize` to take `self` by value and suggest that users implement it for `&'a TheirType` then we could do it without any `RefCell` code.
I'll try other workarounds, maybe this is unnecessary, it seems inelegant to me.
The backend has moved to by value. So now this is mainly a question of how the helper functions of specific serializers expose it.
We still need to evaluate these methods:
- `Serializer::serialize_newtype_struct`
- `Serializer::serialize_newtype_variant`
- `Serializer::serialize_some`
- `SerializeSeq::serialize_element`
- `SerializeTuple::serialize_element`
- `SerializeTupleStruct::serialize_field`
- `SerializeTupleVariant::serialize_field`
- `SerializeMap::serialize_key`
- `SerializeMap::serialize_value`
- `SerializeStruct::serialize_field`
- `SerializeStructVariant::serialize_field`
All of those currently take T by value which is inconsistent with Serialize taking Self by reference. I think I am still in favor of updating it all to be &T.
Gah, neither solution is obviously better. I don't think we should spend more time on this. The current approach is decent and consistent enough.
If we are not moving to changing `Serialize::serialize` to take the argument by value, we should move all functions to by ref and remove the impl for references.
The only advantage of moving to values is wrapper helpers not requiring any runtime checks. | 8cb6607e827717136a819caa44d8e43702724883 |
715 | diff --git a/serde_derive/no-std-tests/Cargo.toml b/serde_derive/no-std-tests/Cargo.toml
new file mode 100644
index 000000000..432a962c7
--- /dev/null
+++ b/serde_derive/no-std-tests/Cargo.toml
@@ -0,0 +1,8 @@
+[package]
+name = "serde_derive_tests_no_std"
+version = "0.9.0-rc2"
+publish = false
+
+[dependencies]
+serde = { path = "../../serde", default-features = false }
+serde_derive = { path = ".." }
diff --git a/serde_derive/no-std-tests/src/main.rs b/serde_derive/no-std-tests/src/main.rs
new file mode 100644
index 000000000..5eae52672
--- /dev/null
+++ b/serde_derive/no-std-tests/src/main.rs
@@ -0,0 +1,50 @@
+#![feature(lang_items, start, libc)]
+#![no_std]
+
+extern crate libc;
+
+#[start]
+fn start(_argc: isize, _argv: *const *const u8) -> isize {
+ 0
+}
+
+#[lang = "eh_personality"]
+#[no_mangle]
+pub extern fn rust_eh_personality() {}
+
+#[lang = "eh_unwind_resume"]
+#[no_mangle]
+pub extern fn rust_eh_unwind_resume() {}
+
+#[lang = "panic_fmt"]
+#[no_mangle]
+pub extern fn rust_begin_panic(_msg: core::fmt::Arguments,
+ _file: &'static str,
+ _line: u32) -> ! {
+ loop {}
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize, Deserialize)]
+struct Unit;
+
+#[derive(Serialize, Deserialize)]
+struct Newtype(u8);
+
+#[derive(Serialize, Deserialize)]
+struct Tuple(u8, u8);
+
+#[derive(Serialize, Deserialize)]
+struct Struct { f: u8 }
+
+#[derive(Serialize, Deserialize)]
+enum Enum {
+ Unit,
+ Newtype(u8),
+ Tuple(u8, u8),
+ Struct { f: u8 },
+}
| [
"666"
] | serde-rs__serde-715 | Use serde_derive with no_std
```rust
#![no_std]
#[macro_use]
extern crate serde_derive;
#[derive(Serialize, Deserialize)]
struct S;
```
```
error[E0433]: failed to resolve. Maybe a missing `extern crate std;`?
--> src/lib.rs:6:21
|
6 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^ Maybe a missing `extern crate std;`?
error[E0433]: failed to resolve. Maybe a missing `extern crate std;`?
--> src/lib.rs:6:21
|
6 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^ Maybe a missing `extern crate std;`?
error[E0433]: failed to resolve. Maybe a missing `extern crate std;`?
--> src/lib.rs:6:21
|
6 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^ Maybe a missing `extern crate std;`?
error[E0433]: failed to resolve. Maybe a missing `extern crate std;`?
--> src/lib.rs:6:10
|
6 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^ Maybe a missing `extern crate std;`?
error: aborting due to 4 previous errors
```
The culprit is `::std::result::Result`. We can get around it by reexporting Result as serde::Result and generating code against that.
| null | a982d275369f3c8949026f7d3b540ca9f1cae6ba | diff --git a/.travis.yml b/.travis.yml
index 729796b5b..ea9e7fe83 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -18,6 +18,7 @@ script:
- (cd testing && travis-cargo --skip nightly test)
- (cd testing && travis-cargo --only nightly test -- --features unstable-testing)
- (cd serde_derive && travis-cargo --only nightly test)
+- (cd serde_derive/no-std-tests && travis-cargo --only nightly build)
#- (cd examples/serde-syntex-example && travis-cargo --skip nightly run)
#- (cd examples/serde-syntex-example && travis-cargo --only nightly run -- --no-default-features --features unstable)
- (cd serde && travis-cargo --only stable doc)
diff --git a/serde/src/export.rs b/serde/src/export.rs
new file mode 100644
index 000000000..61c9ba67c
--- /dev/null
+++ b/serde/src/export.rs
@@ -0,0 +1,33 @@
+#[cfg(all(feature = "collections", not(feature = "std")))]
+use collections::String;
+
+#[cfg(feature = "std")]
+use std::borrow::Cow;
+#[cfg(all(feature = "collections", not(feature = "std")))]
+use collections::borrow::Cow;
+
+pub use core::default::Default;
+pub use core::fmt;
+pub use core::marker::PhantomData;
+pub use core::result::Result;
+
+#[cfg(any(feature = "collections", feature = "std"))]
+pub fn from_utf8_lossy(bytes: &[u8]) -> Cow<str> {
+ String::from_utf8_lossy(bytes)
+}
+
+// The generated code calls this like:
+//
+// let value = &_serde::export::from_utf8_lossy(bytes);
+// Err(_serde::de::Error::unknown_variant(value, VARIANTS))
+//
+// so it is okay for the return type to be different from the std case as long
+// as the above works.
+#[cfg(not(any(feature = "collections", feature = "std")))]
+pub fn from_utf8_lossy(bytes: &[u8]) -> &str {
+ use core::str;
+ // Three unicode replacement characters if it fails. They look like a
+ // white-on-black question mark. The user will recognize it as invalid
+ // UTF-8.
+ str::from_utf8(bytes).unwrap_or("\u{fffd}\u{fffd}\u{fffd}")
+}
diff --git a/serde/src/lib.rs b/serde/src/lib.rs
index 093fa2860..77a04932d 100644
--- a/serde/src/lib.rs
+++ b/serde/src/lib.rs
@@ -31,7 +31,7 @@ extern crate core as actual_core;
#[cfg(feature = "std")]
mod core {
pub use std::{ops, hash, fmt, cmp, marker, mem, i8, i16, i32, i64, u8, u16, u32, u64, isize,
- usize, f32, f64, char, str, num, slice, iter, cell};
+ usize, f32, f64, char, str, num, slice, iter, cell, default, result};
#[cfg(feature = "unstable")]
pub use actual_core::nonzero;
}
@@ -50,3 +50,7 @@ pub mod ser;
#[cfg_attr(feature = "std", doc(hidden))]
pub mod error;
mod utils;
+
+// Generated code uses these to support no_std. Not public API.
+#[doc(hidden)]
+pub mod export;
diff --git a/serde_codegen/src/de.rs b/serde_codegen/src/de.rs
index eda81859b..65f4905c6 100644
--- a/serde_codegen/src/de.rs
+++ b/serde_codegen/src/de.rs
@@ -36,7 +36,7 @@ pub fn expand_derive_deserialize(item: &syn::MacroInput) -> Result<Tokens, Strin
extern crate serde as _serde;
#[automatically_derived]
impl #impl_generics _serde::Deserialize for #ty #where_clause {
- fn deserialize<__D>(deserializer: __D) -> ::std::result::Result<#ty, __D::Error>
+ fn deserialize<__D>(deserializer: __D) -> _serde::export::Result<#ty, __D::Error>
where __D: _serde::Deserializer
#body
}
@@ -158,11 +158,11 @@ fn deserialize_visitor(generics: &syn::Generics) -> (Tokens, Tokens, Tokens) {
let phantom_types = generics.lifetimes.iter()
.map(|lifetime_def| {
let lifetime = &lifetime_def.lifetime;
- quote!(::std::marker::PhantomData<& #lifetime ()>)
+ quote!(_serde::export::PhantomData<& #lifetime ()>)
}).chain(generics.ty_params.iter()
.map(|ty_param| {
let ident = &ty_param.ident;
- quote!(::std::marker::PhantomData<#ident>)
+ quote!(_serde::export::PhantomData<#ident>)
}));
let all_params = generics.lifetimes.iter()
@@ -182,7 +182,7 @@ fn deserialize_visitor(generics: &syn::Generics) -> (Tokens, Tokens, Tokens) {
Some(quote!(::<#(#ty_param_idents),*>))
};
- let phantom_exprs = iter::repeat(quote!(::std::marker::PhantomData)).take(num_phantoms);
+ let phantom_exprs = iter::repeat(quote!(_serde::export::PhantomData)).take(num_phantoms);
(
quote! {
@@ -208,19 +208,19 @@ fn deserialize_unit_struct(
impl _serde::de::Visitor for __Visitor {
type Value = #type_ident;
- fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+ fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
formatter.write_str(#expecting)
}
#[inline]
- fn visit_unit<__E>(self) -> ::std::result::Result<#type_ident, __E>
+ fn visit_unit<__E>(self) -> _serde::export::Result<#type_ident, __E>
where __E: _serde::de::Error,
{
Ok(#type_ident)
}
#[inline]
- fn visit_seq<__V>(self, _: __V) -> ::std::result::Result<#type_ident, __V::Error>
+ fn visit_seq<__V>(self, _: __V) -> _serde::export::Result<#type_ident, __V::Error>
where __V: _serde::de::SeqVisitor,
{
Ok(#type_ident)
@@ -297,14 +297,14 @@ fn deserialize_tuple(
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
type Value = #ty;
- fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+ fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
formatter.write_str(#expecting)
}
#visit_newtype_struct
#[inline]
- fn visit_seq<__V>(self, #visitor_var: __V) -> ::std::result::Result<#ty, __V::Error>
+ fn visit_seq<__V>(self, #visitor_var: __V) -> _serde::export::Result<#ty, __V::Error>
where __V: _serde::de::SeqVisitor
{
#visit_seq
@@ -408,7 +408,7 @@ fn deserialize_newtype_struct(
};
quote! {
#[inline]
- fn visit_newtype_struct<__E>(self, __e: __E) -> ::std::result::Result<Self::Value, __E::Error>
+ fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::export::Result<Self::Value, __E::Error>
where __E: _serde::Deserializer,
{
Ok(#type_path(#value))
@@ -480,19 +480,19 @@ fn deserialize_struct(
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
type Value = #ty;
- fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+ fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
formatter.write_str(#expecting)
}
#[inline]
- fn visit_seq<__V>(self, #visitor_var: __V) -> ::std::result::Result<#ty, __V::Error>
+ fn visit_seq<__V>(self, #visitor_var: __V) -> _serde::export::Result<#ty, __V::Error>
where __V: _serde::de::SeqVisitor
{
#visit_seq
}
#[inline]
- fn visit_map<__V>(self, mut visitor: __V) -> ::std::result::Result<#ty, __V::Error>
+ fn visit_map<__V>(self, mut visitor: __V) -> _serde::export::Result<#ty, __V::Error>
where __V: _serde::de::MapVisitor
{
#visit_map
@@ -585,11 +585,11 @@ fn deserialize_item_enum(
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
type Value = #ty;
- fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+ fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
formatter.write_str(#expecting)
}
- fn visit_enum<__V>(self, visitor: __V) -> ::std::result::Result<#ty, __V::Error>
+ fn visit_enum<__V>(self, visitor: __V) -> _serde::export::Result<#ty, __V::Error>
where __V: _serde::de::EnumVisitor,
{
#match_variant
@@ -696,7 +696,7 @@ fn deserialize_field_visitor(
let variant_indices = 0usize..;
let fallthrough_msg = format!("variant index 0 <= i < {}", fields.len());
Some(quote! {
- fn visit_usize<__E>(self, value: usize) -> ::std::result::Result<__Field, __E>
+ fn visit_usize<__E>(self, value: usize) -> _serde::export::Result<__Field, __E>
where __E: _serde::de::Error
{
match value {
@@ -731,7 +731,7 @@ fn deserialize_field_visitor(
Some(quote! {
// TODO https://github.com/serde-rs/serde/issues/666
// update this to use str::from_utf8(value).unwrap_or("���") on no_std
- let value = &::std::string::String::from_utf8_lossy(value);
+ let value = &_serde::export::from_utf8_lossy(value);
})
} else {
None
@@ -746,7 +746,7 @@ fn deserialize_field_visitor(
impl _serde::Deserialize for __Field {
#[inline]
- fn deserialize<__D>(deserializer: __D) -> ::std::result::Result<__Field, __D::Error>
+ fn deserialize<__D>(deserializer: __D) -> _serde::export::Result<__Field, __D::Error>
where __D: _serde::Deserializer,
{
struct __FieldVisitor;
@@ -754,13 +754,13 @@ fn deserialize_field_visitor(
impl _serde::de::Visitor for __FieldVisitor {
type Value = __Field;
- fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+ fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
formatter.write_str("field name")
}
#visit_usize
- fn visit_str<__E>(self, value: &str) -> ::std::result::Result<__Field, __E>
+ fn visit_str<__E>(self, value: &str) -> _serde::export::Result<__Field, __E>
where __E: _serde::de::Error
{
match value {
@@ -771,7 +771,7 @@ fn deserialize_field_visitor(
}
}
- fn visit_bytes<__E>(self, value: &[u8]) -> ::std::result::Result<__Field, __E>
+ fn visit_bytes<__E>(self, value: &[u8]) -> _serde::export::Result<__Field, __E>
where __E: _serde::de::Error
{
match value {
@@ -981,18 +981,18 @@ fn wrap_deserialize_with(
quote! {
struct __SerdeDeserializeWithStruct #impl_generics #where_clause {
value: #field_ty,
- phantom: ::std::marker::PhantomData<#phantom_ty>,
+ phantom: _serde::export::PhantomData<#phantom_ty>,
}
},
quote! {
impl #impl_generics _serde::Deserialize for #wrapper_ty #where_clause {
- fn deserialize<__D>(__d: __D) -> ::std::result::Result<Self, __D::Error>
+ fn deserialize<__D>(__d: __D) -> _serde::export::Result<Self, __D::Error>
where __D: _serde::Deserializer
{
let value = try!(#deserialize_with(__d));
Ok(__SerdeDeserializeWithStruct {
value: value,
- phantom: ::std::marker::PhantomData,
+ phantom: _serde::export::PhantomData,
})
}
}
@@ -1004,7 +1004,7 @@ fn wrap_deserialize_with(
fn expr_is_missing(attrs: &attr::Field) -> Tokens {
match *attrs.default() {
attr::FieldDefault::Default => {
- return quote!(::std::default::Default::default());
+ return quote!(_serde::export::Default::default());
}
attr::FieldDefault::Path(ref path) => {
return quote!(#path());
diff --git a/serde_codegen/src/ser.rs b/serde_codegen/src/ser.rs
index 3374d5acf..ae3a6c7fa 100644
--- a/serde_codegen/src/ser.rs
+++ b/serde_codegen/src/ser.rs
@@ -30,7 +30,7 @@ pub fn expand_derive_serialize(item: &syn::MacroInput) -> Result<Tokens, String>
extern crate serde as _serde;
#[automatically_derived]
impl #impl_generics _serde::Serialize for #ty #where_clause {
- fn serialize<__S>(&self, _serializer: __S) -> ::std::result::Result<__S::Ok, __S::Error>
+ fn serialize<__S>(&self, _serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error>
where __S: _serde::Serializer
{
#body
@@ -541,7 +541,7 @@ fn wrap_serialize_with(
}
impl #wrapper_generics _serde::Serialize for #wrapper_ty #where_clause {
- fn serialize<__S>(&self, __s: __S) -> ::std::result::Result<__S::Ok, __S::Error>
+ fn serialize<__S>(&self, __s: __S) -> _serde::export::Result<__S::Ok, __S::Error>
where __S: _serde::Serializer
{
#path(self.value, __s)
| serde-rs/serde | 2017-01-24T00:04:38Z | This line is the only thing causing trouble: [`serde_codegen/src/de.rs#L729`](https://github.com/serde-rs/serde/blob/v0.8.21/serde_codegen/src/de.rs#L729)
I filed https://github.com/serde-rs/serde/issues/667 to eliminate the obstacle.
A hack of a workaround:
```rust
mod std {
pub use core::*;
pub mod string {
pub struct String;
impl String {
pub fn from_utf8_lossy(_value: &[u8]) -> &'static str {
""
}
}
}
}
``` | 8cb6607e827717136a819caa44d8e43702724883 |
710 | diff --git a/serde_test/Cargo.toml b/serde_test/Cargo.toml
index de037b79e..b4ea1c74e 100644
--- a/serde_test/Cargo.toml
+++ b/serde_test/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_test"
-version = "0.9.0-rc1"
+version = "0.9.0-rc2"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Token De/Serializer for testing De/Serialize implementations"
@@ -12,4 +12,4 @@ keywords = ["serde", "serialization"]
include = ["Cargo.toml", "src/**/*.rs"]
[dependencies]
-serde = { version = "0.9.0-rc1", path = "../serde" }
+serde = { version = "0.9.0-rc2", path = "../serde" }
diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index 3630d7247..fc29ccd94 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -43,7 +43,7 @@ impl<I> Deserializer<I>
Err(Error::UnexpectedToken(token))
}
}
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -259,7 +259,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
Some(Token::Option(false)) => visitor.visit_none(),
Some(Token::Option(true)) => visitor.visit_some(self),
Some(Token::Unit) => visitor.visit_unit(),
- Some(Token::UnitStruct(name)) => visitor.visit_unit_struct(name),
+ Some(Token::UnitStruct(_name)) => visitor.visit_unit(),
Some(Token::SeqStart(len)) => {
self.visit_seq(len, visitor)
}
@@ -273,7 +273,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
self.visit_map(Some(len), visitor)
}
Some(token) => Err(Error::UnexpectedToken(token)),
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -296,7 +296,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
visitor.visit_none()
}
Some(_) => visitor.visit_some(self),
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -326,7 +326,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
let token = self.tokens.next().unwrap();
Err(Error::UnexpectedToken(token))
}
- None => { return Err(Error::EndOfStream); }
+ None => { return Err(Error::EndOfTokens); }
}
}
@@ -343,7 +343,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
}
}
Some(_) => self.deserialize(visitor),
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -362,7 +362,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
}
}
Some(_) => self.deserialize(visitor),
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -377,7 +377,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
self.visit_array(len, visitor)
}
Some(_) => self.deserialize(visitor),
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -412,7 +412,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
self.visit_tuple_struct(len, visitor)
}
Some(_) => self.deserialize(visitor),
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -456,7 +456,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
}
}
Some(_) => self.deserialize(visitor),
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -480,7 +480,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
self.visit_map(Some(fields.len()), visitor)
}
Some(_) => self.deserialize(visitor),
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
}
@@ -511,7 +511,7 @@ impl<'a, I> SeqVisitor for DeserializerSeqVisitor<'a, I>
let token = self.de.tokens.next().unwrap();
Err(Error::UnexpectedToken(token))
}
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -547,7 +547,7 @@ impl<'a, I> SeqVisitor for DeserializerArrayVisitor<'a, I>
let token = self.de.tokens.next().unwrap();
Err(Error::UnexpectedToken(token))
}
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -582,7 +582,7 @@ impl<'a, I> SeqVisitor for DeserializerTupleVisitor<'a, I>
let token = self.de.tokens.next().unwrap();
Err(Error::UnexpectedToken(token))
}
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -617,7 +617,7 @@ impl<'a, I> SeqVisitor for DeserializerTupleStructVisitor<'a, I>
let token = self.de.tokens.next().unwrap();
Err(Error::UnexpectedToken(token))
}
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -652,7 +652,7 @@ impl<'a, I> SeqVisitor for DeserializerVariantSeqVisitor<'a, I>
let token = self.de.tokens.next().unwrap();
Err(Error::UnexpectedToken(token))
}
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -688,7 +688,7 @@ impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
let token = self.de.tokens.next().unwrap();
Err(Error::UnexpectedToken(token))
}
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -730,7 +730,7 @@ impl<'a, I> MapVisitor for DeserializerStructVisitor<'a, I>
let token = self.de.tokens.next().unwrap();
Err(Error::UnexpectedToken(token))
}
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -773,7 +773,7 @@ impl<'a, I> EnumVisitor for DeserializerEnumVisitor<'a, I>
let value = try!(seed.deserialize(&mut *self.de));
Ok((value, self))
}
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
}
@@ -792,7 +792,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
Some(_) => {
Deserialize::deserialize(self.de)
}
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -807,7 +807,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
Some(_) => {
seed.deserialize(self.de)
}
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -838,7 +838,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
Some(_) => {
de::Deserializer::deserialize(self.de, visitor)
}
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
@@ -869,7 +869,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
Some(_) => {
de::Deserializer::deserialize(self.de, visitor)
}
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
}
@@ -900,7 +900,7 @@ impl<'a, I> MapVisitor for DeserializerVariantMapVisitor<'a, I>
let token = self.de.tokens.next().unwrap();
Err(Error::UnexpectedToken(token))
}
- None => Err(Error::EndOfStream),
+ None => Err(Error::EndOfTokens),
}
}
diff --git a/serde_test/src/error.rs b/serde_test/src/error.rs
index d5c4c6e72..a09252ab2 100644
--- a/serde_test/src/error.rs
+++ b/serde_test/src/error.rs
@@ -1,4 +1,5 @@
-use std::{error, fmt};
+use std::error;
+use std::fmt::{self, Display};
use serde::{ser, de};
@@ -6,82 +7,42 @@ use token::Token;
#[derive(Clone, PartialEq, Debug)]
pub enum Error {
- // Shared
- Custom(String),
- InvalidValue(String),
-
- // De
- EndOfStream,
- InvalidType(de::Type),
- InvalidLength(usize),
- UnknownVariant(String),
- UnknownField(String),
- MissingField(&'static str),
- DuplicateField(&'static str),
+ Message(String),
InvalidName(&'static str),
UnexpectedToken(Token<'static>),
+ EndOfTokens,
}
impl ser::Error for Error {
- fn custom<T: Into<String>>(msg: T) -> Error {
- Error::Custom(msg.into())
- }
-
- fn invalid_value(msg: &str) -> Error {
- Error::InvalidValue(msg.to_owned())
+ fn custom<T: Display>(msg: T) -> Error {
+ Error::Message(msg.to_string())
}
}
impl de::Error for Error {
- fn custom<T: Into<String>>(msg: T) -> Error {
- Error::Custom(msg.into())
- }
-
- fn end_of_stream() -> Error {
- Error::EndOfStream
- }
-
- fn invalid_type(ty: de::Type) -> Error {
- Error::InvalidType(ty)
- }
-
- fn invalid_value(msg: &str) -> Error {
- Error::InvalidValue(msg.to_owned())
- }
-
- fn invalid_length(len: usize) -> Error {
- Error::InvalidLength(len)
- }
-
- fn unknown_variant(variant: &str) -> Error {
- Error::UnknownVariant(variant.to_owned())
- }
-
- fn unknown_field(field: &str) -> Error {
- Error::UnknownField(field.to_owned())
- }
-
- fn missing_field(field: &'static str) -> Error {
- Error::MissingField(field)
- }
-
- fn duplicate_field(field: &'static str) -> Error {
- Error::DuplicateField(field)
+ fn custom<T: Display>(msg: T) -> Error {
+ Error::Message(msg.to_string())
}
}
impl fmt::Display for Error {
- fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
- formatter.write_str(format!("{:?}", self).as_ref())
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ match *self {
+ Error::Message(ref msg) => formatter.write_str(msg),
+ Error::InvalidName(name) => write!(formatter, "invalid name `{}`", name),
+ Error::UnexpectedToken(_) => formatter.write_str("unexpected token"),
+ Error::EndOfTokens => formatter.write_str("end of tokens"),
+ }
}
}
impl error::Error for Error {
fn description(&self) -> &str {
- "Serde Error"
- }
-
- fn cause(&self) -> Option<&error::Error> {
- None
+ match *self {
+ Error::Message(ref msg) => msg,
+ Error::InvalidName(_) => "invalid name",
+ Error::UnexpectedToken(_) => "unexpected token",
+ Error::EndOfTokens => "end of tokens",
+ }
}
}
diff --git a/testing/Cargo.toml b/testing/Cargo.toml
index 7a31c31ed..b592a2143 100644
--- a/testing/Cargo.toml
+++ b/testing/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_testing"
-version = "0.9.0-rc1"
+version = "0.9.0-rc2"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "A generic serialization/deserialization framework"
diff --git a/testing/tests/test_annotations.rs b/testing/tests/test_annotations.rs
index e17741223..7df8bb1c7 100644
--- a/testing/tests/test_annotations.rs
+++ b/testing/tests/test_annotations.rs
@@ -343,7 +343,7 @@ fn test_ignore_unknown() {
Token::StructSep,
Token::Str("whoops"),
],
- Error::UnknownField("whoops".to_owned())
+ Error::Message("unknown field `whoops`, expected `a1`".to_owned())
);
}
@@ -905,7 +905,7 @@ fn test_missing_renamed_field_struct() {
Token::StructEnd,
],
- Error::MissingField("a3"),
+ Error::Message("missing field `a3`".to_owned()),
);
assert_de_tokens_error::<RenameStructSerializeDeserialize>(
@@ -918,7 +918,7 @@ fn test_missing_renamed_field_struct() {
Token::StructEnd,
],
- Error::MissingField("a5"),
+ Error::Message("missing field `a5`".to_owned()),
);
}
@@ -930,7 +930,7 @@ fn test_missing_renamed_field_enum() {
Token::EnumMapEnd,
],
- Error::MissingField("b"),
+ Error::Message("missing field `b`".to_owned()),
);
assert_de_tokens_error::<RenameEnumSerializeDeserialize<i8>>(
@@ -943,7 +943,7 @@ fn test_missing_renamed_field_enum() {
Token::EnumMapEnd,
],
- Error::MissingField("d"),
+ Error::Message("missing field `d`".to_owned()),
);
}
@@ -962,7 +962,7 @@ fn test_invalid_length_enum() {
Token::I32(1),
Token::EnumSeqEnd,
],
- Error::InvalidLength(1),
+ Error::Message("invalid length 1, expected tuple of 3 elements".to_owned()),
);
assert_de_tokens_error::<InvalidLengthEnum>(
&[
@@ -971,6 +971,6 @@ fn test_invalid_length_enum() {
Token::I32(1),
Token::EnumSeqEnd,
],
- Error::InvalidLength(1),
+ Error::Message("invalid length 1, expected tuple of 2 elements".to_owned()),
);
}
diff --git a/testing/tests/test_de.rs b/testing/tests/test_de.rs
index 3359492e8..451d3d891 100644
--- a/testing/tests/test_de.rs
+++ b/testing/tests/test_de.rs
@@ -3,7 +3,7 @@ use std::net;
use std::path::PathBuf;
use std::time::Duration;
-use serde::de::{Deserialize, Type};
+use serde::Deserialize;
extern crate fnv;
use self::fnv::FnvHasher;
@@ -849,7 +849,7 @@ declare_error_tests! {
Token::StructSep,
Token::Str("d"),
],
- Error::UnknownField("d".to_owned()),
+ Error::Message("unknown field `d`, expected `a`".to_owned()),
}
test_skipped_field_is_unknown<StructDenyUnknown> {
&[
@@ -857,7 +857,7 @@ declare_error_tests! {
Token::StructSep,
Token::Str("b"),
],
- Error::UnknownField("b".to_owned()),
+ Error::Message("unknown field `b`, expected `a`".to_owned()),
}
test_skip_all_deny_unknown<StructSkipAllDenyUnknown> {
&[
@@ -865,25 +865,25 @@ declare_error_tests! {
Token::StructSep,
Token::Str("a"),
],
- Error::UnknownField("a".to_owned()),
+ Error::Message("unknown field `a`, there are no fields".to_owned()),
}
test_unknown_variant<Enum> {
&[
Token::EnumUnit("Enum", "Foo"),
],
- Error::UnknownVariant("Foo".to_owned()),
+ Error::Message("unknown variant `Foo`, expected one of `Unit`, `Simple`, `Seq`, `Map`".to_owned()),
}
test_enum_skipped_variant<Enum> {
&[
Token::EnumUnit("Enum", "Skipped"),
],
- Error::UnknownVariant("Skipped".to_owned()),
+ Error::Message("unknown variant `Skipped`, expected one of `Unit`, `Simple`, `Seq`, `Map`".to_owned()),
}
test_enum_skip_all<EnumSkipAll> {
&[
Token::EnumUnit("EnumSkipAll", "Skipped"),
],
- Error::UnknownVariant("Skipped".to_owned()),
+ Error::Message("unknown variant `Skipped`, there are no variants".to_owned()),
}
test_struct_seq_too_long<Struct> {
&[
@@ -904,7 +904,7 @@ declare_error_tests! {
Token::MapSep,
Token::Str("a"),
],
- Error::DuplicateField("a"),
+ Error::Message("duplicate field `a`".to_owned()),
}
test_duplicate_field_enum<Enum> {
&[
@@ -916,7 +916,7 @@ declare_error_tests! {
Token::EnumMapSep,
Token::Str("a"),
],
- Error::DuplicateField("a"),
+ Error::Message("duplicate field `a`".to_owned()),
}
test_enum_unit_usize<Enum> {
&[
@@ -924,7 +924,7 @@ declare_error_tests! {
Token::Usize(0),
Token::Unit,
],
- Error::InvalidType(Type::U64),
+ Error::Message("invalid type: integer `0`, expected field name".into()),
}
test_enum_unit_bytes<Enum> {
&[
@@ -932,6 +932,6 @@ declare_error_tests! {
Token::Bytes(b"Unit"),
Token::Unit,
],
- Error::InvalidType(Type::Bytes),
+ Error::Message("invalid type: byte array, expected field name".into()),
}
}
diff --git a/testing/tests/test_ser.rs b/testing/tests/test_ser.rs
index 5d54b4327..25df26d1e 100644
--- a/testing/tests/test_ser.rs
+++ b/testing/tests/test_ser.rs
@@ -432,7 +432,7 @@ fn test_cannot_serialize_paths() {
assert_ser_tokens_error(
&Path::new(path),
&[],
- Error::InvalidValue("Path contains invalid UTF-8 characters".to_owned()));
+ Error::Message("Path contains invalid UTF-8 characters".to_owned()));
let mut path_buf = PathBuf::new();
path_buf.push(path);
@@ -440,7 +440,7 @@ fn test_cannot_serialize_paths() {
assert_ser_tokens_error(
&path_buf,
&[],
- Error::InvalidValue("Path contains invalid UTF-8 characters".to_owned()));
+ Error::Message("Path contains invalid UTF-8 characters".to_owned()));
}
#[test]
@@ -448,17 +448,17 @@ fn test_enum_skipped() {
assert_ser_tokens_error(
&Enum::SkippedUnit,
&[],
- Error::InvalidValue("The enum variant Enum::SkippedUnit cannot be serialized".to_owned()));
+ Error::Message("the enum variant Enum::SkippedUnit cannot be serialized".to_owned()));
assert_ser_tokens_error(
&Enum::SkippedOne(42),
&[],
- Error::InvalidValue("The enum variant Enum::SkippedOne cannot be serialized".to_owned()));
+ Error::Message("the enum variant Enum::SkippedOne cannot be serialized".to_owned()));
assert_ser_tokens_error(
&Enum::SkippedSeq(1, 2),
&[],
- Error::InvalidValue("The enum variant Enum::SkippedSeq cannot be serialized".to_owned()));
+ Error::Message("the enum variant Enum::SkippedSeq cannot be serialized".to_owned()));
assert_ser_tokens_error(
&Enum::SkippedMap { _a: 1, _b: 2 },
&[],
- Error::InvalidValue("The enum variant Enum::SkippedMap cannot be serialized".to_owned()));
+ Error::Message("the enum variant Enum::SkippedMap cannot be serialized".to_owned()));
}
| [
"528",
"702"
] | serde-rs__serde-710 | Deserialization errors like "Error: Invalid type. Expected `I64`" are hard for users to understand
Thank you for your help parsing mixed strings and structs! Here's a second issue to think over. :-)
Here, I'm parsing a 1,300-line `docker-compose.yml` file which uses bare string notation, and which therefore sometimes accidentally uses an integer value like `1` where it should have used a string:
``` yaml
version: 2
services:
foo:
environment:
NOKOGIRI_USE_SYSTEM_LIBRARIES: 1
REDIS_URL: redis://redis:6379
```
I deserialize this with the following declaration:
``` rust
#[serde(default, skip_serializing_if = "BTreeMap::is_empty",
deserialize_with = "deserialize_map_or_key_value_list")]
pub environment: BTreeMap<String, String>,
```
The function `deserialize_map_or_key_value_list` contains a `visit_map` function which calls `visitor.visit_value::<String>()` to read a string.
When I run this program over the 1,300 line input file, it gives me the following error:
```
target/debug/examples/normalize < docker-compose.yml > test.yml
Error: Invalid type. Expected `I64`
```
There are several problems here:
1. The error message should be the "other way around", and include both the expected type and the one we actually got.
2. The error message should ideally include a line number so the user knows where in the enormous file the error occurs.
3. The error message should include the actual I64 value.
This would ideally give us something like:
```
<input>:869: Expected String, got I64 value `1`.
```
This would make my program much more user friendly. :-) I can easily provide a slightly better workaround in this particular case, but I'd love to find a more general solution.
Reconsider MapVisitor::missing_field
Out of all the Serde deserializers on GitHub, there are exactly four distinct behaviors for missing_field:
- Unconditionally an error
- For options treat it as None, otherwise error
- Treat it as unit
- [Whatever serde_xml is doing](https://github.com/serde-rs/xml/blob/f9330b703c7405ea8f54e1adfa972cb869924e38/src/de/value.rs#L358-L382)
Ideally I would like to standardize on one of these (my preference is None/error) and remove the ability for deserializers to modify the behavior. This would improve consistency and predictability across the ecosystem.
@oli-obk can you explain the various cases that serde_xml needs to handle in missing_field and whether you can think of any alternative ways to accomplish this?
| null | 530c29466e53995508b6980f496231ea2d212799 | diff --git a/serde/Cargo.toml b/serde/Cargo.toml
index ef3dd26d7..a57ff9543 100644
--- a/serde/Cargo.toml
+++ b/serde/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde"
-version = "0.9.0-rc1"
+version = "0.9.0-rc2"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "A generic serialization/deserialization framework"
diff --git a/serde/src/bytes.rs b/serde/src/bytes.rs
index 8402b4bd1..10e95eb8d 100644
--- a/serde/src/bytes.rs
+++ b/serde/src/bytes.rs
@@ -181,6 +181,10 @@ mod bytebuf {
impl de::Visitor for ByteBufVisitor {
type Value = ByteBuf;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("byte array")
+ }
+
#[inline]
fn visit_unit<E>(self) -> Result<ByteBuf, E>
where E: de::Error,
diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index ea17afd25..9c12a6e2c 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -32,6 +32,7 @@ use collections::enum_set::{CLike, EnumSet};
#[cfg(all(feature = "unstable", feature = "collections"))]
use collections::borrow::ToOwned;
+use core::fmt;
use core::hash::{Hash, BuildHasher};
use core::marker::PhantomData;
#[cfg(feature = "std")]
@@ -69,7 +70,7 @@ use de::{
Error,
MapVisitor,
SeqVisitor,
- Type,
+ Unexpected,
VariantVisitor,
Visitor,
};
@@ -83,6 +84,10 @@ pub struct UnitVisitor;
impl Visitor for UnitVisitor {
type Value = ();
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("unit")
+ }
+
fn visit_unit<E>(self) -> Result<(), E>
where E: Error,
{
@@ -112,6 +117,10 @@ pub struct BoolVisitor;
impl Visitor for BoolVisitor {
type Value = bool;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("a boolean")
+ }
+
fn visit_bool<E>(self, v: bool) -> Result<bool, E>
where E: Error,
{
@@ -124,7 +133,7 @@ impl Visitor for BoolVisitor {
match s.trim_matches(::utils::Pattern_White_Space) {
"true" => Ok(true),
"false" => Ok(false),
- _ => Err(Error::invalid_type(Type::Bool)),
+ _ => Err(Error::invalid_type(Unexpected::Str(s), &self)),
}
}
}
@@ -140,70 +149,59 @@ impl Deserialize for bool {
///////////////////////////////////////////////////////////////////////////////
macro_rules! impl_deserialize_num_method {
- ($src_ty:ty, $method:ident, $from_method:ident, $ty:expr) => {
+ ($ty:ident, $src_ty:ident, $method:ident, $from_method:ident, $group:ident, $group_ty:ident) => {
#[inline]
- fn $method<E>(self, v: $src_ty) -> Result<T, E>
+ fn $method<E>(self, v: $src_ty) -> Result<$ty, E>
where E: Error,
{
match FromPrimitive::$from_method(v) {
Some(v) => Ok(v),
- None => Err(Error::invalid_type($ty)),
+ None => Err(Error::invalid_value(Unexpected::$group(v as $group_ty), &self)),
}
}
}
}
-/// A visitor that produces a primitive type.
-struct PrimitiveVisitor<T> {
- marker: PhantomData<T>,
-}
-
-impl<T> PrimitiveVisitor<T> {
- /// Construct a new `PrimitiveVisitor`.
- #[inline]
- fn new() -> Self {
- PrimitiveVisitor {
- marker: PhantomData,
- }
- }
-}
-
-impl<T> Visitor for PrimitiveVisitor<T>
- where T: Deserialize + FromPrimitive + str::FromStr
-{
- type Value = T;
-
- impl_deserialize_num_method!(isize, visit_isize, from_isize, Type::Isize);
- impl_deserialize_num_method!(i8, visit_i8, from_i8, Type::I8);
- impl_deserialize_num_method!(i16, visit_i16, from_i16, Type::I16);
- impl_deserialize_num_method!(i32, visit_i32, from_i32, Type::I32);
- impl_deserialize_num_method!(i64, visit_i64, from_i64, Type::I64);
- impl_deserialize_num_method!(usize, visit_usize, from_usize, Type::Usize);
- impl_deserialize_num_method!(u8, visit_u8, from_u8, Type::U8);
- impl_deserialize_num_method!(u16, visit_u16, from_u16, Type::U16);
- impl_deserialize_num_method!(u32, visit_u32, from_u32, Type::U32);
- impl_deserialize_num_method!(u64, visit_u64, from_u64, Type::U64);
- impl_deserialize_num_method!(f32, visit_f32, from_f32, Type::F32);
- impl_deserialize_num_method!(f64, visit_f64, from_f64, Type::F64);
-
- #[inline]
- fn visit_str<E>(self, s: &str) -> Result<T, E>
- where E: Error,
- {
- str::FromStr::from_str(s.trim_matches(::utils::Pattern_White_Space)).or_else(|_| {
- Err(Error::invalid_type(Type::Str))
- })
- }
-}
-
macro_rules! impl_deserialize_num {
- ($ty:ty, $method:ident) => {
+ ($ty:ident, $method:ident) => {
impl Deserialize for $ty {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<$ty, D::Error>
where D: Deserializer,
{
- deserializer.$method(PrimitiveVisitor::new())
+ struct PrimitiveVisitor;
+
+ impl Visitor for PrimitiveVisitor {
+ type Value = $ty;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str(stringify!($ty))
+ }
+
+ impl_deserialize_num_method!($ty, isize, visit_isize, from_isize, Signed, i64);
+ impl_deserialize_num_method!($ty, i8, visit_i8, from_i8, Signed, i64);
+ impl_deserialize_num_method!($ty, i16, visit_i16, from_i16, Signed, i64);
+ impl_deserialize_num_method!($ty, i32, visit_i32, from_i32, Signed, i64);
+ impl_deserialize_num_method!($ty, i64, visit_i64, from_i64, Signed, i64);
+ impl_deserialize_num_method!($ty, usize, visit_usize, from_usize, Unsigned, u64);
+ impl_deserialize_num_method!($ty, u8, visit_u8, from_u8, Unsigned, u64);
+ impl_deserialize_num_method!($ty, u16, visit_u16, from_u16, Unsigned, u64);
+ impl_deserialize_num_method!($ty, u32, visit_u32, from_u32, Unsigned, u64);
+ impl_deserialize_num_method!($ty, u64, visit_u64, from_u64, Unsigned, u64);
+ impl_deserialize_num_method!($ty, f32, visit_f32, from_f32, Float, f64);
+ impl_deserialize_num_method!($ty, f64, visit_f64, from_f64, Float, f64);
+
+ #[inline]
+ fn visit_str<E>(self, s: &str) -> Result<$ty, E>
+ where E: Error,
+ {
+ str::FromStr::from_str(s.trim_matches(::utils::Pattern_White_Space)).or_else(|_| {
+ Err(Error::invalid_type(Unexpected::Str(s), &self))
+ })
+ }
+ }
+
+ deserializer.$method(PrimitiveVisitor)
}
}
}
@@ -229,6 +227,10 @@ struct CharVisitor;
impl Visitor for CharVisitor {
type Value = char;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("a character")
+ }
+
#[inline]
fn visit_char<E>(self, v: char) -> Result<char, E>
where E: Error,
@@ -241,14 +243,9 @@ impl Visitor for CharVisitor {
where E: Error,
{
let mut iter = v.chars();
- if let Some(v) = iter.next() {
- if iter.next().is_some() {
- Err(Error::invalid_type(Type::Char))
- } else {
- Ok(v)
- }
- } else {
- Err(Error::end_of_stream())
+ match (iter.next(), iter.next()) {
+ (Some(c), None) => Ok(c),
+ _ => Err(Error::invalid_value(Unexpected::Str(v), &self)),
}
}
}
@@ -271,6 +268,10 @@ struct StringVisitor;
impl Visitor for StringVisitor {
type Value = String;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("a string")
+ }
+
fn visit_str<E>(self, v: &str) -> Result<String, E>
where E: Error,
{
@@ -294,7 +295,7 @@ impl Visitor for StringVisitor {
{
match str::from_utf8(v) {
Ok(s) => Ok(s.to_owned()),
- Err(_) => Err(Error::invalid_type(Type::String)),
+ Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
}
}
@@ -303,7 +304,7 @@ impl Visitor for StringVisitor {
{
match String::from_utf8(v) {
Ok(s) => Ok(s),
- Err(_) => Err(Error::invalid_type(Type::String)),
+ Err(e) => Err(Error::invalid_value(Unexpected::Bytes(&e.into_bytes()), &self)),
}
}
}
@@ -328,6 +329,10 @@ impl<
> Visitor for OptionVisitor<T> {
type Value = Option<T>;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("option")
+ }
+
#[inline]
fn visit_unit<E>(self) -> Result<Option<T>, E>
where E: Error,
@@ -368,6 +373,10 @@ pub struct PhantomDataVisitor<T> {
impl<T> Visitor for PhantomDataVisitor<T> {
type Value = PhantomData<T>;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("unit")
+ }
+
#[inline]
fn visit_unit<E>(self) -> Result<PhantomData<T>, E>
where E: Error,
@@ -417,6 +426,10 @@ macro_rules! seq_impl {
{
type Value = $ty;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("a sequence")
+ }
+
#[inline]
fn visit_unit<E>(self) -> Result<$ty, E>
where E: Error,
@@ -531,6 +544,10 @@ impl<A> ArrayVisitor<A> {
impl<T> Visitor for ArrayVisitor<[T; 0]> where T: Deserialize {
type Value = [T; 0];
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("an empty array")
+ }
+
#[inline]
fn visit_unit<E>(self) -> Result<[T; 0], E>
where E: Error,
@@ -562,6 +579,10 @@ macro_rules! array_impls {
impl<T> Visitor for ArrayVisitor<[T; $len]> where T: Deserialize {
type Value = [T; $len];
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str(concat!("an array of length ", $len))
+ }
+
#[inline]
fn visit_seq<V>(self, mut visitor: V) -> Result<[T; $len], V::Error>
where V: SeqVisitor,
@@ -569,7 +590,7 @@ macro_rules! array_impls {
$(
let $name = match try!(visitor.visit()) {
Some(val) => val,
- None => return Err(Error::end_of_stream()),
+ None => return Err(Error::invalid_length(0, &self)),
};
)+
@@ -645,6 +666,10 @@ macro_rules! tuple_impls {
impl<$($name: Deserialize),+> Visitor for $visitor<$($name,)+> {
type Value = ($($name,)+);
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str(concat!("a tuple of size ", $len))
+ }
+
#[inline]
#[allow(non_snake_case)]
fn visit_seq<V>(self, mut visitor: V) -> Result<($($name,)+), V::Error>
@@ -653,7 +678,7 @@ macro_rules! tuple_impls {
$(
let $name = match try!(visitor.visit()) {
Some(value) => value,
- None => return Err(Error::end_of_stream()),
+ None => return Err(Error::invalid_length(0, &self)),
};
)+
@@ -723,6 +748,10 @@ macro_rules! map_impl {
{
type Value = $ty;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("a map")
+ }
+
#[inline]
fn visit_unit<E>(self) -> Result<$ty, E>
where E: Error,
@@ -785,7 +814,7 @@ impl Deserialize for net::IpAddr {
let s = try!(String::deserialize(deserializer));
match s.parse() {
Ok(s) => Ok(s),
- Err(err) => Err(D::Error::invalid_value(&err.to_string())),
+ Err(err) => Err(D::Error::custom(err)),
}
}
}
@@ -798,7 +827,7 @@ impl Deserialize for net::Ipv4Addr {
let s = try!(String::deserialize(deserializer));
match s.parse() {
Ok(s) => Ok(s),
- Err(err) => Err(D::Error::invalid_value(&err.to_string())),
+ Err(err) => Err(D::Error::custom(err)),
}
}
}
@@ -811,7 +840,7 @@ impl Deserialize for net::Ipv6Addr {
let s = try!(String::deserialize(deserializer));
match s.parse() {
Ok(s) => Ok(s),
- Err(err) => Err(D::Error::invalid_value(&err.to_string())),
+ Err(err) => Err(D::Error::custom(err)),
}
}
}
@@ -826,7 +855,7 @@ impl Deserialize for net::SocketAddr {
let s = try!(String::deserialize(deserializer));
match s.parse() {
Ok(s) => Ok(s),
- Err(err) => Err(D::Error::invalid_value(&err.to_string())),
+ Err(err) => Err(D::Error::custom(err)),
}
}
}
@@ -839,7 +868,7 @@ impl Deserialize for net::SocketAddrV4 {
let s = try!(String::deserialize(deserializer));
match s.parse() {
Ok(s) => Ok(s),
- Err(err) => Err(D::Error::invalid_value(&err.to_string())),
+ Err(err) => Err(D::Error::custom(err)),
}
}
}
@@ -852,7 +881,7 @@ impl Deserialize for net::SocketAddrV6 {
let s = try!(String::deserialize(deserializer));
match s.parse() {
Ok(s) => Ok(s),
- Err(err) => Err(D::Error::invalid_value(&err.to_string())),
+ Err(err) => Err(D::Error::custom(err)),
}
}
}
@@ -866,6 +895,10 @@ struct PathBufVisitor;
impl Visitor for PathBufVisitor {
type Value = path::PathBuf;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("path string")
+ }
+
fn visit_str<E>(self, v: &str) -> Result<path::PathBuf, E>
where E: Error,
{
@@ -875,7 +908,7 @@ impl Visitor for PathBufVisitor {
fn visit_string<E>(self, v: String) -> Result<path::PathBuf, E>
where E: Error,
{
- self.visit_str(&v)
+ Ok(From::from(v))
}
}
@@ -977,13 +1010,17 @@ impl Deserialize for Duration {
impl Visitor for FieldVisitor {
type Value = Field;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("`secs` or `nanos`")
+ }
+
fn visit_usize<E>(self, value: usize) -> Result<Field, E>
where E: Error,
{
match value {
0usize => Ok(Field::Secs),
1usize => Ok(Field::Nanos),
- _ => Err(Error::invalid_value("expected a field")),
+ _ => Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self)),
}
}
@@ -993,7 +1030,7 @@ impl Deserialize for Duration {
match value {
"secs" => Ok(Field::Secs),
"nanos" => Ok(Field::Nanos),
- _ => Err(Error::unknown_field(value)),
+ _ => Err(Error::unknown_field(value, FIELDS)),
}
}
@@ -1005,7 +1042,7 @@ impl Deserialize for Duration {
b"nanos" => Ok(Field::Nanos),
_ => {
let value = String::from_utf8_lossy(value);
- Err(Error::unknown_field(&value))
+ Err(Error::unknown_field(&value, FIELDS))
}
}
}
@@ -1020,19 +1057,23 @@ impl Deserialize for Duration {
impl Visitor for DurationVisitor {
type Value = Duration;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("struct Duration")
+ }
+
fn visit_seq<V>(self, mut visitor: V) -> Result<Duration, V::Error>
where V: SeqVisitor,
{
let secs: u64 = match try!(visitor.visit()) {
Some(value) => value,
None => {
- return Err(Error::invalid_length(0));
+ return Err(Error::invalid_length(0, &self));
}
};
let nanos: u32 = match try!(visitor.visit()) {
Some(value) => value,
None => {
- return Err(Error::invalid_length(1));
+ return Err(Error::invalid_length(1, &self));
}
};
Ok(Duration::new(secs, nanos))
@@ -1061,11 +1102,11 @@ impl Deserialize for Duration {
}
let secs = match secs {
Some(secs) => secs,
- None => try!(visitor.missing_field("secs")),
+ None => return Err(<V::Error as Error>::missing_field("secs")),
};
let nanos = match nanos {
Some(nanos) => nanos,
- None => try!(visitor.missing_field("nanos")),
+ None => return Err(<V::Error as Error>::missing_field("nanos")),
};
Ok(Duration::new(secs, nanos))
}
@@ -1083,7 +1124,7 @@ impl<T> Deserialize for NonZero<T> where T: Deserialize + PartialEq + Zeroable +
fn deserialize<D>(deserializer: D) -> Result<NonZero<T>, D::Error> where D: Deserializer {
let value = try!(Deserialize::deserialize(deserializer));
if value == Zero::zero() {
- return Err(Error::invalid_value("expected a non-zero value"))
+ return Err(Error::custom("expected a non-zero value"))
}
unsafe {
Ok(NonZero::new(value))
@@ -1112,23 +1153,15 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
impl Visitor for FieldVisitor {
type Value = Field;
- #[cfg(any(feature = "std", feature = "collections"))]
- fn visit_usize<E>(self, value: usize) -> Result<Field, E> where E: Error {
- #[cfg(feature = "collections")]
- use collections::string::ToString;
- match value {
- 0 => Ok(Field::Ok),
- 1 => Ok(Field::Err),
- _ => Err(Error::unknown_field(&value.to_string())),
- }
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("`Ok` or `Err`")
}
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
fn visit_usize<E>(self, value: usize) -> Result<Field, E> where E: Error {
match value {
0 => Ok(Field::Ok),
1 => Ok(Field::Err),
- _ => Err(Error::unknown_field("some number")),
+ _ => Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self)),
}
}
@@ -1136,7 +1169,7 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
match value {
"Ok" => Ok(Field::Ok),
"Err" => Ok(Field::Err),
- _ => Err(Error::unknown_field(value)),
+ _ => Err(Error::unknown_variant(value, VARIANTS)),
}
}
@@ -1146,8 +1179,8 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
b"Err" => Ok(Field::Err),
_ => {
match str::from_utf8(value) {
- Ok(value) => Err(Error::unknown_field(value)),
- Err(_) => Err(Error::invalid_type(Type::String)),
+ Ok(value) => Err(Error::unknown_variant(value, VARIANTS)),
+ Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)),
}
}
}
@@ -1166,6 +1199,10 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
{
type Value = Result<T, E>;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("enum Result")
+ }
+
fn visit_enum<V>(self, visitor: V) -> Result<Result<T, E>, V::Error>
where V: EnumVisitor
{
@@ -1198,6 +1235,10 @@ impl Deserialize for IgnoredAny {
impl Visitor for IgnoredAnyVisitor {
type Value = IgnoredAny;
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("anything at all")
+ }
+
#[inline]
fn visit_bool<E>(self, _: bool) -> Result<IgnoredAny, E> {
Ok(IgnoredAny)
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index 57616bcb0..967af3504 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -8,7 +8,7 @@ use error;
#[cfg(all(not(feature = "std"), feature = "collections"))]
use collections::{String, Vec};
-use core::fmt;
+use core::fmt::{self, Display};
use core::marker::PhantomData;
///////////////////////////////////////////////////////////////////////////////
@@ -17,208 +17,352 @@ pub mod impls;
pub mod value;
mod from_primitive;
+// Helpers used by generated code. Not public API.
+#[doc(hidden)]
+pub mod private;
+
///////////////////////////////////////////////////////////////////////////////
-/// `Error` is a trait that allows a `Deserialize` to generically create a
-/// `Deserializer` error.
+/// The `Error` trait allows `Deserialize` implementations to create descriptive
+/// error messages belonging to the `Deserializer` against which they are
+/// currently running.
+///
+/// Every `Deserializer` declares an `Error` type that encompasses both
+/// general-purpose deserialization errors as well as errors specific to the
+/// particular deserialization format. For example the `Error` type of
+/// `serde_json` can represent errors like an invalid JSON escape sequence or an
+/// unterminated string literal, in addition to the error cases that are part of
+/// this trait.
+///
+/// Most deserializers should only need to provide the `Error::custom` method
+/// and inherit the default behavior for the other methods.
pub trait Error: Sized + error::Error {
/// Raised when there is general error when deserializing a type.
- #[cfg(any(feature = "std", feature = "collections"))]
- fn custom<T: Into<String>>(msg: T) -> Self;
-
- /// Raised when there is general error when deserializing a type.
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- fn custom<T: Into<&'static str>>(msg: T) -> Self;
-
- /// Raised when a `Deserialize` type unexpectedly hit the end of the stream.
- fn end_of_stream() -> Self;
+ fn custom<T: Display>(msg: T) -> Self;
- /// Raised when a `Deserialize` was passed an incorrect type.
- fn invalid_type(ty: Type) -> Self {
- Error::custom(format!("Invalid type. Expected `{:?}`", ty))
+ /// Raised when a `Deserialize` receives a type different from what it was
+ /// expecting.
+ ///
+ /// The `unexp` argument provides information about what type was received.
+ /// This is the type that was present in the input file or other source data
+ /// of the Deserializer.
+ ///
+ /// The `exp` argument provides information about what type was being
+ /// expected. This is the type that is written in the program.
+ ///
+ /// For example if we try to deserialize a String out of a JSON file
+ /// containing an integer, the unexpected type is the integer and the
+ /// expected type is the string.
+ fn invalid_type(unexp: Unexpected, exp: &Expected) -> Self {
+ struct InvalidType<'a> {
+ unexp: Unexpected<'a>,
+ exp: &'a Expected,
+ }
+ impl<'a> Display for InvalidType<'a> {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ write!(formatter, "invalid type: {}, expected {}", self.unexp, self.exp)
+ }
+ }
+ Error::custom(InvalidType { unexp: unexp, exp: exp })
}
- /// Raised when a `Deserialize` was passed an incorrect value.
- fn invalid_value(msg: &str) -> Self {
- Error::custom(format!("Invalid value: {}", msg))
+ /// Raised when a `Deserialize` receives a value of the right type but that
+ /// is wrong for some other reason.
+ ///
+ /// The `unexp` argument provides information about what value was received.
+ /// This is the value that was present in the input file or other source
+ /// data of the Deserializer.
+ ///
+ /// The `exp` argument provides information about what value was being
+ /// expected. This is the type that is written in the program.
+ ///
+ /// For example if we try to deserialize a String out of some binary data
+ /// that is not valid UTF-8, the unexpected value is the bytes and the
+ /// expected value is a string.
+ fn invalid_value(unexp: Unexpected, exp: &Expected) -> Self {
+ struct InvalidValue<'a> {
+ unexp: Unexpected<'a>,
+ exp: &'a Expected,
+ }
+ impl<'a> Display for InvalidValue<'a> {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ write!(formatter, "invalid value: {}, expected {}", self.unexp, self.exp)
+ }
+ }
+ Error::custom(InvalidValue { unexp: unexp, exp: exp })
}
- /// Raised when a fixed sized sequence or map was passed in the wrong amount of arguments.
+ /// Raised when deserializing a sequence or map and the input data contains
+ /// too many or too few elements.
///
- /// The parameter `len` is the number of arguments found in the serialization. The sequence
- /// may either expect more arguments or less arguments.
- fn invalid_length(len: usize) -> Self {
- Error::custom(format!("Invalid length: {}", len))
+ /// The `len` argument is the number of elements encountered. The sequence
+ /// or map may have expected more arguments or fewer arguments.
+ ///
+ /// The `exp` argument provides information about what data was being
+ /// expected. For example `exp` might say that a tuple of size 6 was
+ /// expected.
+ fn invalid_length(len: usize, exp: &Expected) -> Self {
+ struct InvalidLength<'a> {
+ len: usize,
+ exp: &'a Expected,
+ }
+ impl<'a> Display for InvalidLength<'a> {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ write!(formatter, "invalid length {}, expected {}", self.len, self.exp)
+ }
+ }
+ Error::custom(InvalidLength { len: len, exp: exp })
}
- /// Raised when a `Deserialize` enum type received an unexpected variant.
- fn unknown_variant(field: &str) -> Self {
- Error::custom(format!("Unknown variant `{}`", field))
+ /// Raised when a `Deserialize` enum type received a variant with an
+ /// unrecognized name.
+ fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self {
+ struct UnknownVariant<'a> {
+ variant: &'a str,
+ expected: &'static [&'static str],
+ }
+ impl<'a> Display for UnknownVariant<'a> {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ if self.expected.is_empty() {
+ write!(formatter,
+ "unknown variant `{}`, there are no variants",
+ self.variant)
+ } else {
+ write!(formatter,
+ "unknown variant `{}`, expected {}",
+ self.variant,
+ OneOf { names: self.expected })
+ }
+ }
+ }
+ Error::custom(UnknownVariant { variant: variant, expected: expected })
}
- /// Raised when a `Deserialize` struct type received an unexpected struct field.
- fn unknown_field(field: &str) -> Self {
- Error::custom(format!("Unknown field `{}`", field))
+ /// Raised when a `Deserialize` struct type received a field with an
+ /// unrecognized name.
+ fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
+ struct UnknownField<'a> {
+ field: &'a str,
+ expected: &'static [&'static str],
+ }
+ impl<'a> Display for UnknownField<'a> {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ if self.expected.is_empty() {
+ write!(formatter,
+ "unknown field `{}`, there are no fields",
+ self.field)
+ } else {
+ write!(formatter,
+ "unknown field `{}`, expected {}",
+ self.field,
+ OneOf { names: self.expected })
+ }
+ }
+ }
+ Error::custom(UnknownField { field: field, expected: expected })
}
- /// raised when a `deserialize` struct type did not receive a field.
+ /// Raised when a `Deserialize` struct type expected to receive a required
+ /// field with a particular name but that field was not present in the
+ /// input.
fn missing_field(field: &'static str) -> Self {
- Error::custom(format!("Missing field `{}`", field))
+ struct MissingField {
+ field: &'static str,
+ }
+ impl Display for MissingField {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ write!(formatter, "missing field `{}`", self.field)
+ }
+ }
+ Error::custom(MissingField { field: field })
}
/// Raised when a `Deserialize` struct type received more than one of the
- /// same struct field.
+ /// same field.
fn duplicate_field(field: &'static str) -> Self {
- Error::custom(format!("Duplicate field `{}`", field))
+ struct DuplicateField {
+ field: &'static str,
+ }
+ impl Display for DuplicateField {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ write!(formatter, "duplicate field `{}`", self.field)
+ }
+ }
+ Error::custom(DuplicateField { field: field })
}
}
-/// `Type` represents all the primitive types that can be deserialized. This is used by
-/// `Error::invalid_type`.
-#[derive(Copy, Clone, PartialEq, Eq, Debug)]
-pub enum Type {
- /// Represents a `bool` type.
- Bool,
-
- /// Represents a `usize` type.
- Usize,
-
- /// Represents a `u8` type.
- U8,
-
- /// Represents a `u16` type.
- U16,
-
- /// Represents a `u32` type.
- U32,
-
- /// Represents a `u64` type.
- U64,
-
- /// Represents a `isize` type.
- Isize,
-
- /// Represents a `i8` type.
- I8,
-
- /// Represents a `i16` type.
- I16,
-
- /// Represents a `i32` type.
- I32,
+/// `Unexpected` represents an unexpected invocation of any one of the `Visitor`
+/// trait methods.
+///
+/// This is used as an argument to the `invalid_type`, `invalid_value`, and
+/// `invalid_length` methods of the `Error` trait to build error messages.
+///
+/// ```rust
+/// # use serde::de::{Error, Unexpected, Visitor};
+/// # use std::fmt;
+/// # struct Example;
+/// # impl Visitor for Example {
+/// # type Value = ();
+/// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
+/// where E: Error
+/// {
+/// Err(Error::invalid_type(Unexpected::Bool(v), &self))
+/// }
+/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+/// # write!(formatter, "definitely not a boolean")
+/// # }
+/// # }
+/// ```
+#[derive(Clone, PartialEq, Debug)]
+pub enum Unexpected<'a> {
+ /// The input contained a boolean value that was not expected.
+ Bool(bool),
- /// Represents a `i64` type.
- I64,
+ /// The input contained an unsigned integer `usize`, `u8`, `u16`, `u32` or
+ /// `u64` that was not expected.
+ Unsigned(u64),
- /// Represents a `f32` type.
- F32,
+ /// The input contained a signed integer `isize`, `i8`, `i16`, `i32` or
+ /// `i64` that was not expected.
+ Signed(i64),
- /// Represents a `f64` type.
- F64,
+ /// The input contained a floating point `f32` or `f64` that was not
+ /// expected.
+ Float(f64),
- /// Represents a `char` type.
- Char,
+ /// The input contained a `char` that was not expected.
+ Char(char),
- /// Represents a `&str` type.
- Str,
+ /// The input contained a `&str` or `String` that was not expected.
+ Str(&'a str),
- /// Represents a `String` type.
- String,
+ /// The input contained a `&[u8]` or `Vec<u8>` that was not expected.
+ Bytes(&'a [u8]),
- /// Represents a `()` type.
+ /// The input contained a unit `()` that was not expected.
Unit,
- /// Represents an `Option<T>` type.
+ /// The input contained an `Option<T>` that was not expected.
Option,
- /// Represents a sequence type.
- Seq,
-
- /// Represents a map type.
- Map,
-
- /// Represents a unit struct type.
- UnitStruct,
-
- /// Represents a newtype type.
+ /// The input contained a newtype struct that was not expected.
NewtypeStruct,
- /// Represents a tuple struct type.
- TupleStruct,
+ /// The input contained a sequence that was not expected.
+ Seq,
- /// Represents a struct type.
- Struct,
+ /// The input contained a map that was not expected.
+ Map,
- /// Represents a struct field name.
- FieldName,
+ /// The input contained an enum that was not expected.
+ Enum,
- /// Represents a tuple type.
- Tuple,
+ /// The input contained a unit variant that was not expected.
+ UnitVariant,
- /// Represents an `enum` type.
- Enum,
+ /// The input contained a newtype variant that was not expected.
+ NewtypeVariant,
- /// Represents an enum variant name.
- VariantName,
+ /// The input contained a tuple variant that was not expected.
+ TupleVariant,
- /// Represents a struct variant.
+ /// The input contained a struct variant that was not expected.
StructVariant,
- /// Represents a tuple variant.
- TupleVariant,
+ /// A message stating what uncategorized thing the input contained that was
+ /// not expected.
+ ///
+ /// The message should be a noun or noun phrase, not capitalized and without
+ /// a period. An example message is "unoriginal superhero".
+ Other(&'a str),
+}
- /// Represents a unit variant.
- UnitVariant,
+impl<'a> fmt::Display for Unexpected<'a> {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+ use self::Unexpected::*;
+ match *self {
+ Bool(b) => write!(formatter, "boolean `{}`", b),
+ Unsigned(i) => write!(formatter, "integer `{}`", i),
+ Signed(i) => write!(formatter, "integer `{}`", i),
+ Float(f) => write!(formatter, "floating point `{}`", f),
+ Char(c) => write!(formatter, "character `{}`", c),
+ Str(s) => write!(formatter, "string {:?}", s),
+ Bytes(_) => write!(formatter, "byte array"),
+ Unit => write!(formatter, "unit value"),
+ Option => write!(formatter, "Option value"),
+ NewtypeStruct => write!(formatter, "newtype struct"),
+ Seq => write!(formatter, "sequence"),
+ Map => write!(formatter, "map"),
+ Enum => write!(formatter, "enum"),
+ UnitVariant => write!(formatter, "unit variant"),
+ NewtypeVariant => write!(formatter, "newtype variant"),
+ TupleVariant => write!(formatter, "tuple variant"),
+ StructVariant => write!(formatter, "struct variant"),
+ Other(other) => formatter.write_str(other),
+ }
+ }
+}
- /// Represents a newtype variant.
- NewtypeVariant,
+/// `Expected` represents an explanation of what data a `Visitor` was expecting
+/// to receive.
+///
+/// This is used as an argument to the `invalid_type`, `invalid_value`, and
+/// `invalid_length` methods of the `Error` trait to build error messages. The
+/// message should complete the sentence "This Visitor expects to receive ...",
+/// for example the message could be "an integer between 0 and 64". The message
+/// should not be capitalized and should not end with a period.
+///
+/// Within the context of a `Visitor` implementation, the `Visitor` itself
+/// (`&self`) is an implementation of this trait.
+///
+/// ```rust
+/// # use serde::de::{Error, Unexpected, Visitor};
+/// # use std::fmt;
+/// # struct Example;
+/// # impl Visitor for Example {
+/// # type Value = ();
+/// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
+/// where E: Error
+/// {
+/// Err(Error::invalid_type(Unexpected::Bool(v), &self))
+/// }
+/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+/// # write!(formatter, "definitely not a boolean")
+/// # }
+/// # }
+/// ```
+///
+/// Outside of a `Visitor`, `&"..."` can be used.
+///
+/// ```rust
+/// # use serde::de::{Error, Unexpected};
+/// # fn example<E: Error>() -> Result<(), E> {
+/// # let v = true;
+/// return Err(Error::invalid_type(Unexpected::Bool(v), &"a negative integer"));
+/// # }
+/// ```
+pub trait Expected {
+ /// Format an explanation of what data was being expected. Same signature as
+ /// the `Display` and `Debug` traits.
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result;
+}
- /// Represents a `&[u8]` type.
- Bytes,
+impl<T> Expected for T where T: Visitor {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ self.expecting(formatter)
+ }
+}
- /// Represents a `Vec<u8>` type.
- ByteBuf,
+impl<'a> Expected for &'a str {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str(self)
+ }
}
-impl fmt::Display for Type {
- fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
- let display = match *self {
- Type::Bool => "bool",
- Type::Usize => "usize",
- Type::U8 => "u8",
- Type::U16 => "u16",
- Type::U32 => "u32",
- Type::U64 => "u64",
- Type::Isize => "isize",
- Type::I8 => "i8",
- Type::I16 => "i16",
- Type::I32 => "i32",
- Type::I64 => "i64",
- Type::F32 => "f32",
- Type::F64 => "f64",
- Type::Char => "char",
- Type::Str => "str",
- Type::String => "string",
- Type::Unit => "unit",
- Type::Option => "option",
- Type::Seq => "seq",
- Type::Map => "map",
- Type::UnitStruct => "unit struct",
- Type::NewtypeStruct => "newtype struct",
- Type::TupleStruct => "tuple struct",
- Type::Struct => "struct",
- Type::FieldName => "field name",
- Type::Tuple => "tuple",
- Type::Enum => "enum",
- Type::VariantName => "variant name",
- Type::StructVariant => "struct variant",
- Type::TupleVariant => "tuple variant",
- Type::UnitVariant => "unit variant",
- Type::NewtypeVariant => "newtype variant",
- Type::Bytes => "bytes",
- Type::ByteBuf => "bytes buf",
- };
- display.fmt(formatter)
+impl<'a> Display for Expected + 'a {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ Expected::fmt(self, formatter)
}
}
@@ -276,6 +420,7 @@ pub trait Deserialize: Sized {
///
/// ```rust
/// # use serde::de::{Deserialize, DeserializeSeed, Deserializer, Visitor, SeqVisitor};
+/// # use std::fmt;
/// # use std::marker::PhantomData;
/// #
/// // A DeserializeSeed implementation that uses stateful deserialization to
@@ -315,6 +460,10 @@ pub trait Deserialize: Sized {
/// }
/// Ok(())
/// }
+/// #
+/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+/// # write!(formatter, "an array of integers")
+/// # }
/// }
///
/// deserializer.deserialize_seq(ExtendVecVisitor(self.0))
@@ -345,6 +494,10 @@ pub trait Deserialize: Sized {
/// // Return the finished vec.
/// Ok(vec)
/// }
+/// #
+/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+/// # write!(formatter, "an array of arrays")
+/// # }
/// }
///
/// # fn example<D: Deserializer>(deserializer: D) -> Result<(), D::Error> {
@@ -570,16 +723,62 @@ pub trait Deserializer: Sized {
///////////////////////////////////////////////////////////////////////////////
/// This trait represents a visitor that walks through a deserializer.
+///
+/// ```rust
+/// # use serde::de::{Error, Unexpected, Visitor};
+/// # use std::fmt;
+/// /// A visitor that deserializes a long string - a string containing at least
+/// /// some minimum number of bytes.
+/// struct LongString {
+/// min: usize,
+/// }
+///
+/// impl Visitor for LongString {
+/// type Value = String;
+///
+/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+/// write!(formatter, "a string containing at least {} bytes", self.min)
+/// }
+///
+/// fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
+/// where E: Error
+/// {
+/// if s.len() >= self.min {
+/// Ok(s.to_owned())
+/// } else {
+/// Err(Error::invalid_value(Unexpected::Str(s), &self))
+/// }
+/// }
+/// }
+/// ```
pub trait Visitor: Sized {
/// The value produced by this visitor.
type Value;
+ /// Format a message stating what data this Visitor expects to receive.
+ ///
+ /// This is used in error messages. The message should complete the sentence
+ /// "This Visitor expects to receive ...", for example the message could be
+ /// "an integer between 0 and 64". The message should not be capitalized and
+ /// should not end with a period.
+ ///
+ /// ```rust
+ /// # use std::fmt;
+ /// # struct S { max: usize }
+ /// # impl serde::de::Visitor for S {
+ /// # type Value = ();
+ /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ /// write!(formatter, "an integer between 0 and {}", self.max)
+ /// }
+ /// # }
+ /// ```
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result;
+
/// `visit_bool` deserializes a `bool` into a `Value`.
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where E: Error,
{
- let _ = v;
- Err(Error::invalid_type(Type::Bool))
+ Err(Error::invalid_type(Unexpected::Bool(v), &self))
}
/// `visit_isize` deserializes a `isize` into a `Value`.
@@ -614,8 +813,7 @@ pub trait Visitor: Sized {
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where E: Error,
{
- let _ = v;
- Err(Error::invalid_type(Type::I64))
+ Err(Error::invalid_type(Unexpected::Signed(v), &self))
}
/// `visit_usize` deserializes a `usize` into a `Value`.
@@ -650,8 +848,7 @@ pub trait Visitor: Sized {
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
where E: Error,
{
- let _ = v;
- Err(Error::invalid_type(Type::U64))
+ Err(Error::invalid_type(Unexpected::Unsigned(v), &self))
}
/// `visit_f32` deserializes a `f32` into a `Value`.
@@ -665,8 +862,7 @@ pub trait Visitor: Sized {
fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
where E: Error,
{
- let _ = v;
- Err(Error::invalid_type(Type::F64))
+ Err(Error::invalid_type(Unexpected::Float(v), &self))
}
/// `visit_char` deserializes a `char` into a `Value`.
@@ -681,8 +877,7 @@ pub trait Visitor: Sized {
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where E: Error,
{
- let _ = v;
- Err(Error::invalid_type(Type::Str))
+ Err(Error::invalid_type(Unexpected::Str(v), &self))
}
/// `visit_string` deserializes a `String` into a `Value`. This allows a deserializer to avoid
@@ -700,23 +895,14 @@ pub trait Visitor: Sized {
fn visit_unit<E>(self) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::invalid_type(Type::Unit))
- }
-
- /// `visit_unit_struct` deserializes a unit struct into a `Value`.
- #[inline]
- fn visit_unit_struct<E>(self, name: &'static str) -> Result<Self::Value, E>
- where E: Error,
- {
- let _ = name;
- self.visit_unit()
+ Err(Error::invalid_type(Unexpected::Unit, &self))
}
/// `visit_none` deserializes a none value into a `Value`.
fn visit_none<E>(self) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::invalid_type(Type::Option))
+ Err(Error::invalid_type(Unexpected::Option, &self))
}
/// `visit_some` deserializes a value into a `Value`.
@@ -724,7 +910,7 @@ pub trait Visitor: Sized {
where D: Deserializer,
{
let _ = deserializer;
- Err(Error::invalid_type(Type::Option))
+ Err(Error::invalid_type(Unexpected::Option, &self))
}
/// `visit_newtype_struct` deserializes a value into a `Value`.
@@ -732,7 +918,7 @@ pub trait Visitor: Sized {
where D: Deserializer,
{
let _ = deserializer;
- Err(Error::invalid_type(Type::NewtypeStruct))
+ Err(Error::invalid_type(Unexpected::NewtypeStruct, &self))
}
/// `visit_seq` deserializes a `SeqVisitor` into a `Value`.
@@ -740,7 +926,7 @@ pub trait Visitor: Sized {
where V: SeqVisitor,
{
let _ = visitor;
- Err(Error::invalid_type(Type::Seq))
+ Err(Error::invalid_type(Unexpected::Seq, &self))
}
/// `visit_map` deserializes a `MapVisitor` into a `Value`.
@@ -748,7 +934,7 @@ pub trait Visitor: Sized {
where V: MapVisitor,
{
let _ = visitor;
- Err(Error::invalid_type(Type::Map))
+ Err(Error::invalid_type(Unexpected::Map, &self))
}
/// `visit_enum` deserializes a `EnumVisitor` into a `Value`.
@@ -756,7 +942,7 @@ pub trait Visitor: Sized {
where V: EnumVisitor,
{
let _ = visitor;
- Err(Error::invalid_type(Type::Enum))
+ Err(Error::invalid_type(Unexpected::Enum, &self))
}
/// `visit_bytes` deserializes a `&[u8]` into a `Value`.
@@ -764,7 +950,7 @@ pub trait Visitor: Sized {
where E: Error,
{
let _ = v;
- Err(Error::invalid_type(Type::Bytes))
+ Err(Error::invalid_type(Unexpected::Bytes(v), &self))
}
/// `visit_byte_buf` deserializes a `Vec<u8>` into a `Value`.
@@ -927,31 +1113,6 @@ pub trait MapVisitor {
fn size_hint(&self) -> (usize, Option<usize>) {
(0, None)
}
-
- /// Report that the struct has a field that wasn't deserialized. The
- /// MapVisitor may consider this an error or it may return a default value
- /// for the field.
- ///
- /// `Deserialize` implementations should typically use
- /// `MapVisitor::missing_field` instead.
- fn missing_field_seed<V>(&mut self, _seed: V, field: &'static str) -> Result<V::Value, Self::Error>
- where V: DeserializeSeed
- {
- Err(Error::missing_field(field))
- }
-
- /// Report that the struct has a field that wasn't deserialized. The
- /// MapVisitor may consider this an error or it may return a default value
- /// for the field.
- ///
- /// This method exists as a convenience for `Deserialize` implementations.
- /// `MapVisitor` implementations should not need to override the default
- /// behavior.
- fn missing_field<V>(&mut self, field: &'static str) -> Result<V, Self::Error>
- where V: Deserialize,
- {
- self.missing_field_seed(PhantomData, field)
- }
}
impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
@@ -1005,20 +1166,6 @@ impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
fn size_hint(&self) -> (usize, Option<usize>) {
(**self).size_hint()
}
-
- #[inline]
- fn missing_field_seed<V>(&mut self, seed: V, field: &'static str) -> Result<V::Value, Self::Error>
- where V: DeserializeSeed
- {
- (**self).missing_field_seed(seed, field)
- }
-
- #[inline]
- fn missing_field<V>(&mut self, field: &'static str) -> Result<V, Self::Error>
- where V: Deserialize
- {
- (**self).missing_field(field)
- }
}
///////////////////////////////////////////////////////////////////////////////
@@ -1100,3 +1247,34 @@ pub trait VariantVisitor: Sized {
visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
}
+
+///////////////////////////////////////////////////////////////////////////////
+
+/// Used in error messages.
+///
+/// - expected `a`
+/// - expected `a` or `b`
+/// - expected one of `a`, `b`, `c`
+struct OneOf {
+ names: &'static [&'static str],
+}
+
+impl Display for OneOf {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ match self.names.len() {
+ 0 => panic!(), // special case elsewhere
+ 1 => write!(formatter, "`{}`", self.names[0]),
+ 2 => write!(formatter, "`{}` or `{}`", self.names[0], self.names[1]),
+ _ => {
+ try!(write!(formatter, "one of "));
+ for (i, alt) in self.names.iter().enumerate() {
+ if i > 0 {
+ try!(write!(formatter, ", "));
+ }
+ try!(write!(formatter, "`{}`", alt));
+ }
+ Ok(())
+ }
+ }
+ }
+}
diff --git a/serde/src/de/private.rs b/serde/src/de/private.rs
new file mode 100644
index 000000000..92e71cf86
--- /dev/null
+++ b/serde/src/de/private.rs
@@ -0,0 +1,40 @@
+use core::marker::PhantomData;
+
+use de::{Deserialize, Deserializer, Error, Visitor};
+
+/// If the missing field is of type `Option<T>` then treat is as `None`,
+/// otherwise it is an error.
+pub fn missing_field<V, E>(field: &'static str) -> Result<V, E>
+ where V: Deserialize,
+ E: Error
+{
+ struct MissingFieldDeserializer<E>(&'static str, PhantomData<E>);
+
+ impl<E> Deserializer for MissingFieldDeserializer<E>
+ where E: Error
+ {
+ type Error = E;
+
+ fn deserialize<V>(self, _visitor: V) -> Result<V::Value, E>
+ where V: Visitor
+ {
+ Err(Error::missing_field(self.0))
+ }
+
+ fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E>
+ where V: Visitor
+ {
+ visitor.visit_none()
+ }
+
+ forward_to_deserialize! {
+ bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str
+ string unit seq seq_fixed_size bytes byte_buf map unit_struct
+ newtype_struct tuple_struct struct struct_field tuple enum
+ ignored_any
+ }
+ }
+
+ let deserializer = MissingFieldDeserializer(field, PhantomData);
+ Deserialize::deserialize(deserializer)
+}
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 9e2bdf76f..f34fb0873 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -28,6 +28,10 @@ use collections::{
};
#[cfg(all(feature = "collections", not(feature = "std")))]
use collections::borrow::Cow;
+#[cfg(all(feature = "collections", not(feature = "std")))]
+use collections::boxed::Box;
+#[cfg(all(feature = "collections", not(feature = "std")))]
+use collections::string::ToString;
#[cfg(all(feature = "unstable", feature = "collections"))]
use collections::borrow::ToOwned;
@@ -38,112 +42,57 @@ use std::error;
#[cfg(not(feature = "std"))]
use error;
-use core::fmt;
+use core::fmt::{self, Display};
+use core::iter::{self, Iterator};
use core::marker::PhantomData;
-use de::{self, SeqVisitor};
+use de::{self, Expected, SeqVisitor};
use bytes;
///////////////////////////////////////////////////////////////////////////////
/// This represents all the possible errors that can occur using the `ValueDeserializer`.
#[derive(Clone, Debug, PartialEq)]
-pub enum Error {
- /// The value had some custom error.
- #[cfg(any(feature = "std", feature = "collections"))]
- Custom(String),
- /// The value had some custom error.
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- Custom(&'static str),
+pub struct Error(ErrorImpl);
- /// The value had an incorrect type.
- InvalidType(de::Type),
-
- /// The value had an invalid length.
- InvalidLength(usize),
-
- /// The value is invalid and cannot be deserialized.
- #[cfg(any(feature = "std", feature = "collections"))]
- InvalidValue(String),
- /// The value is invalid and cannot be deserialized.
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- InvalidValue(&'static str),
-
- /// EOF while deserializing a value.
- EndOfStream,
-
- /// Unknown variant in enum.
- #[cfg(any(feature = "std", feature = "collections"))]
- UnknownVariant(String),
- /// Unknown variant in enum.
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- UnknownVariant(&'static str),
-
- /// Unknown field in struct.
- #[cfg(any(feature = "std", feature = "collections"))]
- UnknownField(String),
- /// Unknown field in struct.
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- UnknownField(&'static str),
-
- /// Struct is missing a field.
- MissingField(&'static str),
-}
+#[cfg(any(feature = "std", feature = "collections"))]
+type ErrorImpl = Box<str>;
+#[cfg(not(any(feature = "std", feature = "collections")))]
+type ErrorImpl = ();
impl de::Error for Error {
#[cfg(any(feature = "std", feature = "collections"))]
- fn custom<T: Into<String>>(msg: T) -> Self { Error::Custom(msg.into()) }
-
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- fn custom<T: Into<&'static str>>(msg: T) -> Self { Error::Custom(msg.into()) }
-
- fn end_of_stream() -> Self { Error::EndOfStream }
- fn invalid_type(ty: de::Type) -> Self { Error::InvalidType(ty) }
-
- #[cfg(any(feature = "std", feature = "collections"))]
- fn invalid_value(msg: &str) -> Self { Error::InvalidValue(msg.to_owned()) }
-
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- fn invalid_value(msg: &str) -> Self { Error::InvalidValue("invalid value") }
+ fn custom<T: Display>(msg: T) -> Self {
+ Error(msg.to_string().into_boxed_str())
+ }
- fn invalid_length(len: usize) -> Self { Error::InvalidLength(len) }
+ #[cfg(not(any(feature = "std", feature = "collections")))]
+ fn custom<T: Display>(msg: T) -> Self {
+ Error(())
+ }
+}
+impl Display for Error {
#[cfg(any(feature = "std", feature = "collections"))]
- fn unknown_variant(variant: &str) -> Self { Error::UnknownVariant(String::from(variant)) }
- #[cfg(any(feature = "std", feature = "collections"))]
- fn unknown_field(field: &str) -> Self { Error::UnknownField(String::from(field)) }
-
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- fn unknown_variant(variant: &str) -> Self { Error::UnknownVariant("unknown variant") }
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- fn unknown_field(field: &str) -> Self { Error::UnknownField("unknown field") }
- fn missing_field(field: &'static str) -> Self { Error::MissingField(field) }
-}
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+ formatter.write_str(&self.0)
+ }
-impl fmt::Display for Error {
+ #[cfg(not(any(feature = "std", feature = "collections")))]
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
- match *self {
- Error::Custom(ref s) => write!(formatter, "{}", s),
- Error::EndOfStream => formatter.write_str("End of stream"),
- Error::InvalidType(ty) => write!(formatter, "Invalid type, expected `{:?}`", ty),
- Error::InvalidValue(ref value) => write!(formatter, "Invalid value: {}", value),
- Error::InvalidLength(len) => write!(formatter, "Invalid length: {}", len),
- Error::UnknownVariant(ref variant) => {
- write!(formatter, "Unknown variant: {}", variant)
- }
- Error::UnknownField(ref field) => write!(formatter, "Unknown field: {}", field),
- Error::MissingField(field) => write!(formatter, "Missing field: {}", field),
- }
+ formatter.write_str("Serde deserialization error")
}
}
impl error::Error for Error {
+ #[cfg(any(feature = "std", feature = "collections"))]
fn description(&self) -> &str {
- "Serde Deserialization Error"
+ &self.0
}
- fn cause(&self) -> Option<&error::Error> {
- None
+ #[cfg(not(any(feature = "std", feature = "collections")))]
+ fn description(&self) -> &str {
+ "Serde deserialization error"
}
}
@@ -430,22 +379,37 @@ impl<'a, E> de::EnumVisitor for CowStrDeserializer<'a, E>
/// A helper deserializer that deserializes a sequence.
pub struct SeqDeserializer<I, E> {
- iter: I,
- len: usize,
+ iter: iter::Fuse<I>,
+ count: usize,
marker: PhantomData<E>,
}
impl<I, E> SeqDeserializer<I, E>
- where E: de::Error,
+ where I: Iterator,
+ E: de::Error,
{
/// Construct a new `SeqDeserializer<I>`.
- pub fn new(iter: I, len: usize) -> Self {
+ pub fn new(iter: I) -> Self {
SeqDeserializer {
- iter: iter,
- len: len,
+ iter: iter.fuse(),
+ count: 0,
marker: PhantomData,
}
}
+
+ fn end(&mut self) -> Result<(), E> {
+ let mut remaining = 0;
+ while self.iter.next().is_some() {
+ remaining += 1;
+ }
+ if remaining == 0 {
+ Ok(())
+ } else {
+ // First argument is the number of elements in the data, second
+ // argument is the number of elements expected by the Deserialize.
+ Err(de::Error::invalid_length(self.count + remaining, &ExpectedInSeq(self.count)))
+ }
+ }
}
impl<I, T, E> de::Deserializer for SeqDeserializer<I, E>
@@ -459,11 +423,8 @@ impl<I, T, E> de::Deserializer for SeqDeserializer<I, E>
where V: de::Visitor,
{
let v = try!(visitor.visit_seq(&mut self));
- if self.len == 0 {
- Ok(v)
- } else {
- Err(de::Error::invalid_length(self.len))
- }
+ try!(self.end());
+ Ok(v)
}
forward_to_deserialize! {
@@ -485,7 +446,7 @@ impl<I, T, E> de::SeqVisitor for SeqDeserializer<I, E>
{
match self.iter.next() {
Some(value) => {
- self.len -= 1;
+ self.count += 1;
seed.deserialize(value.into_deserializer()).map(Some)
}
None => Ok(None),
@@ -493,7 +454,19 @@ impl<I, T, E> de::SeqVisitor for SeqDeserializer<I, E>
}
fn size_hint(&self) -> (usize, Option<usize>) {
- (self.len, Some(self.len))
+ self.iter.size_hint()
+ }
+}
+
+struct ExpectedInSeq(usize);
+
+impl Expected for ExpectedInSeq {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ if self.0 == 1 {
+ write!(formatter, "1 element in sequence")
+ } else {
+ write!(formatter, "{} elements in sequence", self.0)
+ }
}
}
@@ -507,8 +480,7 @@ impl<T, E> ValueDeserializer<E> for Vec<T>
type Deserializer = SeqDeserializer<vec::IntoIter<T>, E>;
fn into_deserializer(self) -> Self::Deserializer {
- let len = self.len();
- SeqDeserializer::new(self.into_iter(), len)
+ SeqDeserializer::new(self.into_iter())
}
}
@@ -520,8 +492,7 @@ impl<T, E> ValueDeserializer<E> for BTreeSet<T>
type Deserializer = SeqDeserializer<btree_set::IntoIter<T>, E>;
fn into_deserializer(self) -> Self::Deserializer {
- let len = self.len();
- SeqDeserializer::new(self.into_iter(), len)
+ SeqDeserializer::new(self.into_iter())
}
}
@@ -533,8 +504,7 @@ impl<T, E> ValueDeserializer<E> for HashSet<T>
type Deserializer = SeqDeserializer<hash_set::IntoIter<T>, E>;
fn into_deserializer(self) -> Self::Deserializer {
- let len = self.len();
- SeqDeserializer::new(self.into_iter(), len)
+ SeqDeserializer::new(self.into_iter())
}
}
@@ -579,66 +549,66 @@ impl<V_, E> de::Deserializer for SeqVisitorDeserializer<V_, E>
///////////////////////////////////////////////////////////////////////////////
/// A helper deserializer that deserializes a map.
-pub struct MapDeserializer<I, K, V, E>
- where I: Iterator<Item=(K, V)>,
- K: ValueDeserializer<E>,
- V: ValueDeserializer<E>,
+pub struct MapDeserializer<I, E>
+ where I: Iterator,
+ I::Item: private::Pair,
+ <I::Item as private::Pair>::First: ValueDeserializer<E>,
+ <I::Item as private::Pair>::Second: ValueDeserializer<E>,
E: de::Error,
{
- iter: I,
- value: Option<V>,
- len: Option<usize>,
+ iter: iter::Fuse<I>,
+ value: Option<<I::Item as private::Pair>::Second>,
+ count: usize,
marker: PhantomData<E>,
}
-impl<I, K, V, E> MapDeserializer<I, K, V, E>
- where I: Iterator<Item=(K, V)>,
- K: ValueDeserializer<E>,
- V: ValueDeserializer<E>,
+impl<I, E> MapDeserializer<I, E>
+ where I: Iterator,
+ I::Item: private::Pair,
+ <I::Item as private::Pair>::First: ValueDeserializer<E>,
+ <I::Item as private::Pair>::Second: ValueDeserializer<E>,
E: de::Error,
{
- /// Construct a new `MapDeserializer<I, K, V, E>` with a specific length.
- pub fn new(iter: I, len: usize) -> Self {
+ /// Construct a new `MapDeserializer<I, K, V, E>`.
+ pub fn new(iter: I) -> Self {
MapDeserializer {
- iter: iter,
+ iter: iter.fuse(),
value: None,
- len: Some(len),
+ count: 0,
marker: PhantomData,
}
}
- /// Construct a new `MapDeserializer<I, K, V, E>` that is not bounded
- /// by a specific length and that delegates to `iter` for its size hint.
- pub fn unbounded(iter: I) -> Self {
- MapDeserializer {
- iter: iter,
- value: None,
- len: None,
- marker: PhantomData,
- }
- }
-
- fn next(&mut self) -> Option<(K, V)> {
- self.iter.next().map(|(k, v)| {
- if let Some(len) = self.len.as_mut() {
- *len -= 1;
+ fn next(&mut self) -> Option<(<I::Item as private::Pair>::First, <I::Item as private::Pair>::Second)> {
+ match self.iter.next() {
+ Some(kv) => {
+ self.count += 1;
+ Some(private::Pair::split(kv))
}
- (k, v)
- })
+ None => None,
+ }
}
fn end(&mut self) -> Result<(), E> {
- match self.len {
- Some(len) if len > 0 => Err(de::Error::invalid_length(len)),
- _ => Ok(())
+ let mut remaining = 0;
+ while self.iter.next().is_some() {
+ remaining += 1;
+ }
+ if remaining == 0 {
+ Ok(())
+ } else {
+ // First argument is the number of elements in the data, second
+ // argument is the number of elements expected by the Deserialize.
+ Err(de::Error::invalid_length(self.count + remaining, &ExpectedInMap(self.count)))
}
}
}
-impl<I, K, V, E> de::Deserializer for MapDeserializer<I, K, V, E>
- where I: Iterator<Item=(K, V)>,
- K: ValueDeserializer<E>,
- V: ValueDeserializer<E>,
+impl<I, E> de::Deserializer for MapDeserializer<I, E>
+ where I: Iterator,
+ I::Item: private::Pair,
+ <I::Item as private::Pair>::First: ValueDeserializer<E>,
+ <I::Item as private::Pair>::Second: ValueDeserializer<E>,
E: de::Error,
{
type Error = E;
@@ -659,17 +629,10 @@ impl<I, K, V, E> de::Deserializer for MapDeserializer<I, K, V, E>
Ok(value)
}
- fn deserialize_seq_fixed_size<V_>(mut self, len: usize, visitor: V_) -> Result<V_::Value, Self::Error>
+ fn deserialize_seq_fixed_size<V_>(self, _len: usize, visitor: V_) -> Result<V_::Value, Self::Error>
where V_: de::Visitor,
{
- match self.len {
- Some(map_len) if map_len != len => Err(de::Error::invalid_length(len)),
- _ => {
- let value = try!(visitor.visit_seq(&mut self));
- try!(self.end());
- Ok(value)
- }
- }
+ self.deserialize_seq(visitor)
}
forward_to_deserialize! {
@@ -679,10 +642,11 @@ impl<I, K, V, E> de::Deserializer for MapDeserializer<I, K, V, E>
}
}
-impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
- where I: Iterator<Item=(K, V)>,
- K: ValueDeserializer<E>,
- V: ValueDeserializer<E>,
+impl<I, E> de::MapVisitor for MapDeserializer<I, E>
+ where I: Iterator,
+ I::Item: private::Pair,
+ <I::Item as private::Pair>::First: ValueDeserializer<E>,
+ <I::Item as private::Pair>::Second: ValueDeserializer<E>,
E: de::Error,
{
type Error = E;
@@ -702,14 +666,11 @@ impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
where T: de::DeserializeSeed,
{
- match self.value.take() {
- Some(value) => {
- seed.deserialize(value.into_deserializer())
- }
- None => {
- Err(de::Error::end_of_stream())
- }
- }
+ let value = self.value.take();
+ // Panic because this indicates a bug in the program rather than an
+ // expected failure.
+ let value = value.expect("MapVisitor::visit_value called before visit_key");
+ seed.deserialize(value.into_deserializer())
}
fn visit_seed<TK, TV>(&mut self, kseed: TK, vseed: TV) -> Result<Option<(TK::Value, TV::Value)>, Self::Error>
@@ -727,16 +688,15 @@ impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
}
fn size_hint(&self) -> (usize, Option<usize>) {
- self.len.map_or_else(
- || self.iter.size_hint(),
- |len| (len, Some(len)))
+ self.iter.size_hint()
}
}
-impl<I, K, V, E> de::SeqVisitor for MapDeserializer<I, K, V, E>
- where I: Iterator<Item=(K, V)>,
- K: ValueDeserializer<E>,
- V: ValueDeserializer<E>,
+impl<I, E> de::SeqVisitor for MapDeserializer<I, E>
+ where I: Iterator,
+ I::Item: private::Pair,
+ <I::Item as private::Pair>::First: ValueDeserializer<E>,
+ <I::Item as private::Pair>::Second: ValueDeserializer<E>,
E: de::Error,
{
type Error = E;
@@ -754,7 +714,7 @@ impl<I, K, V, E> de::SeqVisitor for MapDeserializer<I, K, V, E>
}
fn size_hint(&self) -> (usize, Option<usize>) {
- de::MapVisitor::size_hint(self)
+ self.iter.size_hint()
}
}
@@ -789,7 +749,10 @@ impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E>
if pair_visitor.1.is_none() {
Ok(pair)
} else {
- Err(de::Error::invalid_length(pair_visitor.size_hint().0))
+ let remaining = pair_visitor.size_hint().0;
+ // First argument is the number of elements in the data, second
+ // argument is the number of elements expected by the Deserialize.
+ Err(de::Error::invalid_length(2, &ExpectedInSeq(2 - remaining)))
}
}
@@ -799,7 +762,9 @@ impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E>
if len == 2 {
self.deserialize_seq(visitor)
} else {
- Err(de::Error::invalid_length(len))
+ // First argument is the number of elements in the data, second
+ // argument is the number of elements expected by the Deserialize.
+ Err(de::Error::invalid_length(2, &ExpectedInSeq(len)))
}
}
}
@@ -837,6 +802,18 @@ impl<A, B, E> de::SeqVisitor for PairVisitor<A, B, E>
}
}
+struct ExpectedInMap(usize);
+
+impl Expected for ExpectedInMap {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ if self.0 == 1 {
+ write!(formatter, "1 element in map")
+ } else {
+ write!(formatter, "{} elements in map", self.0)
+ }
+ }
+}
+
///////////////////////////////////////////////////////////////////////////////
#[cfg(any(feature = "std", feature = "collections"))]
@@ -845,11 +822,10 @@ impl<K, V, E> ValueDeserializer<E> for BTreeMap<K, V>
V: ValueDeserializer<E>,
E: de::Error,
{
- type Deserializer = MapDeserializer<btree_map::IntoIter<K, V>, K, V, E>;
+ type Deserializer = MapDeserializer<btree_map::IntoIter<K, V>, E>;
fn into_deserializer(self) -> Self::Deserializer {
- let len = self.len();
- MapDeserializer::new(self.into_iter(), len)
+ MapDeserializer::new(self.into_iter())
}
}
@@ -859,11 +835,10 @@ impl<K, V, E> ValueDeserializer<E> for HashMap<K, V>
V: ValueDeserializer<E>,
E: de::Error,
{
- type Deserializer = MapDeserializer<hash_map::IntoIter<K, V>, K, V, E>;
+ type Deserializer = MapDeserializer<hash_map::IntoIter<K, V>, E>;
fn into_deserializer(self) -> Self::Deserializer {
- let len = self.len();
- MapDeserializer::new(self.into_iter(), len)
+ MapDeserializer::new(self.into_iter())
}
}
@@ -977,7 +952,7 @@ impl<E> de::Deserializer for ByteBufDeserializer<E>
///////////////////////////////////////////////////////////////////////////////
mod private {
- use de;
+ use de::{self, Unexpected};
use core::marker::PhantomData;
pub struct UnitOnly<E>(PhantomData<E>);
@@ -998,7 +973,7 @@ mod private {
fn visit_newtype_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
where T: de::DeserializeSeed,
{
- Err(de::Error::invalid_type(de::Type::NewtypeVariant))
+ Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant"))
}
fn visit_tuple<V>(self,
@@ -1006,7 +981,7 @@ mod private {
_visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor
{
- Err(de::Error::invalid_type(de::Type::TupleVariant))
+ Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"))
}
fn visit_struct<V>(self,
@@ -1014,7 +989,21 @@ mod private {
_visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor
{
- Err(de::Error::invalid_type(de::Type::StructVariant))
+ Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant"))
}
}
+
+ /// Avoid having to restate the generic types on MapDeserializer. The
+ /// Iterator::Item contains enough information to figure out K and V.
+ pub trait Pair {
+ type First;
+ type Second;
+ fn split(self) -> (Self::First, Self::Second);
+ }
+
+ impl<A, B> Pair for (A, B) {
+ type First = A;
+ type Second = B;
+ fn split(self) -> (A, B) { self }
+ }
}
diff --git a/serde/src/error.rs b/serde/src/error.rs
index f6b704c74..6c411f847 100644
--- a/serde/src/error.rs
+++ b/serde/src/error.rs
@@ -1,5 +1,4 @@
//! A stand-in for `std::error`
-use core::any::TypeId;
use core::fmt::{Debug, Display};
/// A stand-in for `std::error::Error`, which requires no allocation.
@@ -13,10 +12,4 @@ pub trait Error: Debug + Display {
/// The lower-level cause of this error, if any.
fn cause(&self) -> Option<&Error> { None }
-
- /// Get the `TypeId` of `self`
- #[doc(hidden)]
- fn type_id(&self) -> TypeId where Self: 'static {
- TypeId::of::<Self>()
- }
}
diff --git a/serde/src/lib.rs b/serde/src/lib.rs
index 2046872bb..24f2a6772 100644
--- a/serde/src/lib.rs
+++ b/serde/src/lib.rs
@@ -40,11 +40,6 @@ mod core {
pub use ser::{Serialize, Serializer};
pub use de::{Deserialize, Deserializer};
-#[cfg(not(feature = "std"))]
-macro_rules! format {
- ($s:expr, $($rest:tt)*) => ($s)
-}
-
#[macro_use]
mod macros;
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index f09b28718..e89f0cd3f 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -772,7 +772,7 @@ impl Serialize for path::Path {
{
match self.to_str() {
Some(s) => s.serialize(serializer),
- None => Err(Error::invalid_value("Path contains invalid UTF-8 characters")),
+ None => Err(Error::custom("Path contains invalid UTF-8 characters")),
}
}
}
diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs
index 3b2e3d342..10b14fdac 100644
--- a/serde/src/ser/mod.rs
+++ b/serde/src/ser/mod.rs
@@ -23,6 +23,8 @@ use core::marker::PhantomData;
#[cfg(feature = "unstable")]
use core::cell::RefCell;
+use core::fmt::Display;
+
pub mod impls;
///////////////////////////////////////////////////////////////////////////////
@@ -31,17 +33,7 @@ pub mod impls;
/// `Serializer` error.
pub trait Error: Sized + error::Error {
/// Raised when there is a general error when serializing a type.
- #[cfg(any(feature = "std", feature = "collections"))]
- fn custom<T: Into<String>>(msg: T) -> Self;
-
- /// Raised when there is a general error when serializing a type.
- #[cfg(all(not(feature = "std"), not(feature = "collections")))]
- fn custom<T: Into<&'static str>>(msg: T) -> Self;
-
- /// Raised when a `Serialize` was passed an incorrect value.
- fn invalid_value(msg: &str) -> Self {
- Error::custom(format!("invalid value: {}", msg))
- }
+ fn custom<T: Display>(msg: T) -> Self;
}
///////////////////////////////////////////////////////////////////////////////
diff --git a/serde_codegen/Cargo.toml b/serde_codegen/Cargo.toml
index 757e838f3..6161e373e 100644
--- a/serde_codegen/Cargo.toml
+++ b/serde_codegen/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_codegen"
-version = "0.9.0-rc1"
+version = "0.9.0-rc2"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Macros to auto-generate implementations for the serde framework"
diff --git a/serde_codegen/src/de.rs b/serde_codegen/src/de.rs
index e9771247c..f1274bca6 100644
--- a/serde_codegen/src/de.rs
+++ b/serde_codegen/src/de.rs
@@ -200,12 +200,18 @@ fn deserialize_unit_struct(
) -> Tokens {
let type_name = item_attrs.name().deserialize_name();
+ let expecting = format!("unit struct {}", type_ident);
+
quote!({
struct __Visitor;
impl _serde::de::Visitor for __Visitor {
type Value = #type_ident;
+ fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+ formatter.write_str(#expecting)
+ }
+
#[inline]
fn visit_unit<__E>(self) -> ::std::result::Result<#type_ident, __E>
where __E: _serde::de::Error,
@@ -242,6 +248,10 @@ fn deserialize_tuple(
Some(variant_ident) => quote!(#type_ident::#variant_ident),
None => quote!(#type_ident),
};
+ let expecting = match variant_ident {
+ Some(variant_ident) => format!("tuple variant {}::{}", type_ident, variant_ident),
+ None => format!("tuple struct {}", type_ident),
+ };
let nfields = fields.len();
@@ -287,6 +297,10 @@ fn deserialize_tuple(
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
type Value = #ty;
+ fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+ formatter.write_str(#expecting)
+ }
+
#visit_newtype_struct
#[inline]
@@ -310,6 +324,11 @@ fn deserialize_seq(
) -> Tokens {
let vars = (0..fields.len()).map(field_i as fn(_) -> _);
+ let deserialized_count = fields.iter()
+ .filter(|field| !field.attrs.skip_deserializing())
+ .count();
+ let expecting = format!("tuple of {} elements", deserialized_count);
+
let mut index_in_seq = 0usize;
let let_values = vars.clone().zip(fields)
.map(|(var, field)| {
@@ -338,7 +357,7 @@ fn deserialize_seq(
let #var = match #visit {
Some(value) => { value },
None => {
- return Err(_serde::de::Error::invalid_length(#index_in_seq));
+ return Err(_serde::de::Error::invalid_length(#index_in_seq, &#expecting));
}
};
};
@@ -413,6 +432,10 @@ fn deserialize_struct(
Some(variant_ident) => quote!(#type_ident::#variant_ident),
None => quote!(#type_ident),
};
+ let expecting = match variant_ident {
+ Some(variant_ident) => format!("struct variant {}::{}", type_ident, variant_ident),
+ None => format!("struct {}", type_ident),
+ };
let visit_seq = deserialize_seq(
type_ident,
@@ -457,6 +480,10 @@ fn deserialize_struct(
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
type Value = #ty;
+ fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+ formatter.write_str(#expecting)
+ }
+
#[inline]
fn visit_seq<__V>(self, #visitor_var: __V) -> ::std::result::Result<#ty, __V::Error>
where __V: _serde::de::SeqVisitor
@@ -489,6 +516,8 @@ fn deserialize_item_enum(
let type_name = item_attrs.name().deserialize_name();
+ let expecting = format!("enum {}", type_ident);
+
let variant_names_idents: Vec<_> = variants.iter()
.enumerate()
.filter(|&(_, variant)| !variant.attrs.skip_deserializing())
@@ -556,6 +585,10 @@ fn deserialize_item_enum(
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
type Value = #ty;
+ fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+ formatter.write_str(#expecting)
+ }
+
fn visit_enum<__V>(self, visitor: __V) -> ::std::result::Result<#ty, __V::Error>
where __V: _serde::de::EnumVisitor,
{
@@ -660,11 +693,11 @@ fn deserialize_field_visitor(
let fallthrough_arm = if is_variant {
quote! {
- Err(_serde::de::Error::unknown_variant(value))
+ Err(_serde::de::Error::unknown_variant(value, VARIANTS))
}
} else if item_attrs.deny_unknown_fields() {
quote! {
- Err(_serde::de::Error::unknown_field(value))
+ Err(_serde::de::Error::unknown_field(value, FIELDS))
}
} else {
quote! {
@@ -689,6 +722,10 @@ fn deserialize_field_visitor(
impl _serde::de::Visitor for __FieldVisitor {
type Value = __Field;
+ fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+ formatter.write_str("field name")
+ }
+
fn visit_str<__E>(self, value: &str) -> ::std::result::Result<__Field, __E>
where __E: _serde::de::Error
{
@@ -931,7 +968,7 @@ fn expr_is_missing(attrs: &attr::Field) -> Tokens {
match attrs.deserialize_with() {
None => {
quote! {
- try!(visitor.missing_field(#name))
+ try!(_serde::de::private::missing_field(#name))
}
}
Some(_) => {
diff --git a/serde_codegen/src/ser.rs b/serde_codegen/src/ser.rs
index acd9973cd..3374d5acf 100644
--- a/serde_codegen/src/ser.rs
+++ b/serde_codegen/src/ser.rs
@@ -257,10 +257,10 @@ fn serialize_variant(
let variant_name = variant.attrs.name().serialize_name();
if variant.attrs.skip_serializing() {
- let skipped_msg = format!("The enum variant {}::{} cannot be serialized",
+ let skipped_msg = format!("the enum variant {}::{} cannot be serialized",
type_ident, variant_ident);
let skipped_err = quote! {
- Err(_serde::ser::Error::invalid_value(#skipped_msg))
+ Err(_serde::ser::Error::custom(#skipped_msg))
};
let fields_pat = match variant.style {
Style::Unit => quote!(),
diff --git a/serde_derive/Cargo.toml b/serde_derive/Cargo.toml
index 183370454..ddc3f62f8 100644
--- a/serde_derive/Cargo.toml
+++ b/serde_derive/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "serde_derive"
-version = "0.9.0-rc1"
+version = "0.9.0-rc2"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]"
@@ -15,7 +15,7 @@ name = "serde_derive"
proc-macro = true
[dependencies.serde_codegen]
-version = "=0.9.0-rc1"
+version = "=0.9.0-rc2"
path = "../serde_codegen"
default-features = false
features = ["with-syn"]
@@ -23,5 +23,5 @@ features = ["with-syn"]
[dev-dependencies]
compiletest_rs = "^0.2.0"
fnv = "1.0"
-serde = { version = "0.9.0-rc1", path = "../serde" }
-serde_test = { version = "0.9.0-rc1", path = "../serde_test" }
+serde = { version = "0.9.0-rc2", path = "../serde" }
+serde_test = { version = "0.9.0-rc2", path = "../serde_test" }
| serde-rs/serde | 2017-01-21T10:36:09Z |
mwhaha, `serde_xml` should not be a benchmark of good `Deserializer` design. It's what you'd get if you wrote a test-suite and threw a neural network against it that gets encouraged to pass more tests.
What we do at the location you linked is to rename a field to `$value`, and in case a tag like `<tag>content</tag>` comes along, you end up triggering `missing_field` for the `$value` field and extract "content" to be the value of that field. One would think that a string-newtype or similar could also suffice, but we can also have `<tag attr="foo">content</tag>`, where we need a field named `attr`.
Mapping xml schemata to Rust types is a nightmare, the experiment is a failure in my opinion. It's not serde's fault, it's just that xml schemata have many weird things that basically only work with object oriented systems with inheritance.
What would serde_xml do if we take away missing_field?
Probably match on an error
And use a seed
Let's do that then. I think this would be a net benefit for every other use case except serde_xml. We replace the three different behaviors with one consistent approach and no longer need this awkwardly placed API. What do you think?
We would still need to settle which behavior to use:
- For options treat missing field as None, otherwise error
- Treat missing field as unit
In practice this matters most for collection types like Vec\<T>. The first one makes it an error, the second one makes it empty vec. I prefer the first approach and if you want the second behavior you can either put #[serde(default)] on the vec field or use Option\<Vec\<T>>.
In theory we could also unconditionally make missing field an error, and require #[serde(default)] on Option\<T> fields to make it None. That seems excessive to me. Option is already a special case in the Serializer and Deserializer traits and it seems pretty intuitive that if your field is optional and it isn't there then it is None. | 8cb6607e827717136a819caa44d8e43702724883 |
703 | diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index 849bdf27c..3630d7247 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -3,6 +3,7 @@ use std::iter;
use serde::de::{
self,
Deserialize,
+ DeserializeSeed,
EnumVisitor,
MapVisitor,
SeqVisitor,
@@ -496,14 +497,14 @@ impl<'a, I> SeqVisitor for DeserializerSeqVisitor<'a, I>
{
type Error = Error;
- fn visit<T>(&mut self) -> Result<Option<T>, Error>
- where T: Deserialize,
+ fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
+ where T: DeserializeSeed,
{
match self.de.tokens.peek() {
Some(&Token::SeqSep) => {
self.de.tokens.next();
self.len = self.len.map(|len| len - 1);
- Deserialize::deserialize(&mut *self.de).map(Some)
+ seed.deserialize(&mut *self.de).map(Some)
}
Some(&Token::SeqEnd) => Ok(None),
Some(_) => {
@@ -532,14 +533,14 @@ impl<'a, I> SeqVisitor for DeserializerArrayVisitor<'a, I>
{
type Error = Error;
- fn visit<T>(&mut self) -> Result<Option<T>, Error>
- where T: Deserialize,
+ fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
+ where T: DeserializeSeed,
{
match self.de.tokens.peek() {
Some(&Token::SeqSep) => {
self.de.tokens.next();
self.len -= 1;
- Deserialize::deserialize(&mut *self.de).map(Some)
+ seed.deserialize(&mut *self.de).map(Some)
}
Some(&Token::SeqEnd) => Ok(None),
Some(_) => {
@@ -567,14 +568,14 @@ impl<'a, I> SeqVisitor for DeserializerTupleVisitor<'a, I>
{
type Error = Error;
- fn visit<T>(&mut self) -> Result<Option<T>, Error>
- where T: Deserialize,
+ fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
+ where T: DeserializeSeed,
{
match self.de.tokens.peek() {
Some(&Token::TupleSep) => {
self.de.tokens.next();
self.len -= 1;
- Deserialize::deserialize(&mut *self.de).map(Some)
+ seed.deserialize(&mut *self.de).map(Some)
}
Some(&Token::TupleEnd) => Ok(None),
Some(_) => {
@@ -602,14 +603,14 @@ impl<'a, I> SeqVisitor for DeserializerTupleStructVisitor<'a, I>
{
type Error = Error;
- fn visit<T>(&mut self) -> Result<Option<T>, Error>
- where T: Deserialize,
+ fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
+ where T: DeserializeSeed,
{
match self.de.tokens.peek() {
Some(&Token::TupleStructSep) => {
self.de.tokens.next();
self.len -= 1;
- Deserialize::deserialize(&mut *self.de).map(Some)
+ seed.deserialize(&mut *self.de).map(Some)
}
Some(&Token::TupleStructEnd) => Ok(None),
Some(_) => {
@@ -637,14 +638,14 @@ impl<'a, I> SeqVisitor for DeserializerVariantSeqVisitor<'a, I>
{
type Error = Error;
- fn visit<T>(&mut self) -> Result<Option<T>, Error>
- where T: Deserialize,
+ fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
+ where T: DeserializeSeed,
{
match self.de.tokens.peek() {
Some(&Token::EnumSeqSep) => {
self.de.tokens.next();
self.len = self.len.map(|len| len - 1);
- Deserialize::deserialize(&mut *self.de).map(Some)
+ seed.deserialize(&mut *self.de).map(Some)
}
Some(&Token::EnumSeqEnd) => Ok(None),
Some(_) => {
@@ -673,14 +674,14 @@ impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
{
type Error = Error;
- fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
- where K: Deserialize,
+ fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
+ where K: DeserializeSeed,
{
match self.de.tokens.peek() {
Some(&Token::MapSep) => {
self.de.tokens.next();
self.len = self.len.map(|len| if len > 0 { len - 1} else { 0 });
- Deserialize::deserialize(&mut *self.de).map(Some)
+ seed.deserialize(&mut *self.de).map(Some)
}
Some(&Token::MapEnd) => Ok(None),
Some(_) => {
@@ -691,10 +692,10 @@ impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
}
}
- fn visit_value<V>(&mut self) -> Result<V, Error>
- where V: Deserialize,
+ fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
+ where V: DeserializeSeed,
{
- Deserialize::deserialize(&mut *self.de)
+ seed.deserialize(&mut *self.de)
}
fn size_hint(&self) -> (usize, Option<usize>) {
@@ -715,14 +716,14 @@ impl<'a, I> MapVisitor for DeserializerStructVisitor<'a, I>
{
type Error = Error;
- fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
- where K: Deserialize,
+ fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
+ where K: DeserializeSeed,
{
match self.de.tokens.peek() {
Some(&Token::StructSep) => {
self.de.tokens.next();
self.len = self.len.saturating_sub(1);
- Deserialize::deserialize(&mut *self.de).map(Some)
+ seed.deserialize(&mut *self.de).map(Some)
}
Some(&Token::StructEnd) => Ok(None),
Some(_) => {
@@ -733,10 +734,10 @@ impl<'a, I> MapVisitor for DeserializerStructVisitor<'a, I>
}
}
- fn visit_value<V>(&mut self) -> Result<V, Error>
- where V: Deserialize,
+ fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
+ where V: DeserializeSeed,
{
- Deserialize::deserialize(&mut *self.de)
+ seed.deserialize(&mut *self.de)
}
fn size_hint(&self) -> (usize, Option<usize>) {
@@ -756,8 +757,8 @@ impl<'a, I> EnumVisitor for DeserializerEnumVisitor<'a, I>
type Error = Error;
type Variant = Self;
- fn visit_variant<V>(self) -> Result<(V, Self), Error>
- where V: Deserialize,
+ fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self), Error>
+ where V: DeserializeSeed,
{
match self.de.tokens.peek() {
Some(&Token::EnumUnit(_, v))
@@ -765,11 +766,11 @@ impl<'a, I> EnumVisitor for DeserializerEnumVisitor<'a, I>
| Some(&Token::EnumSeqStart(_, v, _))
| Some(&Token::EnumMapStart(_, v, _)) => {
let de = v.into_deserializer();
- let value = try!(Deserialize::deserialize(de));
+ let value = try!(seed.deserialize(de));
Ok((value, self))
}
Some(_) => {
- let value = try!(Deserialize::deserialize(&mut *self.de));
+ let value = try!(seed.deserialize(&mut *self.de));
Ok((value, self))
}
None => Err(Error::EndOfStream),
@@ -795,16 +796,16 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
}
}
- fn visit_newtype<T>(self) -> Result<T, Self::Error>
- where T: Deserialize,
+ fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
+ where T: DeserializeSeed,
{
match self.de.tokens.peek() {
Some(&Token::EnumNewType(_, _)) => {
self.de.tokens.next();
- Deserialize::deserialize(self.de)
+ seed.deserialize(self.de)
}
Some(_) => {
- Deserialize::deserialize(self.de)
+ seed.deserialize(self.de)
}
None => Err(Error::EndOfStream),
}
@@ -885,14 +886,14 @@ impl<'a, I> MapVisitor for DeserializerVariantMapVisitor<'a, I>
{
type Error = Error;
- fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
- where K: Deserialize,
+ fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
+ where K: DeserializeSeed,
{
match self.de.tokens.peek() {
Some(&Token::EnumMapSep) => {
self.de.tokens.next();
self.len = self.len.map(|len| if len > 0 { len - 1} else { 0 });
- Deserialize::deserialize(&mut *self.de).map(Some)
+ seed.deserialize(&mut *self.de).map(Some)
}
Some(&Token::EnumMapEnd) => Ok(None),
Some(_) => {
@@ -903,10 +904,10 @@ impl<'a, I> MapVisitor for DeserializerVariantMapVisitor<'a, I>
}
}
- fn visit_value<V>(&mut self) -> Result<V, Error>
- where V: Deserialize,
+ fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
+ where V: DeserializeSeed,
{
- Deserialize::deserialize(&mut *self.de)
+ seed.deserialize(&mut *self.de)
}
fn size_hint(&self) -> (usize, Option<usize>) {
| [
"650"
] | serde-rs__serde-703 | Stateful deserialization
In many places the current Serde API has reasonable support for deserializing in a stateful way - where the deserialization depends on some data structure that previously exists. As a concrete example the following code deserializes a JSON array into a preallocated slice. Something similar could be useful in a time series database that wants to reuse a single buffer rather than allocating a new Vec for each array in the input.
```rust
extern crate serde;
extern crate serde_json;
use serde::de::{Deserialize, Deserializer, Visitor, SeqVisitor};
fn main() {
let j = "[10, 20, 30]";
let mut vec = vec![0; 5];
deserialize_into_slice(&mut vec, j).unwrap();
println!("{:?}", vec); // [10, 20, 30, 0, 0]
}
fn deserialize_into_slice<T>(out: &mut [T], j: &str) -> Result<(), serde_json::Error>
where T: Deserialize
{
struct IntoSlice<'a, T: 'a>(&'a mut [T]);
impl<'a, T> Visitor for IntoSlice<'a, T>
where T: Deserialize
{
type Value = ();
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error>
where V: SeqVisitor
{
let mut iter = self.0.iter_mut();
while let Some(elem) = visitor.visit()? {
iter.next().map(|spot| *spot = elem);
}
visitor.end()
}
}
let mut deserializer = serde_json::Deserializer::new(j.bytes().map(Ok));
deserializer.deserialize_seq(IntoSlice(out))
}
```
In other places the support is a lot worse. Some libraries ([serde-transcode](https://github.com/sfackler/serde-transcode), [erased-serde](https://github.com/dtolnay/erased-serde)) are able to work around the limitations by using a thread_local stack to pass state into Deserialize::deserialize but this is confusing and unsafe.
Let's see if we can come up with an API that supports stateful use case in a better way. It may even be possible to prototype a solution as a helper crate which uses thread_local behind the scenes.
CC @sfackler who has been hoping for progress on this.
| null | aa88f01cdcf26509c46bc6bfa68f43cc0bd0588e | diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index f6307eabe..12fc98c87 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -9,6 +9,7 @@ use error;
use collections::{String, Vec};
use core::fmt;
+use core::marker::PhantomData;
///////////////////////////////////////////////////////////////////////////////
@@ -230,6 +231,149 @@ pub trait Deserialize: Sized {
where D: Deserializer;
}
+/// `DeserializeSeed` is the stateful form of the `Deserialize` trait. If you
+/// ever find yourself looking for a way to pass data into a `Deserialize` impl,
+/// this trait is the way to do it.
+///
+/// As one example of stateful deserialization consider deserializing a JSON
+/// array into an existing buffer. Using the `Deserialize` trait we could
+/// deserialize a JSON array into a `Vec<T>` but it would be a freshly allocated
+/// `Vec<T>`; there is no way for `Deserialize` to reuse a previously allocated
+/// buffer. Using `DeserializeSeed` instead makes this possible as in the
+/// example code below.
+///
+/// The canonical API for stateless deserialization looks like this:
+///
+/// ```rust
+/// # use serde::Deserialize;
+/// # enum Error {}
+/// fn func<T: Deserialize>() -> Result<T, Error>
+/// # { unimplemented!() }
+/// ```
+///
+/// Adjusting an API like this to support stateful deserialization is a matter
+/// of accepting a seed as input:
+///
+/// ```rust
+/// # use serde::de::DeserializeSeed;
+/// # enum Error {}
+/// fn func_seed<T: DeserializeSeed>(seed: T) -> Result<T::Value, Error>
+/// # { unimplemented!() }
+/// ```
+///
+/// In practice the majority of deserialization is stateless. An API expecting a
+/// seed can be appeased by passing `std::marker::PhantomData` as a seed in the
+/// case of stateless deserialization.
+///
+/// # Example
+///
+/// Suppose we have JSON that looks like `[[1, 2], [3, 4, 5], [6]]` and we need
+/// to deserialize it into a flat representation like `vec![1, 2, 3, 4, 5, 6]`.
+/// Allocating a brand new `Vec<T>` for each subarray would be slow. Instead we
+/// would like to allocate a single `Vec<T>` and then deserialize each subarray
+/// into it. This requires stateful deserialization using the DeserializeSeed
+/// trait.
+///
+/// ```rust
+/// # use serde::de::{Deserialize, DeserializeSeed, Deserializer, Visitor, SeqVisitor};
+/// # use std::marker::PhantomData;
+/// #
+/// // A DeserializeSeed implementation that uses stateful deserialization to
+/// // append array elements onto the end of an existing vector. The preexisting
+/// // state ("seed") in this case is the Vec<T>. The `deserialize` method of
+/// // `ExtendVec` will be traversing the inner arrays of the JSON input and
+/// // appending each integer into the existing Vec.
+/// struct ExtendVec<'a, T: 'a>(&'a mut Vec<T>);
+///
+/// impl<'a, T> DeserializeSeed for ExtendVec<'a, T>
+/// where T: Deserialize
+/// {
+/// // The return type of the `deserialize` method. This implementation
+/// // appends onto an existing vector but does not create any new data
+/// // structure, so the return type is ().
+/// type Value = ();
+///
+/// fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
+/// where D: Deserializer
+/// {
+/// // Visitor implementation that will walk an inner array of the JSON
+/// // input.
+/// struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec<T>);
+///
+/// impl<'a, T> Visitor for ExtendVecVisitor<'a, T>
+/// where T: Deserialize
+/// {
+/// type Value = ();
+///
+/// fn visit_seq<V>(self, mut visitor: V) -> Result<(), V::Error>
+/// where V: SeqVisitor
+/// {
+/// // Visit each element in the inner array and push it onto
+/// // the existing vector.
+/// while let Some(elem) = visitor.visit()? {
+/// self.0.push(elem);
+/// }
+/// Ok(())
+/// }
+/// }
+///
+/// deserializer.deserialize_seq(ExtendVecVisitor(self.0))
+/// }
+/// }
+///
+/// // Visitor implementation that will walk the outer array of the JSON input.
+/// struct FlattenedVecVisitor<T>(PhantomData<T>);
+///
+/// impl<T> Visitor for FlattenedVecVisitor<T>
+/// where T: Deserialize
+/// {
+/// // This Visitor constructs a single Vec<T> to hold the flattened
+/// // contents of the inner arrays.
+/// type Value = Vec<T>;
+///
+/// fn visit_seq<V>(self, mut visitor: V) -> Result<Vec<T>, V::Error>
+/// where V: SeqVisitor
+/// {
+/// // Create a single Vec to hold the flattened contents.
+/// let mut vec = Vec::new();
+///
+/// // Each iteration through this loop is one inner array.
+/// while let Some(()) = visitor.visit_seed(ExtendVec(&mut vec))? {
+/// // Nothing to do; inner array has been appended into `vec`.
+/// }
+///
+/// // Return the finished vec.
+/// Ok(vec)
+/// }
+/// }
+///
+/// # fn example<D: Deserializer>(deserializer: D) -> Result<(), D::Error> {
+/// let visitor = FlattenedVecVisitor(PhantomData);
+/// let flattened: Vec<u64> = deserializer.deserialize_seq(visitor)?;
+/// # Ok(()) }
+/// ```
+pub trait DeserializeSeed: Sized {
+ /// The type produced by using this seed.
+ type Value;
+
+ /// Equivalent to the more common `Deserialize::deserialize` method, except
+ /// with some initial piece of data (the seed) passed in.
+ fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
+ where D: Deserializer;
+}
+
+impl<T> DeserializeSeed for PhantomData<T>
+ where T: Deserialize
+{
+ type Value = T;
+
+ fn deserialize<D>(self, deserializer: D) -> Result<T, D::Error>
+ where D: Deserializer
+ {
+ T::deserialize(deserializer)
+ }
+}
+
///////////////////////////////////////////////////////////////////////////////
/// `Deserializer` is a trait that can deserialize values by threading a `Visitor` trait through a
@@ -244,7 +388,7 @@ pub trait Deserialize: Sized {
/// with the `deserialize_*` methods how it should parse the next value. One downside though to
/// only supporting the `deserialize_*` types is that it does not allow for deserializing into a
/// generic `json::Value`-esque type.
-pub trait Deserializer {
+pub trait Deserializer: Sized {
/// The error type that can be returned if some error occurs during deserialization.
type Error: Error;
@@ -641,10 +785,26 @@ pub trait SeqVisitor {
/// The error type that can be returned if some error occurs during deserialization.
type Error: Error;
- /// This returns a `Ok(Some(value))` for the next value in the sequence, or `Ok(None)` if there
- /// are no more remaining items.
+ /// This returns `Ok(Some(value))` for the next value in the sequence, or
+ /// `Ok(None)` if there are no more remaining items.
+ ///
+ /// `Deserialize` implementations should typically use `SeqVisitor::visit`
+ /// instead.
+ fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
+ where T: DeserializeSeed;
+
+ /// This returns `Ok(Some(value))` for the next value in the sequence, or
+ /// `Ok(None)` if there are no more remaining items.
+ ///
+ /// This method exists as a convenience for `Deserialize` implementations.
+ /// `SeqVisitor` implementations should not need to override the default
+ /// behavior.
+ #[inline]
fn visit<T>(&mut self) -> Result<Option<T>, Self::Error>
- where T: Deserialize;
+ where T: Deserialize
+ {
+ self.visit_seed(PhantomData)
+ }
/// Return the lower and upper bound of items remaining in the sequence.
#[inline]
@@ -656,6 +816,13 @@ pub trait SeqVisitor {
impl<'a, V> SeqVisitor for &'a mut V where V: SeqVisitor {
type Error = V::Error;
+ #[inline]
+ fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, V::Error>
+ where T: DeserializeSeed
+ {
+ (**self).visit_seed(seed)
+ }
+
#[inline]
fn visit<T>(&mut self) -> Result<Option<T>, V::Error>
where T: Deserialize
@@ -678,30 +845,81 @@ pub trait MapVisitor {
/// The error type that can be returned if some error occurs during deserialization.
type Error: Error;
- /// This returns a `Ok(Some((key, value)))` for the next (key-value) pair in the map, or
- /// `Ok(None)` if there are no more remaining items.
+ /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
+ /// if there are no more remaining entries.
+ ///
+ /// `Deserialize` implementations should typically use
+ /// `MapVisitor::visit_key` or `MapVisitor::visit` instead.
+ fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
+ where K: DeserializeSeed;
+
+ /// This returns a `Ok(value)` for the next value in the map.
+ ///
+ /// `Deserialize` implementations should typically use
+ /// `MapVisitor::visit_value` instead.
+ fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
+ where V: DeserializeSeed;
+
+ /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in
+ /// the map, or `Ok(None)` if there are no more remaining items.
+ ///
+ /// `MapVisitor` implementations should override the default behavior if a
+ /// more efficient implementation is possible.
+ ///
+ /// `Deserialize` implementations should typically use `MapVisitor::visit`
+ /// instead.
#[inline]
- fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>
- where K: Deserialize,
- V: Deserialize,
+ fn visit_seed<K, V>(&mut self, key_seed: K, vseed: V) -> Result<Option<(K::Value, V::Value)>, Self::Error>
+ where K: DeserializeSeed,
+ V: DeserializeSeed
{
- match try!(self.visit_key()) {
+ match try!(self.visit_key_seed(key_seed)) {
Some(key) => {
- let value = try!(self.visit_value());
+ let value = try!(self.visit_value_seed(vseed));
Ok(Some((key, value)))
}
None => Ok(None)
}
}
- /// This returns a `Ok(Some(key))` for the next key in the map, or `Ok(None)` if there are no
- /// more remaining items.
+ /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
+ /// if there are no more remaining entries.
+ ///
+ /// This method exists as a convenience for `Deserialize` implementations.
+ /// `MapVisitor` implementations should not need to override the default
+ /// behavior.
+ #[inline]
fn visit_key<K>(&mut self) -> Result<Option<K>, Self::Error>
- where K: Deserialize;
+ where K: Deserialize
+ {
+ self.visit_key_seed(PhantomData)
+ }
/// This returns a `Ok(value)` for the next value in the map.
+ ///
+ /// This method exists as a convenience for `Deserialize` implementations.
+ /// `MapVisitor` implementations should not need to override the default
+ /// behavior.
+ #[inline]
fn visit_value<V>(&mut self) -> Result<V, Self::Error>
- where V: Deserialize;
+ where V: Deserialize
+ {
+ self.visit_value_seed(PhantomData)
+ }
+
+ /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in
+ /// the map, or `Ok(None)` if there are no more remaining items.
+ ///
+ /// This method exists as a convenience for `Deserialize` implementations.
+ /// `MapVisitor` implementations should not need to override the default
+ /// behavior.
+ #[inline]
+ fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>
+ where K: Deserialize,
+ V: Deserialize,
+ {
+ self.visit_seed(PhantomData, PhantomData)
+ }
/// Return the lower and upper bound of items remaining in the sequence.
#[inline]
@@ -709,17 +927,57 @@ pub trait MapVisitor {
(0, None)
}
- /// Report that the struct has a field that wasn't deserialized
+ /// Report that the struct has a field that wasn't deserialized. The
+ /// MapVisitor may consider this an error or it may return a default value
+ /// for the field.
+ ///
+ /// `Deserialize` implementations should typically use
+ /// `MapVisitor::missing_field` instead.
+ fn missing_field_seed<V>(&mut self, _seed: V, field: &'static str) -> Result<V::Value, Self::Error>
+ where V: DeserializeSeed
+ {
+ Err(Error::missing_field(field))
+ }
+
+ /// Report that the struct has a field that wasn't deserialized. The
+ /// MapVisitor may consider this an error or it may return a default value
+ /// for the field.
+ ///
+ /// This method exists as a convenience for `Deserialize` implementations.
+ /// `MapVisitor` implementations should not need to override the default
+ /// behavior.
fn missing_field<V>(&mut self, field: &'static str) -> Result<V, Self::Error>
where V: Deserialize,
{
- Err(Error::missing_field(field))
+ self.missing_field_seed(PhantomData, field)
}
}
impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
type Error = V_::Error;
+ #[inline]
+ fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
+ where K: DeserializeSeed
+ {
+ (**self).visit_key_seed(seed)
+ }
+
+ #[inline]
+ fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
+ where V: DeserializeSeed
+ {
+ (**self).visit_value_seed(seed)
+ }
+
+ #[inline]
+ fn visit_seed<K, V>(&mut self, kseed: K, value_seed: V) -> Result<Option<(K::Value, V::Value)>, Self::Error>
+ where K: DeserializeSeed,
+ V: DeserializeSeed
+ {
+ (**self).visit_seed(kseed, value_seed)
+ }
+
#[inline]
fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, V_::Error>
where K: Deserialize,
@@ -747,6 +1005,13 @@ impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
(**self).size_hint()
}
+ #[inline]
+ fn missing_field_seed<V>(&mut self, seed: V, field: &'static str) -> Result<V::Value, Self::Error>
+ where V: DeserializeSeed
+ {
+ (**self).missing_field_seed(seed, field)
+ }
+
#[inline]
fn missing_field<V>(&mut self, field: &'static str) -> Result<V, Self::Error>
where V: Deserialize
@@ -760,7 +1025,7 @@ impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
/// `EnumVisitor` is a visitor that is created by the `Deserializer` and passed
/// to the `Deserialize` in order to identify which variant of an enum to
/// deserialize.
-pub trait EnumVisitor {
+pub trait EnumVisitor: Sized {
/// The error type that can be returned if some error occurs during deserialization.
type Error: Error;
/// The `Visitor` that will be used to deserialize the content of the enum
@@ -768,14 +1033,29 @@ pub trait EnumVisitor {
type Variant: VariantVisitor<Error=Self::Error>;
/// `visit_variant` is called to identify which variant to deserialize.
+ ///
+ /// `Deserialize` implementations should typically use
+ /// `EnumVisitor::visit_variant` instead.
+ fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
+ where V: DeserializeSeed;
+
+ /// `visit_variant` is called to identify which variant to deserialize.
+ ///
+ /// This method exists as a convenience for `Deserialize` implementations.
+ /// `EnumVisitor` implementations should not need to override the default
+ /// behavior.
+ #[inline]
fn visit_variant<V>(self) -> Result<(V, Self::Variant), Self::Error>
- where V: Deserialize;
+ where V: Deserialize
+ {
+ self.visit_variant_seed(PhantomData)
+ }
}
/// `VariantVisitor` is a visitor that is created by the `Deserializer` and
/// passed to the `Deserialize` to deserialize the content of a particular enum
/// variant.
-pub trait VariantVisitor {
+pub trait VariantVisitor: Sized {
/// The error type that can be returned if some error occurs during deserialization.
type Error: Error;
@@ -784,8 +1064,24 @@ pub trait VariantVisitor {
/// `visit_newtype` is called when deserializing a variant with a single value.
/// A good default is often to use the `visit_tuple` method to deserialize a `(value,)`.
+ ///
+ /// `Deserialize` implementations should typically use
+ /// `VariantVisitor::visit_newtype` instead.
+ fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
+ where T: DeserializeSeed;
+
+ /// `visit_newtype` is called when deserializing a variant with a single value.
+ /// A good default is often to use the `visit_tuple` method to deserialize a `(value,)`.
+ ///
+ /// This method exists as a convenience for `Deserialize` implementations.
+ /// `VariantVisitor` implementations should not need to override the default
+ /// behavior.
+ #[inline]
fn visit_newtype<T>(self) -> Result<T, Self::Error>
- where T: Deserialize;
+ where T: Deserialize
+ {
+ self.visit_newtype_seed(PhantomData)
+ }
/// `visit_tuple` is called when deserializing a tuple-like variant.
/// If no tuple variants are expected, yield a
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index c64724742..9e2bdf76f 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -298,10 +298,10 @@ impl<'a, E> de::EnumVisitor for StrDeserializer<'a, E>
type Error = E;
type Variant = private::UnitOnly<E>;
- fn visit_variant<T>(self) -> Result<(T, Self::Variant), Self::Error>
- where T: de::Deserialize,
+ fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
+ where T: de::DeserializeSeed,
{
- de::Deserialize::deserialize(self).map(private::unit_only)
+ seed.deserialize(self).map(private::unit_only)
}
}
@@ -357,10 +357,10 @@ impl<'a, E> de::EnumVisitor for StringDeserializer<E>
type Error = E;
type Variant = private::UnitOnly<E>;
- fn visit_variant<T>(self) -> Result<(T, Self::Variant), Self::Error>
- where T: de::Deserialize,
+ fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
+ where T: de::DeserializeSeed,
{
- de::Deserialize::deserialize(self).map(private::unit_only)
+ seed.deserialize(self).map(private::unit_only)
}
}
@@ -419,10 +419,10 @@ impl<'a, E> de::EnumVisitor for CowStrDeserializer<'a, E>
type Error = E;
type Variant = private::UnitOnly<E>;
- fn visit_variant<T>(self) -> Result<(T, Self::Variant), Self::Error>
- where T: de::Deserialize,
+ fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
+ where T: de::DeserializeSeed,
{
- de::Deserialize::deserialize(self).map(private::unit_only)
+ seed.deserialize(self).map(private::unit_only)
}
}
@@ -480,13 +480,13 @@ impl<I, T, E> de::SeqVisitor for SeqDeserializer<I, E>
{
type Error = E;
- fn visit<V>(&mut self) -> Result<Option<V>, Self::Error>
- where V: de::Deserialize
+ fn visit_seed<V>(&mut self, seed: V) -> Result<Option<V::Value>, Self::Error>
+ where V: de::DeserializeSeed
{
match self.iter.next() {
Some(value) => {
self.len -= 1;
- de::Deserialize::deserialize(value.into_deserializer()).map(Some)
+ seed.deserialize(value.into_deserializer()).map(Some)
}
None => Ok(None),
}
@@ -687,24 +687,24 @@ impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
{
type Error = E;
- fn visit_key<T>(&mut self) -> Result<Option<T>, Self::Error>
- where T: de::Deserialize,
+ fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
+ where T: de::DeserializeSeed,
{
match self.next() {
Some((key, value)) => {
self.value = Some(value);
- de::Deserialize::deserialize(key.into_deserializer()).map(Some)
+ seed.deserialize(key.into_deserializer()).map(Some)
}
None => Ok(None),
}
}
- fn visit_value<T>(&mut self) -> Result<T, Self::Error>
- where T: de::Deserialize,
+ fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
+ where T: de::DeserializeSeed,
{
match self.value.take() {
Some(value) => {
- de::Deserialize::deserialize(value.into_deserializer())
+ seed.deserialize(value.into_deserializer())
}
None => {
Err(de::Error::end_of_stream())
@@ -712,14 +712,14 @@ impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
}
}
- fn visit<TK, TV>(&mut self) -> Result<Option<(TK, TV)>, Self::Error>
- where TK: de::Deserialize,
- TV: de::Deserialize
+ fn visit_seed<TK, TV>(&mut self, kseed: TK, vseed: TV) -> Result<Option<(TK::Value, TV::Value)>, Self::Error>
+ where TK: de::DeserializeSeed,
+ TV: de::DeserializeSeed
{
match self.next() {
Some((key, value)) => {
- let key = try!(de::Deserialize::deserialize(key.into_deserializer()));
- let value = try!(de::Deserialize::deserialize(value.into_deserializer()));
+ let key = try!(kseed.deserialize(key.into_deserializer()));
+ let value = try!(vseed.deserialize(value.into_deserializer()));
Ok(Some((key, value)))
}
None => Ok(None)
@@ -741,13 +741,13 @@ impl<I, K, V, E> de::SeqVisitor for MapDeserializer<I, K, V, E>
{
type Error = E;
- fn visit<T>(&mut self) -> Result<Option<T>, Self::Error>
- where T: de::Deserialize,
+ fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
+ where T: de::DeserializeSeed,
{
match self.next() {
Some((k, v)) => {
let de = PairDeserializer(k, v, PhantomData);
- de::Deserialize::deserialize(de).map(Some)
+ seed.deserialize(de).map(Some)
}
None => Ok(None),
}
@@ -813,13 +813,13 @@ impl<A, B, E> de::SeqVisitor for PairVisitor<A, B, E>
{
type Error = E;
- fn visit<T>(&mut self) -> Result<Option<T>, Self::Error>
- where T: de::Deserialize,
+ fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
+ where T: de::DeserializeSeed,
{
if let Some(k) = self.0.take() {
- de::Deserialize::deserialize(k.into_deserializer()).map(Some)
+ seed.deserialize(k.into_deserializer()).map(Some)
} else if let Some(v) = self.1.take() {
- de::Deserialize::deserialize(v.into_deserializer()).map(Some)
+ seed.deserialize(v.into_deserializer()).map(Some)
} else {
Ok(None)
}
@@ -995,8 +995,8 @@ mod private {
Ok(())
}
- fn visit_newtype<T>(self) -> Result<T, Self::Error>
- where T: de::Deserialize,
+ fn visit_newtype_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
+ where T: de::DeserializeSeed,
{
Err(de::Error::invalid_type(de::Type::NewtypeVariant))
}
| serde-rs/serde | 2017-01-19T09:13:57Z | This would also enable things like
```rust
#[derive(Deserialize)]
struct Foo {
#[serde(deserialize_keys_using = "key_deserializer")]
bar: Map<String, String>,
}
fn key_deserializer<D>(d: &mut D) -> Result<String, D::Error>
where D: Deserializer
{
// ...
}
```
This may be as simple as any place we do `fn<T: Deserialize>(...) -> Result<T>`, instead doing `fn<X: DeserializeState>(x: X, ...) -> Result<X::Value>`.
Then providing:
```rust
pub use std::marker::PhantomData as Stateless;
impl<T> DeserializeState for Stateless<T>
where T: Deserialize
{
type Value = T;
fn deserialize<D>(self, deserializer: &mut D) -> Result<Self::Value, D::Error>
where D: Deserializer
{
T::deserialize(deserializer)
}
}
```
Yep, that's about it I think. I'm writing up a quick `serde-stateful-deserialize` crate right now and I think all it is is the trait definition, that, and a proxy object to use with current serde.
https://github.com/sfackler/serde-stateful-deserialize
Ok, implementation is actually pretty simple! https://github.com/sfackler/serde-stateful-deserialize/blob/master/src/lib.rs
Using it in serde-transcode: https://github.com/sfackler/serde-transcode/commit/16b770e3c8637875a45e62c38b6c914911907276
I updated erased-serde: https://github.com/dtolnay/erased-serde/commit/d3ac4bbf84606c26a8482404667ba508cdbc1e95. It compiles but the tests fail, still investigating. I think I actually rely on there being a stack of states rather than a single one at a time.
I though I could get away with not needing an explicit stack since the states should be moved out immediately, but that could be wrong?
In any case, it's only broken because of the thread_local hack and it would definitely work fine if this were the actual SeqVisitor / MapVisitor API. So far this seems like a promising direction.
The next step is to mitigate the damage as much as possible given that the vast majority of calls are going to be with stateless Deserialize.
The best name I have so far is `Seed` which is more concise and also more evocative than DeserializeState. It means seed in the same sense that PRNGs have a seed - some initial state that exists before you start using the thing. Also google search for `serde state` returns a bunch of unrelated results, especially since we already used the word "state" in the Serializer. Google search for `serde seed` returns low-quality results which means it will be easy to search for after we add it.
For the stateless case I like `Scratch` which means deserialize the thing "from scratch" without relying on any pre-existing state. Is this usage confusing for non-native english speakers? `Void` could also be good although it is used by the void crate. That may be less of a concern now that `!` exists and pretty much supersedes `Void`.
Any other suggestions?
I personally find `Seed` and `Scratch` too confusing initially. `DeserializeState ` is more verbose, but more straightforward as well
How about `Initializer` + `Stateless` or `Factory` + `Stateless`?
Is it better to scrap the Stateless / Scratch / Void idea and ask people to pass PhantomData directly? | 8cb6607e827717136a819caa44d8e43702724883 |
692 | diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index 80ba9e803..849bdf27c 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -160,6 +160,10 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
where __V: de::Visitor {
self.deserialize(visitor)
}
+ fn deserialize_byte_buf<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
+ where __V: de::Visitor {
+ self.deserialize(visitor)
+ }
fn deserialize_ignored_any<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
@@ -250,6 +254,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
Some(Token::Str(v)) => visitor.visit_str(v),
Some(Token::String(v)) => visitor.visit_string(v),
Some(Token::Bytes(v)) => visitor.visit_bytes(v),
+ Some(Token::ByteBuf(v)) => visitor.visit_byte_buf(v),
Some(Token::Option(false)) => visitor.visit_none(),
Some(Token::Option(true)) => visitor.visit_some(self),
Some(Token::Unit) => visitor.visit_unit(),
diff --git a/serde_test/src/token.rs b/serde_test/src/token.rs
index e4b3a8253..b8bd23c66 100644
--- a/serde_test/src/token.rs
+++ b/serde_test/src/token.rs
@@ -17,6 +17,7 @@ pub enum Token<'a> {
Str(&'a str),
String(String),
Bytes(&'a [u8]),
+ ByteBuf(Vec<u8>),
Option(bool),
diff --git a/testing/tests/test_bytes.rs b/testing/tests/test_bytes.rs
index 6968f9001..86067627c 100644
--- a/testing/tests/test_bytes.rs
+++ b/testing/tests/test_bytes.rs
@@ -15,6 +15,7 @@ fn test_bytes() {
fn test_byte_buf() {
let empty = ByteBuf::new();
assert_tokens(&empty, &[Token::Bytes(b"")]);
+ assert_de_tokens(&empty, &[Token::ByteBuf(Vec::new())]);
assert_de_tokens(&empty, &[Token::Str("")]);
assert_de_tokens(&empty, &[Token::String(String::new())]);
assert_de_tokens(&empty, &[
@@ -28,6 +29,7 @@ fn test_byte_buf() {
let buf = ByteBuf::from(vec![65, 66, 67]);
assert_tokens(&buf, &[Token::Bytes(b"ABC")]);
+ assert_de_tokens(&buf, &[Token::ByteBuf(vec![65, 66, 67])]);
assert_de_tokens(&buf, &[Token::Str("ABC")]);
assert_de_tokens(&buf, &[Token::String("ABC".to_owned())]);
assert_de_tokens(&buf, &[
| [
"647"
] | serde-rs__serde-692 | Deserializer::deserialize_byte_buf
For strings we have deserialize_str and deserialize_string which allows the Deserialize to indicate to the Deserializer whether it would prefer to take ownership of the data. Correspondingly we have Visitor::visit_str and visit_string. Visitor also has visit_bytes and visit_byte_buf but Deserializer only has deserialize_bytes. There is no way to indicate the Deserialize's preference around ownership.
We could add this with a default implementation of forwarding to deserialize_bytes, then remove the default in a breaking change.
| null | bc6bc9e3f089e159515349fe5d2e4c673afea803 | diff --git a/serde/src/bytes.rs b/serde/src/bytes.rs
index 574a673d4..8402b4bd1 100644
--- a/serde/src/bytes.rs
+++ b/serde/src/bytes.rs
@@ -234,7 +234,7 @@ mod bytebuf {
fn deserialize<D>(deserializer: D) -> Result<ByteBuf, D::Error>
where D: de::Deserializer
{
- deserializer.deserialize_bytes(ByteBufVisitor)
+ deserializer.deserialize_byte_buf(ByteBufVisitor)
}
}
}
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index af488dd42..f6307eabe 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -174,6 +174,9 @@ pub enum Type {
/// Represents a `&[u8]` type.
Bytes,
+
+ /// Represents a `Vec<u8>` type.
+ ByteBuf,
}
impl fmt::Display for Type {
@@ -212,6 +215,7 @@ impl fmt::Display for Type {
Type::UnitVariant => "unit variant",
Type::NewtypeVariant => "newtype variant",
Type::Bytes => "bytes",
+ Type::ByteBuf => "bytes buf",
};
display.fmt(formatter)
}
@@ -343,12 +347,19 @@ pub trait Deserializer {
visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
- /// This method hints that the `Deserialize` type is expecting a `Vec<u8>`. This allows
+ /// This method hints that the `Deserialize` type is expecting a `&[u8]`. This allows
/// deserializers that provide a custom byte vector serialization to properly deserialize the
/// type.
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
+ /// This method hints that the `Deserialize` type is expecting a `Vec<u8>`. This allows
+ /// deserializers that provide a custom byte vector serialization to properly deserialize the
+ /// type and prevent needless intermediate allocations that would occur when going through
+ /// `&[u8]`.
+ fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ where V: Visitor;
+
/// This method hints that the `Deserialize` type is expecting a map of values. This allows
/// deserializers to parse sequences that aren't tagged as maps.
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 52342cec6..c64724742 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -181,7 +181,7 @@ impl<E> de::Deserializer for UnitDeserializer<E>
forward_to_deserialize! {
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
unit seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
+ tuple_struct struct struct_field tuple enum ignored_any byte_buf
}
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
@@ -223,7 +223,7 @@ macro_rules! primitive_deserializer {
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str
string unit option seq seq_fixed_size bytes map unit_struct
newtype_struct tuple_struct struct struct_field tuple enum
- ignored_any
+ ignored_any byte_buf
}
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
@@ -288,7 +288,7 @@ impl<'a, E> de::Deserializer for StrDeserializer<'a, E>
forward_to_deserialize! {
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple ignored_any
+ tuple_struct struct struct_field tuple ignored_any byte_buf
}
}
@@ -346,7 +346,7 @@ impl<E> de::Deserializer for StringDeserializer<E>
forward_to_deserialize! {
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple ignored_any
+ tuple_struct struct struct_field tuple ignored_any byte_buf
}
}
@@ -408,7 +408,7 @@ impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E>
forward_to_deserialize! {
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple ignored_any
+ tuple_struct struct struct_field tuple ignored_any byte_buf
}
}
@@ -469,7 +469,7 @@ impl<I, T, E> de::Deserializer for SeqDeserializer<I, E>
forward_to_deserialize! {
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
+ tuple_struct struct struct_field tuple enum ignored_any byte_buf
}
}
@@ -572,7 +572,7 @@ impl<V_, E> de::Deserializer for SeqVisitorDeserializer<V_, E>
forward_to_deserialize! {
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
+ tuple_struct struct struct_field tuple enum ignored_any byte_buf
}
}
@@ -675,7 +675,7 @@ impl<I, K, V, E> de::Deserializer for MapDeserializer<I, K, V, E>
forward_to_deserialize! {
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
unit option bytes map unit_struct newtype_struct tuple_struct struct
- struct_field tuple enum ignored_any
+ struct_field tuple enum ignored_any byte_buf
}
}
@@ -772,7 +772,7 @@ impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E>
forward_to_deserialize! {
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
unit option bytes map unit_struct newtype_struct tuple_struct struct
- struct_field tuple enum ignored_any
+ struct_field tuple enum ignored_any byte_buf
}
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
@@ -901,7 +901,7 @@ impl<V_, E> de::Deserializer for MapVisitorDeserializer<V_, E>
forward_to_deserialize! {
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
+ tuple_struct struct struct_field tuple enum ignored_any byte_buf
}
}
@@ -934,7 +934,7 @@ impl<'a, E> de::Deserializer for BytesDeserializer<'a, E>
forward_to_deserialize! {
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
+ tuple_struct struct struct_field tuple enum ignored_any byte_buf
}
}
@@ -970,7 +970,7 @@ impl<E> de::Deserializer for ByteBufDeserializer<E>
forward_to_deserialize! {
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
unit option seq seq_fixed_size bytes map unit_struct newtype_struct
- tuple_struct struct struct_field tuple enum ignored_any
+ tuple_struct struct struct_field tuple enum ignored_any byte_buf
}
}
diff --git a/serde/src/macros.rs b/serde/src/macros.rs
index 2580980f3..447181087 100644
--- a/serde/src/macros.rs
+++ b/serde/src/macros.rs
@@ -92,6 +92,9 @@ macro_rules! forward_to_deserialize_helper {
(bytes) => {
forward_to_deserialize_method!{deserialize_bytes()}
};
+ (byte_buf) => {
+ forward_to_deserialize_method!{deserialize_byte_buf()}
+ };
(map) => {
forward_to_deserialize_method!{deserialize_map()}
};
| serde-rs/serde | 2017-01-16T15:59:09Z | Correspondingly - we need to add `serde_test::Token::ByteBuf`. | 8cb6607e827717136a819caa44d8e43702724883 |
2,847 | diff --git a/test_suite/tests/regression/issue2846.rs b/test_suite/tests/regression/issue2846.rs
new file mode 100644
index 000000000..c5258a5b3
--- /dev/null
+++ b/test_suite/tests/regression/issue2846.rs
@@ -0,0 +1,27 @@
+#![allow(clippy::trivially_copy_pass_by_ref)]
+
+use serde_derive::Deserialize;
+
+macro_rules! declare_in_macro {
+ ($with:literal) => {
+ #[derive(Deserialize)]
+ pub struct S(
+ #[serde(with = $with)]
+ #[allow(dead_code)]
+ i32,
+ );
+ };
+}
+
+declare_in_macro!("with");
+
+mod with {
+ use serde::Deserializer;
+
+ pub fn deserialize<'de, D>(_: D) -> Result<i32, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ unimplemented!()
+ }
+}
| [
"2846"
] | serde-rs__serde-2847 | Serde still causing errors even after 1.0.212
Serde 1.0.211 broke some call sites described in #2844 and later fixed in #2845
I believe it is still broken. The number of errors is reduced, but I am still seeing one:
```
...
Downloaded serde_derive v1.0.212
...
error[E0425]: cannot find value `__e` in this scope
--> components/datetime/src/provider/calendar/symbols.rs:336:36
|
336 | deserialize_with = "icu_provider::serde_borrow_de_utils::array_of_cow"
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not found in this scope
```
CC @robertbastian
| 1.21 | 49e11ce1bae9fbb9128c9144c4e1051daf7a29ed | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index a50010ca3..518f84320 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -875,13 +875,14 @@ fn deserialize_newtype_struct(
) -> TokenStream {
let delife = params.borrowed.de_lifetime();
let field_ty = field.ty;
+ let deserializer_var = quote!(__e);
let value = match field.attrs.deserialize_with() {
None => {
let span = field.original.span();
let func = quote_spanned!(span=> <#field_ty as _serde::Deserialize>::deserialize);
quote! {
- #func(__e)?
+ #func(#deserializer_var)?
}
}
Some(path) => {
@@ -890,7 +891,7 @@ fn deserialize_newtype_struct(
// on the #[serde(with = "...")]
// ^^^^^
quote_spanned! {path.span()=>
- #path(__e)?
+ #path(#deserializer_var)?
}
}
};
@@ -906,7 +907,7 @@ fn deserialize_newtype_struct(
quote! {
#[inline]
- fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::__private::Result<Self::Value, __E::Error>
+ fn visit_newtype_struct<__E>(self, #deserializer_var: __E) -> _serde::__private::Result<Self::Value, __E::Error>
where
__E: _serde::Deserializer<#delife>,
{
| serde-rs/serde | 2024-10-22T18:11:35Z | 49e11ce1bae9fbb9128c9144c4e1051daf7a29ed | |
2,845 | diff --git a/test_suite/tests/regression/issue2844.rs b/test_suite/tests/regression/issue2844.rs
new file mode 100644
index 000000000..492718c8b
--- /dev/null
+++ b/test_suite/tests/regression/issue2844.rs
@@ -0,0 +1,31 @@
+use serde_derive::{Deserialize, Serialize};
+
+macro_rules! declare_in_macro {
+ ($with:literal) => {
+ #[derive(Serialize, Deserialize)]
+ pub struct S {
+ #[serde(with = $with)]
+ f: i32,
+ }
+ };
+}
+
+declare_in_macro!("with");
+
+mod with {
+ use serde::{Deserializer, Serializer};
+
+ pub fn serialize<S>(_: &i32, _: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ unimplemented!()
+ }
+
+ pub fn deserialize<'de, D>(_: D) -> Result<i32, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ unimplemented!()
+ }
+}
diff --git a/test_suite/tests/ui/with/incorrect_type.stderr b/test_suite/tests/ui/with/incorrect_type.stderr
index d974fa4a1..cfddf1cec 100644
--- a/test_suite/tests/ui/with/incorrect_type.stderr
+++ b/test_suite/tests/ui/with/incorrect_type.stderr
@@ -19,8 +19,10 @@ note: required by a bound in `w::serialize`
error[E0061]: this function takes 1 argument but 2 arguments were supplied
--> tests/ui/with/incorrect_type.rs:15:25
|
+14 | #[derive(Serialize, Deserialize)]
+ | --------- unexpected argument #2 of type `__S`
15 | struct W(#[serde(with = "w")] u8, u8);
- | ^^^ unexpected argument #2 of type `__S`
+ | ^^^
|
note: function defined here
--> tests/ui/with/incorrect_type.rs:9:12
@@ -68,8 +70,10 @@ note: required by a bound in `w::serialize`
error[E0061]: this function takes 1 argument but 2 arguments were supplied
--> tests/ui/with/incorrect_type.rs:18:35
|
+17 | #[derive(Serialize, Deserialize)]
+ | --------- unexpected argument #2 of type `__S`
18 | struct S(#[serde(serialize_with = "w::serialize")] u8, u8);
- | ^^^^^^^^^^^^^^ unexpected argument #2 of type `__S`
+ | ^^^^^^^^^^^^^^
|
note: function defined here
--> tests/ui/with/incorrect_type.rs:9:12
| [
"2844"
] | serde-rs__serde-2845 | serde 1.0.211 breaks `with = ""` inside of macros
I tried this code:
```rust
macro_rules! declare_in_macro {
($with:literal) => {
#[derive(serde::Serialize)]
pub struct S {
#[serde(with = $with)]
f: i32,
}
};
}
declare_in_macro!("display");
mod display {
pub fn serialize<S: serde::ser::Serializer>(_: &i32, _: S) -> Result<S::Ok, S::Error> {
unimplemented!()
}
}
```
with feature "derive":
- serde 1.0.210 compiles
- serde 1.0.211 fails with:
```rust
error[E0424]: expected value, found module `self`
--> src/lib.rs:10:19
|
3 | #[derive(serde::Serialize)]
| ---------------- this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters
...
10 | declare_in_macro!("display");
| ^^^^^^^^^ `self` value is a keyword only available in methods with a `self` parameter
error[E0425]: cannot find value `__s` in this scope
--> src/lib.rs:10:19
|
10 | declare_in_macro!("display");
| ^^^^^^^^^ not found in this scope
```
Also reported at https://github.com/serde-rs/serde/pull/2558#issuecomment-2428744139
| 1.21 | 29d4f3e88799b10ecfff80e743049e0f58dde56e | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 136da8e9f..a50010ca3 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -2882,13 +2882,14 @@ fn wrap_deserialize_with(
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) =
split_with_de_lifetime(params);
let delife = params.borrowed.de_lifetime();
+ let deserializer_var = quote!(__deserializer);
// If #deserialize_with returns wrong type, error will be reported here (^^^^^).
// We attach span of the path to the function so it will be reported
// on the #[serde(with = "...")]
// ^^^^^
let value = quote_spanned! {deserialize_with.span()=>
- #deserialize_with(__deserializer)?
+ #deserialize_with(#deserializer_var)?
};
let wrapper = quote! {
#[doc(hidden)]
@@ -2899,7 +2900,7 @@ fn wrap_deserialize_with(
}
impl #de_impl_generics _serde::Deserialize<#delife> for __DeserializeWith #de_ty_generics #where_clause {
- fn deserialize<__D>(__deserializer: __D) -> _serde::__private::Result<Self, __D::Error>
+ fn deserialize<__D>(#deserializer_var: __D) -> _serde::__private::Result<Self, __D::Error>
where
__D: _serde::Deserializer<#delife>,
{
diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index 191c0def9..47384f16f 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -1220,12 +1220,15 @@ fn wrap_serialize_with(
})
});
+ let self_var = quote!(self);
+ let serializer_var = quote!(__s);
+
// If #serialize_with returns wrong type, error will be reported on here.
// We attach span of the path to this piece so error will be reported
// on the #[serde(with = "...")]
// ^^^^^
let wrapper_serialize = quote_spanned! {serialize_with.span()=>
- #serialize_with(#(self.values.#field_access, )* __s)
+ #serialize_with(#(#self_var.values.#field_access, )* #serializer_var)
};
quote!({
@@ -1236,7 +1239,7 @@ fn wrap_serialize_with(
}
impl #wrapper_impl_generics _serde::Serialize for __SerializeWith #wrapper_ty_generics #where_clause {
- fn serialize<__S>(&self, __s: __S) -> _serde::__private::Result<__S::Ok, __S::Error>
+ fn serialize<__S>(&#self_var, #serializer_var: __S) -> _serde::__private::Result<__S::Ok, __S::Error>
where
__S: _serde::Serializer,
{
| serde-rs/serde | 2024-10-22T16:38:40Z | Not sure if this is the same error, also worked on serde v1.0.210 but not on v1.0.211
```
error[E0425]: cannot find value `__deserializer` in this scope
--> /cargo-0.83.0/src/cargo/core/features.rs:759:32
|
759 | #[serde(deserialize_with = "deserialize_build_std")]
| ^^^^^^^^^^^^^^^^^^^^^^^ not found in this scope
error[E0425]: cannot find value `__deserializer` in this scope
--> /cargo-0.83.0/src/cargo/core/features.rs:770:32
|
770 | #[serde(deserialize_with = "deserialize_git_features")]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ not found in this scope
error[E0425]: cannot find value `__deserializer` in this scope
--> /cargo-0.83.0/src/cargo/core/features.rs:772:32
|
772 | #[serde(deserialize_with = "deserialize_gitoxide_features")]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not found in this scope
```
I wonder if this is a hygiene issue
Serde 1.0.211 breaks ICU4X with errors such as
```
error[E0425]: cannot find value `__deserializer` in this scope
--> /path/to/icu4x/components/datetime/src/provider/calendar/symbols.rs:269:40
|
269 | ... = "icu_provider::serde_borrow_de_utils::array_of_cow"
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not found in this scope
``` | 49e11ce1bae9fbb9128c9144c4e1051daf7a29ed |
2,802 | diff --git a/test_suite/tests/test_annotations.rs b/test_suite/tests/test_annotations.rs
index 1174be6d2..63cb3dd1b 100644
--- a/test_suite/tests/test_annotations.rs
+++ b/test_suite/tests/test_annotations.rs
@@ -1815,6 +1815,32 @@ fn test_flatten_unit() {
);
}
+#[test]
+fn test_flatten_unit_struct() {
+ #[derive(Debug, PartialEq, Serialize, Deserialize)]
+ struct Response<T> {
+ #[serde(flatten)]
+ data: T,
+ status: usize,
+ }
+
+ #[derive(Debug, PartialEq, Serialize, Deserialize)]
+ struct Unit;
+
+ assert_tokens(
+ &Response {
+ data: Unit,
+ status: 0,
+ },
+ &[
+ Token::Map { len: None },
+ Token::Str("status"),
+ Token::U64(0),
+ Token::MapEnd,
+ ],
+ );
+}
+
#[test]
fn test_flatten_unsupported_type() {
#[derive(Debug, PartialEq, Serialize, Deserialize)]
| [
"2801"
] | serde-rs__serde-2802 | Flattening a unit struct should work like flattening unit itself
https://github.com/serde-rs/serde/pull/1874 landed support for flattening the unit type after a report in https://github.com/serde-rs/serde/issues/1873. However, it did not override `deserialize_unit_struct` and `serialize_unit_struct`, so while flattening `()` now works, flattening `struct Unit;` does not. It's not clear whether this was intentional or not, though it seems reasonable to support unit structs the same as unit here.
| 1.20 | 1b4da41f970555e111f471633205bbcb4dadbc63 | diff --git a/serde/src/private/de.rs b/serde/src/private/de.rs
index c402d2c66..c146539ee 100644
--- a/serde/src/private/de.rs
+++ b/serde/src/private/de.rs
@@ -2710,6 +2710,17 @@ where
visitor.visit_unit()
}
+ fn deserialize_unit_struct<V>(
+ self,
+ _name: &'static str,
+ visitor: V,
+ ) -> Result<V::Value, Self::Error>
+ where
+ V: Visitor<'de>,
+ {
+ visitor.visit_unit()
+ }
+
fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
@@ -2734,7 +2745,6 @@ where
deserialize_string()
deserialize_bytes()
deserialize_byte_buf()
- deserialize_unit_struct(&'static str)
deserialize_seq()
deserialize_tuple(usize)
deserialize_tuple_struct(&'static str, usize)
diff --git a/serde/src/private/ser.rs b/serde/src/private/ser.rs
index 9570629e9..ebfeba97e 100644
--- a/serde/src/private/ser.rs
+++ b/serde/src/private/ser.rs
@@ -51,8 +51,6 @@ enum Unsupported {
String,
ByteArray,
Optional,
- #[cfg(any(feature = "std", feature = "alloc"))]
- UnitStruct,
Sequence,
Tuple,
TupleStruct,
@@ -69,8 +67,6 @@ impl Display for Unsupported {
Unsupported::String => formatter.write_str("a string"),
Unsupported::ByteArray => formatter.write_str("a byte array"),
Unsupported::Optional => formatter.write_str("an optional"),
- #[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"),
@@ -1092,7 +1088,7 @@ where
}
fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
- Err(Self::bad_type(Unsupported::UnitStruct))
+ Ok(())
}
fn serialize_unit_variant(
| serde-rs/serde | 2024-08-15T13:51:17Z | 1b4da41f970555e111f471633205bbcb4dadbc63 | |
2,791 | diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index f8d577bb8..3dacf00ab 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -4,6 +4,7 @@
#![deny(warnings)]
#![allow(
+ confusable_idents,
unknown_lints,
mixed_script_confusables,
clippy::derive_partial_eq_without_eq,
@@ -19,6 +20,7 @@
clippy::trivially_copy_pass_by_ref,
clippy::type_repetition_in_bounds
)]
+#![deny(clippy::collection_is_never_read)]
use serde::de::{Deserialize, DeserializeOwned, Deserializer};
use serde::ser::{Serialize, Serializer};
@@ -724,6 +726,19 @@ fn test_gen() {
flat: T,
}
+ #[derive(Serialize, Deserialize)]
+ #[serde(untagged)]
+ pub enum Inner<T> {
+ Builder {
+ s: T,
+ #[serde(flatten)]
+ o: T,
+ },
+ Default {
+ s: T,
+ },
+ }
+
// https://github.com/serde-rs/serde/issues/1804
#[derive(Serialize, Deserialize)]
pub enum Message {
| [
"2789"
] | serde-rs__serde-2791 | `error: collection is never read` on `#[derive(Deserialize)]`
On both current stable 1.80.0 and nightly 1.82.0-nightly (2024-08-06 60d146580c10036ce89e)
sample code:
```rust
#![deny(clippy::collection_is_never_read)]
use serde::Deserialize;
#[derive(Deserialize)]
struct Options {
a: bool,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum Inner<'a> {
Default {
s: &'a str,
},
Builder {
s: &'a str,
#[serde(flatten)]
o: Options,
},
}
```
Getting:
```text
error: collection is never read
--> src/lib.rs:10:10
|
10 | #[derive(Deserialize)]
| ^^^^^^^^^^^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#collection_is_never_read
note: the lint level is defined here
--> src/lib.rs:1:9
|
1 | #![deny(clippy::collection_is_never_read)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
= note: this error originates in the derive macro `Deserialize` (in Nightly builds, run with -Z macro-backtrace for more info)
```
[Playground link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d82d6da1e402e39a9c4b30b72b5a6074)
| 1.20 | e08c5de5dd62571a5687f77d99609f9d9e60784e | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index e3b737c61..c5861d9bc 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -2480,7 +2480,10 @@ fn deserialize_map(
});
// Collect contents for flatten fields into a buffer
- let let_collect = if cattrs.has_flatten() {
+ let has_flatten = fields
+ .iter()
+ .any(|field| field.attrs.flatten() && !field.attrs.skip_deserializing());
+ let let_collect = if has_flatten {
Some(quote! {
let mut __collect = _serde::__private::Vec::<_serde::__private::Option<(
_serde::__private::de::Content,
@@ -2532,7 +2535,7 @@ fn deserialize_map(
});
// Visit ignored values to consume them
- let ignored_arm = if cattrs.has_flatten() {
+ let ignored_arm = if has_flatten {
Some(quote! {
__Field::__other(__name) => {
__collect.push(_serde::__private::Some((
@@ -2602,7 +2605,7 @@ fn deserialize_map(
}
});
- let collected_deny_unknown_fields = if cattrs.has_flatten() && cattrs.deny_unknown_fields() {
+ let collected_deny_unknown_fields = if has_flatten && cattrs.deny_unknown_fields() {
Some(quote! {
if let _serde::__private::Some(_serde::__private::Some((__key, _))) =
__collect.into_iter().filter(_serde::__private::Option::is_some).next()
| serde-rs/serde | 2024-08-08T01:47:34Z | 1b4da41f970555e111f471633205bbcb4dadbc63 | |
2,709 | diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index 3ca0fde36..8a7310cd2 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -23,7 +23,7 @@ use std::iter;
use std::net;
use std::num::{
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
- NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, Wrapping,
+ NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, Saturating, Wrapping,
};
use std::ops::Bound;
use std::path::{Path, PathBuf};
@@ -2065,6 +2065,43 @@ fn test_wrapping() {
test(Wrapping(1usize), &[Token::U64(1)]);
}
+#[test]
+fn test_saturating() {
+ test(Saturating(1usize), &[Token::U32(1)]);
+ test(Saturating(1usize), &[Token::U64(1)]);
+ test(Saturating(0u8), &[Token::I8(0)]);
+ test(Saturating(0u16), &[Token::I16(0)]);
+
+ // saturate input values at the minimum or maximum value
+ test(Saturating(u8::MAX), &[Token::U16(u16::MAX)]);
+ test(Saturating(u8::MAX), &[Token::U16(u8::MAX as u16 + 1)]);
+ test(Saturating(u16::MAX), &[Token::U32(u32::MAX)]);
+ test(Saturating(u32::MAX), &[Token::U64(u64::MAX)]);
+ test(Saturating(u8::MIN), &[Token::I8(i8::MIN)]);
+ test(Saturating(u16::MIN), &[Token::I16(i16::MIN)]);
+ test(Saturating(u32::MIN), &[Token::I32(i32::MIN)]);
+ test(Saturating(i8::MIN), &[Token::I16(i16::MIN)]);
+ test(Saturating(i16::MIN), &[Token::I32(i32::MIN)]);
+ test(Saturating(i32::MIN), &[Token::I64(i64::MIN)]);
+
+ test(Saturating(u8::MIN), &[Token::I8(-1)]);
+ test(Saturating(u16::MIN), &[Token::I16(-1)]);
+
+ #[cfg(target_pointer_width = "64")]
+ {
+ test(Saturating(usize::MIN), &[Token::U64(u64::MIN)]);
+ test(Saturating(usize::MAX), &[Token::U64(u64::MAX)]);
+ test(Saturating(isize::MIN), &[Token::I64(i64::MIN)]);
+ test(Saturating(isize::MAX), &[Token::I64(i64::MAX)]);
+ test(Saturating(0usize), &[Token::I64(i64::MIN)]);
+
+ test(
+ Saturating(9_223_372_036_854_775_807usize),
+ &[Token::I64(i64::MAX)],
+ );
+ }
+}
+
#[test]
fn test_rc_dst() {
test(Rc::<str>::from("s"), &[Token::Str("s")]);
diff --git a/test_suite/tests/test_ser.rs b/test_suite/tests/test_ser.rs
index 71ec3bc57..b60d03ab2 100644
--- a/test_suite/tests/test_ser.rs
+++ b/test_suite/tests/test_ser.rs
@@ -8,7 +8,7 @@ use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::ffi::CString;
use std::net;
-use std::num::Wrapping;
+use std::num::{Saturating, Wrapping};
use std::ops::Bound;
use std::path::{Path, PathBuf};
use std::rc::{Rc, Weak as RcWeak};
@@ -624,6 +624,11 @@ fn test_wrapping() {
assert_ser_tokens(&Wrapping(1usize), &[Token::U64(1)]);
}
+#[test]
+fn test_saturating() {
+ assert_ser_tokens(&Saturating(1usize), &[Token::U64(1)]);
+}
+
#[test]
fn test_rc_dst() {
assert_ser_tokens(&Rc::<str>::from("s"), &[Token::Str("s")]);
| [
"2708"
] | serde-rs__serde-2709 | Impl Serialize/Deserialize for std::num::Saturating<T>
It would be nice if we could get
```
use std::num::Saturating;
impl Deserialize for Saturating<T: Deserialize> { ... }
impl Serialize for Saturating<T: Serialize> { ... }
```
so that it is possible to handle wrapped types, that already support those traits.
| 1.19 | 5b24f88e73caa9c607527b5b4696fc34263cd238 | diff --git a/serde/build.rs b/serde/build.rs
index fe5486a7a..0074df63f 100644
--- a/serde/build.rs
+++ b/serde/build.rs
@@ -64,6 +64,12 @@ fn main() {
if minor < 64 {
println!("cargo:rustc-cfg=no_core_cstr");
}
+
+ // Support for core::num::Saturating and std::num::Saturating stabilized in Rust 1.74
+ // https://blog.rust-lang.org/2023/11/16/Rust-1.74.0.html#stabilized-apis
+ if minor < 74 {
+ println!("cargo:rustc-cfg=no_core_num_saturating");
+ }
}
fn rustc_minor_version() -> Option<u32> {
diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index d89f1872b..9ccb3ce69 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -387,6 +387,73 @@ impl_deserialize_num! {
num_as_self!(u8:visit_u8 u16:visit_u16 u32:visit_u32 u64:visit_u64);
}
+#[cfg(not(no_core_num_saturating))]
+macro_rules! visit_saturating {
+ ($primitive:ident, $ty:ident : $visit:ident) => {
+ #[inline]
+ fn $visit<E>(self, v: $ty) -> Result<Saturating<$primitive>, E>
+ where
+ E: Error,
+ {
+ let out: $primitive = core::convert::TryFrom::<$ty>::try_from(v).unwrap_or_else(|_| {
+ #[allow(unused_comparisons)]
+ if v < 0 {
+ // never true for unsigned values
+ $primitive::MIN
+ } else {
+ $primitive::MAX
+ }
+ });
+ Ok(Saturating(out))
+ }
+ };
+}
+
+macro_rules! impl_deserialize_saturating_num {
+ ($primitive:ident, $deserialize:ident ) => {
+ #[cfg(not(no_core_num_saturating))]
+ impl<'de> Deserialize<'de> for Saturating<$primitive> {
+ #[inline]
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ struct SaturatingVisitor;
+
+ impl<'de> Visitor<'de> for SaturatingVisitor {
+ type Value = Saturating<$primitive>;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("An integer with support for saturating semantics")
+ }
+
+ visit_saturating!($primitive, u8:visit_u8);
+ visit_saturating!($primitive, u16:visit_u16);
+ visit_saturating!($primitive, u32:visit_u32);
+ visit_saturating!($primitive, u64:visit_u64);
+ visit_saturating!($primitive, i8:visit_i8);
+ visit_saturating!($primitive, i16:visit_i16);
+ visit_saturating!($primitive, i32:visit_i32);
+ visit_saturating!($primitive, i64:visit_i64);
+ }
+
+ deserializer.$deserialize(SaturatingVisitor)
+ }
+ }
+ };
+}
+
+impl_deserialize_saturating_num!(u8, deserialize_u8);
+impl_deserialize_saturating_num!(u16, deserialize_u16);
+impl_deserialize_saturating_num!(u32, deserialize_u32);
+impl_deserialize_saturating_num!(u64, deserialize_u64);
+impl_deserialize_saturating_num!(usize, deserialize_u64);
+impl_deserialize_saturating_num!(i8, deserialize_i8);
+impl_deserialize_saturating_num!(i16, deserialize_i16);
+impl_deserialize_saturating_num!(i32, deserialize_i32);
+impl_deserialize_saturating_num!(i64, deserialize_i64);
+impl_deserialize_saturating_num!(isize, deserialize_i64);
+
macro_rules! num_128 {
($ty:ident : $visit:ident) => {
fn $visit<E>(self, v: $ty) -> Result<Self::Value, E>
diff --git a/serde/src/lib.rs b/serde/src/lib.rs
index 5cf44c1c1..dc6d392bd 100644
--- a/serde/src/lib.rs
+++ b/serde/src/lib.rs
@@ -274,6 +274,9 @@ mod lib {
pub use std::sync::atomic::{AtomicI64, AtomicU64};
#[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "ptr"))]
pub use std::sync::atomic::{AtomicIsize, AtomicUsize};
+
+ #[cfg(not(no_core_num_saturating))]
+ pub use self::core::num::Saturating;
}
// None of this crate's error handling needs the `From::from` error conversion
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index 7aa11621c..ffc4c70f9 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -1026,6 +1026,20 @@ where
}
}
+#[cfg(not(no_core_num_saturating))]
+impl<T> Serialize for Saturating<T>
+where
+ T: Serialize,
+{
+ #[inline]
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ self.0.serialize(serializer)
+ }
+}
+
impl<T> Serialize for Reverse<T>
where
T: Serialize,
| serde-rs/serde | 2024-03-04T18:04:22Z | Edit: I mixed up `Wrapping` and `Saturating`. However, I still want to link to the implementations for [Serialize](https://github.com/serde-rs/serde/blob/89139e2c11c9e975753ebe82745071acb47ecb03/serde/src/ser/impls.rs#L1016-L1027) and [Deserialize](https://github.com/serde-rs/serde/blob/89139e2c11c9e975753ebe82745071acb47ecb03/serde/src/de/impls.rs#L2995-L3005) for `Wrapping<T>`, because the future implementations for `Saturating<T>` will probably be very similar. | 5b24f88e73caa9c607527b5b4696fc34263cd238 |
2,592 | diff --git a/test_suite/tests/test_remote.rs b/test_suite/tests/test_remote.rs
index 7069cf9b6..c1f152eb8 100644
--- a/test_suite/tests/test_remote.rs
+++ b/test_suite/tests/test_remote.rs
@@ -127,7 +127,7 @@ struct Test {
enum_concrete: remote::EnumGeneric<u8>,
#[serde(with = "ErrorKindDef")]
- io_error_kind: std::io::ErrorKind,
+ io_error_kind: ErrorKind,
}
#[derive(Serialize, Deserialize)]
@@ -200,8 +200,16 @@ enum EnumConcrete {
Variant(u8),
}
+#[derive(Debug)]
+enum ErrorKind {
+ NotFound,
+ PermissionDenied,
+ #[allow(dead_code)]
+ ConnectionRefused,
+}
+
#[derive(Serialize, Deserialize)]
-#[serde(remote = "std::io::ErrorKind")]
+#[serde(remote = "ErrorKind")]
#[non_exhaustive]
enum ErrorKindDef {
NotFound,
| [
"2591"
] | serde-rs__serde-2592 | 1.0.184 might be causing a compilation error.
I got a compilation error which doesn't occur with `serde 1.0.183`. Is it a some breaking change?
[example project](https://github.com/tacogips/serde_184_error)
Cargo.toml
```
[package]
name = "serde_184_error"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
sentry = "0.31.5"
#The compile error not occured on serde = "= 1.0.183"
serde = "1.0.184"
```
Error message
```
Updating crates.io index
Checking sentry-types v0.31.5
error[E0507]: cannot move out of `*self` which is behind a shared reference
--> /g/cargo/registry/src/index.crates.io-6f17d22bba15001f/sentry-types-0.31.5/src/protocol/v7.rs:1083:10
|
1083 | #[derive(Serialize, Deserialize, Debug, Clone, Parti...
| ^^^^^^^^^
| |
| data moved here
| move occurs because `unrecognized` has type `v7::Context`, which does not implement the `Copy` trait
|
= note: this error originates in the derive macro `Serialize` (in Nightly builds, run with -Z macro-backtrace for moreinfo)
help: consider borrowing here
|
1083 | #[derive(&Serialize, Deserialize, Debug, Clone, PartialEq)]
| +
For more information about this error, try `rustc --explain E0507`.
error: could not compile `sentry-types` (lib) due to previouserror
```
| 1.18 | d593215ef703d1fe343b62b00e21880dfe501007 | diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index 1f67f0430..a2cab263c 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -409,9 +409,9 @@ fn serialize_enum(params: &Parameters, variants: &[Variant], cattrs: &attr::Cont
})
.collect();
- if cattrs.non_exhaustive() {
+ if cattrs.remote().is_some() && cattrs.non_exhaustive() {
arms.push(quote! {
- unrecognized => _serde::__private::Err(_serde::ser::Error::custom(_serde::__private::ser::CannotSerializeVariant(unrecognized))),
+ ref unrecognized => _serde::__private::Err(_serde::ser::Error::custom(_serde::__private::ser::CannotSerializeVariant(unrecognized))),
});
}
| serde-rs/serde | 2023-08-21T04:37:53Z | d593215ef703d1fe343b62b00e21880dfe501007 | |
2,570 | diff --git a/test_suite/tests/test_remote.rs b/test_suite/tests/test_remote.rs
index 2a37909fd..7069cf9b6 100644
--- a/test_suite/tests/test_remote.rs
+++ b/test_suite/tests/test_remote.rs
@@ -125,6 +125,9 @@ struct Test {
#[serde(with = "EnumConcrete")]
enum_concrete: remote::EnumGeneric<u8>,
+
+ #[serde(with = "ErrorKindDef")]
+ io_error_kind: std::io::ErrorKind,
}
#[derive(Serialize, Deserialize)]
@@ -197,6 +200,15 @@ enum EnumConcrete {
Variant(u8),
}
+#[derive(Serialize, Deserialize)]
+#[serde(remote = "std::io::ErrorKind")]
+#[non_exhaustive]
+enum ErrorKindDef {
+ NotFound,
+ PermissionDenied,
+ // ...
+}
+
impl From<PrimitivePrivDef> for remote::PrimitivePriv {
fn from(def: PrimitivePrivDef) -> Self {
remote::PrimitivePriv::new(def.0)
| [
"2361"
] | serde-rs__serde-2570 | Add exhaustive match arm in `#[derive(Serialize)]` expansion
Closes #2360
| 1.18 | 45271c36760c59a86a59d2a80eae58efd87ae577 | diff --git a/serde/src/private/ser.rs b/serde/src/private/ser.rs
index 7876542ee..50bcb251e 100644
--- a/serde/src/private/ser.rs
+++ b/serde/src/private/ser.rs
@@ -1370,3 +1370,16 @@ impl Serialize for AdjacentlyTaggedEnumVariant {
serializer.serialize_unit_variant(self.enum_name, self.variant_index, self.variant_name)
}
}
+
+// Error when Serialize for a non_exhaustive remote enum encounters a variant
+// that is not recognized.
+pub struct CannotSerializeVariant<T>(pub T);
+
+impl<T> Display for CannotSerializeVariant<T>
+where
+ T: Debug,
+{
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ write!(formatter, "enum variant cannot be serialized: {:?}", self.0)
+ }
+}
diff --git a/serde_derive/src/internals/attr.rs b/serde_derive/src/internals/attr.rs
index d5512348b..0b25c7c0d 100644
--- a/serde_derive/src/internals/attr.rs
+++ b/serde_derive/src/internals/attr.rs
@@ -221,6 +221,7 @@ pub struct Container {
is_packed: bool,
/// Error message generated when type can't be deserialized
expecting: Option<String>,
+ non_exhaustive: bool,
}
/// Styles of representing an enum.
@@ -306,9 +307,12 @@ impl Container {
let mut variant_identifier = BoolAttr::none(cx, VARIANT_IDENTIFIER);
let mut serde_path = Attr::none(cx, CRATE);
let mut expecting = Attr::none(cx, EXPECTING);
+ let mut non_exhaustive = false;
for attr in &item.attrs {
if attr.path() != SERDE {
+ non_exhaustive |=
+ matches!(&attr.meta, syn::Meta::Path(path) if path == NON_EXHAUSTIVE);
continue;
}
@@ -587,6 +591,7 @@ impl Container {
serde_path: serde_path.get(),
is_packed,
expecting: expecting.get(),
+ non_exhaustive,
}
}
@@ -672,6 +677,10 @@ impl Container {
pub fn expecting(&self) -> Option<&str> {
self.expecting.as_ref().map(String::as_ref)
}
+
+ pub fn non_exhaustive(&self) -> bool {
+ self.non_exhaustive
+ }
}
fn decide_tag(
diff --git a/serde_derive/src/internals/symbol.rs b/serde_derive/src/internals/symbol.rs
index 68091fb85..572391a80 100644
--- a/serde_derive/src/internals/symbol.rs
+++ b/serde_derive/src/internals/symbol.rs
@@ -19,6 +19,7 @@ pub const FLATTEN: Symbol = Symbol("flatten");
pub const FROM: Symbol = Symbol("from");
pub const GETTER: Symbol = Symbol("getter");
pub const INTO: Symbol = Symbol("into");
+pub const NON_EXHAUSTIVE: Symbol = Symbol("non_exhaustive");
pub const OTHER: Symbol = Symbol("other");
pub const REMOTE: Symbol = Symbol("remote");
pub const RENAME: Symbol = Symbol("rename");
diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index dc02466f5..1f67f0430 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -401,7 +401,7 @@ fn serialize_enum(params: &Parameters, variants: &[Variant], cattrs: &attr::Cont
let self_var = ¶ms.self_var;
- let arms: Vec<_> = variants
+ let mut arms: Vec<_> = variants
.iter()
.enumerate()
.map(|(variant_index, variant)| {
@@ -409,6 +409,12 @@ fn serialize_enum(params: &Parameters, variants: &[Variant], cattrs: &attr::Cont
})
.collect();
+ if cattrs.non_exhaustive() {
+ arms.push(quote! {
+ unrecognized => _serde::__private::Err(_serde::ser::Error::custom(_serde::__private::ser::CannotSerializeVariant(unrecognized))),
+ });
+ }
+
quote_expr! {
match *#self_var {
#(#arms)*
| serde-rs/serde | 2023-08-14T04:18:08Z | d593215ef703d1fe343b62b00e21880dfe501007 | |
2,567 | diff --git a/test_suite/tests/regression/issue1904.rs b/test_suite/tests/regression/issue1904.rs
new file mode 100644
index 000000000..99736c078
--- /dev/null
+++ b/test_suite/tests/regression/issue1904.rs
@@ -0,0 +1,65 @@
+#![allow(dead_code)] // we do not read enum fields
+use serde_derive::Deserialize;
+
+#[derive(Deserialize)]
+pub struct Nested;
+
+#[derive(Deserialize)]
+pub enum ExternallyTagged1 {
+ Tuple(f64, String),
+ Flatten {
+ #[serde(flatten)]
+ nested: Nested,
+ },
+}
+
+#[derive(Deserialize)]
+pub enum ExternallyTagged2 {
+ Flatten {
+ #[serde(flatten)]
+ nested: Nested,
+ },
+ Tuple(f64, String),
+}
+
+// Internally tagged enums cannot contain tuple variants so not tested here
+
+#[derive(Deserialize)]
+#[serde(tag = "tag", content = "content")]
+pub enum AdjacentlyTagged1 {
+ Tuple(f64, String),
+ Flatten {
+ #[serde(flatten)]
+ nested: Nested,
+ },
+}
+
+#[derive(Deserialize)]
+#[serde(tag = "tag", content = "content")]
+pub enum AdjacentlyTagged2 {
+ Flatten {
+ #[serde(flatten)]
+ nested: Nested,
+ },
+ Tuple(f64, String),
+}
+
+#[derive(Deserialize)]
+#[serde(untagged)]
+pub enum Untagged1 {
+ Tuple(f64, String),
+ Flatten {
+ #[serde(flatten)]
+ nested: Nested,
+ },
+}
+
+#[derive(Deserialize)]
+#[serde(untagged)]
+pub enum Untagged2 {
+ Flatten {
+ #[serde(flatten)]
+ nested: Nested,
+ },
+ Tuple(f64, String),
+}
diff --git a/test_suite/tests/regression/issue2565.rs b/test_suite/tests/regression/issue2565.rs
new file mode 100644
index 000000000..65cbb0a31
--- /dev/null
+++ b/test_suite/tests/regression/issue2565.rs
@@ -0,0 +1,41 @@
+use serde_derive::{Serialize, Deserialize};
+use serde_test::{assert_tokens, Token};
+
+#[derive(Serialize, Deserialize, Debug, PartialEq)]
+enum Enum {
+ Simple {
+ a: i32,
+ },
+ Flatten {
+ #[serde(flatten)]
+ flatten: (),
+ a: i32,
+ },
+}
+
+#[test]
+fn simple_variant() {
+ assert_tokens(
+ &Enum::Simple { a: 42 },
+ &[
+ Token::StructVariant { name: "Enum", variant: "Simple", len: 1 },
+ Token::Str("a"),
+ Token::I32(42),
+ Token::StructVariantEnd,
+ ]
+ );
+}
+
+#[test]
+fn flatten_variant() {
+ assert_tokens(
+ &Enum::Flatten { flatten: (), a: 42 },
+ &[
+ Token::NewtypeVariant { name: "Enum", variant: "Flatten" },
+ Token::Map { len: None },
+ Token::Str("a"),
+ Token::I32(42),
+ Token::MapEnd,
+ ]
+ );
+}
diff --git a/test_suite/tests/regression/issue2792.rs b/test_suite/tests/regression/issue2792.rs
new file mode 100644
index 000000000..13c0b7103
--- /dev/null
+++ b/test_suite/tests/regression/issue2792.rs
@@ -0,0 +1,16 @@
+#![allow(dead_code)] // we do not read enum fields
+use serde_derive::Deserialize;
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub enum A {
+ B {
+ c: String,
+ },
+ D {
+ #[serde(flatten)]
+ e: E,
+ },
+}
+#[derive(Deserialize)]
+pub struct E {}
diff --git a/test_suite/tests/test_annotations.rs b/test_suite/tests/test_annotations.rs
index 566f7d43f..1488c8364 100644
--- a/test_suite/tests/test_annotations.rs
+++ b/test_suite/tests/test_annotations.rs
@@ -2380,6 +2380,56 @@ fn test_partially_untagged_enum_desugared() {
);
}
+/// Regression test for https://github.com/serde-rs/serde/issues/1904
+#[test]
+fn test_enum_tuple_and_struct_with_flatten() {
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
+ enum Outer {
+ Tuple(f64, i32),
+ Flatten {
+ #[serde(flatten)]
+ nested: Nested,
+ },
+ }
+
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
+ struct Nested {
+ a: i32,
+ b: i32,
+ }
+
+ assert_tokens(
+ &Outer::Tuple(1.2, 3),
+ &[
+ Token::TupleVariant {
+ name: "Outer",
+ variant: "Tuple",
+ len: 2,
+ },
+ Token::F64(1.2),
+ Token::I32(3),
+ Token::TupleVariantEnd,
+ ],
+ );
+ assert_tokens(
+ &Outer::Flatten {
+ nested: Nested { a: 1, b: 2 },
+ },
+ &[
+ Token::NewtypeVariant {
+ name: "Outer",
+ variant: "Flatten",
+ },
+ Token::Map { len: None },
+ Token::Str("a"),
+ Token::I32(1),
+ Token::Str("b"),
+ Token::I32(2),
+ Token::MapEnd,
+ ],
+ );
+}
+
#[test]
fn test_partially_untagged_internally_tagged_enum() {
#[derive(Serialize, Deserialize, PartialEq, Debug)]
| [
"1904",
"2792"
] | serde-rs__serde-2567 | Deserialize failed to derive on enums with tuple variant and flatten struct variant
[Instead of thousand of words](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f1ea8c90736214e52d74c4ca0cab973b)
This code is failed to compile due to panic in serde derive:
```rust
#[derive(Deserialize)]
enum Failed {
Tuple(f64, String),
Flatten {
#[serde(flatten)]
nested: Nested,
},
}
```
Output:
```bash
Compiling playground v0.0.1 (/playground)
error: proc-macro derive panicked
--> src/lib.rs:30:10
|
30 | #[derive(Deserialize)]
| ^^^^^^^^^^^
|
= help: message: assertion failed: !cattrs.has_flatten()
error: aborting due to previous error
error: could not compile `playground`.
To learn more, run the command again with --verbose.
```
Each variant individually and `Serialize` derive works well, problem is only in combination of tuple variant and struct variant, when struct variant contains flattened field.
`deny_unknown_fields` can break in 1.0.205
The following (reduction of a less artificial example)
```rust
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
enum A {
B {
c: String,
},
D {
#[serde(flatten)]
e: E,
},
}
#[derive(serde::Deserialize)]
struct E {}
```
compiles fine with 1.0.204 but produces the following error in 1.0.205:
```
error[E0004]: non-exhaustive patterns: `<_::<impl Deserialize<'de> for A>::deserialize::__Visitor<'de> as Visitor<'de>>::visit_enum::__Field::__other(_)` not covered
--> src/main.rs:1:10
|
1 | #[derive(serde::Deserialize)]
| ^^^^^^^^^^^^^^^^^^ pattern `<_::<impl Deserialize<'de> for A>::deserialize::__Visitor<'de> as Visitor<'de>>::visit_enum::__Field::__other(_)` not covered
|
note: `<_::<impl Deserialize<'de> for A>::deserialize::__Visitor<'de> as Visitor<'de>>::visit_enum::__Field<'_>` defined here
--> src/main.rs:1:10
|
1 | #[derive(serde::Deserialize)]
| ^^^^^^^^^^^^^^^^^^
| |
| not covered
= note: the matched value is of type `<_::<impl Deserialize<'de> for A>::deserialize::__Visitor<'de> as Visitor<'de>>::visit_enum::__Field<'_>`
= note: this error originates in the derive macro `serde::Deserialize` (in Nightly builds, run with -Z macro-backtrace for more info)
```
I have bisected the changes, and the issue appears in 32958dec3bf3886961166ec651194d6f0243a497
| 1.20 | 9b868ef831c95f50dd4bde51a7eb52e3b9ee265a | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index c5861d9bc..ef85385f6 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -281,11 +281,21 @@ fn deserialize_body(cont: &Container, params: &Parameters) -> Fragment {
} else if let attr::Identifier::No = cont.attrs.identifier() {
match &cont.data {
Data::Enum(variants) => deserialize_enum(params, variants, &cont.attrs),
- Data::Struct(Style::Struct, fields) => {
- deserialize_struct(params, fields, &cont.attrs, StructForm::Struct)
- }
+ Data::Struct(Style::Struct, fields) => deserialize_struct(
+ params,
+ fields,
+ &cont.attrs,
+ cont.attrs.has_flatten(),
+ StructForm::Struct,
+ ),
Data::Struct(Style::Tuple, fields) | Data::Struct(Style::Newtype, fields) => {
- deserialize_tuple(params, fields, &cont.attrs, TupleForm::Tuple)
+ deserialize_tuple(
+ params,
+ fields,
+ &cont.attrs,
+ cont.attrs.has_flatten(),
+ TupleForm::Tuple,
+ )
}
Data::Struct(Style::Unit, _) => deserialize_unit_struct(params, &cont.attrs),
}
@@ -459,9 +469,13 @@ fn deserialize_tuple(
params: &Parameters,
fields: &[Field],
cattrs: &attr::Container,
+ has_flatten: bool,
form: TupleForm,
) -> Fragment {
- assert!(!cattrs.has_flatten());
+ assert!(
+ !has_flatten,
+ "tuples and tuple variants cannot have flatten fields"
+ );
let field_count = fields
.iter()
@@ -579,7 +593,10 @@ fn deserialize_tuple_in_place(
fields: &[Field],
cattrs: &attr::Container,
) -> Fragment {
- assert!(!cattrs.has_flatten());
+ assert!(
+ !cattrs.has_flatten(),
+ "tuples and tuple variants cannot have flatten fields"
+ );
let field_count = fields
.iter()
@@ -910,6 +927,7 @@ fn deserialize_struct(
params: &Parameters,
fields: &[Field],
cattrs: &attr::Container,
+ has_flatten: bool,
form: StructForm,
) -> Fragment {
let this_type = ¶ms.this_type;
@@ -958,13 +976,13 @@ fn deserialize_struct(
)
})
.collect();
- let field_visitor = deserialize_field_identifier(&field_names_idents, cattrs);
+ let field_visitor = deserialize_field_identifier(&field_names_idents, cattrs, has_flatten);
// 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 form {
StructForm::Untagged(..) => None,
- _ if cattrs.has_flatten() => None,
+ _ if has_flatten => None,
_ => {
let mut_seq = if field_names_idents.is_empty() {
quote!(_)
@@ -987,10 +1005,16 @@ fn deserialize_struct(
})
}
};
- let visit_map = Stmts(deserialize_map(&type_path, params, fields, cattrs));
+ let visit_map = Stmts(deserialize_map(
+ &type_path,
+ params,
+ fields,
+ cattrs,
+ has_flatten,
+ ));
let visitor_seed = match form {
- StructForm::ExternallyTagged(..) if cattrs.has_flatten() => Some(quote! {
+ StructForm::ExternallyTagged(..) if has_flatten => Some(quote! {
impl #de_impl_generics _serde::de::DeserializeSeed<#delife> for __Visitor #de_ty_generics #where_clause {
type Value = #this_type #ty_generics;
@@ -1005,7 +1029,7 @@ fn deserialize_struct(
_ => None,
};
- let fields_stmt = if cattrs.has_flatten() {
+ let fields_stmt = if has_flatten {
None
} else {
let field_names = field_names_idents
@@ -1025,7 +1049,7 @@ fn deserialize_struct(
}
};
let dispatch = match form {
- StructForm::Struct if cattrs.has_flatten() => quote! {
+ StructForm::Struct if has_flatten => quote! {
_serde::Deserializer::deserialize_map(__deserializer, #visitor_expr)
},
StructForm::Struct => {
@@ -1034,7 +1058,7 @@ fn deserialize_struct(
_serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, #visitor_expr)
}
}
- StructForm::ExternallyTagged(_) if cattrs.has_flatten() => quote! {
+ StructForm::ExternallyTagged(_) if has_flatten => quote! {
_serde::de::VariantAccess::newtype_variant_seed(__variant, #visitor_expr)
},
StructForm::ExternallyTagged(_) => quote! {
@@ -1116,7 +1140,7 @@ fn deserialize_struct_in_place(
})
.collect();
- let field_visitor = deserialize_field_identifier(&field_names_idents, cattrs);
+ let field_visitor = deserialize_field_identifier(&field_names_idents, cattrs, false);
let mut_seq = if field_names_idents.is_empty() {
quote!(_)
@@ -1210,10 +1234,7 @@ fn deserialize_homogeneous_enum(
}
}
-fn prepare_enum_variant_enum(
- variants: &[Variant],
- cattrs: &attr::Container,
-) -> (TokenStream, Stmts) {
+fn prepare_enum_variant_enum(variants: &[Variant]) -> (TokenStream, Stmts) {
let mut deserialized_variants = variants
.iter()
.enumerate()
@@ -1247,7 +1268,7 @@ fn prepare_enum_variant_enum(
let variant_visitor = Stmts(deserialize_generated_identifier(
&variant_names_idents,
- cattrs,
+ false, // variant identifiers does not depend on the presence of flatten fields
true,
None,
fallthrough,
@@ -1270,7 +1291,7 @@ fn deserialize_externally_tagged_enum(
let expecting = format!("enum {}", params.type_name());
let expecting = cattrs.expecting().unwrap_or(&expecting);
- let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants, cattrs);
+ let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants);
// Match arms to extract a variant from a string
let variant_arms = variants
@@ -1355,7 +1376,7 @@ fn deserialize_internally_tagged_enum(
cattrs: &attr::Container,
tag: &str,
) -> Fragment {
- let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants, cattrs);
+ let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants);
// Match arms to extract a variant from a string
let variant_arms = variants
@@ -1409,7 +1430,7 @@ fn deserialize_adjacently_tagged_enum(
split_with_de_lifetime(params);
let delife = params.borrowed.de_lifetime();
- let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants, cattrs);
+ let (variants_stmt, variant_visitor) = prepare_enum_variant_enum(variants);
let variant_arms: &Vec<_> = &variants
.iter()
@@ -1810,12 +1831,14 @@ fn deserialize_externally_tagged_variant(
params,
&variant.fields,
cattrs,
+ variant.attrs.has_flatten(),
TupleForm::ExternallyTagged(variant_ident),
),
Style::Struct => deserialize_struct(
params,
&variant.fields,
cattrs,
+ variant.attrs.has_flatten(),
StructForm::ExternallyTagged(variant_ident),
),
}
@@ -1859,6 +1882,7 @@ fn deserialize_internally_tagged_variant(
params,
&variant.fields,
cattrs,
+ variant.attrs.has_flatten(),
StructForm::InternallyTagged(variant_ident, deserializer),
),
Style::Tuple => unreachable!("checked in serde_derive_internals"),
@@ -1909,12 +1933,14 @@ fn deserialize_untagged_variant(
params,
&variant.fields,
cattrs,
+ variant.attrs.has_flatten(),
TupleForm::Untagged(variant_ident, deserializer),
),
Style::Struct => deserialize_struct(
params,
&variant.fields,
cattrs,
+ variant.attrs.has_flatten(),
StructForm::Untagged(variant_ident, deserializer),
),
}
@@ -1985,7 +2011,7 @@ fn deserialize_untagged_newtype_variant(
fn deserialize_generated_identifier(
fields: &[(&str, Ident, &BTreeSet<String>)],
- cattrs: &attr::Container,
+ has_flatten: bool,
is_variant: bool,
ignore_variant: Option<TokenStream>,
fallthrough: Option<TokenStream>,
@@ -1999,11 +2025,11 @@ fn deserialize_generated_identifier(
is_variant,
fallthrough,
None,
- !is_variant && cattrs.has_flatten(),
+ !is_variant && has_flatten,
None,
));
- let lifetime = if !is_variant && cattrs.has_flatten() {
+ let lifetime = if !is_variant && has_flatten {
Some(quote!(<'de>))
} else {
None
@@ -2043,8 +2069,9 @@ fn deserialize_generated_identifier(
fn deserialize_field_identifier(
fields: &[(&str, Ident, &BTreeSet<String>)],
cattrs: &attr::Container,
+ has_flatten: bool,
) -> Stmts {
- let (ignore_variant, fallthrough) = if cattrs.has_flatten() {
+ let (ignore_variant, fallthrough) = if has_flatten {
let ignore_variant = quote!(__other(_serde::__private::de::Content<'de>),);
let fallthrough = quote!(_serde::__private::Ok(__Field::__other(__value)));
(Some(ignore_variant), Some(fallthrough))
@@ -2058,7 +2085,7 @@ fn deserialize_field_identifier(
Stmts(deserialize_generated_identifier(
fields,
- cattrs,
+ has_flatten,
false,
ignore_variant,
fallthrough,
@@ -2460,6 +2487,7 @@ fn deserialize_map(
params: &Parameters,
fields: &[Field],
cattrs: &attr::Container,
+ has_flatten: bool,
) -> Fragment {
// Create the field names for the fields.
let fields_names: Vec<_> = fields
@@ -2480,9 +2508,6 @@ fn deserialize_map(
});
// Collect contents for flatten fields into a buffer
- let has_flatten = fields
- .iter()
- .any(|field| field.attrs.flatten() && !field.attrs.skip_deserializing());
let let_collect = if has_flatten {
Some(quote! {
let mut __collect = _serde::__private::Vec::<_serde::__private::Option<(
@@ -2681,7 +2706,10 @@ fn deserialize_map_in_place(
fields: &[Field],
cattrs: &attr::Container,
) -> Fragment {
- assert!(!cattrs.has_flatten());
+ assert!(
+ !cattrs.has_flatten(),
+ "inplace deserialization of maps doesn't support flatten fields"
+ );
// Create the field names for the fields.
let fields_names: Vec<_> = fields
diff --git a/serde_derive/src/internals/ast.rs b/serde_derive/src/internals/ast.rs
index a28d3ae7e..4ec709952 100644
--- a/serde_derive/src/internals/ast.rs
+++ b/serde_derive/src/internals/ast.rs
@@ -85,6 +85,7 @@ impl<'a> Container<'a> {
for field in &mut variant.fields {
if field.attrs.flatten() {
has_flatten = true;
+ variant.attrs.mark_has_flatten();
}
field.attrs.rename_by_rules(
variant
diff --git a/serde_derive/src/internals/attr.rs b/serde_derive/src/internals/attr.rs
index 0cfb23bf1..5064d079a 100644
--- a/serde_derive/src/internals/attr.rs
+++ b/serde_derive/src/internals/attr.rs
@@ -216,6 +216,22 @@ pub struct Container {
type_into: Option<syn::Type>,
remote: Option<syn::Path>,
identifier: Identifier,
+ /// `true` if container is a `struct` and it has a field with `#[serde(flatten)]`
+ /// attribute or it is an `enum` with a struct variant which has a field with
+ /// `#[serde(flatten)]` attribute. Examples:
+ ///
+ /// ```ignore
+ /// struct Container {
+ /// #[serde(flatten)]
+ /// some_field: (),
+ /// }
+ /// enum Container {
+ /// Variant {
+ /// #[serde(flatten)]
+ /// some_field: (),
+ /// },
+ /// }
+ /// ```
has_flatten: bool,
serde_path: Option<syn::Path>,
is_packed: bool,
@@ -794,6 +810,18 @@ pub struct Variant {
rename_all_rules: RenameAllRules,
ser_bound: Option<Vec<syn::WherePredicate>>,
de_bound: Option<Vec<syn::WherePredicate>>,
+ /// `true` if variant is a struct variant which contains a field with `#[serde(flatten)]`
+ /// attribute. Examples:
+ ///
+ /// ```ignore
+ /// enum Enum {
+ /// Variant {
+ /// #[serde(flatten)]
+ /// some_field: (),
+ /// },
+ /// }
+ /// ```
+ has_flatten: bool,
skip_deserializing: bool,
skip_serializing: bool,
other: bool,
@@ -963,6 +991,7 @@ impl Variant {
},
ser_bound: ser_bound.get(),
de_bound: de_bound.get(),
+ has_flatten: false,
skip_deserializing: skip_deserializing.get(),
skip_serializing: skip_serializing.get(),
other: other.get(),
@@ -1005,6 +1034,14 @@ impl Variant {
self.de_bound.as_ref().map(|vec| &vec[..])
}
+ pub fn has_flatten(&self) -> bool {
+ self.has_flatten
+ }
+
+ pub fn mark_has_flatten(&mut self) {
+ self.has_flatten = true;
+ }
+
pub fn skip_deserializing(&self) -> bool {
self.skip_deserializing
}
| serde-rs/serde | 2023-08-10T22:04:01Z | 1b4da41f970555e111f471633205bbcb4dadbc63 | |
2,562 | diff --git a/test_suite/tests/ui/conflict/alias-enum.rs b/test_suite/tests/ui/conflict/alias-enum.rs
new file mode 100644
index 000000000..52af74b97
--- /dev/null
+++ b/test_suite/tests/ui/conflict/alias-enum.rs
@@ -0,0 +1,79 @@
+#![allow(non_camel_case_types)]
+
+use serde_derive::Deserialize;
+
+#[derive(Deserialize)]
+enum E {
+ S1 {
+ /// Expected error on "alias b", because this is a name of other field
+ /// Error on "alias a" is not expected because this is a name of this field
+ /// Error on "alias c" is not expected because field `c` is skipped
+ #[serde(alias = "a", alias = "b", alias = "c")]
+ a: (),
+
+ /// Expected error on "alias c", because it is already used as alias of `a`
+ #[serde(alias = "c")]
+ b: (),
+
+ #[serde(skip_deserializing)]
+ c: (),
+ },
+
+ S2 {
+ /// Expected error on "alias c", because this is a name of other field after
+ /// applying rename rules
+ #[serde(alias = "b", alias = "c")]
+ a: (),
+
+ #[serde(rename = "c")]
+ b: (),
+ },
+
+ #[serde(rename_all = "UPPERCASE")]
+ S3 {
+ /// Expected error on "alias B", because this is a name of field after
+ /// applying rename rules
+ #[serde(alias = "B", alias = "c")]
+ a: (),
+ b: (),
+ },
+}
+
+#[derive(Deserialize)]
+enum E1 {
+ /// Expected error on "alias b", because this is a name of other variant
+ /// Error on "alias a" is not expected because this is a name of this variant
+ /// Error on "alias c" is not expected because variant `c` is skipped
+ #[serde(alias = "a", alias = "b", alias = "c")]
+ a,
+
+ /// Expected error on "alias c", because it is already used as alias of `a`
+ #[serde(alias = "c")]
+ b,
+
+ #[serde(skip_deserializing)]
+ c,
+}
+
+#[derive(Deserialize)]
+enum E2 {
+ /// Expected error on "alias c", because this is a name of other variant after
+ /// applying rename rules
+ #[serde(alias = "b", alias = "c")]
+ a,
+
+ #[serde(rename = "c")]
+ b,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "UPPERCASE")]
+enum E3 {
+ /// Expected error on "alias B", because this is a name of variant after
+ /// applying rename rules
+ #[serde(alias = "B", alias = "c")]
+ a,
+ b,
+}
+
+fn main() {}
diff --git a/test_suite/tests/ui/conflict/alias-enum.stderr b/test_suite/tests/ui/conflict/alias-enum.stderr
new file mode 100644
index 000000000..36e036f65
--- /dev/null
+++ b/test_suite/tests/ui/conflict/alias-enum.stderr
@@ -0,0 +1,71 @@
+error: alias `b` conflicts with deserialization name of other field
+ --> tests/ui/conflict/alias-enum.rs:8:9
+ |
+8 | / /// Expected error on "alias b", because this is a name of other field
+9 | | /// Error on "alias a" is not expected because this is a name of this field
+10 | | /// Error on "alias c" is not expected because field `c` is skipped
+11 | | #[serde(alias = "a", alias = "b", alias = "c")]
+12 | | a: (),
+ | |_____________^
+
+error: alias `c` already used by field a
+ --> tests/ui/conflict/alias-enum.rs:14:9
+ |
+14 | / /// Expected error on "alias c", because it is already used as alias of `a`
+15 | | #[serde(alias = "c")]
+16 | | b: (),
+ | |_____________^
+
+error: alias `c` conflicts with deserialization name of other field
+ --> tests/ui/conflict/alias-enum.rs:23:9
+ |
+23 | / /// Expected error on "alias c", because this is a name of other field after
+24 | | /// applying rename rules
+25 | | #[serde(alias = "b", alias = "c")]
+26 | | a: (),
+ | |_____________^
+
+error: alias `B` conflicts with deserialization name of other field
+ --> tests/ui/conflict/alias-enum.rs:34:9
+ |
+34 | / /// Expected error on "alias B", because this is a name of field after
+35 | | /// applying rename rules
+36 | | #[serde(alias = "B", alias = "c")]
+37 | | a: (),
+ | |_____________^
+
+error: alias `b` conflicts with deserialization name of other variant
+ --> tests/ui/conflict/alias-enum.rs:44:5
+ |
+44 | / /// Expected error on "alias b", because this is a name of other variant
+45 | | /// Error on "alias a" is not expected because this is a name of this variant
+46 | | /// Error on "alias c" is not expected because variant `c` is skipped
+47 | | #[serde(alias = "a", alias = "b", alias = "c")]
+48 | | a,
+ | |_____^
+
+error: alias `c` already used by variant a
+ --> tests/ui/conflict/alias-enum.rs:50:5
+ |
+50 | / /// Expected error on "alias c", because it is already used as alias of `a`
+51 | | #[serde(alias = "c")]
+52 | | b,
+ | |_____^
+
+error: alias `c` conflicts with deserialization name of other variant
+ --> tests/ui/conflict/alias-enum.rs:60:5
+ |
+60 | / /// Expected error on "alias c", because this is a name of other variant after
+61 | | /// applying rename rules
+62 | | #[serde(alias = "b", alias = "c")]
+63 | | a,
+ | |_____^
+
+error: alias `B` conflicts with deserialization name of other variant
+ --> tests/ui/conflict/alias-enum.rs:72:5
+ |
+72 | / /// Expected error on "alias B", because this is a name of variant after
+73 | | /// applying rename rules
+74 | | #[serde(alias = "B", alias = "c")]
+75 | | a,
+ | |_____^
diff --git a/test_suite/tests/ui/conflict/alias.rs b/test_suite/tests/ui/conflict/alias.rs
new file mode 100644
index 000000000..f52a90586
--- /dev/null
+++ b/test_suite/tests/ui/conflict/alias.rs
@@ -0,0 +1,40 @@
+use serde_derive::Deserialize;
+
+#[derive(Deserialize)]
+struct S1 {
+ /// Expected error on "alias b", because this is a name of other field
+ /// Error on "alias a" is not expected because this is a name of this field
+ /// Error on "alias c" is not expected because field `c` is skipped
+ #[serde(alias = "a", alias = "b", alias = "c")]
+ a: (),
+
+ /// Expected error on "alias c", because it is already used as alias of `a`
+ #[serde(alias = "c")]
+ b: (),
+
+ #[serde(skip_deserializing)]
+ c: (),
+}
+
+#[derive(Deserialize)]
+struct S2 {
+ /// Expected error on "alias c", because this is a name of other field after
+ /// applying rename rules
+ #[serde(alias = "b", alias = "c")]
+ a: (),
+
+ #[serde(rename = "c")]
+ b: (),
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "UPPERCASE")]
+struct S3 {
+ /// Expected error on "alias B", because this is a name of field after
+ /// applying rename rules
+ #[serde(alias = "B", alias = "c")]
+ a: (),
+ b: (),
+}
+
+fn main() {}
diff --git a/test_suite/tests/ui/conflict/alias.stderr b/test_suite/tests/ui/conflict/alias.stderr
new file mode 100644
index 000000000..2115b21b1
--- /dev/null
+++ b/test_suite/tests/ui/conflict/alias.stderr
@@ -0,0 +1,35 @@
+error: alias `b` conflicts with deserialization name of other field
+ --> tests/ui/conflict/alias.rs:5:5
+ |
+5 | / /// Expected error on "alias b", because this is a name of other field
+6 | | /// Error on "alias a" is not expected because this is a name of this field
+7 | | /// Error on "alias c" is not expected because field `c` is skipped
+8 | | #[serde(alias = "a", alias = "b", alias = "c")]
+9 | | a: (),
+ | |_________^
+
+error: alias `c` already used by field a
+ --> tests/ui/conflict/alias.rs:11:5
+ |
+11 | / /// Expected error on "alias c", because it is already used as alias of `a`
+12 | | #[serde(alias = "c")]
+13 | | b: (),
+ | |_________^
+
+error: alias `c` conflicts with deserialization name of other field
+ --> tests/ui/conflict/alias.rs:21:5
+ |
+21 | / /// Expected error on "alias c", because this is a name of other field after
+22 | | /// applying rename rules
+23 | | #[serde(alias = "b", alias = "c")]
+24 | | a: (),
+ | |_________^
+
+error: alias `B` conflicts with deserialization name of other field
+ --> tests/ui/conflict/alias.rs:33:5
+ |
+33 | / /// Expected error on "alias B", because this is a name of field after
+34 | | /// applying rename rules
+35 | | #[serde(alias = "B", alias = "c")]
+36 | | a: (),
+ | |_________^
| [
"2308",
"2551"
] | serde-rs__serde-2562 | No unreachable warning when duplicate field names on enum after rename attributes
Looking into the rename feature I discovered that rustc does not gives an unreachable warning with serde rename collisions with `enums` whereas it does on `structs` as mentioned in #754
Would you still be open to a PR to make clashing renames an error? If so I'm happy to give it a go.
## Example
```rust
use serde::{Deserialize};
#[derive(Deserialize)]
enum Message {
#[serde(rename = "Response")]
Request { id: String},
#[serde(rename = "Response")]
Response { id: String},
}
fn main() {
let json = "{\"Response\": {\"id\": \"...\"}}";
let parsed: Message = match serde_json::from_str(&json) {
Ok(contact) => contact,
Err(err) => {
println!("{:?}", err);
unimplemented!()
}
};
match parsed {
Message::Request { id } => println!("request {}", id),
Message::Response { id } => println!("response {}", id)
}
}
```
### Output
`request ...`
with no compiler warnings
playgrounds link https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c6a787d51f1290af999a0e36b9a6d366
Field/variant aliases are not checked for uniqueness
[The code](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0551945af3b0581fefd8c0c9684e4182)
```rust
use serde::Deserialize; // 1.0.171;
use serde_json; // 1.0.102;
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct Thing {
pub w: u8,
#[serde(alias = "z", alias = "x")]
pub y: u8,
#[serde(alias = "same", alias = "other", alias = "same", alias = "x", alias = "y")]
pub same: u8,
}
fn main() {
let j = r#" {"j":null} "#;
println!("{}", serde_json::from_str::<Thing>(j).unwrap_err());
}
```
gives the following output:
```
unknown field `j`, expected one of `w`, `x`, `z`, `y`, `other`, `same`, `x`, `y` at line 1 column 5
```
| 1.21 | 58a8d229315553c4ae0a8d7eee8e382fbae4b4bf | diff --git a/serde_derive/src/internals/check.rs b/serde_derive/src/internals/check.rs
index 52b0f379f..df5d63f01 100644
--- a/serde_derive/src/internals/check.rs
+++ b/serde_derive/src/internals/check.rs
@@ -1,6 +1,8 @@
-use crate::internals::ast::{Container, Data, Field, Style};
+use crate::internals::ast::{Container, Data, Field, Style, Variant};
use crate::internals::attr::{Default, Identifier, TagType};
use crate::internals::{ungroup, Ctxt, Derive};
+use std::collections::btree_map::Entry;
+use std::collections::{BTreeMap, BTreeSet};
use syn::{Member, Type};
// Cross-cutting checks that require looking at more than a single attrs object.
@@ -16,6 +18,7 @@ pub fn check(cx: &Ctxt, cont: &mut Container, derive: Derive) {
check_adjacent_tag_conflict(cx, cont);
check_transparent(cx, cont, derive);
check_from_and_try_from(cx, cont);
+ check_name_conflicts(cx, cont, derive);
}
// If some field of a tuple struct is marked #[serde(default)] then all fields
@@ -475,3 +478,134 @@ fn check_from_and_try_from(cx: &Ctxt, cont: &mut Container) {
);
}
}
+
+// Checks that aliases does not repeated
+fn check_name_conflicts(cx: &Ctxt, cont: &Container, derive: Derive) {
+ if let Derive::Deserialize = derive {
+ match &cont.data {
+ Data::Enum(variants) => check_variant_name_conflicts(cx, &variants),
+ Data::Struct(Style::Struct, fields) => check_field_name_conflicts(cx, fields),
+ _ => {}
+ }
+ }
+}
+
+// All renames already applied
+fn check_variant_name_conflicts(cx: &Ctxt, variants: &[Variant]) {
+ let names: BTreeSet<_> = variants
+ .iter()
+ .filter_map(|variant| {
+ if variant.attrs.skip_deserializing() {
+ None
+ } else {
+ Some(variant.attrs.name().deserialize_name().to_owned())
+ }
+ })
+ .collect();
+ let mut alias_owners = BTreeMap::new();
+
+ for variant in variants {
+ let name = variant.attrs.name().deserialize_name();
+
+ for alias in variant.attrs.aliases().intersection(&names) {
+ // Aliases contains variant names, so filter them out
+ if alias == name {
+ continue;
+ }
+
+ // TODO: report other variant location when this become possible
+ cx.error_spanned_by(
+ variant.original,
+ format!(
+ "alias `{}` conflicts with deserialization name of other variant",
+ alias
+ ),
+ );
+ }
+
+ for alias in variant.attrs.aliases() {
+ // Aliases contains variant names, so filter them out
+ if alias == name {
+ continue;
+ }
+
+ match alias_owners.entry(alias) {
+ Entry::Vacant(e) => {
+ e.insert(variant);
+ }
+ Entry::Occupied(e) => {
+ // TODO: report other variant location when this become possible
+ cx.error_spanned_by(
+ variant.original,
+ format!(
+ "alias `{}` already used by variant {}",
+ alias,
+ e.get().original.ident
+ ),
+ );
+ }
+ }
+ }
+
+ check_field_name_conflicts(cx, &variant.fields);
+ }
+}
+
+// All renames already applied
+fn check_field_name_conflicts(cx: &Ctxt, fields: &[Field]) {
+ let names: BTreeSet<_> = fields
+ .iter()
+ .filter_map(|field| {
+ if field.attrs.skip_deserializing() {
+ None
+ } else {
+ Some(field.attrs.name().deserialize_name().to_owned())
+ }
+ })
+ .collect();
+ let mut alias_owners = BTreeMap::new();
+
+ for field in fields {
+ let name = field.attrs.name().deserialize_name();
+
+ for alias in field.attrs.aliases().intersection(&names) {
+ // Aliases contains field names, so filter them out
+ if alias == name {
+ continue;
+ }
+
+ // TODO: report other field location when this become possible
+ cx.error_spanned_by(
+ field.original,
+ format!(
+ "alias `{}` conflicts with deserialization name of other field",
+ alias
+ ),
+ );
+ }
+
+ for alias in field.attrs.aliases() {
+ // Aliases contains field names, so filter them out
+ if alias == name {
+ continue;
+ }
+
+ match alias_owners.entry(alias) {
+ Entry::Vacant(e) => {
+ e.insert(field);
+ }
+ Entry::Occupied(e) => {
+ // TODO: report other field location when this become possible
+ cx.error_spanned_by(
+ field.original,
+ format!(
+ "alias `{}` already used by field {}",
+ alias,
+ e.get().original.ident.as_ref().unwrap()
+ ),
+ );
+ }
+ }
+ }
+ }
+}
| serde-rs/serde | 2023-08-08T17:44:27Z | or maybe instead of an error it should follow rustc and display a warning
| 49e11ce1bae9fbb9128c9144c4e1051daf7a29ed |
2,499 | diff --git a/test_suite/tests/ui/malformed/str_suffix.rs b/test_suite/tests/ui/malformed/str_suffix.rs
new file mode 100644
index 000000000..836842ee6
--- /dev/null
+++ b/test_suite/tests/ui/malformed/str_suffix.rs
@@ -0,0 +1,10 @@
+use serde::Serialize;
+
+#[derive(Serialize)]
+#[serde(bound = ""huh)]
+pub struct Struct {
+ #[serde(rename = ""what)]
+ pub field: i32,
+}
+
+fn main() {}
diff --git a/test_suite/tests/ui/malformed/str_suffix.stderr b/test_suite/tests/ui/malformed/str_suffix.stderr
new file mode 100644
index 000000000..3d4beae65
--- /dev/null
+++ b/test_suite/tests/ui/malformed/str_suffix.stderr
@@ -0,0 +1,11 @@
+error: unexpected suffix `huh` on string literal
+ --> tests/ui/malformed/str_suffix.rs:4:17
+ |
+4 | #[serde(bound = ""huh)]
+ | ^^^^^
+
+error: unexpected suffix `what` on string literal
+ --> tests/ui/malformed/str_suffix.rs:6:22
+ |
+6 | #[serde(rename = ""what)]
+ | ^^^^^^
| [
"2242"
] | serde-rs__serde-2499 | Proc macro rename attribute ignores trailing content
I just had an interesting bug where I made a spelling error for the `rename` attribute. When I discovered it, I thought the proc macro could probably catch this.
What I did by accident was:
```rust
#[derive(Deserialize)]
struct SomeStruct {
#[serde(rename = ""value)] // This should have been `rename = "value"`
pub a: i32
}
```
The second `"` went in front of the rename value, instead of behind. Apparently, the proc macro accepts this input and only takes `""`, ignoring the `value`. If there is a space between it (like `#[serde(rename = "" value)]`), it'll fail properly, telling about the unknown attribute `value`.
| 1.16 | 3fb5e71c33279500f7e29e2512efafa64fe07e96 | diff --git a/serde_derive/Cargo.toml b/serde_derive/Cargo.toml
index 1897cb1a6..46246bb60 100644
--- a/serde_derive/Cargo.toml
+++ b/serde_derive/Cargo.toml
@@ -24,7 +24,7 @@ proc-macro = true
[dependencies]
proc-macro2 = "1.0"
quote = "1.0"
-syn = "2.0.24"
+syn = "2.0.25"
[dev-dependencies]
serde = { version = "1.0", path = "../serde" }
diff --git a/serde_derive/src/internals/attr.rs b/serde_derive/src/internals/attr.rs
index bff82191b..42212a64d 100644
--- a/serde_derive/src/internals/attr.rs
+++ b/serde_derive/src/internals/attr.rs
@@ -1418,6 +1418,13 @@ fn get_lit_str2(
..
}) = value
{
+ let suffix = lit.suffix();
+ if !suffix.is_empty() {
+ cx.error_spanned_by(
+ lit,
+ format!("unexpected suffix `{}` on string literal", suffix),
+ );
+ }
Ok(Some(lit.clone()))
} else {
cx.error_spanned_by(
diff --git a/serde_derive_internals/Cargo.toml b/serde_derive_internals/Cargo.toml
index 703a43cbb..eb084af67 100644
--- a/serde_derive_internals/Cargo.toml
+++ b/serde_derive_internals/Cargo.toml
@@ -17,7 +17,7 @@ path = "lib.rs"
[dependencies]
proc-macro2 = "1.0"
quote = "1.0"
-syn = { version = "2.0.24", default-features = false, features = ["clone-impls", "derive", "parsing", "printing"] }
+syn = { version = "2.0.25", default-features = false, features = ["clone-impls", "derive", "parsing", "printing"] }
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
| serde-rs/serde | 2023-07-09T18:13:51Z | 3fb5e71c33279500f7e29e2512efafa64fe07e96 | |
1,104 | diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index 6f4022cb3..4a4cbc9f4 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -23,6 +23,7 @@ use self::serde::de::{DeserializeOwned, Deserializer};
use std::borrow::Cow;
use std::marker::PhantomData;
+use std::option::Option as StdOption;
use std::result::Result as StdResult;
// Try to trip up the generated code if it fails to use fully qualified paths.
@@ -32,6 +33,12 @@ struct Result;
struct Ok;
#[allow(dead_code)]
struct Err;
+#[allow(dead_code)]
+struct Option;
+#[allow(dead_code)]
+struct Some;
+#[allow(dead_code)]
+struct None;
//////////////////////////////////////////////////////////////////////////
@@ -56,7 +63,7 @@ fn test_gen() {
#[derive(Serialize, Deserialize)]
struct WithRef<'a, T: 'a> {
#[serde(skip_deserializing)]
- t: Option<&'a T>,
+ t: StdOption<&'a T>,
#[serde(serialize_with="ser_x", deserialize_with="de_x")]
x: X,
}
@@ -77,9 +84,9 @@ fn test_gen() {
#[derive(Serialize, Deserialize)]
struct NoBounds<T> {
t: T,
- option: Option<T>,
+ option: StdOption<T>,
boxed: Box<T>,
- option_boxed: Option<Box<T>>,
+ option_boxed: StdOption<Box<T>>,
}
assert::<NoBounds<i32>>();
@@ -175,8 +182,8 @@ fn test_gen() {
#[derive(Serialize)]
struct OptionStatic<'a> {
- a: Option<&'a str>,
- b: Option<&'static str>,
+ a: StdOption<&'a str>,
+ b: StdOption<&'static str>,
}
assert_ser::<OptionStatic>();
| [
"1103"
] | serde-rs__serde-1104 | Warning at #[derive(Deserialize)] when compiling without prelude
Hi,
When using #[derive(Deserialize)] when compiling with #![no_implicit_prelude], there is a warning about "None". This will be hidden, if `use std::option::Option::None;` is used, but this shouldn't be required.
```
warning: variable `None` should have a snake case name such as `none`
--> [...].rs:212:88
|
212 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^
```
Update: there is also an error with `Option::Some`.
| 1.0 | c650a92bf7773af66e41add39d79c226f982ff08 | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 71326b84f..bfa18b000 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -418,8 +418,8 @@ fn deserialize_seq(
};
let assign = quote! {
let #var = match #visit {
- Some(__value) => __value,
- None => {
+ _serde::export::Some(__value) => __value,
+ _serde::export::None => {
return _serde::export::Err(_serde::de::Error::invalid_length(#index_in_seq, &#expecting));
}
};
| serde-rs/serde | 2017-11-30T03:46:26Z | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 | |
1,083 | diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index 50cd13b70..c6a68213b 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -519,6 +519,17 @@ fn test_gen() {
other: isize,
}
assert::<SkippedStaticStr>();
+
+ macro_rules! T {
+ () => { () }
+ }
+
+ #[derive(Serialize, Deserialize)]
+ struct TypeMacro<T> {
+ mac: T!(),
+ marker: PhantomData<T>,
+ }
+ assert::<TypeMacro<X>>();
}
//////////////////////////////////////////////////////////////////////////
| [
"1081"
] | serde-rs__serde-1083 | Wrong bounds for macro named the same as a type parameter
```rust
use std::marker::PhantomData;
#[macro_use]
extern crate serde_derive;
macro_rules! T {
() => { () };
}
// generates impl<T> Serialize for A<T>
#[derive(Serialize)]
struct A<T> {
f: (),
t: PhantomData<T>,
}
// generates impl<T> Serialize for A<T> where T: Serialize
#[derive(Serialize)]
struct B<T> {
f: T!(),
t: PhantomData<T>,
}
fn main() {}
```
When expanding B\<T\> we see `T` being used as a "path" in the macro and mistakenly conclude that the type parameter needs to be serializable.
| 1.0 | ab68132b1f945b8a1174e58ff68f7591144d4e2a | diff --git a/serde_derive/src/bound.rs b/serde_derive/src/bound.rs
index 5f6e94c02..5dc68a0f1 100644
--- a/serde_derive/src/bound.rs
+++ b/serde_derive/src/bound.rs
@@ -116,6 +116,14 @@ where
}
visit::walk_path(self, path);
}
+
+ // Type parameter should not be considered used by a macro path.
+ //
+ // struct TypeMacro<T> {
+ // mac: T!(),
+ // marker: PhantomData<T>,
+ // }
+ fn visit_mac(&mut self, _mac: &syn::Mac) {}
}
let all_ty_params: HashSet<_> = generics
| serde-rs/serde | 2017-11-05T20:20:03Z | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 | |
1,082 | diff --git a/test_suite/tests/compile-fail/borrow/duplicate_variant.rs b/test_suite/tests/compile-fail/borrow/duplicate_variant.rs
new file mode 100644
index 000000000..5cc3ad3b3
--- /dev/null
+++ b/test_suite/tests/compile-fail/borrow/duplicate_variant.rs
@@ -0,0 +1,21 @@
+// Copyright 2017 Serde Developers
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Deserialize)]
+struct Str<'a>(&'a str);
+
+#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+enum Test<'a> {
+ #[serde(borrow)] //~^^ HELP: duplicate serde attribute `borrow`
+ S(#[serde(borrow)] Str<'a>)
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/borrow/struct_variant.rs b/test_suite/tests/compile-fail/borrow/struct_variant.rs
new file mode 100644
index 000000000..5bab07171
--- /dev/null
+++ b/test_suite/tests/compile-fail/borrow/struct_variant.rs
@@ -0,0 +1,21 @@
+// Copyright 2017 Serde Developers
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Deserialize)]
+struct Str<'a>(&'a str);
+
+#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+enum Test<'a> {
+ #[serde(borrow)] //~^^ HELP: #[serde(borrow)] may only be used on newtype variants
+ S { s: Str<'a> }
+}
+
+fn main() {}
diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index 50cd13b70..515c2f823 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -357,6 +357,12 @@ fn test_gen() {
s: Str<'a>,
}
+ #[derive(Serialize, Deserialize)]
+ enum BorrowVariant<'a> {
+ #[serde(borrow, with = "StrDef")]
+ S(Str<'a>),
+ }
+
mod vis {
pub struct S;
| [
"929"
] | serde-rs__serde-1082 | Support borrow attribute on newtype variants
This is ugly:
```rust
#[derive(Deserialize)]
enum RelData<'a> {
Single(#[serde(borrow)] RelObject<'a>),
Many(#[serde(borrow)] Vec<RelObject<'a>>),
}
```
For newtype variants, the following should be supported:
```rust
#[derive(Deserialize)]
enum RelData<'a> {
#[serde(borrow)]
Single(RelObject<'a>),
#[serde(borrow)]
Many(Vec<RelObject<'a>>),
}
```
| 1.0 | ab68132b1f945b8a1174e58ff68f7591144d4e2a | diff --git a/serde_derive_internals/src/ast.rs b/serde_derive_internals/src/ast.rs
index 818d301bd..dce1acc17 100644
--- a/serde_derive_internals/src/ast.rs
+++ b/serde_derive_internals/src/ast.rs
@@ -51,7 +51,7 @@ impl<'a> Container<'a> {
let mut body = match item.body {
syn::Body::Enum(ref variants) => Body::Enum(enum_from_ast(cx, variants)),
syn::Body::Struct(ref variant_data) => {
- let (style, fields) = struct_from_ast(cx, variant_data);
+ let (style, fields) = struct_from_ast(cx, variant_data, None);
Body::Struct(style, fields)
}
};
@@ -103,10 +103,11 @@ fn enum_from_ast<'a>(cx: &Ctxt, variants: &'a [syn::Variant]) -> Vec<Variant<'a>
.iter()
.map(
|variant| {
- let (style, fields) = struct_from_ast(cx, &variant.data);
+ let attrs = attr::Variant::from_ast(cx, variant);
+ let (style, fields) = struct_from_ast(cx, &variant.data, Some(&attrs));
Variant {
ident: variant.ident.clone(),
- attrs: attr::Variant::from_ast(cx, variant),
+ attrs: attrs,
style: style,
fields: fields,
}
@@ -115,18 +116,18 @@ fn enum_from_ast<'a>(cx: &Ctxt, variants: &'a [syn::Variant]) -> Vec<Variant<'a>
.collect()
}
-fn struct_from_ast<'a>(cx: &Ctxt, data: &'a syn::VariantData) -> (Style, Vec<Field<'a>>) {
+fn struct_from_ast<'a>(cx: &Ctxt, data: &'a syn::VariantData, attrs: Option<&attr::Variant>) -> (Style, Vec<Field<'a>>) {
match *data {
- syn::VariantData::Struct(ref fields) => (Style::Struct, fields_from_ast(cx, fields)),
+ syn::VariantData::Struct(ref fields) => (Style::Struct, fields_from_ast(cx, fields, attrs)),
syn::VariantData::Tuple(ref fields) if fields.len() == 1 => {
- (Style::Newtype, fields_from_ast(cx, fields))
+ (Style::Newtype, fields_from_ast(cx, fields, attrs))
}
- syn::VariantData::Tuple(ref fields) => (Style::Tuple, fields_from_ast(cx, fields)),
+ syn::VariantData::Tuple(ref fields) => (Style::Tuple, fields_from_ast(cx, fields, attrs)),
syn::VariantData::Unit => (Style::Unit, Vec::new()),
}
}
-fn fields_from_ast<'a>(cx: &Ctxt, fields: &'a [syn::Field]) -> Vec<Field<'a>> {
+fn fields_from_ast<'a>(cx: &Ctxt, fields: &'a [syn::Field], attrs: Option<&attr::Variant>) -> Vec<Field<'a>> {
fields
.iter()
.enumerate()
@@ -134,7 +135,7 @@ fn fields_from_ast<'a>(cx: &Ctxt, fields: &'a [syn::Field]) -> Vec<Field<'a>> {
|(i, field)| {
Field {
ident: field.ident.clone(),
- attrs: attr::Field::from_ast(cx, i, field),
+ attrs: attr::Field::from_ast(cx, i, field, attrs),
ty: &field.ty,
}
},
diff --git a/serde_derive_internals/src/attr.rs b/serde_derive_internals/src/attr.rs
index 454b8b59c..7baeb59bb 100644
--- a/serde_derive_internals/src/attr.rs
+++ b/serde_derive_internals/src/attr.rs
@@ -512,6 +512,7 @@ pub struct Variant {
other: bool,
serialize_with: Option<syn::Path>,
deserialize_with: Option<syn::Path>,
+ borrow: Option<syn::MetaItem>,
}
impl Variant {
@@ -524,6 +525,7 @@ impl Variant {
let mut other = BoolAttr::none(cx, "other");
let mut serialize_with = Attr::none(cx, "serialize_with");
let mut deserialize_with = Attr::none(cx, "deserialize_with");
+ let mut borrow = Attr::none(cx, "borrow");
for meta_items in variant.attrs.iter().filter_map(get_serde_meta_items) {
for meta_item in meta_items {
@@ -599,6 +601,18 @@ impl Variant {
}
}
+ // Defer `#[serde(borrow)]` and `#[serde(borrow = "'a + 'b")]`
+ MetaItem(ref mi) if mi.name() == "borrow" => {
+ match variant.data {
+ syn::VariantData::Tuple(ref fields) if fields.len() == 1 => {
+ borrow.set(mi.clone());
+ }
+ _ => {
+ cx.error("#[serde(borrow)] may only be used on newtype variants");
+ }
+ }
+ }
+
MetaItem(ref meta_item) => {
cx.error(format!("unknown serde variant attribute `{}`", meta_item.name()));
}
@@ -627,6 +641,7 @@ impl Variant {
other: other.get(),
serialize_with: serialize_with.get(),
deserialize_with: deserialize_with.get(),
+ borrow: borrow.get(),
}
}
@@ -699,7 +714,7 @@ pub enum Default {
impl Field {
/// Extract out the `#[serde(...)]` attributes from a struct field.
- pub fn from_ast(cx: &Ctxt, index: usize, field: &syn::Field) -> Self {
+ pub fn from_ast(cx: &Ctxt, index: usize, field: &syn::Field, attrs: Option<&Variant>) -> Self {
let mut ser_name = Attr::none(cx, "rename");
let mut de_name = Attr::none(cx, "rename");
let mut skip_serializing = BoolAttr::none(cx, "skip_serializing");
@@ -718,7 +733,13 @@ impl Field {
None => index.to_string(),
};
- for meta_items in field.attrs.iter().filter_map(get_serde_meta_items) {
+ let variant_borrow = attrs
+ .map(|variant| &variant.borrow)
+ .unwrap_or(&None)
+ .as_ref()
+ .map(|borrow| vec![MetaItem(borrow.clone())]);
+
+ for meta_items in field.attrs.iter().filter_map(get_serde_meta_items).chain(variant_borrow) {
for meta_item in meta_items {
match meta_item {
// Parse `#[serde(rename = "foo")]`
| serde-rs/serde | 2017-11-05T20:09:27Z | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 | |
1,079 | diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index f9143099a..50cd13b70 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -511,6 +511,14 @@ fn test_gen() {
Tuple(&'a str, &'static str),
Newtype(&'static str),
}
+
+ #[derive(Serialize, Deserialize)]
+ struct SkippedStaticStr {
+ #[serde(skip_deserializing)]
+ skipped: &'static str,
+ other: isize,
+ }
+ assert::<SkippedStaticStr>();
}
//////////////////////////////////////////////////////////////////////////
| [
"1078"
] | serde-rs__serde-1079 | Lifetime errors with skipped `&'static` variable
I needed to evolve my format, so I went from (simplified)
```rust
#[derive(Debug, PartialEq)]
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SassOptions {
#[serde(skip)]
pub import_dir: &'static str,
pub style: SassOutputStyle,
}
impl Default for SassOptions {
fn default() -> SassOptions {
...
}
}
#[derive(Debug, PartialEq)]
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct ConfigBuilder {
#[serde(skip)]
pub root: path::PathBuf,
pub source: String,
pub destination: String,
pub sass: sass::SassOptions,
}
```
to
```rust
#[derive(Debug, PartialEq)]
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SassOptions {
#[serde(skip)]
pub import_dir: &'static str,
pub style: SassOutputStyle,
}
impl Default for SassOptions {
fn default() -> SassOptions {
...
}
}
#[derive(Debug, PartialEq, Default)]
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AssetsBuilder {
pub sass: sass::SassOptions,
}
#[derive(Debug, PartialEq)]
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct ConfigBuilder {
#[serde(skip)]
pub root: path::PathBuf,
pub source: String,
pub destination: String,
pub assets: AssetsBuilder,
}
```
and I started getting lifetime errors
```
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements
--> src/config.rs:95:21
|
95 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime 'de as defined on the impl at 95:21...
--> src/config.rs:95:21
|
95 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^
note: ...so that types are compatible (expected std::convert::From<<__A as serde::de::MapAccess<'_>>::Error>, found std::convert::From<<__A as serde::de::MapAccess<'de>>::Error>)
--> src/config.rs:95:21
|
95 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that types are compatible (expected serde::Deserialize<'_>, found serde::Deserialize<'static>)
--> src/config.rs:95:21
|
95 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^
= note: this error originates in a macro outside of the current crate
error: aborting due to 2 previous errors
error: Could not compile `cobalt-bin`.
```
Situations
- Adding a layer caused the warning
- Switching `import_dir` to `String` removed the error
- Adding a member to `AssetsBuilder` did not fix things.
Original source: https://github.com/cobalt-org/cobalt.rs
Broken source: not uploaded at the moment
| 1.0 | 2a557a1e36317dd0689bd978a39e254bca454d44 | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 44ed7fa0e..71326b84f 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -203,7 +203,9 @@ impl BorrowedLifetimes {
fn borrowed_lifetimes(cont: &Container) -> BorrowedLifetimes {
let mut lifetimes = BTreeSet::new();
for field in cont.body.all_fields() {
- lifetimes.extend(field.attrs.borrowed_lifetimes().iter().cloned());
+ if !field.attrs.skip_deserializing() {
+ lifetimes.extend(field.attrs.borrowed_lifetimes().iter().cloned());
+ }
}
if lifetimes.iter().any(|b| b.ident == "'static") {
BorrowedLifetimes::Static
| serde-rs/serde | 2017-11-03T17:08:32Z | Broken source: https://github.com/epage/cobalt.rs/tree/serde-broken | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,053 | diff --git a/test_suite/tests/test_macros.rs b/test_suite/tests/test_macros.rs
index f2b478e84..66e72f237 100644
--- a/test_suite/tests/test_macros.rs
+++ b/test_suite/tests/test_macros.rs
@@ -6,6 +6,8 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![deny(trivial_numeric_casts)]
+
#[macro_use]
extern crate serde_derive;
| [
"1051"
] | serde-rs__serde-1053 | v1.0.13 introduced an error if `trivial_numeric_casts` is denied
Hi,
I updated `cargo update`d on my machine and got the new serde versions:
```
Updating serde v1.0.12 -> v1.0.13
Updating serde_derive v1.0.12 -> v1.0.13
Updating serde_derive_internals v0.15.1 -> v0.16.0
```
and now my code fails to compile because I turned on `trivial_numeric_casts` denying:
```
error: trivial numeric cast: `u64` as `u64`. Cast can be replaced by coercion, this might require type ascription or a temporary variable
--> src/file_abstraction/stdio/mapper/json.rs:35:17
|
35 | #[derive(Debug, Deserialize, Serialize)]
| ^^^^^^^^^^^
|
note: lint level defined here
--> src/lib.rs:27:5
|
27 | trivial_numeric_casts,
| ^^^^^^^^^^^^^^^^^^^^^
error: trivial numeric cast: `u64` as `u64`. Cast can be replaced by coercion, this might require type ascription or a temporary variable
--> src/file_abstraction/stdio/mapper/json.rs:55:17
|
55 | #[derive(Debug, Deserialize, Serialize)]
| ^^^^^^^^^^^
error: aborting due to 2 previous errors
error: Could not compile `libimagstore`.
To learn more, run the command again with --verbose.
```
The repository of my code [is here](https://github.com/matthiasbeyer/imag).
| 1.0 | c3eced410fd3cb82122187f5844a54fe6948a1ea | diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index aedbf3323..05b952aa1 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -1428,7 +1428,7 @@ fn deserialize_identifier(
#variant_indices => _serde::export::Ok(#constructors),
)*
_ => _serde::export::Err(_serde::de::Error::invalid_value(
- _serde::de::Unexpected::Unsigned(__value as u64),
+ _serde::de::Unexpected::Unsigned(__value),
&#fallthrough_msg))
}
}
| serde-rs/serde | 2017-09-09T19:37:42Z | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 | |
1,052 | diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index 76c57db8a..fc7b40f2e 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -10,6 +10,8 @@
// successfully when there are a variety of generics and non-(de)serializable
// types involved.
+#![deny(warnings)]
+
#![cfg_attr(feature = "unstable", feature(non_ascii_idents))]
// Clippy false positive
@@ -491,6 +493,28 @@ fn test_gen() {
Unit,
}
assert_ser::<UntaggedVariantWith>();
+
+ #[derive(Serialize, Deserialize)]
+ struct StaticStrStruct<'a> {
+ a: &'a str,
+ b: &'static str,
+ }
+
+ #[derive(Serialize, Deserialize)]
+ struct StaticStrTupleStruct<'a>(&'a str, &'static str);
+
+ #[derive(Serialize, Deserialize)]
+ struct StaticStrNewtypeStruct(&'static str);
+
+ #[derive(Serialize, Deserialize)]
+ enum StaticStrEnum<'a> {
+ Struct {
+ a: &'a str,
+ b: &'static str,
+ },
+ Tuple(&'a str, &'static str),
+ Newtype(&'static str),
+ }
}
//////////////////////////////////////////////////////////////////////////
| [
"975"
] | serde-rs__serde-1052 | Notice 'static lifetime
From #974:
```rust
#[derive(Deserialize)]
struct S {
s: &'static str,
}
```
We treat `'static` the same as any other lifetime so this expands to:
```rust
impl<'de: 'static> Deserialize<'de> for S {
/* ... */
}
```
```
warning: unnecessary lifetime parameter `'de`
|
| #[derive(Deserialize)]
| ^^^^^^^^^^^
|
= help: you can use the `'static` lifetime directly, in place of `'de`
```
Instead it should expand to:
```rust
impl Deserialize<'static> for S {
/* ... */
}
```
| 1.0 | c3eced410fd3cb82122187f5844a54fe6948a1ea | diff --git a/serde_derive/src/bound.rs b/serde_derive/src/bound.rs
index 0160fa85c..5f6e94c02 100644
--- a/serde_derive/src/bound.rs
+++ b/serde_derive/src/bound.rs
@@ -15,7 +15,7 @@ use internals::attr;
macro_rules! path {
($($path:tt)+) => {
- syn::parse_path(stringify!($($path)+)).unwrap()
+ syn::parse_path(quote!($($path)+).as_str()).unwrap()
};
}
diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index aedbf3323..aa8f58ca9 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -26,13 +26,14 @@ pub fn expand_derive_deserialize(input: &syn::DeriveInput) -> Result<Tokens, Str
let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(¶ms);
let dummy_const = Ident::new(format!("_IMPL_DESERIALIZE_FOR_{}", ident));
let body = Stmts(deserialize_body(&cont, ¶ms));
+ let delife = params.borrowed.de_lifetime();
let impl_block = if let Some(remote) = cont.attrs.remote() {
let vis = &input.vis;
quote! {
impl #de_impl_generics #ident #ty_generics #where_clause {
#vis fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<#remote #ty_generics, __D::Error>
- where __D: _serde::Deserializer<'de>
+ where __D: _serde::Deserializer<#delife>
{
#body
}
@@ -41,9 +42,9 @@ pub fn expand_derive_deserialize(input: &syn::DeriveInput) -> Result<Tokens, Str
} else {
quote! {
#[automatically_derived]
- impl #de_impl_generics _serde::Deserialize<'de> for #ident #ty_generics #where_clause {
+ impl #de_impl_generics _serde::Deserialize<#delife> for #ident #ty_generics #where_clause {
fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error>
- where __D: _serde::Deserializer<'de>
+ where __D: _serde::Deserializer<#delife>
{
#body
}
@@ -75,7 +76,7 @@ struct Parameters {
/// Lifetimes borrowed from the deserializer. These will become bounds on
/// the `'de` lifetime of the deserializer.
- borrowed: BTreeSet<syn::Lifetime>,
+ borrowed: BorrowedLifetimes,
/// At least one field has a serde(getter) attribute, implying that the
/// remote type has a private field.
@@ -89,8 +90,8 @@ impl Parameters {
Some(remote) => remote.clone(),
None => cont.ident.clone().into(),
};
- let generics = build_generics(cont);
let borrowed = borrowed_lifetimes(cont);
+ let generics = build_generics(cont, &borrowed);
let has_getter = cont.body.has_getter();
Parameters {
@@ -107,20 +108,12 @@ impl Parameters {
fn type_name(&self) -> &str {
self.this.segments.last().unwrap().ident.as_ref()
}
-
- fn de_lifetime_def(&self) -> syn::LifetimeDef {
- syn::LifetimeDef {
- attrs: Vec::new(),
- lifetime: syn::Lifetime::new("'de"),
- bounds: self.borrowed.iter().cloned().collect(),
- }
- }
}
// All the generics in the input, plus a bound `T: Deserialize` for each generic
// field type that will be deserialized by us, plus a bound `T: Default` for
// each generic field type that will be set to a default value.
-fn build_generics(cont: &Container) -> syn::Generics {
+fn build_generics(cont: &Container, borrowed: &BorrowedLifetimes) -> syn::Generics {
let generics = bound::without_defaults(cont.generics);
let generics = bound::with_where_predicates_from_fields(cont, &generics, attr::Field::de_bound);
@@ -136,11 +129,12 @@ fn build_generics(cont: &Container) -> syn::Generics {
attr::Default::Path(_) => generics,
};
+ let delife = borrowed.de_lifetime();
let generics = bound::with_bound(
cont,
&generics,
needs_deserialize_bound,
- &path!(_serde::Deserialize<'de>),
+ &path!(_serde::Deserialize<#delife>),
);
bound::with_bound(
@@ -170,18 +164,52 @@ fn requires_default(field: &attr::Field, _variant: Option<&attr::Variant>) -> bo
field.default() == &attr::Default::Default
}
+enum BorrowedLifetimes {
+ Borrowed(BTreeSet<syn::Lifetime>),
+ Static,
+}
+
+impl BorrowedLifetimes {
+ fn de_lifetime(&self) -> syn::Lifetime {
+ match *self {
+ BorrowedLifetimes::Borrowed(_) => syn::Lifetime::new("'de"),
+ BorrowedLifetimes::Static => syn::Lifetime::new("'static"),
+ }
+ }
+
+ fn de_lifetime_def(&self) -> Option<syn::LifetimeDef> {
+ match *self {
+ BorrowedLifetimes::Borrowed(ref bounds) => {
+ Some(syn::LifetimeDef {
+ attrs: Vec::new(),
+ lifetime: syn::Lifetime::new("'de"),
+ bounds: bounds.iter().cloned().collect(),
+ })
+ }
+ BorrowedLifetimes::Static => None,
+ }
+ }
+}
+
// The union of lifetimes borrowed by each field of the container.
//
// These turn into bounds on the `'de` lifetime of the Deserialize impl. If
// lifetimes `'a` and `'b` are borrowed but `'c` is not, the impl is:
//
// impl<'de: 'a + 'b, 'a, 'b, 'c> Deserialize<'de> for S<'a, 'b, 'c>
-fn borrowed_lifetimes(cont: &Container) -> BTreeSet<syn::Lifetime> {
+//
+// If any borrowed lifetime is `'static`, then `'de: 'static` would be redundant
+// and we use plain `'static` instead of `'de`.
+fn borrowed_lifetimes(cont: &Container) -> BorrowedLifetimes {
let mut lifetimes = BTreeSet::new();
for field in cont.body.all_fields() {
lifetimes.extend(field.attrs.borrowed_lifetimes().iter().cloned());
}
- lifetimes
+ if lifetimes.iter().any(|b| b.ident == "'static") {
+ BorrowedLifetimes::Static
+ } else {
+ BorrowedLifetimes::Borrowed(lifetimes)
+ }
}
fn deserialize_body(cont: &Container, params: &Parameters) -> Fragment {
@@ -260,6 +288,7 @@ fn deserialize_tuple(
) -> Fragment {
let this = ¶ms.this;
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params,);
+ let delife = params.borrowed.de_lifetime();
// If there are getters (implying private fields), construct the local type
// and use an `Into` conversion to get the remote type. If there are no
@@ -321,10 +350,10 @@ fn deserialize_tuple(
quote_block! {
struct __Visitor #de_impl_generics #where_clause {
marker: _serde::export::PhantomData<#this #ty_generics>,
- lifetime: _serde::export::PhantomData<&'de ()>,
+ lifetime: _serde::export::PhantomData<&#delife ()>,
}
- impl #de_impl_generics _serde::de::Visitor<'de> for __Visitor #de_ty_generics #where_clause {
+ impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause {
type Value = #this #ty_generics;
fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result {
@@ -335,7 +364,7 @@ fn deserialize_tuple(
#[inline]
fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error>
- where __A: _serde::de::SeqAccess<'de>
+ where __A: _serde::de::SeqAccess<#delife>
{
#visit_seq
}
@@ -423,6 +452,8 @@ fn deserialize_seq(
}
fn deserialize_newtype_struct(type_path: &Tokens, params: &Parameters, field: &Field) -> Tokens {
+ let delife = params.borrowed.de_lifetime();
+
let value = match field.attrs.deserialize_with() {
None => {
let field_ty = &field.ty;
@@ -450,7 +481,7 @@ fn deserialize_newtype_struct(type_path: &Tokens, params: &Parameters, field: &F
quote! {
#[inline]
fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::export::Result<Self::Value, __E::Error>
- where __E: _serde::Deserializer<'de>
+ where __E: _serde::Deserializer<#delife>
{
_serde::export::Ok(#result)
}
@@ -469,6 +500,7 @@ fn deserialize_struct(
let this = ¶ms.this;
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params,);
+ let delife = params.borrowed.de_lifetime();
// If there are getters (implying private fields), construct the local type
// and use an `Into` conversion to get the remote type. If there are no
@@ -534,7 +566,7 @@ fn deserialize_struct(
Some(quote! {
#[inline]
fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error>
- where __A: _serde::de::SeqAccess<'de>
+ where __A: _serde::de::SeqAccess<#delife>
{
#visit_seq
}
@@ -546,10 +578,10 @@ fn deserialize_struct(
struct __Visitor #de_impl_generics #where_clause {
marker: _serde::export::PhantomData<#this #ty_generics>,
- lifetime: _serde::export::PhantomData<&'de ()>,
+ lifetime: _serde::export::PhantomData<&#delife ()>,
}
- impl #de_impl_generics _serde::de::Visitor<'de> for __Visitor #de_ty_generics #where_clause {
+ impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause {
type Value = #this #ty_generics;
fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result {
@@ -560,7 +592,7 @@ fn deserialize_struct(
#[inline]
fn visit_map<__A>(self, mut __map: __A) -> _serde::export::Result<Self::Value, __A::Error>
- where __A: _serde::de::MapAccess<'de>
+ where __A: _serde::de::MapAccess<#delife>
{
#visit_map
}
@@ -597,6 +629,7 @@ fn deserialize_externally_tagged_enum(
) -> Fragment {
let this = ¶ms.this;
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params,);
+ let delife = params.borrowed.de_lifetime();
let type_name = cattrs.name().deserialize_name();
@@ -662,10 +695,10 @@ fn deserialize_externally_tagged_enum(
struct __Visitor #de_impl_generics #where_clause {
marker: _serde::export::PhantomData<#this #ty_generics>,
- lifetime: _serde::export::PhantomData<&'de ()>,
+ lifetime: _serde::export::PhantomData<&#delife ()>,
}
- impl #de_impl_generics _serde::de::Visitor<'de> for __Visitor #de_ty_generics #where_clause {
+ impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause {
type Value = #this #ty_generics;
fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result {
@@ -673,7 +706,7 @@ fn deserialize_externally_tagged_enum(
}
fn visit_enum<__A>(self, __data: __A) -> _serde::export::Result<Self::Value, __A::Error>
- where __A: _serde::de::EnumAccess<'de>
+ where __A: _serde::de::EnumAccess<#delife>
{
#match_variant
}
@@ -754,6 +787,7 @@ fn deserialize_adjacently_tagged_enum(
) -> Fragment {
let this = ¶ms.this;
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params,);
+ let delife = params.borrowed.de_lifetime();
let variant_names_idents: Vec<_> = variants
.iter()
@@ -913,14 +947,14 @@ fn deserialize_adjacently_tagged_enum(
struct __Seed #de_impl_generics #where_clause {
field: __Field,
marker: _serde::export::PhantomData<#this #ty_generics>,
- lifetime: _serde::export::PhantomData<&'de ()>,
+ lifetime: _serde::export::PhantomData<&#delife ()>,
}
- impl #de_impl_generics _serde::de::DeserializeSeed<'de> for __Seed #de_ty_generics #where_clause {
+ impl #de_impl_generics _serde::de::DeserializeSeed<#delife> for __Seed #de_ty_generics #where_clause {
type Value = #this #ty_generics;
fn deserialize<__D>(self, __deserializer: __D) -> _serde::export::Result<Self::Value, __D::Error>
- where __D: _serde::Deserializer<'de>
+ where __D: _serde::Deserializer<#delife>
{
match self.field {
#(#variant_arms)*
@@ -930,10 +964,10 @@ fn deserialize_adjacently_tagged_enum(
struct __Visitor #de_impl_generics #where_clause {
marker: _serde::export::PhantomData<#this #ty_generics>,
- lifetime: _serde::export::PhantomData<&'de ()>,
+ lifetime: _serde::export::PhantomData<&#delife ()>,
}
- impl #de_impl_generics _serde::de::Visitor<'de> for __Visitor #de_ty_generics #where_clause {
+ impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause {
type Value = #this #ty_generics;
fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result {
@@ -941,7 +975,7 @@ fn deserialize_adjacently_tagged_enum(
}
fn visit_map<__A>(self, mut __map: __A) -> _serde::export::Result<Self::Value, __A::Error>
- where __A: _serde::de::MapAccess<'de>
+ where __A: _serde::de::MapAccess<#delife>
{
// Visit the first relevant key.
match #next_relevant_key {
@@ -1005,7 +1039,7 @@ fn deserialize_adjacently_tagged_enum(
}
fn visit_seq<__A>(self, mut __seq: __A) -> _serde::export::Result<Self::Value, __A::Error>
- where __A: _serde::de::SeqAccess<'de>
+ where __A: _serde::de::SeqAccess<#delife>
{
// Visit the first element - the tag.
match try!(_serde::de::SeqAccess::next_element(&mut __seq)) {
@@ -1366,6 +1400,7 @@ fn deserialize_custom_identifier(
};
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params,);
+ let delife = params.borrowed.de_lifetime();
let visitor_impl =
Stmts(deserialize_identifier(this.clone(), &names_idents, is_variant, fallthrough),);
@@ -1374,10 +1409,10 @@ fn deserialize_custom_identifier(
struct __FieldVisitor #de_impl_generics #where_clause {
marker: _serde::export::PhantomData<#this #ty_generics>,
- lifetime: _serde::export::PhantomData<&'de ()>,
+ lifetime: _serde::export::PhantomData<&#delife ()>,
}
- impl #de_impl_generics _serde::de::Visitor<'de> for __FieldVisitor #de_ty_generics #where_clause {
+ impl #de_impl_generics _serde::de::Visitor<#delife> for __FieldVisitor #de_ty_generics #where_clause {
type Value = #this #ty_generics;
#visitor_impl
@@ -1694,17 +1729,18 @@ fn wrap_deserialize_with(
) -> (Tokens, Tokens) {
let this = ¶ms.this;
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params,);
+ let delife = params.borrowed.de_lifetime();
let wrapper = quote! {
struct __DeserializeWith #de_impl_generics #where_clause {
value: #value_ty,
phantom: _serde::export::PhantomData<#this #ty_generics>,
- lifetime: _serde::export::PhantomData<&'de ()>,
+ lifetime: _serde::export::PhantomData<&#delife ()>,
}
- impl #de_impl_generics _serde::Deserialize<'de> for __DeserializeWith #de_ty_generics #where_clause {
+ impl #de_impl_generics _serde::Deserialize<#delife> for __DeserializeWith #de_ty_generics #where_clause {
fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error>
- where __D: _serde::Deserializer<'de>
+ where __D: _serde::Deserializer<#delife>
{
_serde::export::Ok(__DeserializeWith {
value: try!(#deserialize_with(__deserializer)),
@@ -1822,20 +1858,24 @@ struct DeImplGenerics<'a>(&'a Parameters);
impl<'a> ToTokens for DeImplGenerics<'a> {
fn to_tokens(&self, tokens: &mut Tokens) {
let mut generics = self.0.generics.clone();
- generics.lifetimes.insert(0, self.0.de_lifetime_def());
+ if let Some(de_lifetime) = self.0.borrowed.de_lifetime_def() {
+ generics.lifetimes.insert(0, de_lifetime);
+ }
let (impl_generics, _, _) = generics.split_for_impl();
impl_generics.to_tokens(tokens);
}
}
-struct DeTyGenerics<'a>(&'a syn::Generics);
+struct DeTyGenerics<'a>(&'a Parameters);
impl<'a> ToTokens for DeTyGenerics<'a> {
fn to_tokens(&self, tokens: &mut Tokens) {
- let mut generics = self.0.clone();
- generics
- .lifetimes
- .insert(0, syn::LifetimeDef::new("'de"));
+ let mut generics = self.0.generics.clone();
+ if self.0.borrowed.de_lifetime_def().is_some() {
+ generics
+ .lifetimes
+ .insert(0, syn::LifetimeDef::new("'de"));
+ }
let (_, ty_generics, _) = generics.split_for_impl();
ty_generics.to_tokens(tokens);
}
@@ -1844,7 +1884,7 @@ impl<'a> ToTokens for DeTyGenerics<'a> {
fn split_with_de_lifetime(params: &Parameters,)
-> (DeImplGenerics, DeTyGenerics, syn::TyGenerics, &syn::WhereClause) {
let de_impl_generics = DeImplGenerics(¶ms);
- let de_ty_generics = DeTyGenerics(¶ms.generics);
+ let de_ty_generics = DeTyGenerics(¶ms);
let (_, ty_generics, where_clause) = params.generics.split_for_impl();
(de_impl_generics, de_ty_generics, ty_generics, where_clause)
}
| serde-rs/serde | 2017-09-09T19:31:19Z | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 | |
1,044 | diff --git a/serde_test/src/assert.rs b/serde_test/src/assert.rs
index 2af2ebf59..7a4b1d4db 100644
--- a/serde_test/src/assert.rs
+++ b/serde_test/src/assert.rs
@@ -47,8 +47,20 @@ pub fn assert_tokens<'de, T>(value: &T, tokens: &'de [Token])
where
T: Serialize + Deserialize<'de> + PartialEq + Debug,
{
- assert_ser_tokens(value, tokens);
- assert_de_tokens(value, tokens);
+ assert_tokens_readable(value, tokens, true);
+}
+
+// Not public API
+#[doc(hidden)]
+/// Runs both `assert_ser_tokens` and `assert_de_tokens`.
+///
+/// See: `assert_tokens`
+pub fn assert_tokens_readable<'de, T>(value: &T, tokens: &'de [Token], human_readable: bool)
+where
+ T: Serialize + Deserialize<'de> + PartialEq + Debug,
+{
+ assert_ser_tokens_readable(value, tokens, human_readable);
+ assert_de_tokens_readable(value, tokens, human_readable);
}
/// Asserts that `value` serializes to the given `tokens`.
@@ -84,7 +96,19 @@ pub fn assert_ser_tokens<T>(value: &T, tokens: &[Token])
where
T: Serialize,
{
- let mut ser = Serializer::new(tokens);
+ assert_ser_tokens_readable(value, tokens, true)
+}
+
+// Not public API
+#[doc(hidden)]
+/// Asserts that `value` serializes to the given `tokens`.
+///
+/// See: `assert_ser_tokens`
+pub fn assert_ser_tokens_readable<T>(value: &T, tokens: &[Token], human_readable: bool)
+where
+ T: Serialize,
+{
+ let mut ser = Serializer::readable(tokens, human_readable);
match value.serialize(&mut ser) {
Ok(_) => {}
Err(err) => panic!("value failed to serialize: {}", err),
@@ -183,7 +207,16 @@ pub fn assert_de_tokens<'de, T>(value: &T, tokens: &'de [Token])
where
T: Deserialize<'de> + PartialEq + Debug,
{
- let mut de = Deserializer::new(tokens);
+ assert_de_tokens_readable(value, tokens, true)
+}
+
+// Not public API
+#[doc(hidden)]
+pub fn assert_de_tokens_readable<'de, T>(value: &T, tokens: &'de [Token], human_readable: bool)
+where
+ T: Deserialize<'de> + PartialEq + Debug,
+{
+ let mut de = Deserializer::readable(tokens, human_readable);
match T::deserialize(&mut de) {
Ok(v) => assert_eq!(v, *value),
Err(e) => panic!("tokens failed to deserialize: {}", e),
diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index 9e465a739..8a281d9da 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -16,6 +16,7 @@ use token::Token;
#[derive(Debug)]
pub struct Deserializer<'de> {
tokens: &'de [Token],
+ is_human_readable: bool,
}
macro_rules! assert_next_token {
@@ -48,7 +49,13 @@ macro_rules! end_of_tokens {
impl<'de> Deserializer<'de> {
pub fn new(tokens: &'de [Token]) -> Self {
- Deserializer { tokens: tokens }
+ Deserializer::readable(tokens, true)
+ }
+
+ // Not public API
+ #[doc(hidden)]
+ pub fn readable(tokens: &'de [Token], is_human_readable: bool) -> Self {
+ Deserializer { tokens: tokens, is_human_readable: is_human_readable }
}
fn peek_token_opt(&self) -> Option<Token> {
@@ -364,6 +371,10 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
_ => self.deserialize_any(visitor),
}
}
+
+ fn is_human_readable(&self) -> bool {
+ self.is_human_readable
+ }
}
//////////////////////////////////////////////////////////////////////////
diff --git a/serde_test/src/lib.rs b/serde_test/src/lib.rs
index 391837d16..7833d942d 100644
--- a/serde_test/src/lib.rs
+++ b/serde_test/src/lib.rs
@@ -168,8 +168,12 @@ mod token;
mod assert;
pub use token::Token;
-pub use assert::{assert_tokens, assert_ser_tokens, assert_ser_tokens_error, assert_de_tokens,
- assert_de_tokens_error};
+pub use assert::{assert_tokens, assert_ser_tokens, assert_ser_tokens_error,
+ assert_de_tokens, assert_de_tokens_error};
+
+// Not public API.
+#[doc(hidden)]
+pub use assert::{assert_tokens_readable, assert_de_tokens_readable, assert_ser_tokens_readable};
// Not public API.
#[doc(hidden)]
diff --git a/serde_test/src/ser.rs b/serde_test/src/ser.rs
index 31ba72eec..a25ade9af 100644
--- a/serde_test/src/ser.rs
+++ b/serde_test/src/ser.rs
@@ -15,12 +15,19 @@ use token::Token;
#[derive(Debug)]
pub struct Serializer<'a> {
tokens: &'a [Token],
+ is_human_readable: bool,
}
impl<'a> Serializer<'a> {
/// Creates the serializer.
pub fn new(tokens: &'a [Token]) -> Self {
- Serializer { tokens: tokens }
+ Serializer::readable(tokens, true)
+ }
+
+ // Not public API
+ #[doc(hidden)]
+ pub fn readable(tokens: &'a [Token], is_human_readable: bool) -> Self {
+ Serializer { tokens: tokens, is_human_readable: is_human_readable }
}
/// Pulls the next token off of the serializer, ignoring it.
@@ -282,6 +289,10 @@ impl<'s, 'a> ser::Serializer for &'s mut Serializer<'a> {
Ok(Variant { ser: self, end: Token::StructVariantEnd })
}
}
+
+ fn is_human_readable(&self) -> bool {
+ self.is_human_readable
+ }
}
pub struct Variant<'s, 'a: 's> {
diff --git a/test_suite/tests/macros/mod.rs b/test_suite/tests/macros/mod.rs
index 4f6ea66e9..9a917bcf4 100644
--- a/test_suite/tests/macros/mod.rs
+++ b/test_suite/tests/macros/mod.rs
@@ -73,3 +73,29 @@ macro_rules! hashmap {
}
}
}
+
+macro_rules! seq_impl {
+ (seq $first:expr,) => {
+ seq_impl!(seq $first)
+ };
+ ($first:expr,) => {
+ seq_impl!($first)
+ };
+ (seq $first:expr) => {
+ $first.into_iter()
+ };
+ ($first:expr) => {
+ Some($first).into_iter()
+ };
+ (seq $first:expr , $( $elem: tt)*) => {
+ $first.into_iter().chain(seq!( $($elem)* ))
+ };
+ ($first:expr , $($elem: tt)*) => {
+ Some($first).into_iter().chain(seq!( $($elem)* ))
+ }
+}
+macro_rules! seq {
+ ($($tt: tt)*) => {
+ seq_impl!($($tt)*).collect::<Vec<_>>()
+ };
+}
diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index 9fbfed46c..5318fd88f 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -28,7 +28,7 @@ extern crate fnv;
use self::fnv::FnvHasher;
extern crate serde_test;
-use self::serde_test::{Token, assert_de_tokens, assert_de_tokens_error};
+use self::serde_test::{Token, assert_de_tokens, assert_de_tokens_error, assert_de_tokens_readable};
#[macro_use]
mod macros;
@@ -110,15 +110,15 @@ enum EnumSkipAll {
//////////////////////////////////////////////////////////////////////////
macro_rules! declare_test {
- ($name:ident { $($value:expr => $tokens:expr,)+ }) => {
+ ($name:ident $readable: ident { $($value:expr => $tokens:expr,)+ }) => {
#[test]
fn $name() {
$(
// Test ser/de roundtripping
- assert_de_tokens(&$value, $tokens);
+ assert_de_tokens_readable(&$value, $tokens, $readable);
// Test that the tokens are ignorable
- assert_de_tokens_ignore($tokens);
+ assert_de_tokens_ignore($tokens, true);
)+
}
}
@@ -127,7 +127,7 @@ macro_rules! declare_test {
macro_rules! declare_tests {
($($name:ident { $($value:expr => $tokens:expr,)+ })+) => {
$(
- declare_test!($name { $($value => $tokens,)+ });
+ declare_test!($name true { $($value => $tokens,)+ });
)+
}
}
@@ -143,7 +143,16 @@ macro_rules! declare_error_tests {
}
}
-fn assert_de_tokens_ignore(ignorable_tokens: &[Token]) {
+macro_rules! declare_non_human_readable_tests {
+ ($($name:ident { $($value:expr => $tokens:expr,)+ })+) => {
+ $(
+ declare_test!($name false { $($value => $tokens,)+ });
+ )+
+ }
+}
+
+
+fn assert_de_tokens_ignore(ignorable_tokens: &[Token], readable: bool) {
#[derive(PartialEq, Debug, Deserialize)]
struct IgnoreBase {
a: i32,
@@ -163,7 +172,7 @@ fn assert_de_tokens_ignore(ignorable_tokens: &[Token]) {
.chain(vec![Token::MapEnd].into_iter())
.collect();
- let mut de = serde_test::Deserializer::new(&concated_tokens);
+ let mut de = serde_test::Deserializer::readable(&concated_tokens, readable);
let base = IgnoreBase::deserialize(&mut de).unwrap();
assert_eq!(base, IgnoreBase { a: 1 });
}
@@ -754,6 +763,70 @@ declare_tests! {
}
}
+declare_non_human_readable_tests!{
+ test_non_human_readable_net_ipv4addr {
+ net::Ipv4Addr::from(*b"1234") => &seq![
+ Token::Tuple { len: 4 },
+ seq b"1234".iter().map(|&b| Token::U8(b)),
+ Token::TupleEnd
+ ],
+ }
+ test_non_human_readable_net_ipv6addr {
+ net::Ipv6Addr::from(*b"1234567890123456") => &seq![
+ Token::Tuple { len: 4 },
+ seq b"1234567890123456".iter().map(|&b| Token::U8(b)),
+ Token::TupleEnd
+ ],
+
+ }
+ test_non_human_readable_net_socketaddr {
+ net::SocketAddr::from((*b"1234567890123456", 1234)) => &seq![
+ Token::NewtypeVariant { name: "SocketAddr", variant: "V6" },
+
+ Token::Tuple { len: 2 },
+
+ Token::Tuple { len: 16 },
+ seq b"1234567890123456".iter().map(|&b| Token::U8(b)),
+ Token::TupleEnd,
+
+ Token::U16(1234),
+ Token::TupleEnd
+ ],
+ net::SocketAddr::from((*b"1234", 1234)) => &seq![
+ Token::NewtypeVariant { name: "SocketAddr", variant: "V4" },
+
+ Token::Tuple { len: 2 },
+
+ Token::Tuple { len: 4 },
+ seq b"1234".iter().map(|&b| Token::U8(b)),
+ Token::TupleEnd,
+
+ Token::U16(1234),
+ Token::TupleEnd
+ ],
+ net::SocketAddrV4::new(net::Ipv4Addr::from(*b"1234"), 1234) => &seq![
+ Token::Tuple { len: 2 },
+
+ Token::Tuple { len: 4 },
+ seq b"1234".iter().map(|&b| Token::U8(b)),
+ Token::TupleEnd,
+
+ Token::U16(1234),
+ Token::TupleEnd
+ ],
+ net::SocketAddrV6::new(net::Ipv6Addr::from(*b"1234567890123456"), 1234, 0, 0) => &seq![
+ Token::Tuple { len: 2 },
+
+ Token::Tuple { len: 16 },
+ seq b"1234567890123456".iter().map(|&b| Token::U8(b)),
+ Token::TupleEnd,
+
+ Token::U16(1234),
+ Token::TupleEnd
+ ],
+ }
+}
+
#[cfg(feature = "unstable")]
declare_tests! {
test_rc_dst {
@@ -795,7 +868,7 @@ fn test_osstring() {
];
assert_de_tokens(&value, &tokens);
- assert_de_tokens_ignore(&tokens);
+ assert_de_tokens_ignore(&tokens, true);
}
#[cfg(windows)]
@@ -815,7 +888,7 @@ fn test_osstring() {
];
assert_de_tokens(&value, &tokens);
- assert_de_tokens_ignore(&tokens);
+ assert_de_tokens_ignore(&tokens, true);
}
#[cfg(feature = "unstable")]
@@ -1078,3 +1151,39 @@ declare_error_tests! {
"invalid type: sequence, expected unit struct UnitStruct",
}
}
+
+#[derive(Debug, PartialEq)]
+struct CompactBinary((u8, u8));
+
+impl<'de> serde::Deserialize<'de> for CompactBinary {
+ fn deserialize<D>(deserializer: D) -> Result<CompactBinary, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ if deserializer.is_human_readable() {
+ <(u8, u8)>::deserialize(deserializer).map(CompactBinary)
+ } else {
+ <&[u8]>::deserialize(deserializer).map(|bytes| {
+ CompactBinary((bytes[0], bytes[1]))
+ })
+ }
+ }
+}
+
+#[test]
+fn test_human_readable() {
+ assert_de_tokens(
+ &CompactBinary((1, 2)),
+ &[
+ Token::Tuple { len: 2},
+ Token::U8(1),
+ Token::U8(2),
+ Token::TupleEnd,
+ ],
+ );
+ assert_de_tokens_readable(
+ &CompactBinary((1, 2)),
+ &[Token::BorrowedBytes(&[1, 2])],
+ false,
+ );
+}
diff --git a/test_suite/tests/test_roundtrip.rs b/test_suite/tests/test_roundtrip.rs
new file mode 100644
index 000000000..eee7e83cd
--- /dev/null
+++ b/test_suite/tests/test_roundtrip.rs
@@ -0,0 +1,45 @@
+extern crate serde_test;
+use self::serde_test::{Token, assert_tokens_readable};
+
+use std::net;
+
+#[macro_use]
+#[allow(unused_macros)]
+mod macros;
+
+#[test]
+fn ip_addr_roundtrip() {
+
+ assert_tokens_readable(
+ &net::IpAddr::from(*b"1234"),
+ &seq![
+ Token::NewtypeVariant { name: "IpAddr", variant: "V4" },
+
+ Token::Tuple { len: 4 },
+ seq b"1234".iter().map(|&b| Token::U8(b)),
+ Token::TupleEnd,
+ ],
+ false,
+ );
+}
+
+#[test]
+fn socked_addr_roundtrip() {
+
+ assert_tokens_readable(
+ &net::SocketAddr::from((*b"1234567890123456", 1234)),
+ &seq![
+ Token::NewtypeVariant { name: "SocketAddr", variant: "V6" },
+
+ Token::Tuple { len: 2 },
+
+ Token::Tuple { len: 16 },
+ seq b"1234567890123456".iter().map(|&b| Token::U8(b)),
+ Token::TupleEnd,
+
+ Token::U16(1234),
+ Token::TupleEnd,
+ ],
+ false,
+ );
+}
diff --git a/test_suite/tests/test_ser.rs b/test_suite/tests/test_ser.rs
index 9dfb70532..3f3fa61c5 100644
--- a/test_suite/tests/test_ser.rs
+++ b/test_suite/tests/test_ser.rs
@@ -23,7 +23,8 @@ use std::str;
extern crate serde;
extern crate serde_test;
-use self::serde_test::{Token, assert_ser_tokens, assert_ser_tokens_error};
+use self::serde_test::{Token, assert_ser_tokens, assert_ser_tokens_error,
+ assert_ser_tokens_readable};
extern crate fnv;
use self::fnv::FnvHasher;
@@ -77,6 +78,19 @@ macro_rules! declare_tests {
}
}
+macro_rules! declare_non_human_readable_tests {
+ ($($name:ident { $($value:expr => $tokens:expr,)+ })+) => {
+ $(
+ #[test]
+ fn $name() {
+ $(
+ assert_ser_tokens_readable(&$value, $tokens, false);
+ )+
+ }
+ )+
+ }
+}
+
declare_tests! {
test_unit {
() => &[Token::Unit],
@@ -397,6 +411,66 @@ declare_tests! {
}
}
+declare_non_human_readable_tests!{
+ test_non_human_readable_net_ipv4addr {
+ net::Ipv4Addr::from(*b"1234") => &seq![
+ Token::Tuple { len: 4 },
+ seq b"1234".iter().map(|&b| Token::U8(b)),
+ Token::TupleEnd,
+ ],
+ }
+ test_non_human_readable_net_ipv6addr {
+ net::Ipv6Addr::from(*b"1234567890123456") => &seq![
+ Token::Tuple { len: 16 },
+ seq b"1234567890123456".iter().map(|&b| Token::U8(b)),
+ Token::TupleEnd,
+ ],
+ }
+ test_non_human_readable_net_ipaddr {
+ net::IpAddr::from(*b"1234") => &seq![
+ Token::NewtypeVariant { name: "IpAddr", variant: "V4" },
+
+ Token::Tuple { len: 4 },
+ seq b"1234".iter().map(|&b| Token::U8(b)),
+ Token::TupleEnd,
+ ],
+ }
+ test_non_human_readable_net_socketaddr {
+ net::SocketAddr::from((*b"1234567890123456", 1234)) => &seq![
+ Token::NewtypeVariant { name: "SocketAddr", variant: "V6" },
+
+ Token::Tuple { len: 2 },
+
+ Token::Tuple { len: 16 },
+ seq b"1234567890123456".iter().map(|&b| Token::U8(b)),
+ Token::TupleEnd,
+
+ Token::U16(1234),
+ Token::TupleEnd,
+ ],
+ net::SocketAddrV4::new(net::Ipv4Addr::from(*b"1234"), 1234) => &seq![
+ Token::Tuple { len: 2 },
+
+ Token::Tuple { len: 4 },
+ seq b"1234".iter().map(|&b| Token::U8(b)),
+ Token::TupleEnd,
+
+ Token::U16(1234),
+ Token::TupleEnd,
+ ],
+ net::SocketAddrV6::new(net::Ipv6Addr::from(*b"1234567890123456"), 1234, 0, 0) => &seq![
+ Token::Tuple { len: 2 },
+
+ Token::Tuple { len: 16 },
+ seq b"1234567890123456".iter().map(|&b| Token::U8(b)),
+ Token::TupleEnd,
+
+ Token::U16(1234),
+ Token::TupleEnd,
+ ],
+ }
+}
+
// Serde's implementation is not unstable, but the constructors are.
#[cfg(feature = "unstable")]
declare_tests! {
@@ -474,3 +548,26 @@ fn test_enum_skipped() {
"the enum variant Enum::SkippedMap cannot be serialized",
);
}
+
+struct CompactBinary(String);
+
+impl serde::Serialize for CompactBinary {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer
+ {
+ if serializer.is_human_readable() {
+ serializer.serialize_str(&self.0)
+ } else {
+ serializer.serialize_bytes(self.0.as_bytes())
+ }
+ }
+}
+
+#[test]
+fn test_human_readable() {
+ let value = CompactBinary("test".to_string());
+ assert_ser_tokens(&value, &[Token::String("test")]);
+
+ assert_ser_tokens_readable(&value, &[Token::Bytes(b"test")], false);
+}
| [
"790"
] | serde-rs__serde-1044 | Allow representation to differ between human-readable and binary formats
As an initial brainstormed approach to give an example of what I have in mind:
```rust
trait Serializer {
/* existing associated types and methods */
fn serialize_readable_or_compact<T>(self, t: T) -> Result<Self::Ok, Self::Error>
where T: SerializeReadable + SerializeCompact;
}
trait SerializeReadable { /* just like Serialize */ }
trait SerializeCompact { /* just like Serialize */ }
```
... and similar for deserialization.
The idea is that chrono::DateTime, std::net::IpAddr etc can serialize themselves as a string in JSON and YAML but compact bytes in Bincode. Currently a SocketAddrV6 takes up to 55 bytes to represent in Bincode but should only be 18 bytes.
| 1.0 | ea1a7290881508406ff0e704507d98a1fc7d6803 | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index ef3e20e6a..c48d02a75 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -869,37 +869,204 @@ map_impl!(
////////////////////////////////////////////////////////////////////////////////
#[cfg(feature = "std")]
-macro_rules! parse_impl {
- ($ty:ty) => {
+macro_rules! parse_ip_impl {
+ ($ty:ty; $size: expr) => {
impl<'de> Deserialize<'de> for $ty {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
- let s = try!(String::deserialize(deserializer));
- s.parse().map_err(Error::custom)
+ if deserializer.is_human_readable() {
+ let s = try!(String::deserialize(deserializer));
+ s.parse().map_err(Error::custom)
+ } else {
+ <[u8; $size]>::deserialize(deserializer).map(<$ty>::from)
+ }
+ }
+ }
+ }
+}
+
+macro_rules! variant_identifier {
+ (
+ $name_kind: ident ( $($variant: ident; $bytes: expr; $index: expr),* )
+ $expecting_message: expr,
+ $variants_name: ident
+ ) => {
+ enum $name_kind {
+ $( $variant ),*
+ }
+
+ static $variants_name: &'static [&'static str] = &[ $( stringify!($variant) ),*];
+
+ impl<'de> Deserialize<'de> for $name_kind {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ struct KindVisitor;
+
+ impl<'de> Visitor<'de> for KindVisitor {
+ type Value = $name_kind;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str($expecting_message)
+ }
+
+ fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E>
+ where
+ E: Error,
+ {
+ match value {
+ $(
+ $index => Ok($name_kind :: $variant),
+ )*
+ _ => Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self),),
+ }
+ }
+
+ fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
+ where
+ E: Error,
+ {
+ match value {
+ $(
+ stringify!($variant) => Ok($name_kind :: $variant),
+ )*
+ _ => Err(Error::unknown_variant(value, $variants_name)),
+ }
+ }
+
+ fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
+ where
+ E: Error,
+ {
+ match value {
+ $(
+ $bytes => Ok($name_kind :: $variant),
+ )*
+ _ => {
+ match str::from_utf8(value) {
+ Ok(value) => Err(Error::unknown_variant(value, $variants_name)),
+ Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)),
+ }
+ }
+ }
+ }
+ }
+
+ deserializer.deserialize_identifier(KindVisitor)
+ }
+ }
+ }
+}
+
+macro_rules! deserialize_enum {
+ (
+ $name: ident $name_kind: ident ( $($variant: ident; $bytes: expr; $index: expr),* )
+ $expecting_message: expr,
+ $deserializer: expr
+ ) => {
+ variant_identifier!{
+ $name_kind ( $($variant; $bytes; $index),* )
+ $expecting_message,
+ VARIANTS
+ }
+
+ struct EnumVisitor;
+ impl<'de> Visitor<'de> for EnumVisitor {
+ type Value = $name;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str(concat!("a ", stringify!($name)))
+ }
+
+
+ fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
+ where
+ A: EnumAccess<'de>,
+ {
+ match try!(data.variant()) {
+ $(
+ ($name_kind :: $variant, v) => v.newtype_variant().map($name :: $variant),
+ )*
+ }
+ }
+ }
+ $deserializer.deserialize_enum(stringify!($name), VARIANTS, EnumVisitor)
+ }
+}
+
+#[cfg(feature = "std")]
+impl<'de> Deserialize<'de> for net::IpAddr {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ if deserializer.is_human_readable() {
+ let s = try!(String::deserialize(deserializer));
+ s.parse().map_err(Error::custom)
+ } else {
+ use lib::net::IpAddr;
+ deserialize_enum!{
+ IpAddr IpAddrKind (V4; b"V4"; 0, V6; b"V6"; 1)
+ "`V4` or `V6`",
+ deserializer
}
}
}
}
#[cfg(feature = "std")]
-parse_impl!(net::IpAddr);
+parse_ip_impl!(net::Ipv4Addr; 4);
#[cfg(feature = "std")]
-parse_impl!(net::Ipv4Addr);
+parse_ip_impl!(net::Ipv6Addr; 16);
#[cfg(feature = "std")]
-parse_impl!(net::Ipv6Addr);
+macro_rules! parse_socket_impl {
+ ($ty:ty, $new: expr) => {
+ impl<'de> Deserialize<'de> for $ty {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ if deserializer.is_human_readable() {
+ let s = try!(String::deserialize(deserializer));
+ s.parse().map_err(Error::custom)
+ } else {
+ <(_, u16)>::deserialize(deserializer).map(|(ip, port)| $new(ip, port))
+ }
+ }
+ }
+ }
+}
#[cfg(feature = "std")]
-parse_impl!(net::SocketAddr);
+impl<'de> Deserialize<'de> for net::SocketAddr {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ if deserializer.is_human_readable() {
+ let s = try!(String::deserialize(deserializer));
+ s.parse().map_err(Error::custom)
+ } else {
+ use lib::net::SocketAddr;
+ deserialize_enum!{
+ SocketAddr SocketAddrKind (V4; b"V4"; 0, V6; b"V6"; 1)
+ "`V4` or `V6`",
+ deserializer
+ }
+ }
+ }
+}
#[cfg(feature = "std")]
-parse_impl!(net::SocketAddrV4);
+parse_socket_impl!(net::SocketAddrV4, net::SocketAddrV4::new);
#[cfg(feature = "std")]
-parse_impl!(net::SocketAddrV6);
+parse_socket_impl!(net::SocketAddrV6, |ip, port| net::SocketAddrV6::new(ip, port, 0, 0));
////////////////////////////////////////////////////////////////////////////////
@@ -984,70 +1151,10 @@ impl<'de> Deserialize<'de> for PathBuf {
// #[derive(Deserialize)]
// #[serde(variant_identifier)]
#[cfg(all(feature = "std", any(unix, windows)))]
-enum OsStringKind {
- Unix,
- Windows,
-}
-
-#[cfg(all(feature = "std", any(unix, windows)))]
-static OSSTR_VARIANTS: &'static [&'static str] = &["Unix", "Windows"];
-
-#[cfg(all(feature = "std", any(unix, windows)))]
-impl<'de> Deserialize<'de> for OsStringKind {
- fn deserialize<D>(deserializer: D) -> Result<OsStringKind, D::Error>
- where
- D: Deserializer<'de>,
- {
- struct KindVisitor;
-
- impl<'de> Visitor<'de> for KindVisitor {
- type Value = OsStringKind;
-
- fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
- formatter.write_str("`Unix` or `Windows`")
- }
-
- fn visit_u32<E>(self, value: u32) -> Result<OsStringKind, E>
- where
- E: Error,
- {
- match value {
- 0 => Ok(OsStringKind::Unix),
- 1 => Ok(OsStringKind::Windows),
- _ => Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self),),
- }
- }
-
- fn visit_str<E>(self, value: &str) -> Result<OsStringKind, E>
- where
- E: Error,
- {
- match value {
- "Unix" => Ok(OsStringKind::Unix),
- "Windows" => Ok(OsStringKind::Windows),
- _ => Err(Error::unknown_variant(value, OSSTR_VARIANTS)),
- }
- }
-
- fn visit_bytes<E>(self, value: &[u8]) -> Result<OsStringKind, E>
- where
- E: Error,
- {
- match value {
- b"Unix" => Ok(OsStringKind::Unix),
- b"Windows" => Ok(OsStringKind::Windows),
- _ => {
- match str::from_utf8(value) {
- Ok(value) => Err(Error::unknown_variant(value, OSSTR_VARIANTS)),
- Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)),
- }
- }
- }
- }
- }
-
- deserializer.deserialize_identifier(KindVisitor)
- }
+variant_identifier!{
+ OsStringKind (Unix; b"Unix"; 0, Windows; b"Windows"; 1)
+ "`Unix` or `Windows`",
+ OSSTR_VARIANTS
}
#[cfg(all(feature = "std", any(unix, windows)))]
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index e90ced27f..71a707efc 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -1011,6 +1011,15 @@ pub trait Deserializer<'de>: Sized {
fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>;
+
+ /// Returns whether the serialized data is human readable or not.
+ ///
+ /// Some formats are not intended to be human readable. For these formats
+ /// a type being serialized may opt to serialize into a more compact form.
+ ///
+ /// NOTE: Implementing this method and returning `false` is considered a breaking
+ /// change as it may alter how any given type tries to deserialize itself.
+ fn is_human_readable(&self) -> bool { true }
}
////////////////////////////////////////////////////////////////////////////////
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index ea59b78dd..3fa2ad9cc 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -506,9 +506,18 @@ impl Serialize for net::IpAddr {
where
S: Serializer,
{
- match *self {
- net::IpAddr::V4(ref a) => a.serialize(serializer),
- net::IpAddr::V6(ref a) => a.serialize(serializer),
+ if serializer.is_human_readable() {
+ match *self {
+ net::IpAddr::V4(ref a) => a.serialize(serializer),
+ net::IpAddr::V6(ref a) => a.serialize(serializer),
+ }
+ } else {
+ match *self {
+ net::IpAddr::V4(ref a) =>
+ serializer.serialize_newtype_variant("IpAddr", 0, "V4", a),
+ net::IpAddr::V6(ref a) =>
+ serializer.serialize_newtype_variant("IpAddr", 1, "V6", a),
+ }
}
}
}
@@ -519,9 +528,13 @@ impl Serialize for net::Ipv4Addr {
where
S: Serializer,
{
- /// "101.102.103.104".len()
- const MAX_LEN: usize = 15;
- serialize_display_bounded_length!(self, MAX_LEN, serializer)
+ if serializer.is_human_readable() {
+ /// "101.102.103.104".len()
+ const MAX_LEN: usize = 15;
+ serialize_display_bounded_length!(self, MAX_LEN, serializer)
+ } else {
+ self.octets().serialize(serializer)
+ }
}
}
@@ -531,9 +544,13 @@ impl Serialize for net::Ipv6Addr {
where
S: Serializer,
{
- /// "1000:1002:1003:1004:1005:1006:1007:1008".len()
- const MAX_LEN: usize = 39;
- serialize_display_bounded_length!(self, MAX_LEN, serializer)
+ if serializer.is_human_readable() {
+ /// "1000:1002:1003:1004:1005:1006:1007:1008".len()
+ const MAX_LEN: usize = 39;
+ serialize_display_bounded_length!(self, MAX_LEN, serializer)
+ } else {
+ self.octets().serialize(serializer)
+ }
}
}
@@ -543,9 +560,18 @@ impl Serialize for net::SocketAddr {
where
S: Serializer,
{
- match *self {
- net::SocketAddr::V4(ref addr) => addr.serialize(serializer),
- net::SocketAddr::V6(ref addr) => addr.serialize(serializer),
+ if serializer.is_human_readable() {
+ match *self {
+ net::SocketAddr::V4(ref addr) => addr.serialize(serializer),
+ net::SocketAddr::V6(ref addr) => addr.serialize(serializer),
+ }
+ } else {
+ match *self {
+ net::SocketAddr::V4(ref addr) =>
+ serializer.serialize_newtype_variant("SocketAddr", 0, "V4", addr),
+ net::SocketAddr::V6(ref addr) =>
+ serializer.serialize_newtype_variant("SocketAddr", 1, "V6", addr),
+ }
}
}
}
@@ -556,9 +582,13 @@ impl Serialize for net::SocketAddrV4 {
where
S: Serializer,
{
- /// "101.102.103.104:65000".len()
- const MAX_LEN: usize = 21;
- serialize_display_bounded_length!(self, MAX_LEN, serializer)
+ if serializer.is_human_readable() {
+ /// "101.102.103.104:65000".len()
+ const MAX_LEN: usize = 21;
+ serialize_display_bounded_length!(self, MAX_LEN, serializer)
+ } else {
+ (self.ip(), self.port()).serialize(serializer)
+ }
}
}
@@ -568,9 +598,13 @@ impl Serialize for net::SocketAddrV6 {
where
S: Serializer,
{
- /// "[1000:1002:1003:1004:1005:1006:1007:1008]:65000".len()
- const MAX_LEN: usize = 47;
- serialize_display_bounded_length!(self, MAX_LEN, serializer)
+ if serializer.is_human_readable() {
+ /// "[1000:1002:1003:1004:1005:1006:1007:1008]:65000".len()
+ const MAX_LEN: usize = 47;
+ serialize_display_bounded_length!(self, MAX_LEN, serializer)
+ } else {
+ (self.ip(), self.port()).serialize(serializer)
+ }
}
}
diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs
index 4356f9303..bbcceac7f 100644
--- a/serde/src/ser/mod.rs
+++ b/serde/src/ser/mod.rs
@@ -1363,6 +1363,15 @@ pub trait Serializer: Sized {
fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: Display;
+
+ /// Returns wheter the data format is human readable or not.
+ ///
+ /// Some formats are not intended to be human readable. For these formats
+ /// a type being serialized may opt to serialize into a more compact form.
+ ///
+ /// NOTE: Implementing this method and returning `false` is considered a breaking
+ /// change as it may alter how any given type tries to serialize itself.
+ fn is_human_readable(&self) -> bool { true }
}
/// Returned from `Serializer::serialize_seq`.
| serde-rs/serde | 2017-09-07T14:16:40Z | I think I'd describe data in this form as a "blob;" formats like JSON can only store arbitrary data as strings, whereas formats like bincode can store any arbitrary bytes. I have an idea for how I'd implement this and I'll post it later once I write it up.
Perhaps like this?
```
trait Serializer {
// existing stuff
fn serialize_blob<T>(self, t: T) -> Result<Self::Ok, Self::Error> where T: SerializeBlob;
}
trait SerializeBlob: Display {
fn fmt_bytes<W>(&self, writer: W) -> io::Result<()> where W: io::Write {
write!(writer, "{}", self)
}
}
```
I'm open for ideas on how to do this without requiring libstd. I'd rather it not be too complicated, though.
What do you see as the advantages of that approach? Here are some disadvantages:
- If you are calling serialize_blob, you want the representation to be different in bytes form vs string form so the default implementation of fmt_bytes is never what you want. Otherwise you would just use collect_str instead of serialize_blob.
- Only supports string/byte representations rather than a more general concept of readable and compact, which may be a non-string in the readable case (for example a map) and non-bytes in the compact case (for example a tuple of integers for an IP address).
Of course here is the KISS approach:
```rust
trait Serializer {
/* existing associated types and methods */
#[inline]
fn is_human_readable() -> bool { true }
}
```
```rust
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
if S::is_human_readable() {
serializer.collect_str(self)
} else {
serializer.serialize_bytes(self.as_bytes())
}
}
```
I like it, although I think that it'd be nice to have a method that enables the user to test both branches without having to change anything in the serializer.
Perhaps we could add a separate `serialize_binary` method that defaults to delegating to `serialize` and is called by the serializer if appropriate? | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,022 | diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index 9fbfed46c..da7232a51 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -521,6 +521,15 @@ declare_tests! {
Token::I32(2),
Token::MapEnd,
],
+ Struct { a: 1, b: 2, c: 0 } => &[
+ Token::Map { len: Some(3) },
+ Token::U32(0),
+ Token::I32(1),
+
+ Token::U32(1),
+ Token::I32(2),
+ Token::MapEnd,
+ ],
Struct { a: 1, b: 2, c: 0 } => &[
Token::Struct { name: "Struct", len: 3 },
Token::Str("a"),
| [
"960"
] | serde-rs__serde-1022 | Pass field index to SerializeStruct::serialize_field
Similar to how `Serializer::serialize_*_variant` receives both the index and name of the variant. This would enable CBOR to deserialize correctly from a packed representation (integer keys) with fields that are conditionally skipped - https://github.com/pyfisch/cbor/issues/37.
| 1.0 | d4042872f5afa48a25fea933bfb749388f76dd8d | diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs
index 4356f9303..e934adb96 100644
--- a/serde/src/ser/mod.rs
+++ b/serde/src/ser/mod.rs
@@ -1727,6 +1727,13 @@ pub trait SerializeStruct {
where
T: Serialize;
+ /// Indicate that a struct field has been skipped.
+ #[inline]
+ fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
+ let _ = key;
+ Ok(())
+ }
+
/// Finish serializing a struct.
fn end(self) -> Result<Self::Ok, Self::Error>;
}
@@ -1772,6 +1779,13 @@ pub trait SerializeStructVariant {
where
T: Serialize;
+ /// Indicate that a struct variant field has been skipped.
+ #[inline]
+ fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
+ let _ = key;
+ Ok(())
+ }
+
/// Finish serializing a struct variant.
fn end(self) -> Result<Self::Ok, Self::Error>;
}
diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 5ab6d0a9b..8f6f717ba 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -1384,26 +1384,27 @@ fn deserialize_identifier(
"field identifier"
};
- let visit_index = if is_variant {
- let variant_indices = 0u32..;
- let fallthrough_msg = format!("variant index 0 <= i < {}", fields.len());
- let visit_index = quote! {
- fn visit_u32<__E>(self, __value: u32) -> _serde::export::Result<Self::Value, __E>
- where __E: _serde::de::Error
- {
- match __value {
- #(
- #variant_indices => _serde::export::Ok(#constructors),
- )*
- _ => _serde::export::Err(_serde::de::Error::invalid_value(
- _serde::de::Unexpected::Unsigned(__value as u64),
- &#fallthrough_msg))
- }
- }
- };
- Some(visit_index)
+ let index_expecting = if is_variant {
+ "variant"
} else {
- None
+ "field"
+ };
+
+ let variant_indices = 0u32..;
+ let fallthrough_msg = format!("{} index 0 <= i < {}", index_expecting, fields.len());
+ let visit_index = quote! {
+ fn visit_u32<__E>(self, __value: u32) -> _serde::export::Result<Self::Value, __E>
+ where __E: _serde::de::Error
+ {
+ match __value {
+ #(
+ #variant_indices => _serde::export::Ok(#constructors),
+ )*
+ _ => _serde::export::Err(_serde::de::Error::invalid_value(
+ _serde::de::Unexpected::Unsigned(__value as u64),
+ &#fallthrough_msg))
+ }
+ }
};
let bytes_to_str = if fallthrough.is_some() {
diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index 9be9bddca..9c3310be5 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -242,6 +242,7 @@ fn serialize_struct(params: &Parameters, fields: &[Field], cattrs: &attr::Contai
params,
false,
quote!(_serde::ser::SerializeStruct::serialize_field),
+ quote!(_serde::ser::SerializeStruct::skip_field),
);
let type_name = cattrs.name().serialize_name();
@@ -707,15 +708,23 @@ fn serialize_struct_variant<'a>(
fields: &[Field],
name: &str,
) -> Fragment {
- let method = match context {
+ let (method, skip_method) = match context {
StructVariant::ExternallyTagged { .. } => {
- quote!(_serde::ser::SerializeStructVariant::serialize_field)
+ (
+ quote!(_serde::ser::SerializeStructVariant::serialize_field),
+ quote!(_serde::ser::SerializeStructVariant::skip_field),
+ )
}
StructVariant::InternallyTagged { .. } |
- StructVariant::Untagged => quote!(_serde::ser::SerializeStruct::serialize_field),
+ StructVariant::Untagged => {
+ (
+ quote!(_serde::ser::SerializeStruct::serialize_field),
+ quote!(_serde::ser::SerializeStruct::skip_field),
+ )
+ }
};
- let serialize_fields = serialize_struct_visitor(fields, params, true, method);
+ let serialize_fields = serialize_struct_visitor(fields, params, true, method, skip_method);
let mut serialized_fields = fields
.iter()
@@ -829,6 +838,7 @@ fn serialize_struct_visitor(
params: &Parameters,
is_enum: bool,
func: Tokens,
+ skip_func: Tokens,
) -> Vec<Tokens> {
fields
.iter()
@@ -859,7 +869,15 @@ fn serialize_struct_visitor(
match skip {
None => ser,
- Some(skip) => quote!(if !#skip { #ser }),
+ Some(skip) => {
+ quote! {
+ if !#skip {
+ #ser
+ } else {
+ try!(#skip_func(&mut __serde_state, #key_expr));
+ }
+ }
+ }
}
},
)
| serde-rs/serde | 2017-08-19T17:30:50Z | Possible approach:
```rust
pub trait SerializeStruct {
type Ok;
type Error: Error;
fn serialize_field<T: ?Sized>(
&mut self,
key: &'static str,
value: &T
) -> Result<(), Self::Error>
where
T: Serialize;
fn serialize_indexed_field<T: ?Sized>(
&mut self,
key: &'static str,
key_index: u32,
value: &T
) -> Result<(), Self::Error>
where
T: Serialize
{
self.serialize_field(key, value)
}
fn end(self) -> Result<Self::Ok, Self::Error>;
}
```
Serializers that care about packed encodings would override both methods and everything else could ignore serialize_indexed_field. serde_derive would call into serialize_indexed_field, assuming it can force a bump of serde along side it which seems reasonable.
A different approach:
```rust
// SerializeStruct
fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
Ok(())
}
// Serialize
if $skip_serializing(&self.x) {
s.skip_field("x")?;
} else {
s.serialize_field("x", &self.x)?;
}
```
- No longer exposes the possibility of serializing fields out of numerical order, as in https://github.com/serde-rs/serde/pull/961#issuecomment-310588663.
- Bincode and friends can return an error on skipped fields with zero overhead when there are no skipped fields.
- Serializers that require a field index don't need to awkwardly override both `serialize_field` and `serialize_indexed_field`.
- Serializers receive the name of skipped fields for better error messages.
Thoughts?
That sounds like a good approach - not having to deal with both `serialize_field` and `serialize_indexed_field` is nice. | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
1,015 | diff --git a/test_suite/tests/compile-fail/with-variant/skip_de_newtype_field.rs b/test_suite/tests/compile-fail/with-variant/skip_de_newtype_field.rs
new file mode 100644
index 000000000..391af1baa
--- /dev/null
+++ b/test_suite/tests/compile-fail/with-variant/skip_de_newtype_field.rs
@@ -0,0 +1,25 @@
+// Copyright 2017 Serde Developers
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+//~^ HELP: variant `Newtype` cannot have both #[serde(deserialize_with)] and a field 0 marked with #[serde(skip_deserializing)]
+enum Enum {
+ #[serde(deserialize_with = "deserialize_some_newtype_variant")]
+ Newtype(#[serde(skip_deserializing)] String),
+}
+
+fn deserialize_some_newtype_variant<'de, D>(_: D) -> StdResult<String, D::Error>
+ where D: Deserializer<'de>,
+{
+ unimplemented!()
+}
+
+fn main() { }
diff --git a/test_suite/tests/compile-fail/with-variant/skip_de_struct_field.rs b/test_suite/tests/compile-fail/with-variant/skip_de_struct_field.rs
new file mode 100644
index 000000000..7c563a8af
--- /dev/null
+++ b/test_suite/tests/compile-fail/with-variant/skip_de_struct_field.rs
@@ -0,0 +1,29 @@
+// Copyright 2017 Serde Developers
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+//~^ HELP: variant `Struct` cannot have both #[serde(deserialize_with)] and a field `f1` marked with #[serde(skip_deserializing)]
+enum Enum {
+ #[serde(deserialize_with = "deserialize_some_other_variant")]
+ Struct {
+ #[serde(skip_deserializing)]
+ f1: String,
+ f2: u8,
+ },
+}
+
+fn deserialize_some_other_variant<'de, D>(_: D) -> StdResult<(String, u8), D::Error>
+ where D: Deserializer<'de>,
+{
+ unimplemented!()
+}
+
+fn main() { }
diff --git a/test_suite/tests/compile-fail/with-variant/skip_de_tuple_field.rs b/test_suite/tests/compile-fail/with-variant/skip_de_tuple_field.rs
new file mode 100644
index 000000000..44fd09581
--- /dev/null
+++ b/test_suite/tests/compile-fail/with-variant/skip_de_tuple_field.rs
@@ -0,0 +1,25 @@
+// Copyright 2017 Serde Developers
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+//~^ HELP: variant `Tuple` cannot have both #[serde(deserialize_with)] and a field 0 marked with #[serde(skip_deserializing)]
+enum Enum {
+ #[serde(deserialize_with = "deserialize_some_other_variant")]
+ Tuple(#[serde(skip_deserializing)] String, u8),
+}
+
+fn deserialize_some_other_variant<'de, D>(_: D) -> StdResult<(String, u8), D::Error>
+ where D: Deserializer<'de>,
+{
+ unimplemented!()
+}
+
+fn main() { }
diff --git a/test_suite/tests/compile-fail/with-variant/skip_de_whole_variant.rs b/test_suite/tests/compile-fail/with-variant/skip_de_whole_variant.rs
new file mode 100644
index 000000000..68c015a28
--- /dev/null
+++ b/test_suite/tests/compile-fail/with-variant/skip_de_whole_variant.rs
@@ -0,0 +1,26 @@
+// Copyright 2017 Serde Developers
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+//~^ HELP: variant `Unit` cannot have both #[serde(deserialize_with)] and #[serde(skip_deserializing)]
+enum Enum {
+ #[serde(deserialize_with = "deserialize_some_unit_variant")]
+ #[serde(skip_deserializing)]
+ Unit,
+}
+
+fn deserialize_some_unit_variant<'de, D>(_: D) -> StdResult<(), D::Error>
+ where D: Deserializer<'de>,
+{
+ unimplemented!()
+}
+
+fn main() { }
diff --git a/test_suite/tests/compile-fail/with-variant/skip_ser_newtype_field.rs b/test_suite/tests/compile-fail/with-variant/skip_ser_newtype_field.rs
new file mode 100644
index 000000000..162812d40
--- /dev/null
+++ b/test_suite/tests/compile-fail/with-variant/skip_ser_newtype_field.rs
@@ -0,0 +1,25 @@
+// Copyright 2017 Serde Developers
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+//~^ HELP: variant `Newtype` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing)]
+enum Enum {
+ #[serde(serialize_with = "serialize_some_newtype_variant")]
+ Newtype(#[serde(skip_serializing)] String),
+}
+
+fn serialize_some_newtype_variant<S>(_: &String) -> StdResult<S::Ok, S::Error>
+ where S: Serializer,
+{
+ unimplemented!()
+}
+
+fn main() { }
diff --git a/test_suite/tests/compile-fail/with-variant/skip_ser_newtype_field_if.rs b/test_suite/tests/compile-fail/with-variant/skip_ser_newtype_field_if.rs
new file mode 100644
index 000000000..065ca20dc
--- /dev/null
+++ b/test_suite/tests/compile-fail/with-variant/skip_ser_newtype_field_if.rs
@@ -0,0 +1,27 @@
+// Copyright 2017 Serde Developers
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+//~^ HELP: variant `Newtype` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing_if)]
+enum Enum {
+ #[serde(serialize_with = "serialize_some_newtype_variant")]
+ Newtype(#[serde(skip_serializing_if = "always")] String),
+}
+
+fn serialize_some_newtype_variant<S>(_: &String) -> StdResult<S::Ok, S::Error>
+ where S: Serializer,
+{
+ unimplemented!()
+}
+
+fn always<T>(_: &T) -> bool { true }
+
+fn main() { }
diff --git a/test_suite/tests/compile-fail/with-variant/skip_ser_struct_field.rs b/test_suite/tests/compile-fail/with-variant/skip_ser_struct_field.rs
new file mode 100644
index 000000000..dc046b86a
--- /dev/null
+++ b/test_suite/tests/compile-fail/with-variant/skip_ser_struct_field.rs
@@ -0,0 +1,29 @@
+// Copyright 2017 Serde Developers
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+//~^ HELP: variant `Struct` cannot have both #[serde(serialize_with)] and a field `f1` marked with #[serde(skip_serializing)]
+enum Enum {
+ #[serde(serialize_with = "serialize_some_other_variant")]
+ Struct {
+ #[serde(skip_serializing)]
+ f1: String,
+ f2: u8,
+ },
+}
+
+fn serialize_some_other_variant<S>(_: &String, _: Option<&u8>, _: S) -> StdResult<S::Ok, S::Error>
+ where S: Serializer,
+{
+ unimplemented!()
+}
+
+fn main() { }
diff --git a/test_suite/tests/compile-fail/with-variant/skip_ser_struct_field_if.rs b/test_suite/tests/compile-fail/with-variant/skip_ser_struct_field_if.rs
new file mode 100644
index 000000000..fd42947d2
--- /dev/null
+++ b/test_suite/tests/compile-fail/with-variant/skip_ser_struct_field_if.rs
@@ -0,0 +1,31 @@
+// Copyright 2017 Serde Developers
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+//~^ HELP: variant `Struct` cannot have both #[serde(serialize_with)] and a field `f1` marked with #[serde(skip_serializing_if)]
+enum Enum {
+ #[serde(serialize_with = "serialize_some_newtype_variant")]
+ Struct {
+ #[serde(skip_serializing_if = "always")]
+ f1: String,
+ f2: u8,
+ },
+}
+
+fn serialize_some_other_variant<S>(_: &String, _: Option<&u8>, _: S) -> StdResult<S::Ok, S::Error>
+ where S: Serializer,
+{
+ unimplemented!()
+}
+
+fn always<T>(_: &T) -> bool { true }
+
+fn main() { }
diff --git a/test_suite/tests/compile-fail/with-variant/skip_ser_tuple_field.rs b/test_suite/tests/compile-fail/with-variant/skip_ser_tuple_field.rs
new file mode 100644
index 000000000..56cbfa450
--- /dev/null
+++ b/test_suite/tests/compile-fail/with-variant/skip_ser_tuple_field.rs
@@ -0,0 +1,25 @@
+// Copyright 2017 Serde Developers
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+//~^ HELP: variant `Tuple` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing)]
+enum Enum {
+ #[serde(serialize_with = "serialize_some_other_variant")]
+ Tuple(#[serde(skip_serializing)] String, u8),
+}
+
+fn serialize_some_other_variant<S>(_: &String, _: Option<&u8>, _: S) -> StdResult<S::Ok, S::Error>
+ where S: Serializer,
+{
+ unimplemented!()
+}
+
+fn main() { }
diff --git a/test_suite/tests/compile-fail/with-variant/skip_ser_tuple_field_if.rs b/test_suite/tests/compile-fail/with-variant/skip_ser_tuple_field_if.rs
new file mode 100644
index 000000000..c85db63d0
--- /dev/null
+++ b/test_suite/tests/compile-fail/with-variant/skip_ser_tuple_field_if.rs
@@ -0,0 +1,27 @@
+// Copyright 2017 Serde Developers
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+//~^ HELP: variant `Tuple` cannot have both #[serde(serialize_with)] and a field 0 marked with #[serde(skip_serializing_if)]
+enum Enum {
+ #[serde(serialize_with = "serialize_some_other_variant")]
+ Tuple(#[serde(skip_serializing_if = "always")] String, u8),
+}
+
+fn serialize_some_other_variant<S>(_: &String, _: Option<&u8>, _: S) -> StdResult<S::Ok, S::Error>
+ where S: Serializer,
+{
+ unimplemented!()
+}
+
+fn always<T>(_: &T) -> bool { true }
+
+fn main() { }
diff --git a/test_suite/tests/compile-fail/with-variant/skip_ser_whole_variant.rs b/test_suite/tests/compile-fail/with-variant/skip_ser_whole_variant.rs
new file mode 100644
index 000000000..8e3291e3e
--- /dev/null
+++ b/test_suite/tests/compile-fail/with-variant/skip_ser_whole_variant.rs
@@ -0,0 +1,26 @@
+// Copyright 2017 Serde Developers
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Serialize)] //~ ERROR: proc-macro derive panicked
+//~^ HELP: variant `Unit` cannot have both #[serde(serialize_with)] and #[serde(skip_serializing)]
+enum Enum {
+ #[serde(serialize_with = "serialize_some_unit_variant")]
+ #[serde(skip_serializing)]
+ Unit,
+}
+
+fn serialize_some_unit_variant<S>(_: S) -> StdResult<S::Ok, S::Error>
+ where S: Serializer,
+{
+ unimplemented!()
+}
+
+fn main() { }
diff --git a/test_suite/tests/test_annotations.rs b/test_suite/tests/test_annotations.rs
index cb9642e8f..fb7961110 100644
--- a/test_suite/tests/test_annotations.rs
+++ b/test_suite/tests/test_annotations.rs
@@ -11,6 +11,7 @@ extern crate serde_derive;
extern crate serde;
use self::serde::{Serialize, Serializer, Deserialize, Deserializer};
+use self::serde::de::{self, Unexpected};
extern crate serde_test;
use self::serde_test::{Token, assert_tokens, assert_ser_tokens, assert_de_tokens,
@@ -811,6 +812,145 @@ fn test_serialize_with_enum() {
);
}
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
+enum WithVariant {
+ #[serde(serialize_with="serialize_unit_variant_as_i8")]
+ #[serde(deserialize_with="deserialize_i8_as_unit_variant")]
+ Unit,
+
+ #[serde(serialize_with="SerializeWith::serialize_with")]
+ #[serde(deserialize_with="DeserializeWith::deserialize_with")]
+ Newtype(i32),
+
+ #[serde(serialize_with="serialize_variant_as_string")]
+ #[serde(deserialize_with="deserialize_string_as_variant")]
+ Tuple(String, u8),
+
+ #[serde(serialize_with="serialize_variant_as_string")]
+ #[serde(deserialize_with="deserialize_string_as_variant")]
+ Struct {
+ f1: String,
+ f2: u8,
+ },
+}
+
+fn serialize_unit_variant_as_i8<S>(serializer: S) -> Result<S::Ok, S::Error>
+ where S: Serializer,
+{
+ serializer.serialize_i8(0)
+}
+
+fn deserialize_i8_as_unit_variant<'de, D>(deserializer: D) -> Result<(), D::Error>
+ where D: Deserializer<'de>,
+{
+ let n = i8::deserialize(deserializer)?;
+ match n {
+ 0 => Ok(()),
+ _ => Err(de::Error::invalid_value(Unexpected::Signed(n as i64), &"0")),
+ }
+}
+
+fn serialize_variant_as_string<S>(f1: &str,
+ f2: &u8,
+ serializer: S)
+ -> Result<S::Ok, S::Error>
+ where S: Serializer,
+{
+ serializer.serialize_str(format!("{};{:?}", f1, f2).as_str())
+}
+
+fn deserialize_string_as_variant<'de, D>(deserializer: D) -> Result<(String, u8), D::Error>
+ where D: Deserializer<'de>,
+{
+ let s = String::deserialize(deserializer)?;
+ let mut pieces = s.split(';');
+ let f1 = match pieces.next() {
+ Some(x) => x,
+ None => return Err(de::Error::invalid_length(0, &"2")),
+ };
+ let f2 = match pieces.next() {
+ Some(x) => x,
+ None => return Err(de::Error::invalid_length(1, &"2")),
+ };
+ let f2 = match f2.parse() {
+ Ok(n) => n,
+ Err(_) => {
+ return Err(de::Error::invalid_value(Unexpected::Str(f2), &"an 8-bit signed integer"));
+ }
+ };
+ Ok((f1.into(), f2))
+}
+
+#[test]
+fn test_serialize_with_variant() {
+ assert_ser_tokens(
+ &WithVariant::Unit,
+ &[
+ Token::NewtypeVariant { name: "WithVariant", variant: "Unit" },
+ Token::I8(0),
+ ],
+ );
+
+ assert_ser_tokens(
+ &WithVariant::Newtype(123),
+ &[
+ Token::NewtypeVariant { name: "WithVariant", variant: "Newtype" },
+ Token::Bool(true),
+ ],
+ );
+
+ assert_ser_tokens(
+ &WithVariant::Tuple("hello".into(), 0),
+ &[
+ Token::NewtypeVariant { name: "WithVariant", variant: "Tuple" },
+ Token::Str("hello;0"),
+ ],
+ );
+
+ assert_ser_tokens(
+ &WithVariant::Struct { f1: "world".into(), f2: 1 },
+ &[
+ Token::NewtypeVariant { name: "WithVariant", variant: "Struct" },
+ Token::Str("world;1"),
+ ],
+ );
+}
+
+#[test]
+fn test_deserialize_with_variant() {
+ assert_de_tokens(
+ &WithVariant::Unit,
+ &[
+ Token::NewtypeVariant { name: "WithVariant", variant: "Unit" },
+ Token::I8(0),
+ ],
+ );
+
+ assert_de_tokens(
+ &WithVariant::Newtype(123),
+ &[
+ Token::NewtypeVariant { name: "WithVariant", variant: "Newtype" },
+ Token::Bool(true),
+ ],
+ );
+
+ assert_de_tokens(
+ &WithVariant::Tuple("hello".into(), 0),
+ &[
+ Token::NewtypeVariant { name: "WithVariant", variant: "Tuple" },
+ Token::Str("hello;0"),
+ ],
+ );
+
+ assert_de_tokens(
+ &WithVariant::Struct { f1: "world".into(), f2: 1 },
+ &[
+ Token::NewtypeVariant { name: "WithVariant", variant: "Struct" },
+ Token::Str("world;1"),
+ ],
+ );
+}
+
#[derive(Debug, PartialEq, Deserialize)]
struct DeserializeWithStruct<B>
where
diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index 5d708014b..76c57db8a 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -373,6 +373,124 @@ fn test_gen() {
#[serde(with = "vis::SDef")]
s: vis::S,
}
+
+ #[derive(Serialize, Deserialize)]
+ enum ExternallyTaggedVariantWith {
+ #[allow(dead_code)]
+ Normal { f1: String },
+
+ #[serde(serialize_with = "ser_x")]
+ #[serde(deserialize_with = "de_x")]
+ #[allow(dead_code)]
+ Newtype(X),
+
+ #[serde(serialize_with = "serialize_some_other_variant")]
+ #[serde(deserialize_with = "deserialize_some_other_variant")]
+ #[allow(dead_code)]
+ Tuple(String, u8),
+
+ #[serde(serialize_with = "serialize_some_other_variant")]
+ #[serde(deserialize_with = "deserialize_some_other_variant")]
+ #[allow(dead_code)]
+ Struct {
+ f1: String,
+ f2: u8,
+ },
+
+ #[serde(serialize_with = "serialize_some_unit_variant")]
+ #[serde(deserialize_with = "deserialize_some_unit_variant")]
+ #[allow(dead_code)]
+ Unit,
+ }
+ assert_ser::<ExternallyTaggedVariantWith>();
+
+ #[derive(Serialize, Deserialize)]
+ #[serde(tag = "t")]
+ enum InternallyTaggedVariantWith {
+ #[allow(dead_code)]
+ Normal { f1: String },
+
+ #[serde(serialize_with = "ser_x")]
+ #[serde(deserialize_with = "de_x")]
+ #[allow(dead_code)]
+ Newtype(X),
+
+ #[serde(serialize_with = "serialize_some_other_variant")]
+ #[serde(deserialize_with = "deserialize_some_other_variant")]
+ #[allow(dead_code)]
+ Struct {
+ f1: String,
+ f2: u8,
+ },
+
+ #[serde(serialize_with = "serialize_some_unit_variant")]
+ #[serde(deserialize_with = "deserialize_some_unit_variant")]
+ #[allow(dead_code)]
+ Unit,
+ }
+ assert_ser::<InternallyTaggedVariantWith>();
+
+ #[derive(Serialize, Deserialize)]
+ #[serde(tag = "t", content = "c")]
+ enum AdjacentlyTaggedVariantWith {
+ #[allow(dead_code)]
+ Normal { f1: String },
+
+ #[serde(serialize_with = "ser_x")]
+ #[serde(deserialize_with = "de_x")]
+ #[allow(dead_code)]
+ Newtype(X),
+
+ #[serde(serialize_with = "serialize_some_other_variant")]
+ #[serde(deserialize_with = "deserialize_some_other_variant")]
+ #[allow(dead_code)]
+ Tuple(String, u8),
+
+ #[serde(serialize_with = "serialize_some_other_variant")]
+ #[serde(deserialize_with = "deserialize_some_other_variant")]
+ #[allow(dead_code)]
+ Struct {
+ f1: String,
+ f2: u8,
+ },
+
+ #[serde(serialize_with = "serialize_some_unit_variant")]
+ #[serde(deserialize_with = "deserialize_some_unit_variant")]
+ #[allow(dead_code)]
+ Unit,
+ }
+ assert_ser::<AdjacentlyTaggedVariantWith>();
+
+ #[derive(Serialize, Deserialize)]
+ #[serde(untagged)]
+ enum UntaggedVariantWith {
+ #[allow(dead_code)]
+ Normal { f1: String },
+
+ #[serde(serialize_with = "ser_x")]
+ #[serde(deserialize_with = "de_x")]
+ #[allow(dead_code)]
+ Newtype(X),
+
+ #[serde(serialize_with = "serialize_some_other_variant")]
+ #[serde(deserialize_with = "deserialize_some_other_variant")]
+ #[allow(dead_code)]
+ Tuple(String, u8),
+
+ #[serde(serialize_with = "serialize_some_other_variant")]
+ #[serde(deserialize_with = "deserialize_some_other_variant")]
+ #[allow(dead_code)]
+ Struct {
+ f1: String,
+ f2: u8,
+ },
+
+ #[serde(serialize_with = "serialize_some_unit_variant")]
+ #[serde(deserialize_with = "deserialize_some_unit_variant")]
+ #[allow(dead_code)]
+ Unit,
+ }
+ assert_ser::<UntaggedVariantWith>();
}
//////////////////////////////////////////////////////////////////////////
@@ -414,3 +532,29 @@ impl DeserializeWith for X {
unimplemented!()
}
}
+
+pub fn serialize_some_unit_variant<S>(_: S) -> StdResult<S::Ok, S::Error>
+ where S: Serializer,
+{
+ unimplemented!()
+}
+
+pub fn deserialize_some_unit_variant<'de, D>(_: D) -> StdResult<(), D::Error>
+ where D: Deserializer<'de>,
+{
+ unimplemented!()
+}
+
+pub fn serialize_some_other_variant<S>(_: &str, _: &u8, _: S) -> StdResult<S::Ok, S::Error>
+ where S: Serializer,
+{
+ unimplemented!()
+}
+
+pub fn deserialize_some_other_variant<'de, D>(_: D) -> StdResult<(String, u8), D::Error>
+ where D: Deserializer<'de>,
+{
+ unimplemented!()
+}
+
+pub fn is_zero(n: &u8) -> bool { *n == 0 }
| [
"1013"
] | serde-rs__serde-1015 | Allow de/serialize_with on enum variants
This still needs to be fleshed out some more, but the idea would be to support things like empty_struct from https://github.com/serde-rs/serde/pull/1008 implemented in user code rather than in Serde.
```rust
#[derive(Serialize)]
#[serde(tag = "t", content = "c")]
enum E {
Hello { foo: String },
// serialize as `{ "t": "World", "c": {} }`
#[serde(serialize_with = "empty_struct")]
World,
}
fn empty_struct<signature TBD> { /* ... */ }
```
| 1.0 | 0681cd50032a548f1ee060110c957997769a14b7 | diff --git a/serde_derive/src/bound.rs b/serde_derive/src/bound.rs
index 77e7824a4..0160fa85c 100644
--- a/serde_derive/src/bound.rs
+++ b/serde_derive/src/bound.rs
@@ -10,7 +10,7 @@ use std::collections::HashSet;
use syn::{self, visit};
-use internals::ast::Container;
+use internals::ast::{Body, Container};
use internals::attr;
macro_rules! path {
@@ -88,7 +88,7 @@ pub fn with_bound<F>(
bound: &syn::Path,
) -> syn::Generics
where
- F: Fn(&attr::Field) -> bool,
+ F: Fn(&attr::Field, Option<&attr::Variant>) -> bool,
{
struct FindTyParams {
// Set of all generic type parameters on the current struct (A, B, C in
@@ -124,17 +124,27 @@ where
.map(|ty_param| ty_param.ident.clone())
.collect();
- let relevant_tys = cont.body
- .all_fields()
- .filter(|&field| filter(&field.attrs))
- .map(|field| &field.ty);
-
let mut visitor = FindTyParams {
all_ty_params: all_ty_params,
relevant_ty_params: HashSet::new(),
};
- for ty in relevant_tys {
- visit::walk_ty(&mut visitor, ty);
+ match cont.body {
+ Body::Enum(ref variants) => {
+ for variant in variants.iter() {
+ let relevant_fields = variant
+ .fields
+ .iter()
+ .filter(|field| filter(&field.attrs, Some(&variant.attrs)));
+ for field in relevant_fields {
+ visit::walk_ty(&mut visitor, field.ty);
+ }
+ }
+ }
+ Body::Struct(_, ref fields) => {
+ for field in fields.iter().filter(|field| filter(&field.attrs, None)) {
+ visit::walk_ty(&mut visitor, field.ty);
+ }
+ }
}
let new_predicates = generics
diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 5ab6d0a9b..b3589f557 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -157,14 +157,17 @@ fn build_generics(cont: &Container) -> syn::Generics {
// deserialized by us so we do not generate a bound. Fields with a `bound`
// attribute specify their own bound so we do not generate one. All other fields
// may need a `T: Deserialize` bound where T is the type of the field.
-fn needs_deserialize_bound(attrs: &attr::Field) -> bool {
- !attrs.skip_deserializing() && attrs.deserialize_with().is_none() && attrs.de_bound().is_none()
+fn needs_deserialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool {
+ !field.skip_deserializing() &&
+ field.deserialize_with().is_none() &&
+ field.de_bound().is_none() &&
+ variant.map_or(true, |variant| variant.deserialize_with().is_none())
}
// Fields with a `default` attribute (not `default=...`), and fields with a
// `skip_deserializing` attribute that do not also have `default=...`.
-fn requires_default(attrs: &attr::Field) -> bool {
- attrs.default() == &attr::Default::Default
+fn requires_default(field: &attr::Field, _variant: Option<&attr::Variant>) -> bool {
+ field.default() == &attr::Default::Default
}
// The union of lifetimes borrowed by each field of the container.
@@ -372,7 +375,7 @@ fn deserialize_seq(
quote!(try!(_serde::de::SeqAccess::next_element::<#field_ty>(&mut __seq)))
}
Some(path) => {
- let (wrapper, wrapper_ty) = wrap_deserialize_with(
+ let (wrapper, wrapper_ty) = wrap_deserialize_field_with(
params, field.ty, path);
quote!({
#wrapper
@@ -428,7 +431,7 @@ fn deserialize_newtype_struct(type_path: &Tokens, params: &Parameters, field: &F
}
}
Some(path) => {
- let (wrapper, wrapper_ty) = wrap_deserialize_with(params, field.ty, path);
+ let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path);
quote!({
#wrapper
try!(<#wrapper_ty as _serde::Deserialize>::deserialize(__e)).value
@@ -1084,6 +1087,16 @@ fn deserialize_externally_tagged_variant(
variant: &Variant,
cattrs: &attr::Container,
) -> Fragment {
+ if let Some(path) = variant.attrs.deserialize_with() {
+ let (wrapper, wrapper_ty, unwrap_fn) =
+ wrap_deserialize_variant_with(params, &variant, path);
+ return quote_block! {
+ #wrapper
+ _serde::export::Result::map(
+ _serde::de::VariantAccess::newtype_variant::<#wrapper_ty>(__variant), #unwrap_fn)
+ };
+ }
+
let variant_ident = &variant.ident;
match variant.style {
@@ -1112,6 +1125,10 @@ fn deserialize_internally_tagged_variant(
cattrs: &attr::Container,
deserializer: Tokens,
) -> Fragment {
+ if variant.attrs.deserialize_with().is_some() {
+ return deserialize_untagged_variant(params, variant, cattrs, deserializer);
+ }
+
let variant_ident = &variant.ident;
match variant.style {
@@ -1137,6 +1154,16 @@ fn deserialize_untagged_variant(
cattrs: &attr::Container,
deserializer: Tokens,
) -> Fragment {
+ if let Some(path) = variant.attrs.deserialize_with() {
+ let (wrapper, wrapper_ty, unwrap_fn) =
+ wrap_deserialize_variant_with(params, &variant, path);
+ return quote_block! {
+ #wrapper
+ _serde::export::Result::map(
+ <#wrapper_ty as _serde::Deserialize>::deserialize(#deserializer), #unwrap_fn)
+ };
+ }
+
let variant_ident = &variant.ident;
match variant.style {
@@ -1198,7 +1225,7 @@ fn deserialize_externally_tagged_newtype_variant(
}
}
Some(path) => {
- let (wrapper, wrapper_ty) = wrap_deserialize_with(params, field.ty, path);
+ let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path);
quote_block! {
#wrapper
_serde::export::Result::map(
@@ -1226,7 +1253,7 @@ fn deserialize_untagged_newtype_variant(
}
}
Some(path) => {
- let (wrapper, wrapper_ty) = wrap_deserialize_with(params, field.ty, path);
+ let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path);
quote_block! {
#wrapper
_serde::export::Result::map(
@@ -1528,7 +1555,7 @@ fn deserialize_map(
}
}
Some(path) => {
- let (wrapper, wrapper_ty) = wrap_deserialize_with(
+ let (wrapper, wrapper_ty) = wrap_deserialize_field_with(
params, field.ty, path);
quote!({
#wrapper
@@ -1661,7 +1688,7 @@ fn field_i(i: usize) -> Ident {
/// in a trait to prevent it from accessing the internal `Deserialize` state.
fn wrap_deserialize_with(
params: &Parameters,
- field_ty: &syn::Ty,
+ value_ty: Tokens,
deserialize_with: &syn::Path,
) -> (Tokens, Tokens) {
let this = ¶ms.this;
@@ -1669,7 +1696,7 @@ fn wrap_deserialize_with(
let wrapper = quote! {
struct __DeserializeWith #de_impl_generics #where_clause {
- value: #field_ty,
+ value: #value_ty,
phantom: _serde::export::PhantomData<#this #ty_generics>,
lifetime: _serde::export::PhantomData<&'de ()>,
}
@@ -1692,6 +1719,68 @@ fn wrap_deserialize_with(
(wrapper, wrapper_ty)
}
+fn wrap_deserialize_field_with(
+ params: &Parameters,
+ field_ty: &syn::Ty,
+ deserialize_with: &syn::Path,
+) -> (Tokens, Tokens) {
+ wrap_deserialize_with(params, quote!(#field_ty), deserialize_with)
+}
+
+fn wrap_deserialize_variant_with(
+ params: &Parameters,
+ variant: &Variant,
+ deserialize_with: &syn::Path,
+) -> (Tokens, Tokens, Tokens) {
+ let this = ¶ms.this;
+ let variant_ident = &variant.ident;
+
+ let field_tys = variant.fields.iter().map(|field| field.ty);
+ let (wrapper, wrapper_ty) =
+ wrap_deserialize_with(params, quote!((#(#field_tys),*)), deserialize_with);
+
+ let field_access = (0..variant.fields.len()).map(|n| Ident::new(format!("{}", n)));
+ let unwrap_fn = match variant.style {
+ Style::Struct => {
+ let field_idents = variant.fields.iter().map(|field| field.ident.as_ref().unwrap());
+ quote! {
+ {
+ |__wrap| {
+ #this::#variant_ident { #(#field_idents: __wrap.value.#field_access),* }
+ }
+ }
+ }
+ }
+ Style::Tuple => {
+ quote! {
+ {
+ |__wrap| {
+ #this::#variant_ident(#(__wrap.value.#field_access),*)
+ }
+ }
+ }
+ }
+ Style::Newtype => {
+ quote! {
+ {
+ |__wrap| {
+ #this::#variant_ident(__wrap.value)
+ }
+ }
+ }
+ }
+ Style::Unit => {
+ quote! {
+ {
+ |__wrap| { #this::#variant_ident }
+ }
+ }
+ }
+ };
+
+ (wrapper, wrapper_ty, unwrap_fn)
+}
+
fn expr_is_missing(field: &Field, cattrs: &attr::Container) -> Fragment {
match *field.attrs.default() {
attr::Default::Default => {
diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index 9be9bddca..c904c45e7 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -143,12 +143,16 @@ fn build_generics(cont: &Container) -> syn::Generics {
}
}
-// Fields with a `skip_serializing` or `serialize_with` attribute are not
-// serialized by us so we do not generate a bound. Fields with a `bound`
-// attribute specify their own bound so we do not generate one. All other fields
-// may need a `T: Serialize` bound where T is the type of the field.
-fn needs_serialize_bound(attrs: &attr::Field) -> bool {
- !attrs.skip_serializing() && attrs.serialize_with().is_none() && attrs.ser_bound().is_none()
+// Fields with a `skip_serializing` or `serialize_with` attribute, or which
+// belong to a variant with a `serialize_with` attribute, are not serialized by
+// us so we do not generate a bound. Fields with a `bound` attribute specify
+// their own bound so we do not generate one. All other fields may need a `T:
+// Serialize` bound where T is the type of the field.
+fn needs_serialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool {
+ !field.skip_serializing() &&
+ field.serialize_with().is_none() &&
+ field.ser_bound().is_none() &&
+ variant.map_or(true, |variant| variant.serialize_with().is_none())
}
fn serialize_body(cont: &Container, params: &Parameters) -> Fragment {
@@ -203,7 +207,7 @@ fn serialize_newtype_struct(
let mut field_expr = get_field(params, field, 0);
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
+ field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr);
}
quote_expr! {
@@ -395,6 +399,19 @@ fn serialize_externally_tagged_variant(
let type_name = cattrs.name().serialize_name();
let variant_name = variant.attrs.name().serialize_name();
+ if let Some(path) = variant.attrs.serialize_with() {
+ let ser = wrap_serialize_variant_with(params, path, &variant);
+ return quote_expr! {
+ _serde::Serializer::serialize_newtype_variant(
+ __serializer,
+ #type_name,
+ #variant_index,
+ #variant_name,
+ #ser,
+ )
+ };
+ }
+
match variant.style {
Style::Unit => {
quote_expr! {
@@ -410,7 +427,7 @@ fn serialize_externally_tagged_variant(
let field = &variant.fields[0];
let mut field_expr = quote!(__field0);
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
+ field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr);
}
quote_expr! {
@@ -460,6 +477,20 @@ fn serialize_internally_tagged_variant(
let enum_ident_str = params.type_name();
let variant_ident_str = variant.ident.as_ref();
+ if let Some(path) = variant.attrs.serialize_with() {
+ let ser = wrap_serialize_variant_with(params, path, &variant);
+ return quote_expr! {
+ _serde::private::ser::serialize_tagged_newtype(
+ __serializer,
+ #enum_ident_str,
+ #variant_ident_str,
+ #tag,
+ #variant_name,
+ #ser,
+ )
+ };
+ }
+
match variant.style {
Style::Unit => {
quote_block! {
@@ -474,7 +505,7 @@ fn serialize_internally_tagged_variant(
let field = &variant.fields[0];
let mut field_expr = quote!(__field0);
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
+ field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr);
}
quote_expr! {
@@ -515,44 +546,57 @@ fn serialize_adjacently_tagged_variant(
let variant_name = variant.attrs.name().serialize_name();
let inner = Stmts(
- match variant.style {
- Style::Unit => {
- return quote_block! {
- let mut __struct = try!(_serde::Serializer::serialize_struct(
- __serializer, #type_name, 1));
- try!(_serde::ser::SerializeStruct::serialize_field(
- &mut __struct, #tag, #variant_name));
- _serde::ser::SerializeStruct::end(__struct)
- };
+ if let Some(path) = variant.attrs.serialize_with() {
+ let ser = wrap_serialize_variant_with(params, path, &variant);
+ quote_expr! {
+ _serde::Serialize::serialize(#ser, __serializer)
}
- Style::Newtype => {
- let field = &variant.fields[0];
- let mut field_expr = quote!(__field0);
- if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
+ } else {
+ match variant.style {
+ Style::Unit => {
+ return quote_block! {
+ let mut __struct = try!(_serde::Serializer::serialize_struct(
+ __serializer, #type_name, 1));
+ try!(_serde::ser::SerializeStruct::serialize_field(
+ &mut __struct, #tag, #variant_name));
+ _serde::ser::SerializeStruct::end(__struct)
+ };
}
+ Style::Newtype => {
+ let field = &variant.fields[0];
+ let mut field_expr = quote!(__field0);
+ if let Some(path) = field.attrs.serialize_with() {
+ field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr);
+ }
- quote_expr! {
- _serde::Serialize::serialize(#field_expr, __serializer)
+ quote_expr! {
+ _serde::Serialize::serialize(#field_expr, __serializer)
+ }
+ }
+ Style::Tuple => {
+ serialize_tuple_variant(TupleVariant::Untagged, params, &variant.fields)
+ }
+ Style::Struct => {
+ serialize_struct_variant(
+ StructVariant::Untagged,
+ params,
+ &variant.fields,
+ &variant_name,
+ )
}
- }
- Style::Tuple => {
- serialize_tuple_variant(TupleVariant::Untagged, params, &variant.fields)
- }
- Style::Struct => {
- serialize_struct_variant(
- StructVariant::Untagged,
- params,
- &variant.fields,
- &variant_name,
- )
}
},
);
let fields_ty = variant.fields.iter().map(|f| &f.ty);
let ref fields_ident: Vec<_> = match variant.style {
- Style::Unit => unreachable!(),
+ Style::Unit => {
+ if variant.attrs.serialize_with().is_some() {
+ vec![]
+ } else {
+ unreachable!()
+ }
+ }
Style::Newtype => vec![Ident::new("__field0")],
Style::Tuple => {
(0..variant.fields.len())
@@ -576,7 +620,11 @@ fn serialize_adjacently_tagged_variant(
let (_, ty_generics, where_clause) = params.generics.split_for_impl();
- let wrapper_generics = bound::with_lifetime_bound(¶ms.generics, "'__a");
+ let wrapper_generics = if let Style::Unit = variant.style {
+ params.generics.clone()
+ } else {
+ bound::with_lifetime_bound(¶ms.generics, "'__a")
+ };
let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl();
quote_block! {
@@ -612,6 +660,13 @@ fn serialize_untagged_variant(
variant: &Variant,
cattrs: &attr::Container,
) -> Fragment {
+ if let Some(path) = variant.attrs.serialize_with() {
+ let ser = wrap_serialize_variant_with(params, path, &variant);
+ return quote_expr! {
+ _serde::Serialize::serialize(#ser, __serializer)
+ };
+ }
+
match variant.style {
Style::Unit => {
quote_expr! {
@@ -622,7 +677,7 @@ fn serialize_untagged_variant(
let field = &variant.fields[0];
let mut field_expr = quote!(__field0);
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
+ field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr);
}
quote_expr! {
@@ -808,7 +863,7 @@ fn serialize_tuple_struct_visitor(
.map(|path| quote!(#path(#field_expr)));
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(params, field.ty, path, field_expr);
+ field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr);
}
let ser = quote! {
@@ -850,7 +905,7 @@ fn serialize_struct_visitor(
.map(|path| quote!(#path(#field_expr)));
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(params, field.ty, path, field_expr)
+ field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr);
}
let ser = quote! {
@@ -866,21 +921,56 @@ fn serialize_struct_visitor(
.collect()
}
-fn wrap_serialize_with(
+fn wrap_serialize_field_with(
params: &Parameters,
field_ty: &syn::Ty,
serialize_with: &syn::Path,
- value: Tokens,
+ field_expr: Tokens,
+) -> Tokens {
+ wrap_serialize_with(params,
+ serialize_with,
+ &[field_ty],
+ &[quote!(#field_expr)])
+}
+
+fn wrap_serialize_variant_with(
+ params: &Parameters,
+ serialize_with: &syn::Path,
+ variant: &Variant,
+) -> Tokens {
+ let field_tys: Vec<_> = variant.fields.iter().map(|field| field.ty).collect();
+ let field_exprs: Vec<_> = variant.fields.iter()
+ .enumerate()
+ .map(|(i, field)| {
+ let id = field.ident.as_ref().map_or_else(|| Ident::new(format!("__field{}", i)),
+ |id| id.clone());
+ quote!(#id)
+ })
+ .collect();
+ wrap_serialize_with(params, serialize_with, field_tys.as_slice(), field_exprs.as_slice())
+}
+
+fn wrap_serialize_with(
+ params: &Parameters,
+ serialize_with: &syn::Path,
+ field_tys: &[&syn::Ty],
+ field_exprs: &[Tokens],
) -> Tokens {
let this = ¶ms.this;
let (_, ty_generics, where_clause) = params.generics.split_for_impl();
- let wrapper_generics = bound::with_lifetime_bound(¶ms.generics, "'__a");
+ let wrapper_generics = if field_exprs.len() == 0 {
+ params.generics.clone()
+ } else {
+ bound::with_lifetime_bound(¶ms.generics, "'__a")
+ };
let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl();
+ let field_access = (0..field_exprs.len()).map(|n| Ident::new(format!("{}", n)));
+
quote!({
struct __SerializeWith #wrapper_impl_generics #where_clause {
- value: &'__a #field_ty,
+ values: (#(&'__a #field_tys, )*),
phantom: _serde::export::PhantomData<#this #ty_generics>,
}
@@ -888,12 +978,12 @@ fn wrap_serialize_with(
fn serialize<__S>(&self, __s: __S) -> _serde::export::Result<__S::Ok, __S::Error>
where __S: _serde::Serializer
{
- #serialize_with(self.value, __s)
+ #serialize_with(#(self.values.#field_access, )* __s)
}
}
&__SerializeWith {
- value: #value,
+ values: (#(#field_exprs, )*),
phantom: _serde::export::PhantomData::<#this #ty_generics>,
}
})
diff --git a/serde_derive_internals/src/attr.rs b/serde_derive_internals/src/attr.rs
index caf306cfa..2803da9d7 100644
--- a/serde_derive_internals/src/attr.rs
+++ b/serde_derive_internals/src/attr.rs
@@ -510,6 +510,8 @@ pub struct Variant {
skip_deserializing: bool,
skip_serializing: bool,
other: bool,
+ serialize_with: Option<syn::Path>,
+ deserialize_with: Option<syn::Path>,
}
impl Variant {
@@ -520,6 +522,8 @@ impl Variant {
let mut skip_serializing = BoolAttr::none(cx, "skip_serializing");
let mut rename_all = Attr::none(cx, "rename_all");
let mut other = BoolAttr::none(cx, "other");
+ let mut serialize_with = Attr::none(cx, "serialize_with");
+ let mut deserialize_with = Attr::none(cx, "deserialize_with");
for meta_items in variant.attrs.iter().filter_map(get_serde_meta_items) {
for meta_item in meta_items {
@@ -569,6 +573,20 @@ impl Variant {
other.set_true();
}
+ // Parse `#[serde(serialize_with = "...")]`
+ MetaItem(NameValue(ref name, ref lit)) if name == "serialize_with" => {
+ if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
+ serialize_with.set(path);
+ }
+ }
+
+ // Parse `#[serde(deserialize_with = "...")]`
+ MetaItem(NameValue(ref name, ref lit)) if name == "deserialize_with" => {
+ if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
+ deserialize_with.set(path);
+ }
+ }
+
MetaItem(ref meta_item) => {
cx.error(format!("unknown serde variant attribute `{}`", meta_item.name()));
}
@@ -595,6 +613,8 @@ impl Variant {
skip_deserializing: skip_deserializing.get(),
skip_serializing: skip_serializing.get(),
other: other.get(),
+ serialize_with: serialize_with.get(),
+ deserialize_with: deserialize_with.get(),
}
}
@@ -626,6 +646,14 @@ impl Variant {
pub fn other(&self) -> bool {
self.other
}
+
+ pub fn serialize_with(&self) -> Option<&syn::Path> {
+ self.serialize_with.as_ref()
+ }
+
+ pub fn deserialize_with(&self) -> Option<&syn::Path> {
+ self.deserialize_with.as_ref()
+ }
}
/// Represents field attribute information
diff --git a/serde_derive_internals/src/check.rs b/serde_derive_internals/src/check.rs
index 84c958ea9..5d6a76ff8 100644
--- a/serde_derive_internals/src/check.rs
+++ b/serde_derive_internals/src/check.rs
@@ -15,6 +15,7 @@ use Ctxt;
pub fn check(cx: &Ctxt, cont: &Container) {
check_getter(cx, cont);
check_identifier(cx, cont);
+ check_variant_skip_attrs(cx, cont);
}
/// Getters are only allowed inside structs (not enums) with the `remote`
@@ -94,3 +95,58 @@ fn check_identifier(cx: &Ctxt, cont: &Container) {
}
}
}
+
+/// Skip-(de)serializing attributes are not allowed on variants marked
+/// (de)serialize_with.
+fn check_variant_skip_attrs(cx: &Ctxt, cont: &Container) {
+ let variants = match cont.body {
+ Body::Enum(ref variants) => variants,
+ Body::Struct(_, _) => {
+ return;
+ }
+ };
+
+ for variant in variants.iter() {
+ if variant.attrs.serialize_with().is_some() {
+ if variant.attrs.skip_serializing() {
+ cx.error(format!("variant `{}` cannot have both #[serde(serialize_with)] and \
+ #[serde(skip_serializing)]", variant.ident));
+ }
+
+ for (i, field) in variant.fields.iter().enumerate() {
+ let ident = field.ident.as_ref().map_or_else(|| format!("{}", i),
+ |ident| format!("`{}`", ident));
+
+ if field.attrs.skip_serializing() {
+ cx.error(format!("variant `{}` cannot have both #[serde(serialize_with)] and \
+ a field {} marked with #[serde(skip_serializing)]",
+ variant.ident, ident));
+ }
+
+ if field.attrs.skip_serializing_if().is_some() {
+ cx.error(format!("variant `{}` cannot have both #[serde(serialize_with)] and \
+ a field {} marked with #[serde(skip_serializing_if)]",
+ variant.ident, ident));
+ }
+ }
+ }
+
+ if variant.attrs.deserialize_with().is_some() {
+ if variant.attrs.skip_deserializing() {
+ cx.error(format!("variant `{}` cannot have both #[serde(deserialize_with)] and \
+ #[serde(skip_deserializing)]", variant.ident));
+ }
+
+ for (i, field) in variant.fields.iter().enumerate() {
+ if field.attrs.skip_deserializing() {
+ let ident = field.ident.as_ref().map_or_else(|| format!("{}", i),
+ |ident| format!("`{}`", ident));
+
+ cx.error(format!("variant `{}` cannot have both #[serde(deserialize_with)] \
+ and a field {} marked with #[serde(skip_deserializing)]",
+ variant.ident, ident));
+ }
+ }
+ }
+ }
+}
| serde-rs/serde | 2017-08-08T02:10:34Z | @spinda may be interested in working on a design.
I would like to propose the following ("design A"):
```rust
#[derive(Serialize, Deserialize)]
#[serde(tag = "t", content = "c")]
enum E {
// normal variant (de)serialization
Hello { world: String },
// (de)serialize_with can be used to add special behavior to variants;
// for tuple structs, each inner value is passed in order to the serialize
// function, and the deserialize function produces a tuple (see below)
#[serde(serialize_with = "my_special_serializer")]
#[serde(deserialize_with = "my_special_deserializer")]
Quux(String, u8),
// struct variants are also supported, and are treated in the same way as
// tuple variants, with inner values ordered by how they appear in the
// definition
#[serde(serialize_with = "my_special_serializer")]
#[serde(deserialize_with = "my_special_deserializer")]
Xyzzy {
foo: String,
bar: u8,
},
// for unit variants, the serialize function is passed only the serializer,
// and the deserialize function is expected to produce ()
#[serde(serialize_with = "serialize_empty_struct")]
#[serde(deserialize_with = "deserialize_empty_struct")]
Baz,
}
fn my_special_serializer<S>(foo: &String, bar: &u8, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
unimplemented!()
}
fn my_special_deserializer<'de, D>(deserializer: D) -> Result<(String, u8), D::Error>
where D: Deserializer<'de>,
{
unimplemented!()
}
fn serialize_empty_struct<S>(serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
unimplemented!()
}
fn deserialize_empty_struct<'de, D>(deserializer: D) -> Result<(), D::Error>
where D: Deserializer<'de>,
{
unimplemented!()
}
```
The alternative, I believe, would be to pass the enumeration type in as a single argument to the serialize function and expect it as the output of the deserialize function ("design B"). Compared:
- Design A has the drawback of requiring long type signatures for variants with a lot of fields/inner types, while design B couldn't result in that situation. This could be avoided under design A by turning such a variant into a newtype variant wrapping around a separately-defined freestanding struct type. One might call this good practice in general, as variants that are so long they easily be pattern-matched are harder to manipulate elsewhere.
- If your (de)serialize functions only need to apply to one variant in an enum, Design B requires matching on the enum type and then either panicking or emitting an error on the alternate cases to make the totality checker happy. Design A avoids this.
- The simple fact that Design B would allow for producing a *different* variant of the enum type than the one which was annotated with `deserialize_with` seems ripe for confusion in my mind.
- Design A is more flexible with regard to reusability of the (de)serialize functions. For example, a single implementation of (de)serialize_empty_struct could be reused across multiple variants and multiple enum types. Design B requires that such functions be tied to a specific enum type and, in the case of deserializing, a specific variant of that enum: if multiple variants of your enum need the empty_struct behavior, a single deserialize function couldn't know which variant to produce.
Sounds good to me. I agree with all of your points and design A seems like a good path forward. | 4cea81f93f12473e0ccbdad2ddecff1f7ea85402 |
839 | diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index 8d21844cc..552e58cb7 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -245,18 +245,6 @@ declare_tests! {
}
test_unit {
() => &[Token::Unit],
- () => &[
- Token::SeqStart(Some(0)),
- Token::SeqEnd,
- ],
- () => &[
- Token::SeqStart(None),
- Token::SeqEnd,
- ],
- () => &[
- Token::TupleStructStart("Anything", 0),
- Token::TupleStructEnd,
- ],
}
test_unit_struct {
UnitStruct => &[Token::Unit],
@@ -272,9 +260,6 @@ declare_tests! {
Token::SeqEnd,
],
}
- test_unit_string {
- String::new() => &[Token::Unit],
- }
test_tuple_struct {
TupleStruct(1, 2, 3) => &[
Token::SeqStart(Some(3)),
@@ -326,9 +311,6 @@ declare_tests! {
],
}
test_btreeset {
- BTreeSet::<isize>::new() => &[
- Token::Unit,
- ],
BTreeSet::<isize>::new() => &[
Token::SeqStart(Some(0)),
Token::SeqEnd,
@@ -355,18 +337,12 @@ declare_tests! {
Token::SeqEnd,
Token::SeqEnd,
],
- BTreeSet::<isize>::new() => &[
- Token::UnitStruct("Anything"),
- ],
BTreeSet::<isize>::new() => &[
Token::TupleStructStart("Anything", 0),
Token::TupleStructEnd,
],
}
test_hashset {
- HashSet::<isize>::new() => &[
- Token::Unit,
- ],
HashSet::<isize>::new() => &[
Token::SeqStart(Some(0)),
Token::SeqEnd,
@@ -383,9 +359,6 @@ declare_tests! {
Token::I32(3),
Token::SeqEnd,
],
- HashSet::<isize>::new() => &[
- Token::UnitStruct("Anything"),
- ],
HashSet::<isize>::new() => &[
Token::TupleStructStart("Anything", 0),
Token::TupleStructEnd,
@@ -404,9 +377,6 @@ declare_tests! {
],
}
test_vec {
- Vec::<isize>::new() => &[
- Token::Unit,
- ],
Vec::<isize>::new() => &[
Token::SeqStart(Some(0)),
Token::SeqEnd,
@@ -433,18 +403,12 @@ declare_tests! {
Token::SeqEnd,
Token::SeqEnd,
],
- Vec::<isize>::new() => &[
- Token::UnitStruct("Anything"),
- ],
Vec::<isize>::new() => &[
Token::TupleStructStart("Anything", 0),
Token::TupleStructEnd,
],
}
test_array {
- [0; 0] => &[
- Token::Unit,
- ],
[0; 0] => &[
Token::SeqStart(Some(0)),
Token::SeqEnd,
@@ -497,9 +461,6 @@ declare_tests! {
Token::SeqEnd,
Token::SeqEnd,
],
- [0; 0] => &[
- Token::UnitStruct("Anything"),
- ],
[0; 0] => &[
Token::TupleStructStart("Anything", 0),
Token::TupleStructEnd,
@@ -544,9 +505,6 @@ declare_tests! {
],
}
test_btreemap {
- BTreeMap::<isize, isize>::new() => &[
- Token::Unit,
- ],
BTreeMap::<isize, isize>::new() => &[
Token::MapStart(Some(0)),
Token::MapEnd,
@@ -589,18 +547,12 @@ declare_tests! {
Token::MapEnd,
Token::MapEnd,
],
- BTreeMap::<isize, isize>::new() => &[
- Token::UnitStruct("Anything"),
- ],
BTreeMap::<isize, isize>::new() => &[
Token::StructStart("Anything", 0),
Token::StructEnd,
],
}
test_hashmap {
- HashMap::<isize, isize>::new() => &[
- Token::Unit,
- ],
HashMap::<isize, isize>::new() => &[
Token::MapStart(Some(0)),
Token::MapEnd,
@@ -643,9 +595,6 @@ declare_tests! {
Token::MapEnd,
Token::MapEnd,
],
- HashMap::<isize, isize>::new() => &[
- Token::UnitStruct("Anything"),
- ],
HashMap::<isize, isize>::new() => &[
Token::StructStart("Anything", 0),
Token::StructEnd,
@@ -1119,4 +1068,115 @@ declare_error_tests! {
],
Error::Message("nul byte found in provided data at position: 2".into()),
}
+ test_unit_from_empty_seq<()> {
+ &[
+ Token::SeqStart(Some(0)),
+ Token::SeqEnd,
+ ],
+ Error::Message("invalid type: sequence, expected unit".into()),
+ }
+ test_unit_from_empty_seq_without_len<()> {
+ &[
+ Token::SeqStart(None),
+ Token::SeqEnd,
+ ],
+ Error::Message("invalid type: sequence, expected unit".into()),
+ }
+ test_unit_from_tuple_struct<()> {
+ &[
+ Token::TupleStructStart("Anything", 0),
+ Token::TupleStructEnd,
+ ],
+ Error::Message("invalid type: sequence, expected unit".into()),
+ }
+ test_string_from_unit<String> {
+ &[
+ Token::Unit,
+ ],
+ Error::Message("invalid type: unit value, expected a string".into()),
+ }
+ test_btreeset_from_unit<BTreeSet<isize>> {
+ &[
+ Token::Unit,
+ ],
+ Error::Message("invalid type: unit value, expected a sequence".into()),
+ }
+ test_btreeset_from_unit_struct<BTreeSet<isize>> {
+ &[
+ Token::UnitStruct("Anything"),
+ ],
+ Error::Message("invalid type: unit value, expected a sequence".into()),
+ }
+ test_hashset_from_unit<HashSet<isize>> {
+ &[
+ Token::Unit,
+ ],
+ Error::Message("invalid type: unit value, expected a sequence".into()),
+ }
+ test_hashset_from_unit_struct<HashSet<isize>> {
+ &[
+ Token::UnitStruct("Anything"),
+ ],
+ Error::Message("invalid type: unit value, expected a sequence".into()),
+ }
+ test_vec_from_unit<Vec<isize>> {
+ &[
+ Token::Unit,
+ ],
+ Error::Message("invalid type: unit value, expected a sequence".into()),
+ }
+ test_vec_from_unit_struct<Vec<isize>> {
+ &[
+ Token::UnitStruct("Anything"),
+ ],
+ Error::Message("invalid type: unit value, expected a sequence".into()),
+ }
+ test_zero_array_from_unit<[isize; 0]> {
+ &[
+ Token::Unit,
+ ],
+ Error::Message("invalid type: unit value, expected an empty array".into()),
+ }
+ test_zero_array_from_unit_struct<[isize; 0]> {
+ &[
+ Token::UnitStruct("Anything"),
+ ],
+ Error::Message("invalid type: unit value, expected an empty array".into()),
+ }
+ test_btreemap_from_unit<BTreeMap<isize, isize>> {
+ &[
+ Token::Unit,
+ ],
+ Error::Message("invalid type: unit value, expected a map".into()),
+ }
+ test_btreemap_from_unit_struct<BTreeMap<isize, isize>> {
+ &[
+ Token::UnitStruct("Anything"),
+ ],
+ Error::Message("invalid type: unit value, expected a map".into()),
+ }
+ test_hashmap_from_unit<HashMap<isize, isize>> {
+ &[
+ Token::Unit,
+ ],
+ Error::Message("invalid type: unit value, expected a map".into()),
+ }
+ test_hashmap_from_unit_struct<HashMap<isize, isize>> {
+ &[
+ Token::UnitStruct("Anything"),
+ ],
+ Error::Message("invalid type: unit value, expected a map".into()),
+ }
+ test_bool_from_string<bool> {
+ &[
+ Token::Str("false"),
+ ],
+ Error::Message("invalid type: string \"false\", expected a boolean".into()),
+ }
+ test_number_from_string<isize> {
+ &[
+ Token::Str("1"),
+ ],
+ Error::Message("invalid type: string \"1\", expected isize".into()),
+ }
}
| [
"836"
] | serde-rs__serde-839 | Audit type conversions
The standard I would like to set is that if Serde successfully deserializes some input into a particular struct, you can be confident that the input matches what your struct says it should look like.
Currently there are conversions that I think violate this, for example deserializing strings and collections from unit:
```rust
#[derive(Deserialize)]
struct Bad {
s: String
}
serde_json::from_str::<Bad>("{\"s\":null}").unwrap();
```
To me, null in the input means you should have used Option\<String> or a deserialize_with function that treats null as default.
Let's go through and critically evaluate all of the type conversions that are being done and eliminate these confusing ones.
| 0.9 | 92bc23e484841554f1715825989df32ae9eedc82 | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 9b6f1f5dd..1aa91db50 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -80,12 +80,6 @@ impl<'de> Visitor<'de> for UnitVisitor {
{
Ok(())
}
-
- fn visit_seq<V>(self, _: V) -> Result<(), V::Error>
- where V: SeqVisitor<'de>
- {
- Ok(())
- }
}
impl<'de> Deserialize<'de> for () {
@@ -113,16 +107,6 @@ impl<'de> Visitor<'de> for BoolVisitor {
{
Ok(v)
}
-
- fn visit_str<E>(self, s: &str) -> Result<bool, E>
- where E: Error
- {
- match s.trim_matches(::utils::Pattern_White_Space) {
- "true" => Ok(true),
- "false" => Ok(false),
- _ => Err(Error::invalid_type(Unexpected::Str(s), &self)),
- }
- }
}
impl<'de> Deserialize<'de> for bool {
@@ -175,15 +159,6 @@ macro_rules! impl_deserialize_num {
impl_deserialize_num_method!($ty, u64, visit_u64, from_u64, Unsigned, u64);
impl_deserialize_num_method!($ty, f32, visit_f32, from_f32, Float, f64);
impl_deserialize_num_method!($ty, f64, visit_f64, from_f64, Float, f64);
-
- #[inline]
- fn visit_str<E>(self, s: &str) -> Result<$ty, E>
- where E: Error,
- {
- str::FromStr::from_str(s.trim_matches(::utils::Pattern_White_Space)).or_else(|_| {
- Err(Error::invalid_type(Unexpected::Str(s), &self))
- })
- }
}
deserializer.$method(PrimitiveVisitor)
@@ -269,12 +244,6 @@ impl<'de> Visitor<'de> for StringVisitor {
Ok(v)
}
- fn visit_unit<E>(self) -> Result<String, E>
- where E: Error
- {
- Ok(String::new())
- }
-
fn visit_bytes<E>(self, v: &[u8]) -> Result<String, E>
where E: Error
{
@@ -503,13 +472,6 @@ macro_rules! seq_impl {
formatter.write_str("a sequence")
}
- #[inline]
- fn visit_unit<E>(self) -> Result<Self::Value, E>
- where E: Error,
- {
- Ok($ctor)
- }
-
#[inline]
fn visit_seq<V>(self, mut $visitor: V) -> Result<Self::Value, V::Error>
where V: SeqVisitor<'de>,
@@ -613,13 +575,6 @@ impl<'de, T> Visitor<'de> for ArrayVisitor<[T; 0]>
formatter.write_str("an empty array")
}
- #[inline]
- fn visit_unit<E>(self) -> Result<[T; 0], E>
- where E: Error
- {
- Ok([])
- }
-
#[inline]
fn visit_seq<V>(self, _: V) -> Result<[T; 0], V::Error>
where V: SeqVisitor<'de>
@@ -819,13 +774,6 @@ macro_rules! map_impl {
formatter.write_str("a map")
}
- #[inline]
- fn visit_unit<E>(self) -> Result<Self::Value, E>
- where E: Error,
- {
- Ok($ctor)
- }
-
#[inline]
fn visit_map<Visitor>(self, mut $visitor: Visitor) -> Result<Self::Value, Visitor::Error>
where Visitor: MapVisitor<'de>,
diff --git a/serde/src/utils.rs b/serde/src/utils.rs
index 927d1256a..4e81616ad 100644
--- a/serde/src/utils.rs
+++ b/serde/src/utils.rs
@@ -48,27 +48,3 @@ impl EncodeUtf8 {
::core::str::from_utf8(&self.buf[self.pos..]).unwrap()
}
}
-
-#[allow(non_upper_case_globals)]
-const Pattern_White_Space_table: &'static [(char, char)] = &[('\u{9}', '\u{d}'),
- ('\u{20}', '\u{20}'),
- ('\u{85}', '\u{85}'),
- ('\u{200e}', '\u{200f}'),
- ('\u{2028}', '\u{2029}')];
-
-fn bsearch_range_table(c: char, r: &'static [(char, char)]) -> bool {
- use core::cmp::Ordering::{Equal, Less, Greater};
- r.binary_search_by(|&(lo, hi)| if c < lo {
- Greater
- } else if hi < c {
- Less
- } else {
- Equal
- })
- .is_ok()
-}
-
-#[allow(non_snake_case)]
-pub fn Pattern_White_Space(c: char) -> bool {
- bsearch_range_table(c, Pattern_White_Space_table)
-}
| serde-rs/serde | 2017-04-05T01:33:44Z | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 | |
837 | diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index b2d6dd127..2ec45f464 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -105,8 +105,10 @@ impl<'de, 'a, I> de::Deserializer<'de> for &'a mut Deserializer<I>
Some(Token::F64(v)) => visitor.visit_f64(v),
Some(Token::Char(v)) => visitor.visit_char(v),
Some(Token::Str(v)) => visitor.visit_str(v),
+ Some(Token::BorrowedStr(v)) => visitor.visit_borrowed_str(v),
Some(Token::String(v)) => visitor.visit_string(v),
Some(Token::Bytes(v)) => visitor.visit_bytes(v),
+ Some(Token::BorrowedBytes(v)) => visitor.visit_borrowed_bytes(v),
Some(Token::ByteBuf(v)) => visitor.visit_byte_buf(v),
Some(Token::Option(false)) => visitor.visit_none(),
Some(Token::Option(true)) => visitor.visit_some(self),
diff --git a/serde_test/src/token.rs b/serde_test/src/token.rs
index 82ccd9f2c..05e15583a 100644
--- a/serde_test/src/token.rs
+++ b/serde_test/src/token.rs
@@ -39,12 +39,18 @@ pub enum Token<'a> {
/// A serialized `str`.
Str(&'a str),
+ /// A borrowed `str`.
+ BorrowedStr(&'a str),
+
/// A serialized `String`.
String(String),
/// A serialized `[u8]`
Bytes(&'a [u8]),
+ /// A borrowed `[u8]`.
+ BorrowedBytes(&'a [u8]),
+
/// A serialized `ByteBuf`
ByteBuf(Vec<u8>),
diff --git a/test_suite/tests/compile-fail/borrow/bad_lifetimes.rs b/test_suite/tests/compile-fail/borrow/bad_lifetimes.rs
new file mode 100644
index 000000000..b4a5e4a38
--- /dev/null
+++ b/test_suite/tests/compile-fail/borrow/bad_lifetimes.rs
@@ -0,0 +1,10 @@
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+struct Test<'a> {
+ #[serde(borrow = "zzz")] //~^^ HELP: failed to parse borrowed lifetimes: "zzz"
+ s: &'a str,
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/borrow/duplicate_lifetime.rs b/test_suite/tests/compile-fail/borrow/duplicate_lifetime.rs
new file mode 100644
index 000000000..542ddc2a7
--- /dev/null
+++ b/test_suite/tests/compile-fail/borrow/duplicate_lifetime.rs
@@ -0,0 +1,10 @@
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+struct Test<'a> {
+ #[serde(borrow = "'a + 'a")] //~^^ HELP: duplicate borrowed lifetime `'a`
+ s: &'a str,
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/borrow/empty_lifetimes.rs b/test_suite/tests/compile-fail/borrow/empty_lifetimes.rs
new file mode 100644
index 000000000..c1d43b579
--- /dev/null
+++ b/test_suite/tests/compile-fail/borrow/empty_lifetimes.rs
@@ -0,0 +1,10 @@
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+struct Test<'a> {
+ #[serde(borrow = "")] //~^^ HELP: at least one lifetime must be borrowed
+ s: &'a str,
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/borrow/no_lifetimes.rs b/test_suite/tests/compile-fail/borrow/no_lifetimes.rs
new file mode 100644
index 000000000..47b3c0d47
--- /dev/null
+++ b/test_suite/tests/compile-fail/borrow/no_lifetimes.rs
@@ -0,0 +1,10 @@
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+struct Test {
+ #[serde(borrow)] //~^^ HELP: field `s` has no lifetimes to borrow
+ s: String,
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/borrow/wrong_lifetime.rs b/test_suite/tests/compile-fail/borrow/wrong_lifetime.rs
new file mode 100644
index 000000000..5cf8999fa
--- /dev/null
+++ b/test_suite/tests/compile-fail/borrow/wrong_lifetime.rs
@@ -0,0 +1,10 @@
+#[macro_use]
+extern crate serde_derive;
+
+#[derive(Deserialize)] //~ ERROR: proc-macro derive panicked
+struct Test<'a> {
+ #[serde(borrow = "'b")] //~^^ HELP: field `s` does not have lifetime 'b
+ s: &'a str,
+}
+
+fn main() {}
diff --git a/test_suite/tests/compile-fail/str_ref_deser.rs b/test_suite/tests/compile-fail/str_ref_deser.rs
deleted file mode 100644
index 51f03f5c7..000000000
--- a/test_suite/tests/compile-fail/str_ref_deser.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-#[macro_use]
-extern crate serde_derive;
-
-#[derive(Serialize, Deserialize)] //~ ERROR: proc-macro derive panicked
-struct Test<'a> {
- s: &'a str, //~^^ HELP: Serde does not support deserializing fields of type &str
-}
-
-fn main() {}
diff --git a/test_suite/tests/test_borrow.rs b/test_suite/tests/test_borrow.rs
new file mode 100644
index 000000000..dd75f70b2
--- /dev/null
+++ b/test_suite/tests/test_borrow.rs
@@ -0,0 +1,199 @@
+#[macro_use]
+extern crate serde_derive;
+
+extern crate serde;
+use serde::{Deserialize, Deserializer};
+
+extern crate serde_test;
+use serde_test::{
+ Error,
+ Token,
+ assert_de_tokens,
+ assert_de_tokens_error,
+};
+
+use std::borrow::Cow;
+
+#[test]
+fn test_borrowed_str() {
+ assert_de_tokens(
+ &"borrowed",
+ &[
+ Token::BorrowedStr("borrowed"),
+ ]
+ );
+}
+
+#[test]
+fn test_borrowed_str_from_string() {
+ assert_de_tokens_error::<&str>(
+ &[
+ Token::String("borrowed".to_owned()),
+ ],
+ Error::Message("invalid type: string \"borrowed\", expected a borrowed string".to_owned()),
+ );
+}
+
+#[test]
+fn test_borrowed_str_from_str() {
+ assert_de_tokens_error::<&str>(
+ &[
+ Token::Str("borrowed"),
+ ],
+ Error::Message("invalid type: string \"borrowed\", expected a borrowed string".to_owned()),
+ );
+}
+
+#[test]
+fn test_string_from_borrowed_str() {
+ assert_de_tokens(
+ &"owned".to_owned(),
+ &[
+ Token::BorrowedStr("owned"),
+ ]
+ );
+}
+
+#[test]
+fn test_borrowed_bytes() {
+ assert_de_tokens(
+ &&b"borrowed"[..],
+ &[
+ Token::BorrowedBytes(b"borrowed"),
+ ]
+ );
+}
+
+#[test]
+fn test_borrowed_bytes_from_bytebuf() {
+ assert_de_tokens_error::<&[u8]>(
+ &[
+ Token::ByteBuf(b"borrowed".to_vec()),
+ ],
+ Error::Message("invalid type: byte array, expected a borrowed byte array".to_owned()),
+ );
+}
+
+#[test]
+fn test_borrowed_bytes_from_bytes() {
+ assert_de_tokens_error::<&[u8]>(
+ &[
+ Token::Bytes(b"borrowed"),
+ ],
+ Error::Message("invalid type: byte array, expected a borrowed byte array".to_owned()),
+ );
+}
+
+#[test]
+fn test_tuple() {
+ assert_de_tokens(
+ &("str", &b"bytes"[..]),
+ &[
+ Token::TupleStart(2),
+
+ Token::TupleSep,
+ Token::BorrowedStr("str"),
+
+ Token::TupleSep,
+ Token::BorrowedBytes(b"bytes"),
+
+ Token::TupleEnd,
+ ]
+ );
+}
+
+#[test]
+fn test_struct() {
+ #[derive(Deserialize, Debug, PartialEq)]
+ struct Borrowing<'a, 'b> {
+ bs: &'a str,
+ bb: &'b [u8],
+ }
+
+ assert_de_tokens(
+ &Borrowing { bs: "str", bb: b"bytes" },
+ &[
+ Token::StructStart("Borrowing", 2),
+
+ Token::StructSep,
+ Token::BorrowedStr("bs"),
+ Token::BorrowedStr("str"),
+
+ Token::StructSep,
+ Token::BorrowedStr("bb"),
+ Token::BorrowedBytes(b"bytes"),
+
+ Token::StructEnd,
+ ]
+ );
+}
+
+#[test]
+fn test_cow() {
+ #[derive(Deserialize)]
+ struct Cows<'a, 'b> {
+ copied: Cow<'a, str>,
+
+ #[serde(borrow)]
+ borrowed: Cow<'b, str>,
+ }
+
+ let tokens = vec![
+ Token::StructStart("Cows", 2),
+
+ Token::StructSep,
+ Token::Str("copied"),
+ Token::BorrowedStr("copied"),
+
+ Token::StructSep,
+ Token::Str("borrowed"),
+ Token::BorrowedStr("borrowed"),
+
+ Token::StructEnd,
+ ];
+
+ let mut de = serde_test::Deserializer::new(tokens.into_iter());
+ let cows = Cows::deserialize(&mut de).unwrap();
+ assert_eq!(de.next_token(), None);
+
+ match cows.copied {
+ Cow::Owned(ref s) if s == "copied" => {}
+ _ => panic!("expected a copied string"),
+ }
+
+ match cows.borrowed {
+ Cow::Borrowed("borrowed") => {}
+ _ => panic!("expected a borrowed string"),
+ }
+}
+
+#[test]
+fn test_lifetimes() {
+ #[derive(Deserialize)]
+ struct Cows<'a, 'b> {
+ _copied: Cow<'a, str>,
+
+ #[serde(borrow)]
+ _borrowed: Cow<'b, str>,
+ }
+
+ // Tests that `'de: 'a` is not required by the Deserialize impl.
+ fn _cows_lifetimes<'de: 'b, 'a, 'b, D>(deserializer: D) -> Cows<'a, 'b>
+ where D: Deserializer<'de>
+ {
+ Deserialize::deserialize(deserializer).unwrap()
+ }
+
+ #[derive(Deserialize)]
+ struct Wrap<'a, 'b> {
+ #[serde(borrow = "'b")]
+ _cows: Cows<'a, 'b>,
+ }
+
+ // Tests that `'de: 'a` is not required by the Deserialize impl.
+ fn _wrap_lifetimes<'de: 'b, 'a, 'b, D>(deserializer: D) -> Wrap<'a, 'b>
+ where D: Deserializer<'de>
+ {
+ Deserialize::deserialize(deserializer).unwrap()
+ }
+}
| [
"492"
] | serde-rs__serde-837 | What's serde zero-copy story so far?
Hi all, first of all huge kudos to all contributors! Serde is already a tried and proven framework for de/serializing!
I was wondering what's the current state or plans to support zero-copy deserialization, aka deserializing into &str and &[u8].
| 0.9 | 8c3e72f2c8f984d6deae3a3a9620efe724e8b849 | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 41698195a..881f0df93 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -328,9 +328,9 @@ impl<'a> Visitor<'a> for StrVisitor {
}
}
-impl<'a> Deserialize<'a> for &'a str {
+impl<'de: 'a, 'a> Deserialize<'de> for &'a str {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer<'a>
+ where D: Deserializer<'de>
{
deserializer.deserialize_str(StrVisitor)
}
@@ -360,9 +360,9 @@ impl<'a> Visitor<'a> for BytesVisitor {
}
}
-impl<'a> Deserialize<'a> for &'a [u8] {
+impl<'de: 'a, 'a> Deserialize<'de> for &'a [u8] {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer<'a>
+ where D: Deserializer<'de>
{
deserializer.deserialize_bytes(BytesVisitor)
}
diff --git a/serde/src/de/private.rs b/serde/src/de/private.rs
index 0e001962e..8121ee156 100644
--- a/serde/src/de/private.rs
+++ b/serde/src/de/private.rs
@@ -1,7 +1,24 @@
+#[cfg(any(feature = "std", feature = "collections"))]
+use core::{fmt, str};
+
use core::marker::PhantomData;
+#[cfg(feature = "collections")]
+use collections::borrow::ToOwned;
+
+#[cfg(feature = "std")]
+use std::borrow::Cow;
+#[cfg(all(feature = "collections", not(feature = "std")))]
+use collections::borrow::Cow;
+
+#[cfg(all(feature = "collections", not(feature = "std")))]
+use collections::{String, Vec};
+
use de::{Deserialize, Deserializer, Error, Visitor};
+#[cfg(any(feature = "std", feature = "collections"))]
+use de::Unexpected;
+
#[cfg(any(feature = "std", feature = "collections"))]
pub use de::content::{Content, ContentRefDeserializer, ContentDeserializer, TaggedContentVisitor,
TagOrContentField, TagOrContentFieldVisitor, InternallyTaggedUnitVisitor,
@@ -42,3 +59,118 @@ pub fn missing_field<'de, V, E>(field: &'static str) -> Result<V, E>
let deserializer = MissingFieldDeserializer(field, PhantomData);
Deserialize::deserialize(deserializer)
}
+
+#[cfg(any(feature = "std", feature = "collections"))]
+pub fn borrow_cow_str<'de: 'a, 'a, D>(deserializer: D) -> Result<Cow<'a, str>, D::Error>
+ where D: Deserializer<'de>
+{
+ struct CowStrVisitor;
+
+ impl<'a> Visitor<'a> for CowStrVisitor {
+ type Value = Cow<'a, str>;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("a string")
+ }
+
+ fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
+ where E: Error
+ {
+ Ok(Cow::Owned(v.to_owned()))
+ }
+
+ fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
+ where E: Error
+ {
+ Ok(Cow::Borrowed(v))
+ }
+
+ fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
+ where E: Error
+ {
+ Ok(Cow::Owned(v))
+ }
+
+ fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
+ where E: Error
+ {
+ match str::from_utf8(v) {
+ Ok(s) => Ok(Cow::Owned(s.to_owned())),
+ Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
+ }
+ }
+
+ fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
+ where E: Error
+ {
+ match str::from_utf8(v) {
+ Ok(s) => Ok(Cow::Borrowed(s)),
+ Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
+ }
+ }
+
+ fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
+ where E: Error
+ {
+ match String::from_utf8(v) {
+ Ok(s) => Ok(Cow::Owned(s)),
+ Err(e) => Err(Error::invalid_value(Unexpected::Bytes(&e.into_bytes()), &self)),
+ }
+ }
+ }
+
+ deserializer.deserialize_str(CowStrVisitor)
+}
+
+#[cfg(any(feature = "std", feature = "collections"))]
+pub fn borrow_cow_bytes<'de: 'a, 'a, D>(deserializer: D) -> Result<Cow<'a, [u8]>, D::Error>
+ where D: Deserializer<'de>
+{
+ struct CowBytesVisitor;
+
+ impl<'a> Visitor<'a> for CowBytesVisitor {
+ type Value = Cow<'a, [u8]>;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("a byte array")
+ }
+
+ fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
+ where E: Error
+ {
+ Ok(Cow::Owned(v.as_bytes().to_vec()))
+ }
+
+ fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
+ where E: Error
+ {
+ Ok(Cow::Borrowed(v.as_bytes()))
+ }
+
+ fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
+ where E: Error
+ {
+ Ok(Cow::Owned(v.into_bytes()))
+ }
+
+ fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
+ where E: Error
+ {
+ Ok(Cow::Owned(v.to_vec()))
+ }
+
+ fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
+ where E: Error
+ {
+ Ok(Cow::Borrowed(v))
+ }
+
+ fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
+ where E: Error
+ {
+ Ok(Cow::Owned(v))
+ }
+ }
+
+ deserializer.deserialize_str(CowBytesVisitor)
+}
diff --git a/serde_codegen_internals/Cargo.toml b/serde_codegen_internals/Cargo.toml
index cd167bfe3..6f006914b 100644
--- a/serde_codegen_internals/Cargo.toml
+++ b/serde_codegen_internals/Cargo.toml
@@ -12,7 +12,8 @@ readme = "../README.md"
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
[dependencies]
-syn = { version = "0.11", default-features = false, features = ["parsing"] }
+syn = { version = "0.11.10", default-features = false, features = ["parsing"] }
+synom = "0.11"
[badges]
travis-ci = { repository = "serde-rs/serde" }
diff --git a/serde_codegen_internals/src/attr.rs b/serde_codegen_internals/src/attr.rs
index 11a2eb2a0..13b429b96 100644
--- a/serde_codegen_internals/src/attr.rs
+++ b/serde_codegen_internals/src/attr.rs
@@ -2,6 +2,8 @@ use Ctxt;
use syn;
use syn::MetaItem::{List, NameValue, Word};
use syn::NestedMetaItem::{Literal, MetaItem};
+use synom::IResult;
+use std::collections::BTreeSet;
use std::str::FromStr;
// This module handles parsing of `#[serde(...)]` attributes. The entrypoints
@@ -528,6 +530,7 @@ pub struct Field {
deserialize_with: Option<syn::Path>,
ser_bound: Option<Vec<syn::WherePredicate>>,
de_bound: Option<Vec<syn::WherePredicate>>,
+ borrowed_lifetimes: BTreeSet<syn::Lifetime>,
}
/// Represents the default to use for a field when deserializing.
@@ -554,6 +557,7 @@ impl Field {
let mut deserialize_with = Attr::none(cx, "deserialize_with");
let mut ser_bound = Attr::none(cx, "bound");
let mut de_bound = Attr::none(cx, "bound");
+ let mut borrowed_lifetimes = Attr::none(cx, "borrow");
let ident = match field.ident {
Some(ref ident) => ident.to_string(),
@@ -651,6 +655,27 @@ impl Field {
}
}
+ // Parse `#[serde(borrow)]`
+ MetaItem(Word(ref name)) if name == "borrow" => {
+ if let Ok(borrowable) = borrowable_lifetimes(cx, &ident, &field.ty) {
+ borrowed_lifetimes.set(borrowable);
+ }
+ }
+
+ // Parse `#[serde(borrow = "'a + 'b")]`
+ MetaItem(NameValue(ref name, ref lit)) if name == "borrow" => {
+ if let Ok(lifetimes) = parse_lit_into_lifetimes(cx, name.as_ref(), lit) {
+ if let Ok(borrowable) = borrowable_lifetimes(cx, &ident, &field.ty) {
+ for lifetime in &lifetimes {
+ if !borrowable.contains(lifetime) {
+ cx.error(format!("field `{}` does not have lifetime {}", ident, lifetime.ident));
+ }
+ }
+ borrowed_lifetimes.set(lifetimes);
+ }
+ }
+ }
+
MetaItem(ref meta_item) => {
cx.error(format!("unknown serde field attribute `{}`", meta_item.name()));
}
@@ -668,6 +693,30 @@ impl Field {
default.set_if_none(Default::Default);
}
+ let mut borrowed_lifetimes = borrowed_lifetimes.get().unwrap_or_default();
+ if !borrowed_lifetimes.is_empty() {
+ // Cow<str> and Cow<[u8]> never borrow by default:
+ //
+ // impl<'de, 'a, T: ?Sized> Deserialize<'de> for Cow<'a, T>
+ //
+ // A #[serde(borrow)] attribute enables borrowing that corresponds
+ // roughly to these impls:
+ //
+ // impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, str>
+ // impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, [u8]>
+ if is_cow(&field.ty, "str") {
+ let path = syn::parse_path("_serde::de::private::borrow_cow_str").unwrap();
+ deserialize_with.set_if_none(path);
+ } else if is_cow(&field.ty, "[u8]") {
+ let path = syn::parse_path("_serde::de::private::borrow_cow_bytes").unwrap();
+ deserialize_with.set_if_none(path);
+ }
+ } else if is_rptr(&field.ty, "str") || is_rptr(&field.ty, "[u8]") {
+ // Types &str and &[u8] are always implicitly borrowed. No need for
+ // a #[serde(borrow)].
+ borrowed_lifetimes = borrowable_lifetimes(cx, &ident, &field.ty).unwrap();
+ }
+
let ser_name = ser_name.get();
let ser_renamed = ser_name.is_some();
let de_name = de_name.get();
@@ -687,6 +736,7 @@ impl Field {
deserialize_with: deserialize_with.get(),
ser_bound: ser_bound.get(),
de_bound: de_bound.get(),
+ borrowed_lifetimes: borrowed_lifetimes,
}
}
@@ -734,6 +784,10 @@ impl Field {
pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
self.de_bound.as_ref().map(|vec| &vec[..])
}
+
+ pub fn borrowed_lifetimes(&self) -> &BTreeSet<syn::Lifetime> {
+ &self.borrowed_lifetimes
+ }
}
type SerAndDe<T> = (Option<T>, Option<T>);
@@ -836,3 +890,174 @@ fn parse_lit_into_ty(cx: &Ctxt,
cx.error(format!("failed to parse type: {} = {:?}", attr_name, string))
})
}
+
+// Parses a string literal like "'a + 'b + 'c" containing a nonempty list of
+// lifetimes separated by `+`.
+fn parse_lit_into_lifetimes(cx: &Ctxt,
+ attr_name: &str,
+ lit: &syn::Lit)
+ -> Result<BTreeSet<syn::Lifetime>, ()> {
+ let string = try!(get_string_from_lit(cx, attr_name, attr_name, lit));
+ if string.is_empty() {
+ cx.error("at least one lifetime must be borrowed");
+ return Err(());
+ }
+
+ named!(lifetimes -> Vec<syn::Lifetime>,
+ separated_nonempty_list!(punct!("+"), syn::parse::lifetime)
+ );
+
+ if let IResult::Done(rest, o) = lifetimes(&string) {
+ if rest.trim().is_empty() {
+ let mut set = BTreeSet::new();
+ for lifetime in o {
+ if !set.insert(lifetime.clone()) {
+ cx.error(format!("duplicate borrowed lifetime `{}`", lifetime.ident));
+ }
+ }
+ return Ok(set);
+ }
+ }
+ Err(cx.error(format!("failed to parse borrowed lifetimes: {:?}", string)))
+}
+
+// Whether the type looks like it might be `std::borrow::Cow<T>` where elem="T".
+// This can have false negatives and false positives.
+//
+// False negative:
+//
+// use std::borrow::Cow as Pig;
+//
+// #[derive(Deserialize)]
+// struct S<'a> {
+// #[serde(borrow)]
+// pig: Pig<'a, str>,
+// }
+//
+// False positive:
+//
+// type str = [i16];
+//
+// #[derive(Deserialize)]
+// struct S<'a> {
+// #[serde(borrow)]
+// cow: Cow<'a, str>,
+// }
+fn is_cow(ty: &syn::Ty, elem: &str) -> bool {
+ let path = match *ty {
+ syn::Ty::Path(None, ref path) => path,
+ _ => {
+ return false;
+ }
+ };
+ let seg = match path.segments.last() {
+ Some(seg) => seg,
+ None => {
+ return false;
+ }
+ };
+ let params = match seg.parameters {
+ syn::PathParameters::AngleBracketed(ref params) => params,
+ _ => {
+ return false;
+ }
+ };
+ seg.ident == "Cow"
+ && params.lifetimes.len() == 1
+ && params.types == vec![syn::parse_type(elem).unwrap()]
+ && params.bindings.is_empty()
+}
+
+// Whether the type looks like it might be `&T` where elem="T". This can have
+// false negatives and false positives.
+//
+// False negative:
+//
+// type Yarn = str;
+//
+// #[derive(Deserialize)]
+// struct S<'a> {
+// r: &'a Yarn,
+// }
+//
+// False positive:
+//
+// type str = [i16];
+//
+// #[derive(Deserialize)]
+// struct S<'a> {
+// r: &'a str,
+// }
+fn is_rptr(ty: &syn::Ty, elem: &str) -> bool {
+ match *ty {
+ syn::Ty::Rptr(Some(_), ref mut_ty) => {
+ mut_ty.mutability == syn::Mutability::Immutable
+ && mut_ty.ty == syn::parse_type(elem).unwrap()
+ }
+ _ => false,
+ }
+}
+
+// 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
+// a type `for<'a> fn(&'a str)` could not borrow `'a` from the Deserializer.
+//
+// This is used when there is an explicit or implicit `#[serde(borrow)]`
+// attribute on the field so there must be at least one borrowable lifetime.
+fn borrowable_lifetimes(cx: &Ctxt,
+ name: &str,
+ ty: &syn::Ty)
+ -> Result<BTreeSet<syn::Lifetime>, ()> {
+ let mut lifetimes = BTreeSet::new();
+ collect_lifetimes(ty, &mut lifetimes);
+ if lifetimes.is_empty() {
+ Err(cx.error(format!("field `{}` has no lifetimes to borrow", name)))
+ } else {
+ Ok(lifetimes)
+ }
+}
+
+fn collect_lifetimes(ty: &syn::Ty, out: &mut BTreeSet<syn::Lifetime>) {
+ match *ty {
+ syn::Ty::Slice(ref elem) |
+ syn::Ty::Array(ref elem, _) |
+ syn::Ty::Paren(ref elem) => {
+ collect_lifetimes(elem, out);
+ }
+ syn::Ty::Ptr(ref elem) => {
+ collect_lifetimes(&elem.ty, out);
+ }
+ syn::Ty::Rptr(ref lifetime, ref elem) => {
+ out.extend(lifetime.iter().cloned());
+ collect_lifetimes(&elem.ty, out);
+ }
+ syn::Ty::Tup(ref elems) => {
+ for elem in elems {
+ collect_lifetimes(elem, out);
+ }
+ }
+ syn::Ty::Path(ref qself, ref path) => {
+ if let Some(ref qself) = *qself {
+ collect_lifetimes(&qself.ty, out);
+ }
+ for seg in &path.segments {
+ if let syn::PathParameters::AngleBracketed(ref params) = seg.parameters {
+ out.extend(params.lifetimes.iter().cloned());
+ for ty in ¶ms.types {
+ collect_lifetimes(ty, out);
+ }
+ for binding in ¶ms.bindings {
+ collect_lifetimes(&binding.ty, out);
+ }
+ }
+ }
+ }
+ syn::Ty::BareFn(_) |
+ syn::Ty::Never |
+ syn::Ty::TraitObject(_) |
+ syn::Ty::ImplTrait(_) |
+ syn::Ty::Infer |
+ syn::Ty::Mac(_) => {}
+ }
+}
diff --git a/serde_codegen_internals/src/lib.rs b/serde_codegen_internals/src/lib.rs
index c5e8885c7..d5baf00b9 100644
--- a/serde_codegen_internals/src/lib.rs
+++ b/serde_codegen_internals/src/lib.rs
@@ -1,4 +1,6 @@
extern crate syn;
+#[macro_use]
+extern crate synom;
pub mod ast;
pub mod attr;
diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 6ab9f95eb..b67ad285c 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -6,20 +6,20 @@ use fragment::{Fragment, Expr, Stmts, Match};
use internals::ast::{Body, Field, Item, Style, Variant};
use internals::{self, attr};
+use std::collections::BTreeSet;
+
pub fn expand_derive_deserialize(item: &syn::DeriveInput) -> Result<Tokens, String> {
- let item = {
- let ctxt = internals::Ctxt::new();
- let item = Item::from_ast(&ctxt, item);
- check_no_str(&ctxt, &item);
- try!(ctxt.check());
- item
- };
+ let ctxt = internals::Ctxt::new();
+ let item = Item::from_ast(&ctxt, item);
+ try!(ctxt.check());
let ident = &item.ident;
let generics = build_generics(&item);
- let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(&generics);
+ let borrowed = borrowed_lifetimes(&item);
+ let params = Parameters { generics: generics, borrowed: borrowed };
+ let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(¶ms);
let dummy_const = Ident::new(format!("_IMPL_DESERIALIZE_FOR_{}", ident));
- let body = Stmts(deserialize_body(&item, &generics));
+ let body = Stmts(deserialize_body(&item, ¶ms));
Ok(quote! {
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
@@ -37,6 +37,11 @@ pub fn expand_derive_deserialize(item: &syn::DeriveInput) -> Result<Tokens, Stri
})
}
+struct Parameters {
+ generics: syn::Generics,
+ borrowed: BTreeSet<syn::Lifetime>,
+}
+
// All the generics in the input, plus a bound `T: Deserialize` for each generic
// field type that will be deserialized by us, plus a bound `T: Default` for
// each generic field type that will be set to a default value.
@@ -84,13 +89,27 @@ fn requires_default(attrs: &attr::Field) -> bool {
attrs.default() == &attr::Default::Default
}
-fn deserialize_body(item: &Item, generics: &syn::Generics) -> Fragment {
+// The union of lifetimes borrowed by each field of the item.
+//
+// These turn into bounds on the `'de` lifetime of the Deserialize impl. If
+// lifetimes `'a` and `'b` are borrowed but `'c` is not, the impl is:
+//
+// impl<'de: 'a + 'b, 'a, 'b, 'c> Deserialize<'de> for S<'a, 'b, 'c>
+fn borrowed_lifetimes(item: &Item) -> BTreeSet<syn::Lifetime> {
+ let mut lifetimes = BTreeSet::new();
+ for field in item.body.all_fields() {
+ lifetimes.extend(field.attrs.borrowed_lifetimes().iter().cloned());
+ }
+ lifetimes
+}
+
+fn deserialize_body(item: &Item, params: &Parameters) -> Fragment {
if let Some(from_type) = item.attrs.from_type() {
deserialize_from(from_type)
} else {
match item.body {
Body::Enum(ref variants) => {
- deserialize_item_enum(&item.ident, generics, variants, &item.attrs)
+ deserialize_item_enum(&item.ident, params, variants, &item.attrs)
}
Body::Struct(Style::Struct, ref fields) => {
if fields.iter().any(|field| field.ident.is_none()) {
@@ -98,7 +117,7 @@ fn deserialize_body(item: &Item, generics: &syn::Generics) -> Fragment {
}
deserialize_struct(&item.ident,
None,
- generics,
+ params,
fields,
&item.attrs,
None)
@@ -110,7 +129,7 @@ fn deserialize_body(item: &Item, generics: &syn::Generics) -> Fragment {
}
deserialize_tuple(&item.ident,
None,
- generics,
+ params,
fields,
&item.attrs,
None)
@@ -164,12 +183,12 @@ fn deserialize_unit_struct(ident: &syn::Ident, item_attrs: &attr::Item) -> Fragm
fn deserialize_tuple(ident: &syn::Ident,
variant_ident: Option<&syn::Ident>,
- generics: &syn::Generics,
+ params: &Parameters,
fields: &[Field],
item_attrs: &attr::Item,
deserializer: Option<Tokens>)
-> Fragment {
- let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(generics);
+ let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params);
let is_enum = variant_ident.is_some();
let type_path = match variant_ident {
@@ -184,12 +203,12 @@ fn deserialize_tuple(ident: &syn::Ident,
let nfields = fields.len();
let visit_newtype_struct = if !is_enum && nfields == 1 {
- Some(deserialize_newtype_struct(ident, &type_path, generics, &fields[0]))
+ Some(deserialize_newtype_struct(ident, &type_path, params, &fields[0]))
} else {
None
};
- let visit_seq = Stmts(deserialize_seq(ident, &type_path, generics, fields, false, item_attrs));
+ let visit_seq = Stmts(deserialize_seq(ident, &type_path, params, fields, false, item_attrs));
let visitor_expr = quote! {
__Visitor {
@@ -245,7 +264,7 @@ fn deserialize_tuple(ident: &syn::Ident,
fn deserialize_seq(ident: &syn::Ident,
type_path: &Tokens,
- generics: &syn::Generics,
+ params: &Parameters,
fields: &[Field],
is_struct: bool,
item_attrs: &attr::Item)
@@ -273,7 +292,7 @@ fn deserialize_seq(ident: &syn::Ident,
}
Some(path) => {
let (wrapper, wrapper_ty) = wrap_deserialize_with(
- ident, generics, field.ty, path);
+ ident, params, field.ty, path);
quote!({
#wrapper
_serde::export::Option::map(
@@ -314,7 +333,7 @@ fn deserialize_seq(ident: &syn::Ident,
fn deserialize_newtype_struct(ident: &syn::Ident,
type_path: &Tokens,
- generics: &syn::Generics,
+ params: &Parameters,
field: &Field)
-> Tokens {
let value = match field.attrs.deserialize_with() {
@@ -326,7 +345,7 @@ fn deserialize_newtype_struct(ident: &syn::Ident,
}
Some(path) => {
let (wrapper, wrapper_ty) =
- wrap_deserialize_with(ident, generics, field.ty, path);
+ wrap_deserialize_with(ident, params, field.ty, path);
quote!({
#wrapper
try!(<#wrapper_ty as _serde::Deserialize>::deserialize(__e)).value
@@ -345,7 +364,7 @@ fn deserialize_newtype_struct(ident: &syn::Ident,
fn deserialize_struct(ident: &syn::Ident,
variant_ident: Option<&syn::Ident>,
- generics: &syn::Generics,
+ params: &Parameters,
fields: &[Field],
item_attrs: &attr::Item,
deserializer: Option<Tokens>)
@@ -353,7 +372,7 @@ fn deserialize_struct(ident: &syn::Ident,
let is_enum = variant_ident.is_some();
let is_untagged = deserializer.is_some();
- let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(generics);
+ let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params);
let type_path = match variant_ident {
Some(variant_ident) => quote!(#ident::#variant_ident),
@@ -364,10 +383,10 @@ fn deserialize_struct(ident: &syn::Ident,
None => format!("struct {}", ident),
};
- let visit_seq = Stmts(deserialize_seq(ident, &type_path, generics, fields, true, item_attrs));
+ let visit_seq = Stmts(deserialize_seq(ident, &type_path, params, fields, true, item_attrs));
let (field_visitor, fields_stmt, visit_map) =
- deserialize_struct_visitor(ident, type_path, generics, fields, item_attrs);
+ deserialize_struct_visitor(ident, type_path, params, fields, item_attrs);
let field_visitor = Stmts(field_visitor);
let fields_stmt = Stmts(fields_stmt);
let visit_map = Stmts(visit_map);
@@ -446,41 +465,41 @@ fn deserialize_struct(ident: &syn::Ident,
}
fn deserialize_item_enum(ident: &syn::Ident,
- generics: &syn::Generics,
+ params: &Parameters,
variants: &[Variant],
item_attrs: &attr::Item)
-> Fragment {
match *item_attrs.tag() {
attr::EnumTag::External => {
- deserialize_externally_tagged_enum(ident, generics, variants, item_attrs)
+ deserialize_externally_tagged_enum(ident, params, variants, item_attrs)
}
attr::EnumTag::Internal { ref tag } => {
deserialize_internally_tagged_enum(ident,
- generics,
+ params,
variants,
item_attrs,
tag)
}
attr::EnumTag::Adjacent { ref tag, ref content } => {
deserialize_adjacently_tagged_enum(ident,
- generics,
+ params,
variants,
item_attrs,
tag,
content)
}
attr::EnumTag::None => {
- deserialize_untagged_enum(ident, generics, variants, item_attrs)
+ deserialize_untagged_enum(ident, params, variants, item_attrs)
}
}
}
fn deserialize_externally_tagged_enum(ident: &syn::Ident,
- generics: &syn::Generics,
+ params: &Parameters,
variants: &[Variant],
item_attrs: &attr::Item)
-> Fragment {
- let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(generics);
+ let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params);
let type_name = item_attrs.name().deserialize_name();
@@ -509,7 +528,7 @@ fn deserialize_externally_tagged_enum(ident: &syn::Ident,
let variant_name = field_i(i);
let block = Match(deserialize_externally_tagged_variant(ident,
- generics,
+ params,
variant,
item_attrs));
@@ -571,7 +590,7 @@ fn deserialize_externally_tagged_enum(ident: &syn::Ident,
}
fn deserialize_internally_tagged_enum(ident: &syn::Ident,
- generics: &syn::Generics,
+ params: &Parameters,
variants: &[Variant],
item_attrs: &attr::Item,
tag: &str)
@@ -600,7 +619,7 @@ fn deserialize_internally_tagged_enum(ident: &syn::Ident,
let block = Match(deserialize_internally_tagged_variant(
ident,
- generics,
+ params,
variant,
item_attrs,
quote!(_serde::de::private::ContentDeserializer::<__D::Error>::new(__tagged.content)),
@@ -627,13 +646,13 @@ fn deserialize_internally_tagged_enum(ident: &syn::Ident,
}
fn deserialize_adjacently_tagged_enum(ident: &syn::Ident,
- generics: &syn::Generics,
+ params: &Parameters,
variants: &[Variant],
item_attrs: &attr::Item,
tag: &str,
content: &str)
-> Fragment {
- let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(generics);
+ let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params);
let variant_names_idents: Vec<_> = variants.iter()
.enumerate()
@@ -658,7 +677,7 @@ fn deserialize_adjacently_tagged_enum(ident: &syn::Ident,
let block = Match(deserialize_untagged_variant(
ident,
- generics,
+ params,
variant,
item_attrs,
quote!(__deserializer),
@@ -866,7 +885,7 @@ fn deserialize_adjacently_tagged_enum(ident: &syn::Ident,
}
fn deserialize_untagged_enum(ident: &syn::Ident,
- generics: &syn::Generics,
+ params: &Parameters,
variants: &[Variant],
item_attrs: &attr::Item)
-> Fragment {
@@ -875,7 +894,7 @@ fn deserialize_untagged_enum(ident: &syn::Ident,
.map(|variant| {
Expr(deserialize_untagged_variant(
ident,
- generics,
+ params,
variant,
item_attrs,
quote!(_serde::de::private::ContentRefDeserializer::<__D::Error>::new(&__content)),
@@ -904,7 +923,7 @@ fn deserialize_untagged_enum(ident: &syn::Ident,
}
fn deserialize_externally_tagged_variant(ident: &syn::Ident,
- generics: &syn::Generics,
+ params: &Parameters,
variant: &Variant,
item_attrs: &attr::Item)
-> Fragment {
@@ -920,13 +939,13 @@ fn deserialize_externally_tagged_variant(ident: &syn::Ident,
Style::Newtype => {
deserialize_externally_tagged_newtype_variant(ident,
variant_ident,
- generics,
+ params,
&variant.fields[0])
}
Style::Tuple => {
deserialize_tuple(ident,
Some(variant_ident),
- generics,
+ params,
&variant.fields,
item_attrs,
None)
@@ -934,7 +953,7 @@ fn deserialize_externally_tagged_variant(ident: &syn::Ident,
Style::Struct => {
deserialize_struct(ident,
Some(variant_ident),
- generics,
+ params,
&variant.fields,
item_attrs,
None)
@@ -943,7 +962,7 @@ fn deserialize_externally_tagged_variant(ident: &syn::Ident,
}
fn deserialize_internally_tagged_variant(ident: &syn::Ident,
- generics: &syn::Generics,
+ params: &Parameters,
variant: &Variant,
item_attrs: &attr::Item,
deserializer: Tokens)
@@ -961,7 +980,7 @@ fn deserialize_internally_tagged_variant(ident: &syn::Ident,
}
Style::Newtype | Style::Struct => {
deserialize_untagged_variant(ident,
- generics,
+ params,
variant,
item_attrs,
deserializer)
@@ -971,7 +990,7 @@ fn deserialize_internally_tagged_variant(ident: &syn::Ident,
}
fn deserialize_untagged_variant(ident: &syn::Ident,
- generics: &syn::Generics,
+ params: &Parameters,
variant: &Variant,
item_attrs: &attr::Item,
deserializer: Tokens)
@@ -994,14 +1013,14 @@ fn deserialize_untagged_variant(ident: &syn::Ident,
Style::Newtype => {
deserialize_untagged_newtype_variant(ident,
variant_ident,
- generics,
+ params,
&variant.fields[0],
deserializer)
}
Style::Tuple => {
deserialize_tuple(ident,
Some(variant_ident),
- generics,
+ params,
&variant.fields,
item_attrs,
Some(deserializer))
@@ -1009,7 +1028,7 @@ fn deserialize_untagged_variant(ident: &syn::Ident,
Style::Struct => {
deserialize_struct(ident,
Some(variant_ident),
- generics,
+ params,
&variant.fields,
item_attrs,
Some(deserializer))
@@ -1019,7 +1038,7 @@ fn deserialize_untagged_variant(ident: &syn::Ident,
fn deserialize_externally_tagged_newtype_variant(ident: &syn::Ident,
variant_ident: &syn::Ident,
- generics: &syn::Generics,
+ params: &Parameters,
field: &Field)
-> Fragment {
match field.attrs.deserialize_with() {
@@ -1033,7 +1052,7 @@ fn deserialize_externally_tagged_newtype_variant(ident: &syn::Ident,
}
Some(path) => {
let (wrapper, wrapper_ty) =
- wrap_deserialize_with(ident, generics, field.ty, path);
+ wrap_deserialize_with(ident, params, field.ty, path);
quote_block! {
#wrapper
_serde::export::Result::map(
@@ -1046,7 +1065,7 @@ fn deserialize_externally_tagged_newtype_variant(ident: &syn::Ident,
fn deserialize_untagged_newtype_variant(ident: &syn::Ident,
variant_ident: &syn::Ident,
- generics: &syn::Generics,
+ params: &Parameters,
field: &Field,
deserializer: Tokens)
-> Fragment {
@@ -1061,7 +1080,7 @@ fn deserialize_untagged_newtype_variant(ident: &syn::Ident,
}
Some(path) => {
let (wrapper, wrapper_ty) =
- wrap_deserialize_with(ident, generics, field.ty, path);
+ wrap_deserialize_with(ident, params, field.ty, path);
quote_block! {
#wrapper
_serde::export::Result::map(
@@ -1186,7 +1205,7 @@ fn deserialize_field_visitor(fields: Vec<(String, Ident)>,
fn deserialize_struct_visitor(ident: &syn::Ident,
struct_path: Tokens,
- generics: &syn::Generics,
+ params: &Parameters,
fields: &[Field],
item_attrs: &attr::Item)
-> (Fragment, Fragment, Fragment) {
@@ -1205,14 +1224,14 @@ fn deserialize_struct_visitor(ident: &syn::Ident,
let field_visitor = deserialize_field_visitor(field_names_idents, item_attrs, false);
- let visit_map = deserialize_map(ident, struct_path, generics, fields, item_attrs);
+ let visit_map = deserialize_map(ident, struct_path, params, fields, item_attrs);
(field_visitor, fields_stmt, visit_map)
}
fn deserialize_map(ident: &syn::Ident,
struct_path: Tokens,
- generics: &syn::Generics,
+ params: &Parameters,
fields: &[Field],
item_attrs: &attr::Item)
-> Fragment {
@@ -1247,7 +1266,7 @@ fn deserialize_map(ident: &syn::Ident,
}
Some(path) => {
let (wrapper, wrapper_ty) = wrap_deserialize_with(
- ident, generics, field.ty, path);
+ ident, params, field.ty, path);
quote!({
#wrapper
try!(_serde::de::MapVisitor::visit_value::<#wrapper_ty>(&mut __visitor)).value
@@ -1355,11 +1374,11 @@ fn field_i(i: usize) -> Ident {
/// This function wraps the expression in `#[serde(deserialize_with="...")]` in
/// a trait to prevent it from accessing the internal `Deserialize` state.
fn wrap_deserialize_with(ident: &syn::Ident,
- generics: &syn::Generics,
+ params: &Parameters,
field_ty: &syn::Ty,
deserialize_with: &syn::Path)
-> (Tokens, Tokens) {
- let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(generics);
+ let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params);
let wrapper = quote! {
struct __DeserializeWith #de_impl_generics #where_clause {
@@ -1420,34 +1439,16 @@ fn expr_is_missing(field: &Field, item_attrs: &attr::Item) -> Fragment {
}
}
-fn check_no_str(cx: &internals::Ctxt, item: &Item) {
- let fail = || {
- cx.error("Serde does not support deserializing fields of type &str; consider using \
- String instead");
- };
-
- for field in item.body.all_fields() {
- if field.attrs.skip_deserializing() || field.attrs.deserialize_with().is_some() {
- continue;
- }
-
- if let syn::Ty::Rptr(_, ref inner) = *field.ty {
- if let syn::Ty::Path(_, ref path) = inner.ty {
- if path.segments.len() == 1 && path.segments[0].ident == "str" {
- fail();
- return;
- }
- }
- }
- }
-}
-
-struct DeImplGenerics<'a>(&'a syn::Generics);
+struct DeImplGenerics<'a>(&'a Parameters);
impl<'a> ToTokens for DeImplGenerics<'a> {
fn to_tokens(&self, tokens: &mut Tokens) {
- let mut generics = self.0.clone();
- generics.lifetimes.insert(0, syn::LifetimeDef::new("'de"));
+ let mut generics = self.0.generics.clone();
+ generics.lifetimes.insert(0, syn::LifetimeDef {
+ attrs: Vec::new(),
+ lifetime: syn::Lifetime::new("'de"),
+ bounds: self.0.borrowed.iter().cloned().collect(),
+ });
let (impl_generics, _, _) = generics.split_for_impl();
impl_generics.to_tokens(tokens);
}
@@ -1464,9 +1465,9 @@ impl<'a> ToTokens for DeTyGenerics<'a> {
}
}
-fn split_with_de_lifetime(generics: &syn::Generics) -> (DeImplGenerics, DeTyGenerics, syn::TyGenerics, &syn::WhereClause) {
- let de_impl_generics = DeImplGenerics(generics);
- let de_ty_generics = DeTyGenerics(generics);
- let (_, ty_generics, where_clause) = generics.split_for_impl();
+fn split_with_de_lifetime(params: &Parameters) -> (DeImplGenerics, DeTyGenerics, syn::TyGenerics, &syn::WhereClause) {
+ let de_impl_generics = DeImplGenerics(¶ms);
+ let de_ty_generics = DeTyGenerics(¶ms.generics);
+ let (_, ty_generics, where_clause) = params.generics.split_for_impl();
(de_impl_generics, de_ty_generics, ty_generics, where_clause)
}
| serde-rs/serde | 2017-04-03T07:48:50Z | That kind of deserialization is only possible when the original serialized state outlives the deserialized data, and the data is in the correct format.
It's probably nothing more than spraying a few lifetimes around, but it might break the existing use cases, so we have to take care here.
Here is a proof of concept of what @oli-obk meant by "spraying a few lifetimes around." The remaining work on this issue will be figuring out how to support this without polluting every usage of Deserialize and Deserializer with lifetimes.
```rust
trait Deserialize<'a>: Sized {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'a>;
}
trait Deserializer<'a>: Sized {
type Error: Error;
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>;
fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor<'a>;
}
trait Error {
fn whatever() -> Self;
}
trait Visitor<'a>: Sized {
type Value;
fn visit_str_from_input<E>(self, v: &'a str) -> Result<Self::Value, E>
where E: Error
{
self.visit_str(v)
}
fn visit_str<E>(self, _v: &str) -> Result<Self::Value, E>
where E: Error
{
Err(Error::whatever())
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where E: Error
{
self.visit_str(&v)
}
}
impl<'a> Deserialize<'a> for String {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'a>
{
struct StringVisitor;
impl<'a> Visitor<'a> for StringVisitor {
type Value = String;
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where E: Error
{
Ok(v.to_owned())
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where E: Error
{
Ok(v)
}
}
deserializer.deserialize_string(StringVisitor)
}
}
impl<'a> Deserialize<'a> for &'a str {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'a>
{
struct StrVisitor;
impl<'a> Visitor<'a> for StrVisitor {
type Value = &'a str;
fn visit_str_from_input<E>(self, v: &'a str) -> Result<Self::Value, E>
where E: Error
{
Ok(v)
}
}
deserializer.deserialize_str(StrVisitor)
}
}
```
One unfortunate limitation here that would require some sort of lifetime dispatch is that we can't have `Cow<'a, T>` borrow the data if the input outlives the output, and copy the data if the input does not outlive the output. We either need to `impl<'a, 'd, T> Deserialize<'d> for Cow<'a, T>` and have it always copy, or `impl<'a, T> Deserialize<'a> for Cow<'a, T>` and have it always borrow even if you would otherwise want it to copy.
#819 would be a way to preserve the current Deserialize and Deserializer traits without lifetimes.
It makes me sad that the approach in https://github.com/serde-rs/serde/issues/492#issuecomment-287152946 is so simple but would require HRTB to accomplish most things that a person would want to do with Deserialize.
```rust
pub fn from_reader<R, T>(rdr: R) -> Result<T>
where R: Read,
T: for<'a> Deserialize<'a>
```
I would not want an understanding of HRTB as a prerequisite for using Serde. @maciejhirsz have you found this to be a problem with bitsparrow::BitDecode\<'src>?
Maybe if we ever get type aliases in trait bounds, we could somehow have Deserialize be an alias for `for<'a> Deserialize<'a>`.
Maybe we want this sort of setup, but unclear whether this is less or more complicated than HRTB.
```rust
pub trait DeserializeBorrow<'a>;
pub trait Deserialize: for<'a> DeserializeBorrow<'a>;
impl<T> Deserialize for T where T: for<'a> DeserializeBorrow<'a>;
// #[derive(Deserialize)]
struct A;
impl<'a> DeserializeBorrow<'a> for A;
// #[derive(DeserializeBorrow)]
struct B<'b> { b: &'b str }
impl<'b> DeserializeBorrow<'b> for B<'b>;
pub fn from_reader<R, T>(rdr: R) -> Result<T>
where R: Read,
T: Deserialize;
pub fn from_str<'a, T>(s: &'a str) -> Result<T>
where T: DeserializeBorrow<'a>;
```
Didn't run into any issues with HRTB for sparrow. For the most part, the fact that there is a lifetime on the trait is completely opaque to the end user when deriving the impl, which - I imagine - is the vast majority of cases. Even when you implement it manually you just need to stick two `<'a>`s on your `impl` and you are done.
That said, I didn't have backwards compatibility to consider.
Right, deriving is not a problem and I am also not concerned about handwritten impls because that is an advanced use case anyway.
Look at [these 220 places](https://github.com/search?l=Rust&q=%22where+t+deserialize%22&type=Code). Almost all of those would require HRTB and practically all users will need to interact with a function like that to use Serde, for example serde_json::from_reader.
Right now I am leaning toward Deserialize\<'a> along with an explicit setting to opt into borrowing particular fields to address https://github.com/serde-rs/serde/issues/492#issuecomment-287585503.
```rust
#[derive(Deserialize)]
struct S<'a, 'b, 'c, 'd, 'e, 'f, 'g> {
// &str and &[u8] are the only types automatically borrowed
a: &'a str,
b: &'b [u8],
// everything else must use serde(borrow)
#[serde(borrow)]
c: Cow<'c, str>,
#[serde(borrow)]
d: T<'d>,
#[serde(borrow = "'e + 'f")]
x: X<'e, 'f, 'g>,
}
```
Along with possibly a helper trait to simplify bounds. I think `T: DeserializeOwned` is clearer in intent and meaning than `T: for<'a> Deserialize<'a>`.
```rust
pub trait DeserializeOwned: for<'a> Deserialize<'a> {}
impl<T> DeserializeOwned for T where T: for<'a> Deserialize<'a> {}
pub fn from_reader<R, T>(rdr: R) -> Result<T>
where R: Read,
T: DeserializeOwned;
pub fn from_str<'a, T>(s: &'a str) -> Result<T>
where T: Deserialize<'a>;
``` | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 |
824 | diff --git a/test_suite/no_std/src/main.rs b/test_suite/no_std/src/main.rs
index 6639b5ccc..a4469819c 100644
--- a/test_suite/no_std/src/main.rs
+++ b/test_suite/no_std/src/main.rs
@@ -1,7 +1,8 @@
-#![feature(lang_items, start, libc)]
+#![feature(lang_items, start, libc, compiler_builtins_lib)]
#![no_std]
extern crate libc;
+extern crate compiler_builtins;
#[start]
fn start(_argc: isize, _argv: *const *const u8) -> isize {
diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index 066eb2a31..8d21844cc 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -8,7 +8,7 @@ use std::net;
use std::path::PathBuf;
use std::time::Duration;
use std::default::Default;
-use std::ffi::CString;
+use std::ffi::{CString, OsString};
#[cfg(feature = "unstable")]
use std::ffi::CStr;
@@ -913,6 +913,56 @@ declare_tests! {
}
}
+#[cfg(unix)]
+#[test]
+fn test_osstring() {
+ use std::os::unix::ffi::OsStringExt;
+
+ let value = OsString::from_vec(vec![1, 2, 3]);
+ let tokens = [
+ Token::EnumStart("OsString"),
+ Token::Str("Unix"),
+ Token::SeqStart(Some(2)),
+ Token::SeqSep,
+ Token::U8(1),
+
+ Token::SeqSep,
+ Token::U8(2),
+
+ Token::SeqSep,
+ Token::U8(3),
+ Token::SeqEnd,
+ ];
+
+ assert_de_tokens(&value, &tokens);
+ assert_de_tokens_ignore(&tokens);
+}
+
+#[cfg(windows)]
+#[test]
+fn test_osstring() {
+ use std::os::windows::ffi::OsStringExt;
+
+ let value = OsString::from_wide(&[1, 2, 3]);
+ let tokens = [
+ Token::EnumStart("OsString"),
+ Token::Str("Windows"),
+ Token::SeqStart(Some(2)),
+ Token::SeqSep,
+ Token::U16(1),
+
+ Token::SeqSep,
+ Token::U16(2),
+
+ Token::SeqSep,
+ Token::U16(3),
+ Token::SeqEnd,
+ ];
+
+ assert_de_tokens(&value, &tokens);
+ assert_de_tokens_ignore(&tokens);
+}
+
#[cfg(feature = "unstable")]
#[test]
fn test_cstr() {
diff --git a/test_suite/tests/test_ser.rs b/test_suite/tests/test_ser.rs
index d58fdfe71..7613cb8ad 100644
--- a/test_suite/tests/test_ser.rs
+++ b/test_suite/tests/test_ser.rs
@@ -422,6 +422,7 @@ fn test_net_ipaddr() {
}
#[test]
+#[cfg(unix)]
fn test_cannot_serialize_paths() {
let path = unsafe {
str::from_utf8_unchecked(b"Hello \xF0\x90\x80World")
| [
"823"
] | serde-rs__serde-824 | Implementations for OsStr/ing
| 0.9 | 71ccc5753be3f74fba512b8b7e3f237b1bbb89c0 | diff --git a/appveyor.yml b/appveyor.yml
new file mode 100644
index 000000000..f720b046f
--- /dev/null
+++ b/appveyor.yml
@@ -0,0 +1,17 @@
+environment:
+ matrix:
+ - APPVEYOR_RUST_CHANNEL: stable
+ - APPVEYOR_RUST_CHANNEL: nightly
+
+install:
+ # Install rust, x86_64-pc-windows-msvc host
+ - appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe
+ - rustup-init.exe -y --default-host x86_64-pc-windows-msvc --default-toolchain %APPVEYOR_RUST_CHANNEL%
+ - set PATH=C:\msys64\usr\bin;%PATH%;C:\Users\appveyor\.cargo\bin
+ - rustc -vV
+ - cargo -vV
+
+build: false
+
+test_script:
+ - sh -c 'PATH=`rustc --print sysroot`/bin:$PATH ./travis.sh'
diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 35f3cdf23..7bffab32a 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -26,7 +26,7 @@ use std::net;
use std::path;
use core::str;
#[cfg(feature = "std")]
-use std::ffi::CString;
+use std::ffi::{CString, OsString};
#[cfg(all(feature = "std", feature="unstable"))]
use std::ffi::CStr;
@@ -910,6 +910,7 @@ impl Visitor for PathBufVisitor {
}
}
+
#[cfg(feature = "std")]
impl Deserialize for path::PathBuf {
fn deserialize<D>(deserializer: D) -> Result<path::PathBuf, D::Error>
@@ -921,6 +922,110 @@ impl Deserialize for path::PathBuf {
///////////////////////////////////////////////////////////////////////////////
+#[cfg(all(feature = "std", any(unix, windows)))]
+enum OsStringKind {
+ Unix,
+ Windows,
+}
+
+#[cfg(all(feature = "std", any(unix, windows)))]
+static OSSTR_VARIANTS: &'static [&'static str] = &["Unix", "Windows"];
+
+#[cfg(all(feature = "std", any(unix, windows)))]
+impl Deserialize for OsStringKind {
+ fn deserialize<D>(deserializer: D) -> Result<OsStringKind, D::Error>
+ where D: Deserializer
+ {
+ struct KindVisitor;
+
+ impl Visitor for KindVisitor {
+ type Value = OsStringKind;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("`Unix` or `Windows`")
+ }
+
+ fn visit_u32<E>(self, value: u32) -> Result<OsStringKind, E>
+ where E: Error,
+ {
+ match value {
+ 0 => Ok(OsStringKind::Unix),
+ 1 => Ok(OsStringKind::Windows),
+ _ => Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self))
+ }
+ }
+
+ fn visit_str<E>(self, value: &str) -> Result<OsStringKind, E>
+ where E: Error,
+ {
+ match value {
+ "Unix" => Ok(OsStringKind::Unix),
+ "Windows" => Ok(OsStringKind::Windows),
+ _ => Err(Error::unknown_variant(value, OSSTR_VARIANTS)),
+ }
+ }
+
+ fn visit_bytes<E>(self, value: &[u8]) -> Result<OsStringKind, E>
+ where E: Error,
+ {
+ match value {
+ b"Unix" => Ok(OsStringKind::Unix),
+ b"Windows" => Ok(OsStringKind::Windows),
+ _ => {
+ match str::from_utf8(value) {
+ Ok(value) => Err(Error::unknown_variant(value, OSSTR_VARIANTS)),
+ Err(_) => {
+ Err(Error::invalid_value(Unexpected::Bytes(value), &self))
+ }
+ }
+ }
+ }
+ }
+ }
+
+ deserializer.deserialize(KindVisitor)
+ }
+}
+
+#[cfg(all(feature = "std", any(unix, windows)))]
+struct OsStringVisitor;
+
+#[cfg(all(feature = "std", any(unix, windows)))]
+impl Visitor for OsStringVisitor {
+ type Value = OsString;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("os string")
+ }
+
+ #[cfg(unix)]
+ fn visit_enum<V>(self, visitor: V) -> Result<OsString, V::Error>
+ where V: EnumVisitor,
+ {
+ use std::os::unix::ffi::OsStringExt;
+
+ match try!(visitor.visit_variant()) {
+ (OsStringKind::Unix, variant) => {
+ variant.visit_newtype().map(OsString::from_vec)
+ }
+ (OsStringKind::Windows, _) => {
+ Err(Error::custom("cannot deserialize windows os string on unix"))
+ }
+ }
+ }
+}
+
+#[cfg(all(feature = "std", any(unix, windows)))]
+impl Deserialize for OsString {
+ fn deserialize<D>(deserializer: D) -> Result<OsString, D::Error>
+ where D: Deserializer
+ {
+ deserializer.deserialize_enum("OsString", OSSTR_VARIANTS, OsStringVisitor)
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
#[cfg(any(feature = "std", feature = "alloc"))]
impl<T: Deserialize> Deserialize for Box<T> {
fn deserialize<D>(deserializer: D) -> Result<Box<T>, D::Error>
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index 53ac7bf0c..4f8177604 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -20,7 +20,7 @@ use core::ops;
#[cfg(feature = "std")]
use std::path;
#[cfg(feature = "std")]
-use std::ffi::{CString, CStr};
+use std::ffi::{CString, CStr, OsString, OsStr};
#[cfg(feature = "std")]
use std::rc::Rc;
#[cfg(all(feature = "alloc", not(feature = "std")))]
@@ -714,6 +714,41 @@ impl Serialize for path::PathBuf {
}
}
+#[cfg(all(feature = "std", any(unix, windows)))]
+impl Serialize for OsStr {
+ #[cfg(unix)]
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where S: Serializer
+ {
+ use std::os::unix::ffi::OsStrExt;
+ serializer.serialize_newtype_variant("OsString",
+ 0,
+ "Unix",
+ self.as_bytes())
+ }
+ #[cfg(windows)]
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where S: Serializer
+ {
+ use std::os::windows::ffi::OsStrExt;
+ let val = self.encode_wide().collect::<Vec<_>>();
+ serializer.serialize_newtype_variant("OsString",
+ 1,
+ "Windows",
+ &val)
+ }
+}
+
+#[cfg(all(feature = "std", any(unix, windows)))]
+#[cfg(feature = "std")]
+impl Serialize for OsString {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where S: Serializer
+ {
+ self.as_os_str().serialize(serializer)
+ }
+}
+
#[cfg(feature = "unstable")]
impl<T> Serialize for NonZero<T>
where T: Serialize + Zeroable
diff --git a/travis.sh b/travis.sh
index d2e1a998e..d5f62d28c 100755
--- a/travis.sh
+++ b/travis.sh
@@ -10,6 +10,11 @@ channel() {
pwd
(set -x; cargo "$@")
fi
+ elif [ -n "${APPVEYOR}" ]; then
+ if [ "${APPVEYOR_RUST_CHANNEL}" = "${CHANNEL}" ]; then
+ pwd
+ (set -x; cargo "$@")
+ fi
else
pwd
(set -x; cargo "+${CHANNEL}" "$@")
| serde-rs/serde | 2017-03-27T16:21:38Z | It's unclear whether this should be provided at all, given that `OsString` differs by platform, so there's no way to ensure that round-trips (eg. windows -> linux -> windows) are lossless.
If this is going to be added, I think it should tag the encoded string with the platform, and refuse to decode a windows OsString into a linux OsString or vice-versa, given that any data encoded this way will not be portable. | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 |
813 | diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index f77359e25..066eb2a31 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -868,6 +868,28 @@ declare_tests! {
Token::SeqEnd,
],
}
+ test_range {
+ 1u32..2u32 => &[
+ Token::StructStart("Range", 2),
+ Token::StructSep,
+ Token::Str("start"),
+ Token::U32(1),
+
+ Token::StructSep,
+ Token::Str("end"),
+ Token::U32(2),
+ Token::StructEnd,
+ ],
+ 1u32..2u32 => &[
+ Token::SeqStart(Some(2)),
+ Token::SeqSep,
+ Token::U64(1),
+
+ Token::SeqSep,
+ Token::U64(2),
+ Token::SeqEnd,
+ ],
+ }
test_net_ipv4addr {
"1.2.3.4".parse::<net::Ipv4Addr>().unwrap() => &[Token::Str("1.2.3.4")],
}
diff --git a/test_suite/tests/test_ser.rs b/test_suite/tests/test_ser.rs
index 940f463df..d58fdfe71 100644
--- a/test_suite/tests/test_ser.rs
+++ b/test_suite/tests/test_ser.rs
@@ -366,6 +366,19 @@ declare_tests! {
Token::StructEnd,
],
}
+ test_range {
+ 1u32..2u32 => &[
+ Token::StructStart("Range", 2),
+ Token::StructSep,
+ Token::Str("start"),
+ Token::U32(1),
+
+ Token::StructSep,
+ Token::Str("end"),
+ Token::U32(2),
+ Token::StructEnd,
+ ],
+ }
test_net_ipv4addr {
"1.2.3.4".parse::<net::Ipv4Addr>().unwrap() => &[Token::Str("1.2.3.4")],
}
| [
"796"
] | serde-rs__serde-813 | Implent Serialize/Deserialize for `Range`
... when T is Serialize/Deserialize, of course.
| 0.9 | 77ee306b573e9adf6eaacc7204ad5bad3928b28d | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 85bf64c4e..35f3cdf23 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -46,6 +46,9 @@ use alloc::boxed::Box;
#[cfg(feature = "std")]
use std::time::Duration;
+#[cfg(feature = "std")]
+use std;
+
#[cfg(feature = "unstable")]
use core::nonzero::{NonZero, Zeroable};
@@ -1108,6 +1111,137 @@ impl Deserialize for Duration {
}
}
+///////////////////////////////////////////////////////////////////////////////
+
+// Similar to:
+//
+// #[derive(Deserialize)]
+// #[serde(deny_unknown_fields)]
+// struct Range {
+// start: u64,
+// end: u32,
+// }
+#[cfg(feature = "std")]
+impl<Idx: Deserialize> Deserialize for std::ops::Range<Idx> {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where D: Deserializer
+ {
+ enum Field {
+ Start,
+ End,
+ };
+
+ impl Deserialize for Field {
+ fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
+ where D: Deserializer
+ {
+ struct FieldVisitor;
+
+ impl Visitor for FieldVisitor {
+ type Value = Field;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("`start` or `end`")
+ }
+
+ fn visit_str<E>(self, value: &str) -> Result<Field, E>
+ where E: Error
+ {
+ match value {
+ "start" => Ok(Field::Start),
+ "end" => Ok(Field::End),
+ _ => Err(Error::unknown_field(value, FIELDS)),
+ }
+ }
+
+ fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E>
+ where E: Error
+ {
+ match value {
+ b"start" => Ok(Field::Start),
+ b"end" => Ok(Field::End),
+ _ => {
+ let value = String::from_utf8_lossy(value);
+ Err(Error::unknown_field(&value, FIELDS))
+ }
+ }
+ }
+ }
+
+ deserializer.deserialize_struct_field(FieldVisitor)
+ }
+ }
+
+ struct RangeVisitor<Idx> {
+ phantom: PhantomData<Idx>,
+ }
+
+ impl<Idx: Deserialize> Visitor for RangeVisitor<Idx> {
+ type Value = std::ops::Range<Idx>;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("struct Range")
+ }
+
+ fn visit_seq<V>(self, mut visitor: V) -> Result<std::ops::Range<Idx>, V::Error>
+ where V: SeqVisitor
+ {
+ let start: Idx = match try!(visitor.visit()) {
+ Some(value) => value,
+ None => {
+ return Err(Error::invalid_length(0, &self));
+ }
+ };
+ let end: Idx = match try!(visitor.visit()) {
+ Some(value) => value,
+ None => {
+ return Err(Error::invalid_length(1, &self));
+ }
+ };
+ Ok(start..end)
+ }
+
+ fn visit_map<V>(self, mut visitor: V) -> Result<std::ops::Range<Idx>, V::Error>
+ where V: MapVisitor
+ {
+ let mut start: Option<Idx> = None;
+ let mut end: Option<Idx> = None;
+ while let Some(key) = try!(visitor.visit_key::<Field>()) {
+ match key {
+ Field::Start => {
+ if start.is_some() {
+ return Err(<V::Error as Error>::duplicate_field("start"));
+ }
+ start = Some(try!(visitor.visit_value()));
+ }
+ Field::End => {
+ if end.is_some() {
+ return Err(<V::Error as Error>::duplicate_field("end"));
+ }
+ end = Some(try!(visitor.visit_value()));
+ }
+ }
+ }
+ let start = match start {
+ Some(start) => start,
+ None => return Err(<V::Error as Error>::missing_field("start")),
+ };
+ let end = match end {
+ Some(end) => end,
+ None => return Err(<V::Error as Error>::missing_field("end")),
+ };
+ Ok(start..end)
+ }
+ }
+
+ const FIELDS: &'static [&'static str] = &["start", "end"];
+ deserializer.deserialize_struct("Range", FIELDS, RangeVisitor { phantom: PhantomData })
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+
///////////////////////////////////////////////////////////////////////////////
#[cfg(feature = "unstable")]
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index 4c7a263fd..409ec4709 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -29,6 +29,8 @@ use std::rc::Rc;
use alloc::rc::Rc;
#[cfg(feature = "std")]
use std::time::Duration;
+#[cfg(feature = "std")]
+use std;
#[cfg(feature = "std")]
use std::sync::Arc;
@@ -262,6 +264,23 @@ impl<T> Serialize for VecDeque<T>
serialize_seq!();
}
+///////////////////////////////////////////////////////////////////////////////
+
+#[cfg(feature = "std")]
+impl<Idx: Serialize> Serialize for std::ops::Range<Idx> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where S: Serializer
+ {
+ use super::SerializeStruct;
+ let mut state = try!(serializer.serialize_struct("Range", 2));
+ try!(state.serialize_field("start", &self.start));
+ try!(state.serialize_field("end", &self.end));
+ state.end()
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
#[cfg(feature = "unstable")]
impl<A> Serialize for ops::Range<A>
where ops::Range<A>: ExactSizeIterator + iter::Iterator<Item = A> + Clone,
| serde-rs/serde | 2017-03-09T19:44:46Z | Any preference for what the representation would be? Something like `3..6` could be either
```json
[3, 4, 5]
```
... or
```json
{
"start": 3,
"end": 6
}
```
Another important thing to consider is whether people will ever need to deserialize a range without knowing ahead of time whether it is Range or RangeFrom or RangeTo or RangeFull.
Can you provide a bit more detail about your use case for this?
````
{
"start": 3,
"end": 6
}
````
That's all a `Range` is.
> Another important thing to consider is whether people will ever need to deserialize a range without knowing ahead of time whether it is Range or RangeFrom or RangeTo or RangeFull.
No idea, but that would only come up when you consider whether/how to implement `Serialize`/`Deserialize` for `RangeArgument`, which isn't even stable yet.
> Can you provide a bit more detail about your use case for this?
I have a struct containing a field that's of type `Range<MyLocalType>` and I want to auto-derive `Serialize` and `Deserialize` for it, but I can't. I can't implement `Serialize`/`Deserialize` for `Range<MyLocalType>` in my own crate because of the orphan rules. | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 |
811 | diff --git a/test_suite/Cargo.toml b/test_suite/Cargo.toml
index 1cd4ff75c..85fbf395d 100644
--- a/test_suite/Cargo.toml
+++ b/test_suite/Cargo.toml
@@ -5,7 +5,7 @@ authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
publish = false
[features]
-unstable-testing = ["compiletest_rs"]
+unstable = ["serde/unstable", "compiletest_rs"]
[dev-dependencies]
fnv = "1.0"
diff --git a/test_suite/tests/compiletest.rs b/test_suite/tests/compiletest.rs
index 4315a8583..a47730939 100644
--- a/test_suite/tests/compiletest.rs
+++ b/test_suite/tests/compiletest.rs
@@ -1,4 +1,4 @@
-#![cfg(feature = "unstable-testing")]
+#![cfg(feature = "unstable")]
extern crate compiletest_rs as compiletest;
diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index fa5943c2e..f77359e25 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -1,3 +1,5 @@
+#![cfg_attr(feature = "unstable", feature(into_boxed_c_str))]
+
#[macro_use]
extern crate serde_derive;
@@ -8,6 +10,9 @@ use std::time::Duration;
use std::default::Default;
use std::ffi::CString;
+#[cfg(feature = "unstable")]
+use std::ffi::CStr;
+
extern crate serde;
use serde::Deserialize;
@@ -886,15 +891,44 @@ declare_tests! {
}
}
+#[cfg(feature = "unstable")]
+#[test]
+fn test_cstr() {
+ assert_de_tokens::<Box<CStr>>(&CString::new("abc").unwrap().into_boxed_c_str(),
+ &[Token::Bytes(b"abc")]);
+}
+
#[cfg(feature = "unstable")]
#[test]
fn test_net_ipaddr() {
assert_de_tokens(
- "1.2.3.4".parse::<net::IpAddr>().unwrap(),
+ &"1.2.3.4".parse::<net::IpAddr>().unwrap(),
&[Token::Str("1.2.3.4")],
);
}
+#[cfg(feature = "unstable")]
+#[test]
+fn test_cstr_internal_null() {
+ assert_de_tokens_error::<Box<CStr>>(
+ &[
+ Token::Bytes(b"a\0c"),
+ ],
+ Error::Message("nul byte found in provided data at position: 1".into())
+ );
+}
+
+#[cfg(feature = "unstable")]
+#[test]
+fn test_cstr_internal_null_end() {
+ assert_de_tokens_error::<Box<CStr>>(
+ &[
+ Token::Bytes(b"ac\0"),
+ ],
+ Error::Message("nul byte found in provided data at position: 2".into())
+ );
+}
+
declare_error_tests! {
test_unknown_field<StructDenyUnknown> {
&[
diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index ab449e4e3..8cdb254e1 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -2,7 +2,7 @@
// successfully when there are a variety of generics and non-(de)serializable
// types involved.
-#![cfg_attr(feature = "unstable-testing", feature(non_ascii_idents))]
+#![cfg_attr(feature = "unstable", feature(non_ascii_idents))]
#[macro_use]
extern crate serde_derive;
@@ -220,8 +220,8 @@ fn test_gen() {
}
assert::<EmptyEnumVariant>();
- #[cfg(feature = "unstable-testing")]
- #[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
+ #[cfg(feature = "unstable")]
+ #[derive(Serialize, Deserialize)]
struct NonAsciiIdents {
σ: f64
}
@@ -246,12 +246,12 @@ fn test_gen() {
f: u8,
}
- #[cfg(feature = "unstable-testing")]
- #[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
+ #[cfg(feature = "unstable")]
+ #[derive(Serialize, Deserialize)]
struct EmptyTuple();
- #[cfg(feature = "unstable-testing")]
- #[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
+ #[cfg(feature = "unstable")]
+ #[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct EmptyTupleDenyUnknown();
@@ -276,8 +276,8 @@ fn test_gen() {
Variant,
}
- #[cfg(feature = "unstable-testing")]
- #[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
+ #[cfg(feature = "unstable")]
+ #[derive(Serialize, Deserialize)]
enum EmptyVariants {
Braced {},
Tuple(),
@@ -288,8 +288,8 @@ fn test_gen() {
TupleSkip(#[serde(skip_deserializing)] u8),
}
- #[cfg(feature = "unstable-testing")]
- #[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
+ #[cfg(feature = "unstable")]
+ #[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
enum EmptyVariantsDenyUnknown {
Braced {},
diff --git a/test_suite/tests/test_ser.rs b/test_suite/tests/test_ser.rs
index 72ed3f0cd..940f463df 100644
--- a/test_suite/tests/test_ser.rs
+++ b/test_suite/tests/test_ser.rs
@@ -21,9 +21,6 @@ use self::serde_test::{
extern crate fnv;
use self::fnv::FnvHasher;
-#[cfg(feature = "unstable")]
-use serde::ser::iterator;
-
#[macro_use]
mod macros;
@@ -402,54 +399,11 @@ declare_tests! {
}
}
-
-#[cfg(feature = "unstable")]
-#[test]
-fn test_iterator() {
- assert_ser_tokens(iterator([0; 0].iter()), &[
- Token::SeqStart(Some(0)),
- Token::SeqEnd,
- ]);
- assert_ser_tokens(iterator([1, 2, 3].iter()), &[
- Token::SeqStart(Some(3)),
- Token::SeqSep,
- Token::I32(1),
-
- Token::SeqSep,
- Token::I32(2),
-
- Token::SeqSep,
- Token::I32(3),
- Token::SeqEnd,
- ]);
- assert_ser_tokens(iterator([1, 2, 3].iter().map(|x| x * 2)), &[
- Token::SeqStart(Some(3)),
- Token::SeqSep,
- Token::I32(2),
-
- Token::SeqSep,
- Token::I32(4),
-
- Token::SeqSep,
- Token::I32(6),
- Token::SeqEnd,
- ]);
- assert_ser_tokens(iterator([1, 2, 3].iter().filter(|&x| x % 2 != 0)), &[
- Token::SeqStart(None),
- Token::SeqSep,
- Token::I32(1),
-
- Token::SeqSep,
- Token::I32(3),
- Token::SeqEnd,
- ]);
-}
-
#[cfg(feature = "unstable")]
#[test]
fn test_net_ipaddr() {
assert_ser_tokens(
- "1.2.3.4".parse::<net::IpAddr>().unwrap(),
+ &"1.2.3.4".parse::<net::IpAddr>().unwrap(),
&[Token::Str("1.2.3.4")],
);
}
| [
"810"
] | serde-rs__serde-811 | Implement Deserialize for Box<CStr>
This is waiting on a stable [`CString::into_boxed_c_str`](https://doc.rust-lang.org/nightly/std/ffi/struct.CString.html#method.into_boxed_c_str): https://github.com/rust-lang/rust/issues/40380
| 0.9 | a4ee9bd0457bb61cf818cff1c3aaf061bc0ed0a1 | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 5f5307fd8..85bf64c4e 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -27,6 +27,8 @@ use std::path;
use core::str;
#[cfg(feature = "std")]
use std::ffi::CString;
+#[cfg(all(feature = "std", feature="unstable"))]
+use std::ffi::CStr;
#[cfg(feature = "std")]
use std::rc::Rc;
@@ -300,6 +302,16 @@ impl Deserialize for String {
///////////////////////////////////////////////////////////////////////////////
+#[cfg(all(feature = "std", feature="unstable"))]
+impl Deserialize for Box<CStr> {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where D: Deserializer
+ {
+ let s = try!(CString::deserialize(deserializer));
+ Ok(s.into_boxed_c_str())
+ }
+}
+
#[cfg(feature = "std")]
impl Deserialize for CString {
fn deserialize<D>(deserializer: D) -> Result<CString, D::Error>
diff --git a/serde/src/lib.rs b/serde/src/lib.rs
index 9560ecb6e..5c7637938 100644
--- a/serde/src/lib.rs
+++ b/serde/src/lib.rs
@@ -61,7 +61,7 @@
#![doc(html_root_url="https://docs.serde.rs")]
#![cfg_attr(not(feature = "std"), no_std)]
-#![cfg_attr(feature = "unstable", feature(inclusive_range, nonzero, specialization, zero_one))]
+#![cfg_attr(feature = "unstable", feature(inclusive_range, nonzero, specialization, zero_one, into_boxed_c_str))]
#![cfg_attr(feature = "alloc", feature(alloc))]
#![cfg_attr(feature = "collections", feature(collections))]
#![cfg_attr(feature = "cargo-clippy", allow(linkedlist, type_complexity, doc_markdown))]
diff --git a/travis.sh b/travis.sh
index 24de5d288..d2e1a998e 100755
--- a/travis.sh
+++ b/travis.sh
@@ -30,7 +30,7 @@ if [ -n "${CLIPPY}" ]; then
cargo clippy --features unstable-testing -- -Dclippy
cd "$DIR/test_suite"
- cargo clippy --features unstable-testing -- -Dclippy
+ cargo clippy --features unstable -- -Dclippy
cd "$DIR/test_suite/no_std"
cargo clippy -- -Dclippy
@@ -46,7 +46,7 @@ else
cd "$DIR/test_suite/deps"
channel build
cd "$DIR/test_suite"
- channel test --features unstable-testing
+ channel test --features unstable
cd "$DIR/test_suite/no_std"
channel build
| serde-rs/serde | 2017-03-09T04:40:27Z | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 | |
801 | diff --git a/test_suite/tests/test_de.rs b/test_suite/tests/test_de.rs
index f41124288..8e79f1f14 100644
--- a/test_suite/tests/test_de.rs
+++ b/test_suite/tests/test_de.rs
@@ -6,6 +6,7 @@ use std::net;
use std::path::PathBuf;
use std::time::Duration;
use std::default::Default;
+use std::ffi::CString;
extern crate serde;
use serde::Deserialize;
@@ -878,6 +879,11 @@ declare_tests! {
Token::String("/usr/local/lib".to_owned()),
],
}
+ test_cstring {
+ CString::new("abc").unwrap() => &[
+ Token::Bytes(b"abc"),
+ ],
+ }
}
#[cfg(feature = "unstable")]
@@ -995,4 +1001,16 @@ declare_error_tests! {
],
Error::Message("invalid length 1, expected an array of length 3".into()),
}
+ test_cstring_internal_null<CString> {
+ &[
+ Token::Bytes(b"a\0c"),
+ ],
+ Error::Message("unexpected NULL at byte 1".into()),
+ }
+ test_cstring_internal_null_end<CString> {
+ &[
+ Token::Bytes(b"ac\0"),
+ ],
+ Error::Message("unexpected NULL at byte 2".into()),
+ }
}
diff --git a/test_suite/tests/test_ser.rs b/test_suite/tests/test_ser.rs
index e1f298ea9..72ed3f0cd 100644
--- a/test_suite/tests/test_ser.rs
+++ b/test_suite/tests/test_ser.rs
@@ -6,6 +6,7 @@ use std::net;
use std::path::{Path, PathBuf};
use std::str;
use std::time::Duration;
+use std::ffi::CString;
extern crate serde;
@@ -389,6 +390,16 @@ declare_tests! {
Token::Str("/usr/local/lib"),
],
}
+ test_cstring {
+ CString::new("abc").unwrap() => &[
+ Token::Bytes(b"abc"),
+ ],
+ }
+ test_cstr {
+ (&*CString::new("abc").unwrap()) => &[
+ Token::Bytes(b"abc"),
+ ],
+ }
}
| [
"800"
] | serde-rs__serde-801 | Implement Serialize/Deserialize for CStr
`serde` currently ships with an `impl` of `Serialize` and `Deserialize` for [`str`](https://github.com/serde-rs/serde/blob/master/serde/src/ser/impls.rs#L80) and [`String`](https://github.com/serde-rs/serde/blob/master/serde/src/ser/impls.rs#L90), but not for the null-terminated C-like string types [`ffi::CStr`](https://doc.rust-lang.org/std/ffi/struct.CStr.html) and [`ffi::CString`](https://doc.rust-lang.org/std/ffi/struct.CString.html). Under the hood, these string implementations are very similar, and providing serialization implementations for the latter two shouldn't be too hard. Are there any particular reasons why `impl`s for these types are not provided?
| 0.9 | d70636f4d4d5e324df8b6286a9aef99655dcee1f | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index ba0acae2f..2946dcfee 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -25,6 +25,8 @@ use std::net;
#[cfg(feature = "std")]
use std::path;
use core::str;
+#[cfg(feature = "std")]
+use std::ffi::CString;
#[cfg(feature = "std")]
use std::rc::Rc;
@@ -53,6 +55,9 @@ use de::{Deserialize, Deserializer, EnumVisitor, Error, MapVisitor, SeqVisitor,
VariantVisitor, Visitor};
use de::from_primitive::FromPrimitive;
+#[cfg(feature = "std")]
+use bytes::ByteBuf;
+
///////////////////////////////////////////////////////////////////////////////
/// A visitor that produces a `()`.
@@ -295,6 +300,19 @@ impl Deserialize for String {
///////////////////////////////////////////////////////////////////////////////
+#[cfg(feature = "std")]
+impl Deserialize for CString {
+ fn deserialize<D>(deserializer: D) -> Result<CString, D::Error>
+ where D: Deserializer
+ {
+ let v: Vec<u8> = try!(ByteBuf::deserialize(deserializer)).into();
+ CString::new(v)
+ .map_err(|e| Error::custom(format!("unexpected NULL at byte {}", e.nul_position())))
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
struct OptionVisitor<T> {
marker: PhantomData<T>,
}
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index a7ac780f5..4c7a263fd 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -22,6 +22,8 @@ use core::ops;
#[cfg(feature = "std")]
use std::path;
#[cfg(feature = "std")]
+use std::ffi::{CString, CStr};
+#[cfg(feature = "std")]
use std::rc::Rc;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::rc::Rc;
@@ -98,6 +100,28 @@ impl Serialize for String {
///////////////////////////////////////////////////////////////////////////////
+#[cfg(feature = "std")]
+impl Serialize for CStr {
+ #[inline]
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where S: Serializer
+ {
+ serializer.serialize_bytes(self.to_bytes())
+ }
+}
+
+#[cfg(feature = "std")]
+impl Serialize for CString {
+ #[inline]
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where S: Serializer
+ {
+ serializer.serialize_bytes(self.to_bytes())
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
impl<T> Serialize for Option<T>
where T: Serialize
{
| serde-rs/serde | 2017-03-03T21:11:53Z | No reason. Would you be able to send a PR adding these two impls?
@dtolnay I'll give it a shot. Should this be placed under its own flag, given that it's in `ffi`?
No, both types are in std so they should be behind the `std` feature.
One open question is how you intend to handle non-UTF8 strings.
I was thinking of serializing through `[u8]` rather than as strings, which should work fine, right?
Sure, that works. | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 |
782 | diff --git a/test_suite/tests/test_macros.rs b/test_suite/tests/test_macros.rs
index 4b84daeb3..f4ef675d5 100644
--- a/test_suite/tests/test_macros.rs
+++ b/test_suite/tests/test_macros.rs
@@ -884,17 +884,18 @@ fn test_internally_tagged_enum() {
#[test]
fn test_adjacently_tagged_enum() {
- #[derive(Debug, PartialEq, Serialize)]
+ #[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "t", content = "c")]
- enum AdjacentlyTagged {
+ enum AdjacentlyTagged<T> {
Unit,
- Newtype(u8),
+ Newtype(T),
Tuple(u8, u8),
Struct { f: u8 },
}
- assert_ser_tokens(
- &AdjacentlyTagged::Unit,
+ // unit with no content
+ assert_tokens(
+ &AdjacentlyTagged::Unit::<u8>,
&[
Token::StructStart("AdjacentlyTagged", 1),
@@ -906,8 +907,45 @@ fn test_adjacently_tagged_enum() {
]
);
- assert_ser_tokens(
- &AdjacentlyTagged::Newtype(1),
+ // unit with tag first
+ assert_de_tokens(
+ &AdjacentlyTagged::Unit::<u8>,
+ &[
+ Token::StructStart("AdjacentlyTagged", 1),
+
+ Token::StructSep,
+ Token::Str("t"),
+ Token::Str("Unit"),
+
+ Token::StructSep,
+ Token::Str("c"),
+ Token::Unit,
+
+ Token::StructEnd,
+ ]
+ );
+
+ // unit with content first
+ assert_de_tokens(
+ &AdjacentlyTagged::Unit::<u8>,
+ &[
+ Token::StructStart("AdjacentlyTagged", 1),
+
+ Token::StructSep,
+ Token::Str("c"),
+ Token::Unit,
+
+ Token::StructSep,
+ Token::Str("t"),
+ Token::Str("Unit"),
+
+ Token::StructEnd,
+ ]
+ );
+
+ // newtype with tag first
+ assert_tokens(
+ &AdjacentlyTagged::Newtype::<u8>(1),
&[
Token::StructStart("AdjacentlyTagged", 2),
@@ -923,8 +961,27 @@ fn test_adjacently_tagged_enum() {
]
);
- assert_ser_tokens(
- &AdjacentlyTagged::Tuple(1, 1),
+ // newtype with content first
+ assert_de_tokens(
+ &AdjacentlyTagged::Newtype::<u8>(1),
+ &[
+ Token::StructStart("AdjacentlyTagged", 2),
+
+ Token::StructSep,
+ Token::Str("c"),
+ Token::U8(1),
+
+ Token::StructSep,
+ Token::Str("t"),
+ Token::Str("Newtype"),
+
+ Token::StructEnd,
+ ]
+ );
+
+ // tuple with tag first
+ assert_tokens(
+ &AdjacentlyTagged::Tuple::<u8>(1, 1),
&[
Token::StructStart("AdjacentlyTagged", 2),
@@ -945,8 +1002,32 @@ fn test_adjacently_tagged_enum() {
]
);
- assert_ser_tokens(
- &AdjacentlyTagged::Struct { f: 1 },
+ // tuple with content first
+ assert_de_tokens(
+ &AdjacentlyTagged::Tuple::<u8>(1, 1),
+ &[
+ Token::StructStart("AdjacentlyTagged", 2),
+
+ Token::StructSep,
+ Token::Str("c"),
+ Token::TupleStart(2),
+ Token::TupleSep,
+ Token::U8(1),
+ Token::TupleSep,
+ Token::U8(1),
+ Token::TupleEnd,
+
+ Token::StructSep,
+ Token::Str("t"),
+ Token::Str("Tuple"),
+
+ Token::StructEnd,
+ ]
+ );
+
+ // struct with tag first
+ assert_tokens(
+ &AdjacentlyTagged::Struct::<u8> { f: 1 },
&[
Token::StructStart("AdjacentlyTagged", 2),
@@ -965,4 +1046,26 @@ fn test_adjacently_tagged_enum() {
Token::StructEnd,
]
);
+
+ // struct with content first
+ assert_de_tokens(
+ &AdjacentlyTagged::Struct::<u8> { f: 1 },
+ &[
+ Token::StructStart("AdjacentlyTagged", 2),
+
+ Token::StructSep,
+ Token::Str("c"),
+ Token::StructStart("Struct", 1),
+ Token::StructSep,
+ Token::Str("f"),
+ Token::U8(1),
+ Token::StructEnd,
+
+ Token::StructSep,
+ Token::Str("t"),
+ Token::Str("Struct"),
+
+ Token::StructEnd,
+ ]
+ );
}
| [
"758"
] | serde-rs__serde-782 | haskell serialized formats could be better supported
haskell serializes enums to json by encoding a `t` field for the variant name and a `c` field for the content. We can represent this with
```rust
#[derive(Serialize, Deserialize)]
#[serde(tag = "t")]
enum MyType {
Variant { c: ActualContent },
Variant2 { c: (A, B, C) },
}
```
This works fine, but is a little verbose. Not sure if this use case is too niche.
| 0.9 | 599a1b6607972e9eeeb0f513fc0f50605e2c68e9 | diff --git a/serde/src/de/content.rs b/serde/src/de/content.rs
index 1ae2e8696..5ba2a1697 100644
--- a/serde/src/de/content.rs
+++ b/serde/src/de/content.rs
@@ -21,7 +21,7 @@ use collections::{String, Vec};
use alloc::boxed::Box;
use de::{self, Deserialize, DeserializeSeed, Deserializer, Visitor, SeqVisitor, MapVisitor,
- EnumVisitor};
+ EnumVisitor, Unexpected};
/// Used from generated code to buffer the contents of the Deserializer when
/// deserializing untagged enums and internally tagged enums.
@@ -493,6 +493,50 @@ impl<T> Visitor for TaggedContentVisitor<T>
}
}
+/// Used by generated code to deserialize an adjacently tagged enum.
+///
+/// Not public API.
+pub enum TagOrContentField {
+ Tag,
+ Content,
+}
+
+/// Not public API.
+pub struct TagOrContentFieldVisitor {
+ pub tag: &'static str,
+ pub content: &'static str,
+}
+
+impl DeserializeSeed for TagOrContentFieldVisitor {
+ type Value = TagOrContentField;
+
+ fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
+ where D: Deserializer
+ {
+ deserializer.deserialize_str(self)
+ }
+}
+
+impl Visitor for TagOrContentFieldVisitor {
+ type Value = TagOrContentField;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ write!(formatter, "{:?} or {:?}", self.tag, self.content)
+ }
+
+ fn visit_str<E>(self, field: &str) -> Result<Self::Value, E>
+ where E: de::Error
+ {
+ if field == self.tag {
+ Ok(TagOrContentField::Tag)
+ } else if field == self.content {
+ Ok(TagOrContentField::Content)
+ } else {
+ Err(de::Error::invalid_value(Unexpected::Str(field), &self))
+ }
+ }
+}
+
/// Not public API
pub struct ContentDeserializer<E> {
content: Content,
diff --git a/serde/src/de/private.rs b/serde/src/de/private.rs
index 8ef622316..092d66a60 100644
--- a/serde/src/de/private.rs
+++ b/serde/src/de/private.rs
@@ -4,7 +4,8 @@ use de::{Deserialize, Deserializer, Error, Visitor};
#[cfg(any(feature = "std", feature = "collections"))]
pub use de::content::{Content, ContentRefDeserializer, ContentDeserializer, TaggedContentVisitor,
- InternallyTaggedUnitVisitor, UntaggedUnitVisitor};
+ TagOrContentField, TagOrContentFieldVisitor, InternallyTaggedUnitVisitor,
+ UntaggedUnitVisitor};
/// If the missing field is of type `Option<T>` then treat is as `None`,
/// otherwise it is an error.
diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index b73d16696..b47f334bd 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -185,7 +185,7 @@ fn deserialize_tuple(ident: &syn::Ident,
__Visitor { marker: _serde::export::PhantomData::<#ident #ty_generics> }
};
let dispatch = if let Some(deserializer) = deserializer {
- quote!(_serde::Deserializer::deserialize(#deserializer, #visitor_expr))
+ quote!(_serde::Deserializer::deserialize_tuple(#deserializer, #nfields, #visitor_expr))
} else if is_enum {
quote!(_serde::de::VariantVisitor::visit_tuple(visitor, #nfields, #visitor_expr))
} else if nfields == 1 {
@@ -442,7 +442,14 @@ fn deserialize_item_enum(ident: &syn::Ident,
item_attrs,
tag)
}
- attr::EnumTag::Adjacent { .. } => unimplemented!(),
+ attr::EnumTag::Adjacent { ref tag, ref content } => {
+ deserialize_adjacently_tagged_enum(ident,
+ generics,
+ variants,
+ item_attrs,
+ tag,
+ content)
+ }
attr::EnumTag::None => {
deserialize_untagged_enum(ident, generics, variants, item_attrs)
}
@@ -597,6 +604,230 @@ fn deserialize_internally_tagged_enum(ident: &syn::Ident,
}
}
+fn deserialize_adjacently_tagged_enum(ident: &syn::Ident,
+ generics: &syn::Generics,
+ variants: &[Variant],
+ item_attrs: &attr::Item,
+ tag: &str,
+ content: &str)
+ -> Fragment {
+ let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
+
+ let variant_names_idents: Vec<_> = variants.iter()
+ .enumerate()
+ .filter(|&(_, variant)| !variant.attrs.skip_deserializing())
+ .map(|(i, variant)| (variant.attrs.name().deserialize_name(), field_i(i)))
+ .collect();
+
+ let variants_stmt = {
+ let variant_names = variant_names_idents.iter().map(|&(ref name, _)| name);
+ quote! {
+ const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ];
+ }
+ };
+
+ let variant_visitor = Stmts(deserialize_field_visitor(variant_names_idents, item_attrs, true));
+
+ let ref variant_arms: Vec<_> = variants.iter()
+ .enumerate()
+ .filter(|&(_, variant)| !variant.attrs.skip_deserializing())
+ .map(|(i, variant)| {
+ let variant_index = field_i(i);
+
+ let block = Match(deserialize_untagged_variant(
+ ident,
+ generics,
+ variant,
+ item_attrs,
+ quote!(_deserializer),
+ ));
+
+ quote! {
+ __Field::#variant_index => #block
+ }
+ })
+ .collect();
+
+ let expecting = format!("adjacently tagged enum {}", ident);
+ let type_name = item_attrs.name().deserialize_name();
+
+ let tag_or_content = quote! {
+ _serde::de::private::TagOrContentFieldVisitor {
+ tag: #tag,
+ content: #content,
+ }
+ };
+
+ fn is_unit(variant: &Variant) -> bool {
+ match variant.style {
+ Style::Unit => true,
+ Style::Struct | Style::Tuple | Style::Newtype => false,
+ }
+ }
+
+ let mut missing_content = quote! {
+ _serde::export::Err(<__V::Error as _serde::de::Error>::missing_field(#content))
+ };
+ if variants.iter().any(is_unit) {
+ let fallthrough = if variants.iter().all(is_unit) {
+ None
+ } else {
+ Some(quote! {
+ _ => #missing_content
+ })
+ };
+ let arms = variants.iter()
+ .enumerate()
+ .filter(|&(_, variant)| !variant.attrs.skip_deserializing() && is_unit(variant))
+ .map(|(i, variant)| {
+ let variant_index = field_i(i);
+ let variant_ident = &variant.ident;
+ quote! {
+ __Field::#variant_index => _serde::export::Ok(#ident::#variant_ident),
+ }
+ });
+ missing_content = quote! {
+ match __field {
+ #(#arms)*
+ #fallthrough
+ }
+ };
+ }
+
+ let visit_third_key = quote! {
+ // Visit the third key in the map, hopefully there isn't one.
+ match try!(_serde::de::MapVisitor::visit_key_seed(&mut visitor, #tag_or_content)) {
+ _serde::export::Some(_serde::de::private::TagOrContentField::Tag) => {
+ _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#tag))
+ }
+ _serde::export::Some(_serde::de::private::TagOrContentField::Content) => {
+ _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#content))
+ }
+ _serde::export::None => _serde::export::Ok(__ret),
+ }
+ };
+
+ quote_block! {
+ #variant_visitor
+
+ #variants_stmt
+
+ struct __Seed #impl_generics #where_clause {
+ field: __Field,
+ marker: _serde::export::PhantomData<#ident #ty_generics>,
+ }
+
+ impl #impl_generics _serde::de::DeserializeSeed for __Seed #ty_generics #where_clause {
+ type Value = #ident #ty_generics;
+
+ fn deserialize<__D>(self, _deserializer: __D) -> _serde::export::Result<Self::Value, __D::Error>
+ where __D: _serde::Deserializer
+ {
+ match self.field {
+ #(#variant_arms)*
+ }
+ }
+ }
+
+ struct __Visitor #impl_generics #where_clause {
+ marker: _serde::export::PhantomData<#ident #ty_generics>,
+ }
+
+ impl #impl_generics _serde::de::Visitor for __Visitor #ty_generics #where_clause {
+ type Value = #ident #ty_generics;
+
+ fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
+ _serde::export::fmt::Formatter::write_str(formatter, #expecting)
+ }
+
+ fn visit_map<__V>(self, mut visitor: __V) -> _serde::export::Result<Self::Value, __V::Error>
+ where __V: _serde::de::MapVisitor
+ {
+ // Visit the first key.
+ match try!(_serde::de::MapVisitor::visit_key_seed(&mut visitor, #tag_or_content)) {
+ // First key is the tag.
+ _serde::export::Some(_serde::de::private::TagOrContentField::Tag) => {
+ // Parse the tag.
+ let __field = try!(_serde::de::MapVisitor::visit_value(&mut visitor));
+ // Visit the second key.
+ match try!(_serde::de::MapVisitor::visit_key_seed(&mut visitor, #tag_or_content)) {
+ // Second key is a duplicate of the tag.
+ _serde::export::Some(_serde::de::private::TagOrContentField::Tag) => {
+ _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#tag))
+ }
+ // Second key is the content.
+ _serde::export::Some(_serde::de::private::TagOrContentField::Content) => {
+ let __ret = try!(_serde::de::MapVisitor::visit_value_seed(&mut visitor, __Seed { field: __field, marker: _serde::export::PhantomData }));
+ // Visit the third key, hopefully there isn't one.
+ #visit_third_key
+ }
+ // There is no second key; might be okay if the we have a unit variant.
+ _serde::export::None => #missing_content
+ }
+ }
+ // First key is the content.
+ _serde::export::Some(_serde::de::private::TagOrContentField::Content) => {
+ // Buffer up the content.
+ let __content = try!(_serde::de::MapVisitor::visit_value::<_serde::de::private::Content>(&mut visitor));
+ // Visit the second key.
+ match try!(_serde::de::MapVisitor::visit_key_seed(&mut visitor, #tag_or_content)) {
+ // Second key is the tag.
+ _serde::export::Some(_serde::de::private::TagOrContentField::Tag) => {
+ let _deserializer = _serde::de::private::ContentDeserializer::<__V::Error>::new(__content);
+ // Parse the tag.
+ let __ret = try!(match try!(_serde::de::MapVisitor::visit_value(&mut visitor)) {
+ // Deserialize the buffered content now that we know the variant.
+ #(#variant_arms)*
+ });
+ // Visit the third key, hopefully there isn't one.
+ #visit_third_key
+ }
+ // Second key is a duplicate of the content.
+ _serde::export::Some(_serde::de::private::TagOrContentField::Content) => {
+ _serde::export::Err(<__V::Error as _serde::de::Error>::duplicate_field(#content))
+ }
+ // There is no second key.
+ _serde::export::None => {
+ _serde::export::Err(<__V::Error as _serde::de::Error>::missing_field(#tag))
+ }
+ }
+ }
+ // There is no first key.
+ _serde::export::None => {
+ _serde::export::Err(<__V::Error as _serde::de::Error>::missing_field(#tag))
+ }
+ }
+ }
+
+ fn visit_seq<__V>(self, mut visitor: __V) -> _serde::export::Result<Self::Value, __V::Error>
+ where __V: _serde::de::SeqVisitor
+ {
+ // Visit the first element - the tag.
+ match try!(_serde::de::SeqVisitor::visit(&mut visitor)) {
+ _serde::export::Some(__field) => {
+ // Visit the second element - the content.
+ match try!(_serde::de::SeqVisitor::visit_seed(&mut visitor, __Seed { field: __field, marker: _serde::export::PhantomData })) {
+ _serde::export::Some(__ret) => _serde::export::Ok(__ret),
+ // There is no second element.
+ _serde::export::None => {
+ _serde::export::Err(_serde::de::Error::invalid_length(1, &self))
+ }
+ }
+ }
+ // There is no first element.
+ _serde::export::None => {
+ _serde::export::Err(_serde::de::Error::invalid_length(0, &self))
+ }
+ }
+ }
+ }
+
+ const FIELDS: &'static [&'static str] = &[#tag, #content];
+ _serde::Deserializer::deserialize_struct(deserializer, #type_name, FIELDS,
+ __Visitor { marker: _serde::export::PhantomData::<#ident #ty_generics> })
+ }
+}
+
fn deserialize_untagged_enum(ident: &syn::Ident,
generics: &syn::Generics,
variants: &[Variant],
| serde-rs/serde | 2017-02-21T04:03:37Z | This representation also came up in https://github.com/serde-rs/serde/issues/415#issue-162867209 so I don't think it is too niche. How about something like this?
```rust
#[derive(Serialize, Deserialize)]
#[serde(tag = "t", content = "c")]
enum MyType {
Variant(ActualContent),
Variant2(A, B, C),
}
```
Sounds simple enough. We need to be aware of edge cases though. like what happens with empty variants (don't serialize the content field, deserialize without content field and with "unit" content field).
I took a first pass on this in #771, but got stuck at the part where I need to serialize the internal contents of the `"c": ...` portion. If you have any advice, I'd appreciate suggestions in the other thread. | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 |
765 | diff --git a/test_suite/tests/test_gen.rs b/test_suite/tests/test_gen.rs
index 2f53a00e4..d008c0f20 100644
--- a/test_suite/tests/test_gen.rs
+++ b/test_suite/tests/test_gen.rs
@@ -30,6 +30,14 @@ fn test_gen() {
}
assert::<With<i32>>();
+ #[derive(Serialize, Deserialize)]
+ struct WithTogether<T> {
+ t: T,
+ #[serde(with="both_x")]
+ x: X,
+ }
+ assert::<WithTogether<i32>>();
+
#[derive(Serialize, Deserialize)]
struct WithRef<'a, T: 'a> {
#[serde(skip_deserializing)]
@@ -307,16 +315,20 @@ trait DeserializeWith: Sized {
}
// Implements neither Serialize nor Deserialize
-struct X;
+pub struct X;
-fn ser_x<S: Serializer>(_: &X, _: S) -> StdResult<S::Ok, S::Error> {
+pub fn ser_x<S: Serializer>(_: &X, _: S) -> StdResult<S::Ok, S::Error> {
unimplemented!()
}
-fn de_x<D: Deserializer>(_: D) -> StdResult<X, D::Error> {
+pub fn de_x<D: Deserializer>(_: D) -> StdResult<X, D::Error> {
unimplemented!()
}
+mod both_x {
+ pub use super::{ser_x as serialize, de_x as deserialize};
+}
+
impl SerializeWith for X {
fn serialize_with<S: Serializer>(_: &Self, _: S) -> StdResult<S::Ok, S::Error> {
unimplemented!()
| [
"763"
] | serde-rs__serde-765 | Way to pair serialize_with and deserialize_with into one attribute
```rust
#[serde(serialize_with = "url_serde::serialize",
deserialize_with = "url_serde::deserialize")]
```
This gets tedious because you almost always want these paired. Can we deduplicate into one attribute?
```rust
#[serde(with = "url_serde")]
```
| 0.9 | 090c8a7049cff6cd98139a8fcfc28b65ef73ec2d | diff --git a/serde_codegen_internals/src/attr.rs b/serde_codegen_internals/src/attr.rs
index 224bb9398..2ed7bf423 100644
--- a/serde_codegen_internals/src/attr.rs
+++ b/serde_codegen_internals/src/attr.rs
@@ -453,6 +453,18 @@ impl Field {
}
}
+ // Parse `#[serde(with="...")]`
+ MetaItem(NameValue(ref name, ref lit)) if name == "with" => {
+ if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
+ let mut ser_path = path.clone();
+ ser_path.segments.push("serialize".into());
+ serialize_with.set(ser_path);
+ let mut de_path = path;
+ de_path.segments.push("deserialize".into());
+ deserialize_with.set(de_path);
+ }
+ }
+
// Parse `#[serde(bound="D: Serialize")]`
MetaItem(NameValue(ref name, ref lit)) if name == "bound" => {
if let Ok(where_predicates) =
| serde-rs/serde | 2017-02-15T01:37:15Z | So the `use = "type"` would require `type` to implement both `Serialize` and `Deserialize` (barring further attributes like `deserialize_default`)?
I haven't thought about how it would work yet.
I think the way you are suggesting is you give the attribute a path to a wrapper type:
```rust
struct Url(url::Url);
impl Serialize for Url { ... }
impl Deserialize for Url { ... }
```
A different approach that would be more similar to serialize_with and deserialize_with would be to give the attribute a path to a module containing ser and de functions:
```rust
mod url {
fn serialize<S>(...) { ... }
fn deserialize<D>(...) { ... }
}
```
Right now I am leaning toward the module approach because it means that simple wrapper libraries like url_serde can be used just with `#[serde(use = "url_serde")]`.
Oh, your idea is much more general, since it also supports the case where the "wrapper type" is not a wrapper type at all, but e.g. some random type from another crate.
@nox my `mod` proposal would work with hyper_serde out of the box without any code change on your end.
```diff
#[derive(Serialize, Deserialize)]
struct MyStruct {
- #[serde(deserialize_with = "hyper_serde::deserialize",
- serialize_with = "hyper_serde::serialize")]
+ #[serde(with = "hyper_serde")]
headers: Headers,
}
```
Any concerns or suggestions? | 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 |
762 | diff --git a/serde_test/src/assert.rs b/serde_test/src/assert.rs
index b5e03f52e..3abb87d71 100644
--- a/serde_test/src/assert.rs
+++ b/serde_test/src/assert.rs
@@ -8,14 +8,14 @@ use token::Token;
use std::fmt::Debug;
pub fn assert_tokens<T>(value: &T, tokens: &[Token<'static>])
- where T: Serialize + Deserialize + PartialEq + Debug,
+ where T: Serialize + Deserialize + PartialEq + Debug
{
assert_ser_tokens(value, tokens);
assert_de_tokens(value, tokens);
}
pub fn assert_ser_tokens<T>(value: &T, tokens: &[Token])
- where T: Serialize,
+ where T: Serialize
{
let mut ser = Serializer::new(tokens.iter());
assert_eq!(Serialize::serialize(value, &mut ser), Ok(()));
@@ -24,7 +24,7 @@ pub fn assert_ser_tokens<T>(value: &T, tokens: &[Token])
/// Expect an error serializing `T`.
pub fn assert_ser_tokens_error<T>(value: &T, tokens: &[Token], error: Error)
- where T: Serialize + PartialEq + Debug,
+ where T: Serialize + PartialEq + Debug
{
let mut ser = Serializer::new(tokens.iter());
let v: Result<(), Error> = Serialize::serialize(value, &mut ser);
@@ -33,7 +33,7 @@ pub fn assert_ser_tokens_error<T>(value: &T, tokens: &[Token], error: Error)
}
pub fn assert_de_tokens<T>(value: &T, tokens: &[Token<'static>])
- where T: Deserialize + PartialEq + Debug,
+ where T: Deserialize + PartialEq + Debug
{
let mut de = Deserializer::new(tokens.to_vec().into_iter());
let v: Result<T, Error> = Deserialize::deserialize(&mut de);
@@ -43,7 +43,7 @@ pub fn assert_de_tokens<T>(value: &T, tokens: &[Token<'static>])
/// Expect an error deserializing tokens into a `T`.
pub fn assert_de_tokens_error<T>(tokens: &[Token<'static>], error: Error)
- where T: Deserialize + PartialEq + Debug,
+ where T: Deserialize + PartialEq + Debug
{
let mut de = Deserializer::new(tokens.to_vec().into_iter());
let v: Result<T, Error> = Deserialize::deserialize(&mut de);
diff --git a/serde_test/src/de.rs b/serde_test/src/de.rs
index 138ed0cd9..816c7d37c 100644
--- a/serde_test/src/de.rs
+++ b/serde_test/src/de.rs
@@ -1,33 +1,23 @@
use std::iter;
-use serde::de::{
- self,
- Deserialize,
- DeserializeSeed,
- EnumVisitor,
- MapVisitor,
- SeqVisitor,
- VariantVisitor,
- Visitor,
-};
+use serde::de::{self, Deserialize, DeserializeSeed, EnumVisitor, MapVisitor, SeqVisitor,
+ VariantVisitor, Visitor};
use serde::de::value::ValueDeserializer;
use error::Error;
use token::Token;
pub struct Deserializer<I>
- where I: Iterator<Item=Token<'static>>,
+ where I: Iterator<Item = Token<'static>>
{
tokens: iter::Peekable<I>,
}
impl<I> Deserializer<I>
- where I: Iterator<Item=Token<'static>>,
+ where I: Iterator<Item = Token<'static>>
{
pub fn new(tokens: I) -> Deserializer<I> {
- Deserializer {
- tokens: tokens.peekable(),
- }
+ Deserializer { tokens: tokens.peekable() }
}
pub fn next_token(&mut self) -> Option<Token<'static>> {
@@ -47,8 +37,13 @@ impl<I> Deserializer<I>
}
}
- fn visit_seq<V>(&mut self, len: Option<usize>, sep: Token<'static>, end: Token<'static>, visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
+ fn visit_seq<V>(&mut self,
+ len: Option<usize>,
+ sep: Token<'static>,
+ end: Token<'static>,
+ visitor: V)
+ -> Result<V::Value, Error>
+ where V: Visitor
{
let value = try!(visitor.visit_seq(DeserializerSeqVisitor {
de: self,
@@ -60,8 +55,13 @@ impl<I> Deserializer<I>
Ok(value)
}
- fn visit_map<V>(&mut self, len: Option<usize>, sep: Token<'static>, end: Token<'static>, visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
+ fn visit_map<V>(&mut self,
+ len: Option<usize>,
+ sep: Token<'static>,
+ end: Token<'static>,
+ visitor: V)
+ -> Result<V::Value, Error>
+ where V: Visitor
{
let value = try!(visitor.visit_map(DeserializerMapVisitor {
de: self,
@@ -75,7 +75,7 @@ impl<I> Deserializer<I>
}
impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
- where I: Iterator<Item=Token<'static>>,
+ where I: Iterator<Item = Token<'static>>
{
type Error = Error;
@@ -85,7 +85,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
}
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
+ where V: Visitor
{
match self.tokens.next() {
Some(Token::Bool(v)) => visitor.visit_bool(v),
@@ -118,7 +118,10 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
self.visit_seq(Some(len), Token::TupleSep, Token::TupleEnd, visitor)
}
Some(Token::TupleStructStart(_, len)) => {
- self.visit_seq(Some(len), Token::TupleStructSep, Token::TupleStructEnd, visitor)
+ self.visit_seq(Some(len),
+ Token::TupleStructSep,
+ Token::TupleStructEnd,
+ visitor)
}
Some(Token::MapStart(len)) => {
self.visit_map(len, Token::MapSep, Token::MapEnd, visitor)
@@ -134,10 +137,11 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
/// Hook into `Option` deserializing so we can treat `Unit` as a
/// `None`, or a regular value as `Some(value)`.
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
+ where V: Visitor
{
match self.tokens.peek() {
- Some(&Token::Unit) | Some(&Token::Option(false)) => {
+ Some(&Token::Unit) |
+ Some(&Token::Option(false)) => {
self.tokens.next();
visitor.visit_none()
}
@@ -151,26 +155,23 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
}
fn deserialize_enum<V>(self,
- name: &str,
- _variants: &'static [&'static str],
- visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
+ name: &str,
+ _variants: &'static [&'static str],
+ visitor: V)
+ -> Result<V::Value, Error>
+ where V: Visitor
{
match self.tokens.peek() {
Some(&Token::EnumStart(n)) if name == n => {
self.tokens.next();
- visitor.visit_enum(DeserializerEnumVisitor {
- de: self,
- })
+ visitor.visit_enum(DeserializerEnumVisitor { de: self })
}
- Some(&Token::EnumUnit(n, _))
- | Some(&Token::EnumNewType(n, _))
- | Some(&Token::EnumSeqStart(n, _, _))
- | Some(&Token::EnumMapStart(n, _, _)) if name == n => {
- visitor.visit_enum(DeserializerEnumVisitor {
- de: self,
- })
+ Some(&Token::EnumUnit(n, _)) |
+ Some(&Token::EnumNewType(n, _)) |
+ Some(&Token::EnumSeqStart(n, _, _)) |
+ Some(&Token::EnumMapStart(n, _, _)) if name == n => {
+ visitor.visit_enum(DeserializerEnumVisitor { de: self })
}
Some(_) => {
let token = self.tokens.next().unwrap();
@@ -181,7 +182,7 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
}
fn deserialize_unit_struct<V>(self, name: &str, visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
+ where V: Visitor
{
match self.tokens.peek() {
Some(&Token::UnitStruct(n)) => {
@@ -197,10 +198,8 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
}
}
- fn deserialize_newtype_struct<V>(self,
- name: &str,
- visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
+ fn deserialize_newtype_struct<V>(self, name: &str, visitor: V) -> Result<V::Value, Error>
+ where V: Visitor
{
match self.tokens.peek() {
Some(&Token::StructNewType(n)) => {
@@ -216,10 +215,8 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
}
}
- fn deserialize_seq_fixed_size<V>(self,
- len: usize,
- visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
+ fn deserialize_seq_fixed_size<V>(self, len: usize, visitor: V) -> Result<V::Value, Error>
+ where V: Visitor
{
match self.tokens.peek() {
Some(&Token::SeqArrayStart(_)) => {
@@ -231,13 +228,12 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
}
}
- fn deserialize_tuple<V>(self,
- len: usize,
- visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
+ fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Error>
+ where V: Visitor
{
match self.tokens.peek() {
- Some(&Token::Unit) | Some(&Token::UnitStruct(_)) => {
+ Some(&Token::Unit) |
+ Some(&Token::UnitStruct(_)) => {
self.tokens.next();
visitor.visit_unit()
}
@@ -255,7 +251,10 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
}
Some(&Token::TupleStructStart(_, _)) => {
self.tokens.next();
- self.visit_seq(Some(len), Token::TupleStructSep, Token::TupleStructEnd, visitor)
+ self.visit_seq(Some(len),
+ Token::TupleStructSep,
+ Token::TupleStructEnd,
+ visitor)
}
Some(_) => self.deserialize(visitor),
None => Err(Error::EndOfTokens),
@@ -265,8 +264,9 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
fn deserialize_tuple_struct<V>(self,
name: &str,
len: usize,
- visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
+ visitor: V)
+ -> Result<V::Value, Error>
+ where V: Visitor
{
match self.tokens.peek() {
Some(&Token::Unit) => {
@@ -296,7 +296,10 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
Some(&Token::TupleStructStart(n, _)) => {
self.tokens.next();
if name == n {
- self.visit_seq(Some(len), Token::TupleStructSep, Token::TupleStructEnd, visitor)
+ self.visit_seq(Some(len),
+ Token::TupleStructSep,
+ Token::TupleStructEnd,
+ visitor)
} else {
Err(Error::InvalidName(n))
}
@@ -309,14 +312,18 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
fn deserialize_struct<V>(self,
name: &str,
fields: &'static [&'static str],
- visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
+ visitor: V)
+ -> Result<V::Value, Error>
+ where V: Visitor
{
match self.tokens.peek() {
Some(&Token::StructStart(n, _)) => {
self.tokens.next();
if name == n {
- self.visit_map(Some(fields.len()), Token::StructSep, Token::StructEnd, visitor)
+ self.visit_map(Some(fields.len()),
+ Token::StructSep,
+ Token::StructEnd,
+ visitor)
} else {
Err(Error::InvalidName(n))
}
@@ -333,7 +340,9 @@ impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
//////////////////////////////////////////////////////////////////////////
-struct DeserializerSeqVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
+struct DeserializerSeqVisitor<'a, I: 'a>
+ where I: Iterator<Item = Token<'static>>
+{
de: &'a mut Deserializer<I>,
len: Option<usize>,
sep: Token<'static>,
@@ -341,12 +350,12 @@ struct DeserializerSeqVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>>
}
impl<'a, I> SeqVisitor for DeserializerSeqVisitor<'a, I>
- where I: Iterator<Item=Token<'static>>,
+ where I: Iterator<Item = Token<'static>>
{
type Error = Error;
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
- where T: DeserializeSeed,
+ where T: DeserializeSeed
{
if self.de.tokens.peek() == Some(&self.end) {
return Ok(None);
@@ -369,7 +378,9 @@ impl<'a, I> SeqVisitor for DeserializerSeqVisitor<'a, I>
//////////////////////////////////////////////////////////////////////////
-struct DeserializerMapVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
+struct DeserializerMapVisitor<'a, I: 'a>
+ where I: Iterator<Item = Token<'static>>
+{
de: &'a mut Deserializer<I>,
len: Option<usize>,
sep: Token<'static>,
@@ -377,12 +388,12 @@ struct DeserializerMapVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>>
}
impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
- where I: Iterator<Item=Token<'static>>,
+ where I: Iterator<Item = Token<'static>>
{
type Error = Error;
fn visit_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
- where K: DeserializeSeed,
+ where K: DeserializeSeed
{
if self.de.tokens.peek() == Some(&self.end) {
return Ok(None);
@@ -398,7 +409,7 @@ impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
}
fn visit_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
- where V: DeserializeSeed,
+ where V: DeserializeSeed
{
seed.deserialize(&mut *self.de)
}
@@ -411,24 +422,26 @@ impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
//////////////////////////////////////////////////////////////////////////
-struct DeserializerEnumVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
+struct DeserializerEnumVisitor<'a, I: 'a>
+ where I: Iterator<Item = Token<'static>>
+{
de: &'a mut Deserializer<I>,
}
impl<'a, I> EnumVisitor for DeserializerEnumVisitor<'a, I>
- where I: Iterator<Item=Token<'static>>,
+ where I: Iterator<Item = Token<'static>>
{
type Error = Error;
type Variant = Self;
fn visit_variant_seed<V>(self, seed: V) -> Result<(V::Value, Self), Error>
- where V: DeserializeSeed,
+ where V: DeserializeSeed
{
match self.de.tokens.peek() {
- Some(&Token::EnumUnit(_, v))
- | Some(&Token::EnumNewType(_, v))
- | Some(&Token::EnumSeqStart(_, v, _))
- | Some(&Token::EnumMapStart(_, v, _)) => {
+ Some(&Token::EnumUnit(_, v)) |
+ Some(&Token::EnumNewType(_, v)) |
+ Some(&Token::EnumSeqStart(_, v, _)) |
+ Some(&Token::EnumMapStart(_, v, _)) => {
let de = v.into_deserializer();
let value = try!(seed.deserialize(de));
Ok((value, self))
@@ -443,7 +456,7 @@ impl<'a, I> EnumVisitor for DeserializerEnumVisitor<'a, I>
}
impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
- where I: Iterator<Item=Token<'static>>
+ where I: Iterator<Item = Token<'static>>
{
type Error = Error;
@@ -453,32 +466,26 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
self.de.tokens.next();
Ok(())
}
- Some(_) => {
- Deserialize::deserialize(self.de)
- }
+ Some(_) => Deserialize::deserialize(self.de),
None => Err(Error::EndOfTokens),
}
}
fn visit_newtype_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
- where T: DeserializeSeed,
+ where T: DeserializeSeed
{
match self.de.tokens.peek() {
Some(&Token::EnumNewType(_, _)) => {
self.de.tokens.next();
seed.deserialize(self.de)
}
- Some(_) => {
- seed.deserialize(self.de)
- }
+ Some(_) => seed.deserialize(self.de),
None => Err(Error::EndOfTokens),
}
}
- fn visit_tuple<V>(self,
- len: usize,
- visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
+ fn visit_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Error>
+ where V: Visitor
{
match self.de.tokens.peek() {
Some(&Token::EnumSeqStart(_, _, enum_len)) => {
@@ -499,24 +506,23 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
Err(Error::UnexpectedToken(token))
}
}
- Some(_) => {
- de::Deserializer::deserialize(self.de, visitor)
- }
+ Some(_) => de::Deserializer::deserialize(self.de, visitor),
None => Err(Error::EndOfTokens),
}
}
- fn visit_struct<V>(self,
- fields: &'static [&'static str],
- visitor: V) -> Result<V::Value, Error>
- where V: Visitor,
+ fn visit_struct<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Error>
+ where V: Visitor
{
match self.de.tokens.peek() {
Some(&Token::EnumMapStart(_, _, enum_len)) => {
let token = self.de.tokens.next().unwrap();
if fields.len() == enum_len {
- self.de.visit_map(Some(fields.len()), Token::EnumMapSep, Token::EnumMapEnd, visitor)
+ self.de.visit_map(Some(fields.len()),
+ Token::EnumMapSep,
+ Token::EnumMapEnd,
+ visitor)
} else {
Err(Error::UnexpectedToken(token))
}
@@ -530,9 +536,7 @@ impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
Err(Error::UnexpectedToken(token))
}
}
- Some(_) => {
- de::Deserializer::deserialize(self.de, visitor)
- }
+ Some(_) => de::Deserializer::deserialize(self.de, visitor),
None => Err(Error::EndOfTokens),
}
}
diff --git a/serde_test/src/lib.rs b/serde_test/src/lib.rs
index 53f966f67..29668e8c0 100644
--- a/serde_test/src/lib.rs
+++ b/serde_test/src/lib.rs
@@ -2,13 +2,8 @@
extern crate serde;
mod assert;
-pub use assert::{
- assert_tokens,
- assert_ser_tokens,
- assert_ser_tokens_error,
- assert_de_tokens,
- assert_de_tokens_error,
-};
+pub use assert::{assert_tokens, assert_ser_tokens, assert_ser_tokens_error, assert_de_tokens,
+ assert_de_tokens_error};
mod ser;
pub use ser::Serializer;
diff --git a/serde_test/src/ser.rs b/serde_test/src/ser.rs
index 4327733fb..620976a37 100644
--- a/serde_test/src/ser.rs
+++ b/serde_test/src/ser.rs
@@ -6,14 +6,14 @@ use error::Error;
use token::Token;
pub struct Serializer<'a, I>
- where I: Iterator<Item=&'a Token<'a>>,
+ where I: Iterator<Item = &'a Token<'a>>
{
tokens: I,
phantom: PhantomData<&'a Token<'a>>,
}
impl<'a, I> Serializer<'a, I>
- where I: Iterator<Item=&'a Token<'a>>,
+ where I: Iterator<Item = &'a Token<'a>>
{
pub fn new(tokens: I) -> Serializer<'a, I> {
Serializer {
@@ -28,7 +28,7 @@ impl<'a, I> Serializer<'a, I>
}
impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
- where I: Iterator<Item=&'a Token<'a>>,
+ where I: Iterator<Item = &'a Token<'a>>
{
type Ok = ();
type Error = Error;
@@ -124,15 +124,14 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
fn serialize_unit_variant(self,
name: &str,
_variant_index: usize,
- variant: &str) -> Result<(), Error> {
+ variant: &str)
+ -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::EnumUnit(name, variant)));
Ok(())
}
- fn serialize_newtype_struct<T: ?Sized>(self,
- name: &'static str,
- value: &T) -> Result<(), Error>
- where T: Serialize,
+ fn serialize_newtype_struct<T: ?Sized>(self, name: &'static str, value: &T) -> Result<(), Error>
+ where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::StructNewType(name)));
value.serialize(self)
@@ -142,8 +141,9 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
name: &str,
_variant_index: usize,
variant: &str,
- value: &T) -> Result<(), Error>
- where T: Serialize,
+ value: &T)
+ -> Result<(), Error>
+ where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::EnumNewType(name, variant)));
value.serialize(self)
@@ -155,7 +155,7 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
}
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<(), Error>
- where T: Serialize,
+ where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::Option(true)));
value.serialize(self)
@@ -177,7 +177,8 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
}
fn serialize_tuple_struct(self, name: &'static str, len: usize) -> Result<Self, Error> {
- assert_eq!(self.tokens.next(), Some(&Token::TupleStructStart(name, len)));
+ assert_eq!(self.tokens.next(),
+ Some(&Token::TupleStructStart(name, len)));
Ok(self)
}
@@ -185,9 +186,10 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
name: &str,
_variant_index: usize,
variant: &str,
- len: usize) -> Result<Self, Error>
- {
- assert_eq!(self.tokens.next(), Some(&Token::EnumSeqStart(name, variant, len)));
+ len: usize)
+ -> Result<Self, Error> {
+ assert_eq!(self.tokens.next(),
+ Some(&Token::EnumSeqStart(name, variant, len)));
Ok(self)
}
@@ -205,15 +207,16 @@ impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
name: &str,
_variant_index: usize,
variant: &str,
- len: usize) -> Result<Self, Error>
- {
- assert_eq!(self.tokens.next(), Some(&Token::EnumMapStart(name, variant, len)));
+ len: usize)
+ -> Result<Self, Error> {
+ assert_eq!(self.tokens.next(),
+ Some(&Token::EnumMapStart(name, variant, len)));
Ok(self)
}
}
impl<'s, 'a, I> ser::SerializeSeq for &'s mut Serializer<'a, I>
- where I: Iterator<Item=&'a Token<'a>>,
+ where I: Iterator<Item = &'a Token<'a>>
{
type Ok = ();
type Error = Error;
@@ -232,7 +235,7 @@ impl<'s, 'a, I> ser::SerializeSeq for &'s mut Serializer<'a, I>
}
impl<'s, 'a, I> ser::SerializeTuple for &'s mut Serializer<'a, I>
- where I: Iterator<Item=&'a Token<'a>>,
+ where I: Iterator<Item = &'a Token<'a>>
{
type Ok = ();
type Error = Error;
@@ -251,7 +254,7 @@ impl<'s, 'a, I> ser::SerializeTuple for &'s mut Serializer<'a, I>
}
impl<'s, 'a, I> ser::SerializeTupleStruct for &'s mut Serializer<'a, I>
- where I: Iterator<Item=&'a Token<'a>>,
+ where I: Iterator<Item = &'a Token<'a>>
{
type Ok = ();
type Error = Error;
@@ -270,7 +273,7 @@ impl<'s, 'a, I> ser::SerializeTupleStruct for &'s mut Serializer<'a, I>
}
impl<'s, 'a, I> ser::SerializeTupleVariant for &'s mut Serializer<'a, I>
- where I: Iterator<Item=&'a Token<'a>>,
+ where I: Iterator<Item = &'a Token<'a>>
{
type Ok = ();
type Error = Error;
@@ -289,17 +292,21 @@ impl<'s, 'a, I> ser::SerializeTupleVariant for &'s mut Serializer<'a, I>
}
impl<'s, 'a, I> ser::SerializeMap for &'s mut Serializer<'a, I>
- where I: Iterator<Item=&'a Token<'a>>,
+ where I: Iterator<Item = &'a Token<'a>>
{
type Ok = ();
type Error = Error;
- fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error> where T: Serialize {
+ fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
+ where T: Serialize
+ {
assert_eq!(self.tokens.next(), Some(&Token::MapSep));
key.serialize(&mut **self)
}
- fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize {
+ fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
+ where T: Serialize
+ {
value.serialize(&mut **self)
}
@@ -310,12 +317,17 @@ impl<'s, 'a, I> ser::SerializeMap for &'s mut Serializer<'a, I>
}
impl<'s, 'a, I> ser::SerializeStruct for &'s mut Serializer<'a, I>
- where I: Iterator<Item=&'a Token<'a>>,
+ where I: Iterator<Item = &'a Token<'a>>
{
type Ok = ();
type Error = Error;
- fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> where T: Serialize {
+ fn serialize_field<T: ?Sized>(&mut self,
+ key: &'static str,
+ value: &T)
+ -> Result<(), Self::Error>
+ where T: Serialize
+ {
assert_eq!(self.tokens.next(), Some(&Token::StructSep));
try!(key.serialize(&mut **self));
value.serialize(&mut **self)
@@ -328,12 +340,17 @@ impl<'s, 'a, I> ser::SerializeStruct for &'s mut Serializer<'a, I>
}
impl<'s, 'a, I> ser::SerializeStructVariant for &'s mut Serializer<'a, I>
- where I: Iterator<Item=&'a Token<'a>>,
+ where I: Iterator<Item = &'a Token<'a>>
{
type Ok = ();
type Error = Error;
- fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> where T: Serialize {
+ fn serialize_field<T: ?Sized>(&mut self,
+ key: &'static str,
+ value: &T)
+ -> Result<(), Self::Error>
+ where T: Serialize
+ {
assert_eq!(self.tokens.next(), Some(&Token::EnumMapSep));
try!(key.serialize(&mut **self));
value.serialize(&mut **self)
| [
"438"
] | serde-rs__serde-762 | Consider using rustfmt
| 0.9 | 964a2dd4d195b8c14c76df5f7ddb8f321c0d211c | diff --git a/serde/src/bytes.rs b/serde/src/bytes.rs
index 8f9148390..52cc1caff 100644
--- a/serde/src/bytes.rs
+++ b/serde/src/bytes.rs
@@ -60,9 +60,7 @@ pub struct Bytes<'a> {
impl<'a> Bytes<'a> {
/// Wrap an existing `&[u8]`.
pub fn new(bytes: &'a [u8]) -> Self {
- Bytes {
- bytes: bytes,
- }
+ Bytes { bytes: bytes }
}
}
@@ -98,7 +96,9 @@ impl<'a> Into<&'a [u8]> for Bytes<'a> {
impl<'a> ops::Deref for Bytes<'a> {
type Target = [u8];
- fn deref(&self) -> &[u8] { self.bytes }
+ fn deref(&self) -> &[u8] {
+ self.bytes
+ }
}
impl<'a> ser::Serialize for Bytes<'a> {
@@ -161,9 +161,7 @@ mod bytebuf {
/// Wrap existing bytes in a `ByteBuf`.
pub fn from<T: Into<Vec<u8>>>(bytes: T) -> Self {
- ByteBuf {
- bytes: bytes.into(),
- }
+ ByteBuf { bytes: bytes.into() }
}
}
@@ -216,11 +214,15 @@ mod bytebuf {
impl ops::Deref for ByteBuf {
type Target = [u8];
- fn deref(&self) -> &[u8] { &self.bytes[..] }
+ fn deref(&self) -> &[u8] {
+ &self.bytes[..]
+ }
}
impl ops::DerefMut for ByteBuf {
- fn deref_mut(&mut self) -> &mut [u8] { &mut self.bytes[..] }
+ fn deref_mut(&mut self) -> &mut [u8] {
+ &mut self.bytes[..]
+ }
}
impl ser::Serialize for ByteBuf {
@@ -243,14 +245,14 @@ mod bytebuf {
#[inline]
fn visit_unit<E>(self) -> Result<ByteBuf, E>
- where E: de::Error,
+ where E: de::Error
{
Ok(ByteBuf::new())
}
#[inline]
fn visit_seq<V>(self, mut visitor: V) -> Result<ByteBuf, V::Error>
- where V: de::SeqVisitor,
+ where V: de::SeqVisitor
{
let (len, _) = visitor.size_hint();
let mut values = Vec::with_capacity(len);
@@ -264,26 +266,26 @@ mod bytebuf {
#[inline]
fn visit_bytes<E>(self, v: &[u8]) -> Result<ByteBuf, E>
- where E: de::Error,
+ where E: de::Error
{
Ok(ByteBuf::from(v))
}
#[inline]
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<ByteBuf, E>
- where E: de::Error,
+ where E: de::Error
{
Ok(ByteBuf::from(v))
}
fn visit_str<E>(self, v: &str) -> Result<ByteBuf, E>
- where E: de::Error,
+ where E: de::Error
{
Ok(ByteBuf::from(v))
}
fn visit_string<E>(self, v: String) -> Result<ByteBuf, E>
- where E: de::Error,
+ where E: de::Error
{
Ok(ByteBuf::from(v))
}
@@ -302,7 +304,9 @@ mod bytebuf {
///////////////////////////////////////////////////////////////////////////////
#[inline]
-fn escape_bytestring<'a>(bytes: &'a [u8]) -> iter::FlatMap<slice::Iter<'a, u8>, char::EscapeDefault, fn(&u8) -> char::EscapeDefault> {
+fn escape_bytestring<'a>
+ (bytes: &'a [u8])
+ -> iter::FlatMap<slice::Iter<'a, u8>, char::EscapeDefault, fn(&u8) -> char::EscapeDefault> {
fn f(b: &u8) -> char::EscapeDefault {
char::from_u32(*b as u32).unwrap().escape_default()
}
diff --git a/serde/src/de/content.rs b/serde/src/de/content.rs
index 59c3f8ae5..d3bd0b643 100644
--- a/serde/src/de/content.rs
+++ b/serde/src/de/content.rs
@@ -19,16 +19,8 @@ use collections::{String, Vec};
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::boxed::Box;
-use de::{
- self,
- Deserialize,
- DeserializeSeed,
- Deserializer,
- Visitor,
- SeqVisitor,
- MapVisitor,
- EnumVisitor,
-};
+use de::{self, Deserialize, DeserializeSeed, Deserializer, Visitor, SeqVisitor, MapVisitor,
+ EnumVisitor};
/// Used from generated code to buffer the contents of the Deserializer when
/// deserializing untagged enums and internally tagged enums.
@@ -243,9 +235,7 @@ struct TagOrContentVisitor {
impl TagOrContentVisitor {
fn new(name: &'static str) -> Self {
- TagOrContentVisitor {
- name: name,
- }
+ TagOrContentVisitor { name: name }
}
}
@@ -491,9 +481,7 @@ impl<T> Visitor for TaggedContentVisitor<T>
}
}
match tag {
- None => {
- Err(de::Error::missing_field(self.tag_name))
- }
+ None => Err(de::Error::missing_field(self.tag_name)),
Some(tag) => {
Ok(TaggedContent {
tag: tag,
@@ -544,14 +532,15 @@ impl<E> Deserializer for ContentDeserializer<E>
let value = try!(visitor.visit_seq(&mut seq_visitor));
try!(seq_visitor.end());
Ok(value)
- },
+ }
Content::Map(v) => {
- let map = v.into_iter().map(|(k, v)| (ContentDeserializer::new(k), ContentDeserializer::new(v)));
+ let map = v.into_iter()
+ .map(|(k, v)| (ContentDeserializer::new(k), ContentDeserializer::new(v)));
let mut map_visitor = de::value::MapDeserializer::new(map);
let value = try!(visitor.visit_map(&mut map_visitor));
try!(map_visitor.end());
Ok(value)
- },
+ }
Content::Bytes(v) => visitor.visit_byte_buf(v),
}
}
@@ -563,7 +552,7 @@ impl<E> Deserializer for ContentDeserializer<E>
Content::None => visitor.visit_none(),
Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
Content::Unit => visitor.visit_unit(),
- _ => visitor.visit_some(self)
+ _ => visitor.visit_some(self),
}
}
@@ -630,14 +619,16 @@ impl<'a, E> Deserializer for ContentRefDeserializer<'a, E>
let value = try!(visitor.visit_seq(&mut seq_visitor));
try!(seq_visitor.end());
Ok(value)
- },
+ }
Content::Map(ref v) => {
- let map = v.into_iter().map(|&(ref k, ref v)| (ContentRefDeserializer::new(k), ContentRefDeserializer::new(v)));
+ let map = v.into_iter().map(|&(ref k, ref v)| {
+ (ContentRefDeserializer::new(k), ContentRefDeserializer::new(v))
+ });
let mut map_visitor = de::value::MapDeserializer::new(map);
let value = try!(visitor.visit_map(&mut map_visitor));
try!(map_visitor.end());
Ok(value)
- },
+ }
Content::Bytes(ref v) => visitor.visit_bytes(v),
}
}
@@ -649,7 +640,7 @@ impl<'a, E> Deserializer for ContentRefDeserializer<'a, E>
Content::None => visitor.visit_none(),
Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
Content::Unit => visitor.visit_unit(),
- _ => visitor.visit_some(self)
+ _ => visitor.visit_some(self),
}
}
diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index fa3cd214f..e933d6922 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -6,26 +6,10 @@ use std::borrow::Cow;
use collections::borrow::Cow;
#[cfg(all(feature = "collections", not(feature = "std")))]
-use collections::{
- BinaryHeap,
- BTreeMap,
- BTreeSet,
- LinkedList,
- VecDeque,
- Vec,
- String,
-};
+use collections::{BinaryHeap, BTreeMap, BTreeSet, LinkedList, VecDeque, Vec, String};
#[cfg(feature = "std")]
-use std::collections::{
- HashMap,
- HashSet,
- BinaryHeap,
- BTreeMap,
- BTreeSet,
- LinkedList,
- VecDeque,
-};
+use std::collections::{HashMap, HashSet, BinaryHeap, BTreeMap, BTreeSet, LinkedList, VecDeque};
#[cfg(feature = "collections")]
use collections::borrow::ToOwned;
@@ -63,17 +47,8 @@ use core::nonzero::{NonZero, Zeroable};
#[allow(deprecated)] // required for impl Deserialize for NonZero<T>
use core::num::Zero;
-use de::{
- Deserialize,
- Deserializer,
- EnumVisitor,
- Error,
- MapVisitor,
- SeqVisitor,
- Unexpected,
- VariantVisitor,
- Visitor,
-};
+use de::{Deserialize, Deserializer, EnumVisitor, Error, MapVisitor, SeqVisitor, Unexpected,
+ VariantVisitor, Visitor};
use de::from_primitive::FromPrimitive;
///////////////////////////////////////////////////////////////////////////////
@@ -89,13 +64,13 @@ impl Visitor for UnitVisitor {
}
fn visit_unit<E>(self) -> Result<(), E>
- where E: Error,
+ where E: Error
{
Ok(())
}
fn visit_seq<V>(self, _: V) -> Result<(), V::Error>
- where V: SeqVisitor,
+ where V: SeqVisitor
{
Ok(())
}
@@ -103,7 +78,7 @@ impl Visitor for UnitVisitor {
impl Deserialize for () {
fn deserialize<D>(deserializer: D) -> Result<(), D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
deserializer.deserialize_unit(UnitVisitor)
}
@@ -122,13 +97,13 @@ impl Visitor for BoolVisitor {
}
fn visit_bool<E>(self, v: bool) -> Result<bool, E>
- where E: Error,
+ where E: Error
{
Ok(v)
}
fn visit_str<E>(self, s: &str) -> Result<bool, E>
- where E: Error,
+ where E: Error
{
match s.trim_matches(::utils::Pattern_White_Space) {
"true" => Ok(true),
@@ -140,7 +115,7 @@ impl Visitor for BoolVisitor {
impl Deserialize for bool {
fn deserialize<D>(deserializer: D) -> Result<bool, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
deserializer.deserialize_bool(BoolVisitor)
}
@@ -231,14 +206,14 @@ impl Visitor for CharVisitor {
#[inline]
fn visit_char<E>(self, v: char) -> Result<char, E>
- where E: Error,
+ where E: Error
{
Ok(v)
}
#[inline]
fn visit_str<E>(self, v: &str) -> Result<char, E>
- where E: Error,
+ where E: Error
{
let mut iter = v.chars();
match (iter.next(), iter.next()) {
@@ -251,7 +226,7 @@ impl Visitor for CharVisitor {
impl Deserialize for char {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<char, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
deserializer.deserialize_char(CharVisitor)
}
@@ -271,25 +246,25 @@ impl Visitor for StringVisitor {
}
fn visit_str<E>(self, v: &str) -> Result<String, E>
- where E: Error,
+ where E: Error
{
Ok(v.to_owned())
}
fn visit_string<E>(self, v: String) -> Result<String, E>
- where E: Error,
+ where E: Error
{
Ok(v)
}
fn visit_unit<E>(self) -> Result<String, E>
- where E: Error,
+ where E: Error
{
Ok(String::new())
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<String, E>
- where E: Error,
+ where E: Error
{
match str::from_utf8(v) {
Ok(s) => Ok(s.to_owned()),
@@ -298,7 +273,7 @@ impl Visitor for StringVisitor {
}
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<String, E>
- where E: Error,
+ where E: Error
{
match String::from_utf8(v) {
Ok(s) => Ok(s),
@@ -310,7 +285,7 @@ impl Visitor for StringVisitor {
#[cfg(any(feature = "std", feature = "collections"))]
impl Deserialize for String {
fn deserialize<D>(deserializer: D) -> Result<String, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
deserializer.deserialize_string(StringVisitor)
}
@@ -322,9 +297,7 @@ struct OptionVisitor<T> {
marker: PhantomData<T>,
}
-impl<
- T: Deserialize,
-> Visitor for OptionVisitor<T> {
+impl<T: Deserialize> Visitor for OptionVisitor<T> {
type Value = Option<T>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
@@ -333,29 +306,31 @@ impl<
#[inline]
fn visit_unit<E>(self) -> Result<Option<T>, E>
- where E: Error,
+ where E: Error
{
Ok(None)
}
#[inline]
fn visit_none<E>(self) -> Result<Option<T>, E>
- where E: Error,
+ where E: Error
{
Ok(None)
}
#[inline]
fn visit_some<D>(self, deserializer: D) -> Result<Option<T>, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
Ok(Some(try!(Deserialize::deserialize(deserializer))))
}
}
-impl<T> Deserialize for Option<T> where T: Deserialize {
+impl<T> Deserialize for Option<T>
+ where T: Deserialize
+{
fn deserialize<D>(deserializer: D) -> Result<Option<T>, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
deserializer.deserialize_option(OptionVisitor { marker: PhantomData })
}
@@ -377,7 +352,7 @@ impl<T> Visitor for PhantomDataVisitor<T> {
#[inline]
fn visit_unit<E>(self) -> Result<PhantomData<T>, E>
- where E: Error,
+ where E: Error
{
Ok(PhantomData)
}
@@ -385,7 +360,7 @@ impl<T> Visitor for PhantomDataVisitor<T> {
impl<T> Deserialize for PhantomData<T> {
fn deserialize<D>(deserializer: D) -> Result<PhantomData<T>, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
let visitor = PhantomDataVisitor { marker: PhantomData };
deserializer.deserialize_unit_struct("PhantomData", visitor)
@@ -524,13 +499,13 @@ struct ArrayVisitor<A> {
impl<A> ArrayVisitor<A> {
pub fn new() -> Self {
- ArrayVisitor {
- marker: PhantomData,
- }
+ ArrayVisitor { marker: PhantomData }
}
}
-impl<T> Visitor for ArrayVisitor<[T; 0]> where T: Deserialize {
+impl<T> Visitor for ArrayVisitor<[T; 0]>
+ where T: Deserialize
+{
type Value = [T; 0];
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
@@ -539,14 +514,14 @@ impl<T> Visitor for ArrayVisitor<[T; 0]> where T: Deserialize {
#[inline]
fn visit_unit<E>(self) -> Result<[T; 0], E>
- where E: Error,
+ where E: Error
{
Ok([])
}
#[inline]
fn visit_seq<V>(self, _: V) -> Result<[T; 0], V::Error>
- where V: SeqVisitor,
+ where V: SeqVisitor
{
Ok([])
}
@@ -556,7 +531,7 @@ impl<T> Deserialize for [T; 0]
where T: Deserialize
{
fn deserialize<D>(deserializer: D) -> Result<[T; 0], D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
deserializer.deserialize_seq_fixed_size(0, ArrayVisitor::<[T; 0]>::new())
}
@@ -798,7 +773,7 @@ map_impl!(
#[cfg(feature = "std")]
impl Deserialize for net::IpAddr {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
let s = try!(String::deserialize(deserializer));
match s.parse() {
@@ -811,7 +786,7 @@ impl Deserialize for net::IpAddr {
#[cfg(feature = "std")]
impl Deserialize for net::Ipv4Addr {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
let s = try!(String::deserialize(deserializer));
match s.parse() {
@@ -824,7 +799,7 @@ impl Deserialize for net::Ipv4Addr {
#[cfg(feature = "std")]
impl Deserialize for net::Ipv6Addr {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
let s = try!(String::deserialize(deserializer));
match s.parse() {
@@ -839,7 +814,7 @@ impl Deserialize for net::Ipv6Addr {
#[cfg(feature = "std")]
impl Deserialize for net::SocketAddr {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
let s = try!(String::deserialize(deserializer));
match s.parse() {
@@ -852,7 +827,7 @@ impl Deserialize for net::SocketAddr {
#[cfg(feature = "std")]
impl Deserialize for net::SocketAddrV4 {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
let s = try!(String::deserialize(deserializer));
match s.parse() {
@@ -865,7 +840,7 @@ impl Deserialize for net::SocketAddrV4 {
#[cfg(feature = "std")]
impl Deserialize for net::SocketAddrV6 {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
let s = try!(String::deserialize(deserializer));
match s.parse() {
@@ -889,13 +864,13 @@ impl Visitor for PathBufVisitor {
}
fn visit_str<E>(self, v: &str) -> Result<path::PathBuf, E>
- where E: Error,
+ where E: Error
{
Ok(From::from(v))
}
fn visit_string<E>(self, v: String) -> Result<path::PathBuf, E>
- where E: Error,
+ where E: Error
{
Ok(From::from(v))
}
@@ -904,7 +879,7 @@ impl Visitor for PathBufVisitor {
#[cfg(feature = "std")]
impl Deserialize for path::PathBuf {
fn deserialize<D>(deserializer: D) -> Result<path::PathBuf, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
deserializer.deserialize_string(PathBufVisitor)
}
@@ -915,7 +890,7 @@ impl Deserialize for path::PathBuf {
#[cfg(any(feature = "std", feature = "alloc"))]
impl<T: Deserialize> Deserialize for Box<T> {
fn deserialize<D>(deserializer: D) -> Result<Box<T>, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
let val = try!(Deserialize::deserialize(deserializer));
Ok(Box::new(val))
@@ -925,7 +900,7 @@ impl<T: Deserialize> Deserialize for Box<T> {
#[cfg(any(feature = "std", feature = "collections"))]
impl<T: Deserialize> Deserialize for Box<[T]> {
fn deserialize<D>(deserializer: D) -> Result<Box<[T]>, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
let v: Vec<T> = try!(Deserialize::deserialize(deserializer));
Ok(v.into_boxed_slice())
@@ -945,7 +920,7 @@ impl Deserialize for Box<str> {
#[cfg(any(feature = "std", feature = "alloc"))]
impl<T: Deserialize> Deserialize for Arc<T> {
fn deserialize<D>(deserializer: D) -> Result<Arc<T>, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
let val = try!(Deserialize::deserialize(deserializer));
Ok(Arc::new(val))
@@ -955,7 +930,7 @@ impl<T: Deserialize> Deserialize for Arc<T> {
#[cfg(any(feature = "std", feature = "alloc"))]
impl<T: Deserialize> Deserialize for Rc<T> {
fn deserialize<D>(deserializer: D) -> Result<Rc<T>, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
let val = try!(Deserialize::deserialize(deserializer));
Ok(Rc::new(val))
@@ -963,10 +938,13 @@ impl<T: Deserialize> Deserialize for Rc<T> {
}
#[cfg(any(feature = "std", feature = "collections"))]
-impl<'a, T: ?Sized> Deserialize for Cow<'a, T> where T: ToOwned, T::Owned: Deserialize, {
+impl<'a, T: ?Sized> Deserialize for Cow<'a, T>
+ where T: ToOwned,
+ T::Owned: Deserialize
+{
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Cow<'a, T>, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
let val = try!(Deserialize::deserialize(deserializer));
Ok(Cow::Owned(val))
@@ -986,13 +964,16 @@ impl<'a, T: ?Sized> Deserialize for Cow<'a, T> where T: ToOwned, T::Owned: Deser
#[cfg(feature = "std")]
impl Deserialize for Duration {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
- enum Field { Secs, Nanos };
+ enum Field {
+ Secs,
+ Nanos,
+ };
impl Deserialize for Field {
fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
struct FieldVisitor;
@@ -1004,7 +985,7 @@ impl Deserialize for Duration {
}
fn visit_str<E>(self, value: &str) -> Result<Field, E>
- where E: Error,
+ where E: Error
{
match value {
"secs" => Ok(Field::Secs),
@@ -1014,7 +995,7 @@ impl Deserialize for Duration {
}
fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E>
- where E: Error,
+ where E: Error
{
match value {
b"secs" => Ok(Field::Secs),
@@ -1041,7 +1022,7 @@ impl Deserialize for Duration {
}
fn visit_seq<V>(self, mut visitor: V) -> Result<Duration, V::Error>
- where V: SeqVisitor,
+ where V: SeqVisitor
{
let secs: u64 = match try!(visitor.visit()) {
Some(value) => value,
@@ -1059,7 +1040,7 @@ impl Deserialize for Duration {
}
fn visit_map<V>(self, mut visitor: V) -> Result<Duration, V::Error>
- where V: MapVisitor,
+ where V: MapVisitor
{
let mut secs: Option<u64> = None;
let mut nanos: Option<u32> = None;
@@ -1100,24 +1081,30 @@ impl Deserialize for Duration {
#[cfg(feature = "unstable")]
#[allow(deprecated)] // num::Zero is deprecated but there is no replacement
-impl<T> Deserialize for NonZero<T> where T: Deserialize + PartialEq + Zeroable + Zero {
- fn deserialize<D>(deserializer: D) -> Result<NonZero<T>, D::Error> where D: Deserializer {
+impl<T> Deserialize for NonZero<T>
+ where T: Deserialize + PartialEq + Zeroable + Zero
+{
+ fn deserialize<D>(deserializer: D) -> Result<NonZero<T>, D::Error>
+ where D: Deserializer
+ {
let value = try!(Deserialize::deserialize(deserializer));
if value == Zero::zero() {
- return Err(Error::custom("expected a non-zero value"))
- }
- unsafe {
- Ok(NonZero::new(value))
+ return Err(Error::custom("expected a non-zero value"));
}
+ unsafe { Ok(NonZero::new(value)) }
}
}
///////////////////////////////////////////////////////////////////////////////
-impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
+impl<T, E> Deserialize for Result<T, E>
+ where T: Deserialize,
+ E: Deserialize
+{
fn deserialize<D>(deserializer: D) -> Result<Result<T, E>, D::Error>
- where D: Deserializer {
+ where D: Deserializer
+ {
enum Field {
Ok,
Err,
@@ -1137,15 +1124,21 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
formatter.write_str("`Ok` or `Err`")
}
- fn visit_u32<E>(self, value: u32) -> Result<Field, E> where E: Error {
+ fn visit_u32<E>(self, value: u32) -> Result<Field, E>
+ where E: Error
+ {
match value {
0 => Ok(Field::Ok),
1 => Ok(Field::Err),
- _ => Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self)),
+ _ => {
+ Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self))
+ }
}
}
- fn visit_str<E>(self, value: &str) -> Result<Field, E> where E: Error {
+ fn visit_str<E>(self, value: &str) -> Result<Field, E>
+ where E: Error
+ {
match value {
"Ok" => Ok(Field::Ok),
"Err" => Ok(Field::Err),
@@ -1153,14 +1146,18 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
}
}
- fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E> where E: Error {
+ fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E>
+ where E: Error
+ {
match value {
b"Ok" => Ok(Field::Ok),
b"Err" => Ok(Field::Err),
_ => {
match str::from_utf8(value) {
Ok(value) => Err(Error::unknown_variant(value, VARIANTS)),
- Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)),
+ Err(_) => {
+ Err(Error::invalid_value(Unexpected::Bytes(value), &self))
+ }
}
}
}
@@ -1208,7 +1205,7 @@ pub struct IgnoredAny;
impl Deserialize for IgnoredAny {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<IgnoredAny, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
struct IgnoredAnyVisitor;
@@ -1241,7 +1238,7 @@ impl Deserialize for IgnoredAny {
#[inline]
fn visit_str<E>(self, _: &str) -> Result<IgnoredAny, E>
- where E: Error,
+ where E: Error
{
Ok(IgnoredAny)
}
@@ -1253,14 +1250,14 @@ impl Deserialize for IgnoredAny {
#[inline]
fn visit_some<D>(self, _: D) -> Result<IgnoredAny, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
Ok(IgnoredAny)
}
#[inline]
fn visit_newtype_struct<D>(self, _: D) -> Result<IgnoredAny, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
Ok(IgnoredAny)
}
@@ -1272,7 +1269,7 @@ impl Deserialize for IgnoredAny {
#[inline]
fn visit_seq<V>(self, mut visitor: V) -> Result<IgnoredAny, V::Error>
- where V: SeqVisitor,
+ where V: SeqVisitor
{
while let Some(_) = try!(visitor.visit::<IgnoredAny>()) {
// Gobble
@@ -1282,7 +1279,7 @@ impl Deserialize for IgnoredAny {
#[inline]
fn visit_map<V>(self, mut visitor: V) -> Result<IgnoredAny, V::Error>
- where V: MapVisitor,
+ where V: MapVisitor
{
while let Some((_, _)) = try!(visitor.visit::<IgnoredAny, IgnoredAny>()) {
// Gobble
@@ -1292,7 +1289,7 @@ impl Deserialize for IgnoredAny {
#[inline]
fn visit_bytes<E>(self, _: &[u8]) -> Result<IgnoredAny, E>
- where E: Error,
+ where E: Error
{
Ok(IgnoredAny)
}
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index f01988bb9..9ae0ba0c0 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -181,7 +181,10 @@ pub trait Error: Sized + error::Error {
write!(formatter, "invalid type: {}, expected {}", self.unexp, self.exp)
}
}
- Error::custom(InvalidType { unexp: unexp, exp: exp })
+ Error::custom(InvalidType {
+ unexp: unexp,
+ exp: exp,
+ })
}
/// Raised when a `Deserialize` receives a value of the right type but that
@@ -207,7 +210,10 @@ pub trait Error: Sized + error::Error {
write!(formatter, "invalid value: {}, expected {}", self.unexp, self.exp)
}
}
- Error::custom(InvalidValue { unexp: unexp, exp: exp })
+ Error::custom(InvalidValue {
+ unexp: unexp,
+ exp: exp,
+ })
}
/// Raised when deserializing a sequence or map and the input data contains
@@ -229,7 +235,10 @@ pub trait Error: Sized + error::Error {
write!(formatter, "invalid length {}, expected {}", self.len, self.exp)
}
}
- Error::custom(InvalidLength { len: len, exp: exp })
+ Error::custom(InvalidLength {
+ len: len,
+ exp: exp,
+ })
}
/// Raised when a `Deserialize` enum type received a variant with an
@@ -253,7 +262,10 @@ pub trait Error: Sized + error::Error {
}
}
}
- Error::custom(UnknownVariant { variant: variant, expected: expected })
+ Error::custom(UnknownVariant {
+ variant: variant,
+ expected: expected,
+ })
}
/// Raised when a `Deserialize` struct type received a field with an
@@ -277,7 +289,10 @@ pub trait Error: Sized + error::Error {
}
}
}
- Error::custom(UnknownField { field: field, expected: expected })
+ Error::custom(UnknownField {
+ field: field,
+ expected: expected,
+ })
}
/// Raised when a `Deserialize` struct type expected to receive a required
@@ -470,7 +485,9 @@ pub trait Expected {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result;
}
-impl<T> Expected for T where T: Visitor {
+impl<T> Expected for T
+ where T: Visitor
+{
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
self.expecting(formatter)
}
@@ -521,8 +538,7 @@ pub trait Deserialize: Sized {
/// manual for more information about how to implement this method.
///
/// [impl-deserialize]: https://serde.rs/impl-deserialize.html
- fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer;
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer;
}
/// `DeserializeSeed` is the stateful form of the `Deserialize` trait. If you
@@ -670,8 +686,7 @@ pub trait DeserializeSeed: Sized {
/// Equivalent to the more common `Deserialize::deserialize` method, except
/// with some initial piece of data (the seed) passed in.
- fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
- where D: Deserializer;
+ fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer;
}
impl<T> DeserializeSeed for PhantomData<T>
@@ -784,56 +799,43 @@ pub trait Deserializer: Sized {
/// `Deserializer::deserialize` means your data type will be able to
/// deserialize from self-describing formats only, ruling out Bincode and
/// many others.
- fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a `bool` value.
- fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a `u8` value.
- fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a `u16` value.
- fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a `u32` value.
- fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a `u64` value.
- fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting an `i8` value.
- fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting an `i16` value.
- fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting an `i32` value.
- fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting an `i64` value.
- fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a `f32` value.
- fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a `f64` value.
- fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a `char` value.
- fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a string value and does
/// not benefit from taking ownership of buffered data owned by the
@@ -842,8 +844,7 @@ pub trait Deserializer: Sized {
/// If the `Visitor` would benefit from taking ownership of `String` data,
/// indiciate this to the `Deserializer` by using `deserialize_string`
/// instead.
- fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a string value and would
/// benefit from taking ownership of buffered data owned by the
@@ -852,8 +853,7 @@ pub trait Deserializer: Sized {
/// If the `Visitor` would not benefit from taking ownership of `String`
/// data, indicate that to the `Deserializer` by using `deserialize_str`
/// instead.
- fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a byte array and does not
/// benefit from taking ownership of buffered data owned by the
@@ -862,8 +862,7 @@ pub trait Deserializer: Sized {
/// If the `Visitor` would benefit from taking ownership of `Vec<u8>` data,
/// indicate this to the `Deserializer` by using `deserialize_byte_buf`
/// instead.
- fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a byte array and would
/// benefit from taking ownership of buffered data owned by the
@@ -872,44 +871,43 @@ pub trait Deserializer: Sized {
/// If the `Visitor` would not benefit from taking ownership of `Vec<u8>`
/// data, indicate that to the `Deserializer` by using `deserialize_bytes`
/// instead.
- fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting an optional value.
///
/// This allows deserializers that encode an optional value as a nullable
/// value to convert the null value into `None` and a regular value into
/// `Some(value)`.
- fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a unit value.
- fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a unit struct with a
/// particular name.
fn deserialize_unit_struct<V>(self,
name: &'static str,
- visitor: V) -> Result<V::Value, Self::Error>
+ visitor: V)
+ -> Result<V::Value, Self::Error>
where V: Visitor;
/// Hint that the `Deserialize` type is expecting a newtype struct with a
/// particular name.
fn deserialize_newtype_struct<V>(self,
name: &'static str,
- visitor: V) -> Result<V::Value, Self::Error>
+ visitor: V)
+ -> Result<V::Value, Self::Error>
where V: Visitor;
/// Hint that the `Deserialize` type is expecting a sequence of values.
- fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a sequence of values and
/// knows how many values there are without looking at the serialized data.
fn deserialize_seq_fixed_size<V>(self,
len: usize,
- visitor: V) -> Result<V::Value, Self::Error>
+ visitor: V)
+ -> Result<V::Value, Self::Error>
where V: Visitor;
/// Hint that the `Deserialize` type is expecting a tuple value with a
@@ -922,19 +920,20 @@ pub trait Deserializer: Sized {
fn deserialize_tuple_struct<V>(self,
name: &'static str,
len: usize,
- visitor: V) -> Result<V::Value, Self::Error>
+ visitor: V)
+ -> Result<V::Value, Self::Error>
where V: Visitor;
/// Hint that the `Deserialize` type is expecting a map of key-value pairs.
- fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: Visitor;
+ fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor;
/// Hint that the `Deserialize` type is expecting a struct with a particular
/// name and fields.
fn deserialize_struct<V>(self,
name: &'static str,
fields: &'static [&'static str],
- visitor: V) -> Result<V::Value, Self::Error>
+ visitor: V)
+ -> Result<V::Value, Self::Error>
where V: Visitor;
/// Hint that the `Deserialize` type is expecting the name of a struct
@@ -947,7 +946,8 @@ pub trait Deserializer: Sized {
fn deserialize_enum<V>(self,
name: &'static str,
variants: &'static [&'static str],
- visitor: V) -> Result<V::Value, Self::Error>
+ visitor: V)
+ -> Result<V::Value, Self::Error>
where V: Visitor;
/// Hint that the `Deserialize` type needs to deserialize a value whose type
@@ -1016,77 +1016,77 @@ pub trait Visitor: Sized {
/// Deserialize a `bool` into a `Value`.
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
Err(Error::invalid_type(Unexpected::Bool(v), &self))
}
/// Deserialize an `i8` into a `Value`.
fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
self.visit_i64(v as i64)
}
/// Deserialize an `i16` into a `Value`.
fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
self.visit_i64(v as i64)
}
/// Deserialize an `i32` into a `Value`.
fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
self.visit_i64(v as i64)
}
/// Deserialize an `i64` into a `Value`.
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
Err(Error::invalid_type(Unexpected::Signed(v), &self))
}
/// Deserialize a `u8` into a `Value`.
fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
self.visit_u64(v as u64)
}
/// Deserialize a `u16` into a `Value`.
fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
self.visit_u64(v as u64)
}
/// Deserialize a `u32` into a `Value`.
fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
self.visit_u64(v as u64)
}
/// Deserialize a `u64` into a `Value`.
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
Err(Error::invalid_type(Unexpected::Unsigned(v), &self))
}
/// Deserialize a `f32` into a `Value`.
fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
self.visit_f64(v as f64)
}
/// Deserialize a `f64` into a `Value`.
fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
Err(Error::invalid_type(Unexpected::Float(v), &self))
}
@@ -1094,7 +1094,7 @@ pub trait Visitor: Sized {
/// Deserialize a `char` into a `Value`.
#[inline]
fn visit_char<E>(self, v: char) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
self.visit_str(::utils::encode_utf8(v).as_str())
}
@@ -1110,7 +1110,7 @@ pub trait Visitor: Sized {
/// It is never correct to implement `visit_string` without implementing
/// `visit_str`. Implement neither, both, or just `visit_str`.
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
Err(Error::invalid_type(Unexpected::Str(v), &self))
}
@@ -1132,28 +1132,28 @@ pub trait Visitor: Sized {
#[inline]
#[cfg(any(feature = "std", feature = "collections"))]
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
self.visit_str(&v)
}
/// Deserialize a `()` into a `Value`.
fn visit_unit<E>(self) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
Err(Error::invalid_type(Unexpected::Unit, &self))
}
/// Deserialize an absent optional `Value`.
fn visit_none<E>(self) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
Err(Error::invalid_type(Unexpected::Option, &self))
}
/// Deserialize a present optional `Value`.
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
let _ = deserializer;
Err(Error::invalid_type(Unexpected::Option, &self))
@@ -1161,7 +1161,7 @@ pub trait Visitor: Sized {
/// Deserialize `Value` as a newtype struct.
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
- where D: Deserializer,
+ where D: Deserializer
{
let _ = deserializer;
Err(Error::invalid_type(Unexpected::NewtypeStruct, &self))
@@ -1169,7 +1169,7 @@ pub trait Visitor: Sized {
/// Deserialize `Value` as a sequence of elements.
fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error>
- where V: SeqVisitor,
+ where V: SeqVisitor
{
let _ = visitor;
Err(Error::invalid_type(Unexpected::Seq, &self))
@@ -1177,7 +1177,7 @@ pub trait Visitor: Sized {
/// Deserialize `Value` as a key-value map.
fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error>
- where V: MapVisitor,
+ where V: MapVisitor
{
let _ = visitor;
Err(Error::invalid_type(Unexpected::Map, &self))
@@ -1185,7 +1185,7 @@ pub trait Visitor: Sized {
/// Deserialize `Value` as an enum.
fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error>
- where V: EnumVisitor,
+ where V: EnumVisitor
{
let _ = visitor;
Err(Error::invalid_type(Unexpected::Enum, &self))
@@ -1202,7 +1202,7 @@ pub trait Visitor: Sized {
/// It is never correct to implement `visit_byte_buf` without implementing
/// `visit_bytes`. Implement neither, both, or just `visit_bytes`.
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
let _ = v;
Err(Error::invalid_type(Unexpected::Bytes(v), &self))
@@ -1225,7 +1225,7 @@ pub trait Visitor: Sized {
/// `Vec<u8>`.
#[cfg(any(feature = "std", feature = "collections"))]
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
- where E: Error,
+ where E: Error
{
self.visit_bytes(&v)
}
@@ -1269,7 +1269,9 @@ pub trait SeqVisitor {
}
}
-impl<'a, V> SeqVisitor for &'a mut V where V: SeqVisitor {
+impl<'a, V> SeqVisitor for &'a mut V
+ where V: SeqVisitor
+{
type Error = V::Error;
#[inline]
@@ -1326,7 +1328,10 @@ pub trait MapVisitor {
/// `Deserialize` implementations should typically use `MapVisitor::visit`
/// instead.
#[inline]
- fn visit_seed<K, V>(&mut self, kseed: K, vseed: V) -> Result<Option<(K::Value, V::Value)>, Self::Error>
+ fn visit_seed<K, V>(&mut self,
+ kseed: K,
+ vseed: V)
+ -> Result<Option<(K::Value, V::Value)>, Self::Error>
where K: DeserializeSeed,
V: DeserializeSeed
{
@@ -1335,7 +1340,7 @@ pub trait MapVisitor {
let value = try!(self.visit_value_seed(vseed));
Ok(Some((key, value)))
}
- None => Ok(None)
+ None => Ok(None),
}
}
@@ -1370,7 +1375,7 @@ pub trait MapVisitor {
#[inline]
fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error>
where K: Deserialize,
- V: Deserialize,
+ V: Deserialize
{
self.visit_seed(PhantomData, PhantomData)
}
@@ -1382,7 +1387,9 @@ pub trait MapVisitor {
}
}
-impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
+impl<'a, V_> MapVisitor for &'a mut V_
+ where V_: MapVisitor
+{
type Error = V_::Error;
#[inline]
@@ -1400,7 +1407,10 @@ impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
}
#[inline]
- fn visit_seed<K, V>(&mut self, kseed: K, vseed: V) -> Result<Option<(K::Value, V::Value)>, Self::Error>
+ fn visit_seed<K, V>(&mut self,
+ kseed: K,
+ vseed: V)
+ -> Result<Option<(K::Value, V::Value)>, Self::Error>
where K: DeserializeSeed,
V: DeserializeSeed
{
@@ -1410,7 +1420,7 @@ impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
#[inline]
fn visit<K, V>(&mut self) -> Result<Option<(K, V)>, V_::Error>
where K: Deserialize,
- V: Deserialize,
+ V: Deserialize
{
(**self).visit()
}
@@ -1446,7 +1456,7 @@ pub trait EnumVisitor: Sized {
type Error: Error;
/// The `Visitor` that will be used to deserialize the content of the enum
/// variant.
- type Variant: VariantVisitor<Error=Self::Error>;
+ type Variant: VariantVisitor<Error = Self::Error>;
/// `visit_variant` is called to identify which variant to deserialize.
///
@@ -1539,9 +1549,7 @@ pub trait VariantVisitor: Sized {
/// Err(Error::invalid_type(unexp, &"tuple variant"))
/// }
/// ```
- fn visit_tuple<V>(self,
- len: usize,
- visitor: V) -> Result<V::Value, Self::Error>
+ fn visit_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// Called when deserializing a struct-like variant.
@@ -1564,7 +1572,8 @@ pub trait VariantVisitor: Sized {
/// ```
fn visit_struct<V>(self,
fields: &'static [&'static str],
- visitor: V) -> Result<V::Value, Self::Error>
+ visitor: V)
+ -> Result<V::Value, Self::Error>
where V: Visitor;
}
diff --git a/serde/src/de/private.rs b/serde/src/de/private.rs
index 566c4b112..8ef622316 100644
--- a/serde/src/de/private.rs
+++ b/serde/src/de/private.rs
@@ -3,14 +3,8 @@ use core::marker::PhantomData;
use de::{Deserialize, Deserializer, Error, Visitor};
#[cfg(any(feature = "std", feature = "collections"))]
-pub use de::content::{
- Content,
- ContentRefDeserializer,
- ContentDeserializer,
- TaggedContentVisitor,
- InternallyTaggedUnitVisitor,
- UntaggedUnitVisitor,
-};
+pub use de::content::{Content, ContentRefDeserializer, ContentDeserializer, TaggedContentVisitor,
+ InternallyTaggedUnitVisitor, UntaggedUnitVisitor};
/// If the missing field is of type `Option<T>` then treat is as `None`,
/// otherwise it is an error.
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 85d152678..264cdc799 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -1,31 +1,15 @@
//! This module supports deserializing from primitives with the `ValueDeserializer` trait.
#[cfg(feature = "std")]
-use std::collections::{
- BTreeMap,
- BTreeSet,
- HashMap,
- HashSet,
- btree_map,
- btree_set,
- hash_map,
- hash_set,
-};
+use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, btree_map, btree_set, hash_map,
+ hash_set};
#[cfg(feature = "std")]
use std::borrow::Cow;
#[cfg(feature = "std")]
use std::vec;
#[cfg(all(feature = "collections", not(feature = "std")))]
-use collections::{
- BTreeMap,
- BTreeSet,
- Vec,
- String,
- btree_map,
- btree_set,
- vec,
-};
+use collections::{BTreeMap, BTreeSet, Vec, String, btree_map, btree_set, vec};
#[cfg(all(feature = "collections", not(feature = "std")))]
use collections::borrow::Cow;
#[cfg(all(feature = "collections", not(feature = "std")))]
@@ -41,7 +25,7 @@ use std::error;
use error;
use core::fmt::{self, Display};
-use core::iter::{self, Iterator};
+use core::iter::{self, Iterator};
use core::marker::PhantomData;
use de::{self, Expected, SeqVisitor};
@@ -63,16 +47,12 @@ type ErrorImpl = ();
impl de::Error for Error {
#[cfg(any(feature = "std", feature = "collections"))]
fn custom<T: Display>(msg: T) -> Self {
- Error {
- err: msg.to_string().into_boxed_str(),
- }
+ Error { err: msg.to_string().into_boxed_str() }
}
#[cfg(not(any(feature = "std", feature = "collections")))]
fn custom<T: Display>(_msg: T) -> Self {
- Error {
- err: (),
- }
+ Error { err: () }
}
}
@@ -105,7 +85,7 @@ impl error::Error for Error {
/// This trait converts primitive types into a deserializer.
pub trait ValueDeserializer<E: de::Error = Error> {
/// The actual deserializer type.
- type Deserializer: de::Deserializer<Error=E>;
+ type Deserializer: de::Deserializer<Error = E>;
/// Convert this value into a deserializer.
fn into_deserializer(self) -> Self::Deserializer;
@@ -114,14 +94,12 @@ pub trait ValueDeserializer<E: de::Error = Error> {
///////////////////////////////////////////////////////////////////////////////
impl<E> ValueDeserializer<E> for ()
- where E: de::Error,
+ where E: de::Error
{
type Deserializer = UnitDeserializer<E>;
fn into_deserializer(self) -> UnitDeserializer<E> {
- UnitDeserializer {
- marker: PhantomData,
- }
+ UnitDeserializer { marker: PhantomData }
}
}
@@ -142,13 +120,13 @@ impl<E> de::Deserializer for UnitDeserializer<E>
}
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
+ where V: de::Visitor
{
visitor.visit_unit()
}
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
+ where V: de::Visitor
{
visitor.visit_none()
}
@@ -221,7 +199,7 @@ pub struct StrDeserializer<'a, E> {
}
impl<'a, E> ValueDeserializer<E> for &'a str
- where E: de::Error,
+ where E: de::Error
{
type Deserializer = StrDeserializer<'a, E>;
@@ -234,21 +212,22 @@ impl<'a, E> ValueDeserializer<E> for &'a str
}
impl<'a, E> de::Deserializer for StrDeserializer<'a, E>
- where E: de::Error,
+ where E: de::Error
{
type Error = E;
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
+ where V: de::Visitor
{
visitor.visit_str(self.value)
}
fn deserialize_enum<V>(self,
- _name: &str,
- _variants: &'static [&'static str],
- visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
+ _name: &str,
+ _variants: &'static [&'static str],
+ visitor: V)
+ -> Result<V::Value, Self::Error>
+ where V: de::Visitor
{
visitor.visit_enum(self)
}
@@ -261,13 +240,13 @@ impl<'a, E> de::Deserializer for StrDeserializer<'a, E>
}
impl<'a, E> de::EnumVisitor for StrDeserializer<'a, E>
- where E: de::Error,
+ where E: de::Error
{
type Error = E;
type Variant = private::UnitOnly<E>;
fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
- where T: de::DeserializeSeed,
+ where T: de::DeserializeSeed
{
seed.deserialize(self).map(private::unit_only)
}
@@ -284,7 +263,7 @@ pub struct StringDeserializer<E> {
#[cfg(any(feature = "std", feature = "collections"))]
impl<E> ValueDeserializer<E> for String
- where E: de::Error,
+ where E: de::Error
{
type Deserializer = StringDeserializer<E>;
@@ -298,21 +277,22 @@ impl<E> ValueDeserializer<E> for String
#[cfg(any(feature = "std", feature = "collections"))]
impl<E> de::Deserializer for StringDeserializer<E>
- where E: de::Error,
+ where E: de::Error
{
type Error = E;
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
+ where V: de::Visitor
{
visitor.visit_string(self.value)
}
fn deserialize_enum<V>(self,
- _name: &str,
- _variants: &'static [&'static str],
- visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
+ _name: &str,
+ _variants: &'static [&'static str],
+ visitor: V)
+ -> Result<V::Value, Self::Error>
+ where V: de::Visitor
{
visitor.visit_enum(self)
}
@@ -326,13 +306,13 @@ impl<E> de::Deserializer for StringDeserializer<E>
#[cfg(any(feature = "std", feature = "collections"))]
impl<'a, E> de::EnumVisitor for StringDeserializer<E>
- where E: de::Error,
+ where E: de::Error
{
type Error = E;
type Variant = private::UnitOnly<E>;
fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
- where T: de::DeserializeSeed,
+ where T: de::DeserializeSeed
{
seed.deserialize(self).map(private::unit_only)
}
@@ -349,7 +329,7 @@ pub struct CowStrDeserializer<'a, E> {
#[cfg(any(feature = "std", feature = "collections"))]
impl<'a, E> ValueDeserializer<E> for Cow<'a, str>
- where E: de::Error,
+ where E: de::Error
{
type Deserializer = CowStrDeserializer<'a, E>;
@@ -363,12 +343,12 @@ impl<'a, E> ValueDeserializer<E> for Cow<'a, str>
#[cfg(any(feature = "std", feature = "collections"))]
impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E>
- where E: de::Error,
+ where E: de::Error
{
type Error = E;
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
+ where V: de::Visitor
{
match self.value {
Cow::Borrowed(string) => visitor.visit_str(string),
@@ -377,10 +357,11 @@ impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E>
}
fn deserialize_enum<V>(self,
- _name: &str,
- _variants: &'static [&'static str],
- visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
+ _name: &str,
+ _variants: &'static [&'static str],
+ visitor: V)
+ -> Result<V::Value, Self::Error>
+ where V: de::Visitor
{
visitor.visit_enum(self)
}
@@ -394,13 +375,13 @@ impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E>
#[cfg(any(feature = "std", feature = "collections"))]
impl<'a, E> de::EnumVisitor for CowStrDeserializer<'a, E>
- where E: de::Error,
+ where E: de::Error
{
type Error = E;
type Variant = private::UnitOnly<E>;
fn visit_variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error>
- where T: de::DeserializeSeed,
+ where T: de::DeserializeSeed
{
seed.deserialize(self).map(private::unit_only)
}
@@ -417,7 +398,7 @@ pub struct SeqDeserializer<I, E> {
impl<I, E> SeqDeserializer<I, E>
where I: Iterator,
- E: de::Error,
+ E: de::Error
{
/// Construct a new `SeqDeserializer<I>`.
pub fn new(iter: I) -> Self {
@@ -446,14 +427,14 @@ impl<I, E> SeqDeserializer<I, E>
}
impl<I, T, E> de::Deserializer for SeqDeserializer<I, E>
- where I: Iterator<Item=T>,
+ where I: Iterator<Item = T>,
T: ValueDeserializer<E>,
- E: de::Error,
+ E: de::Error
{
type Error = E;
fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
+ where V: de::Visitor
{
let v = try!(visitor.visit_seq(&mut self));
try!(self.end());
@@ -468,9 +449,9 @@ impl<I, T, E> de::Deserializer for SeqDeserializer<I, E>
}
impl<I, T, E> de::SeqVisitor for SeqDeserializer<I, E>
- where I: Iterator<Item=T>,
+ where I: Iterator<Item = T>,
T: ValueDeserializer<E>,
- E: de::Error,
+ E: de::Error
{
type Error = E;
@@ -508,7 +489,7 @@ impl Expected for ExpectedInSeq {
#[cfg(any(feature = "std", feature = "collections"))]
impl<T, E> ValueDeserializer<E> for Vec<T>
where T: ValueDeserializer<E>,
- E: de::Error,
+ E: de::Error
{
type Deserializer = SeqDeserializer<vec::IntoIter<T>, E>;
@@ -520,7 +501,7 @@ impl<T, E> ValueDeserializer<E> for Vec<T>
#[cfg(any(feature = "std", feature = "collections"))]
impl<T, E> ValueDeserializer<E> for BTreeSet<T>
where T: ValueDeserializer<E> + Eq + Ord,
- E: de::Error,
+ E: de::Error
{
type Deserializer = SeqDeserializer<btree_set::IntoIter<T>, E>;
@@ -532,7 +513,7 @@ impl<T, E> ValueDeserializer<E> for BTreeSet<T>
#[cfg(feature = "std")]
impl<T, E> ValueDeserializer<E> for HashSet<T>
where T: ValueDeserializer<E> + Eq + Hash,
- E: de::Error,
+ E: de::Error
{
type Deserializer = SeqDeserializer<hash_set::IntoIter<T>, E>;
@@ -551,20 +532,20 @@ pub struct SeqVisitorDeserializer<V_, E> {
impl<V_, E> SeqVisitorDeserializer<V_, E>
where V_: de::SeqVisitor<Error = E>,
- E: de::Error,
+ E: de::Error
{
/// Construct a new `SeqVisitorDeserializer<V_, E>`.
pub fn new(visitor: V_) -> Self {
- SeqVisitorDeserializer{
+ SeqVisitorDeserializer {
visitor: visitor,
- marker: PhantomData
+ marker: PhantomData,
}
}
}
impl<V_, E> de::Deserializer for SeqVisitorDeserializer<V_, E>
where V_: de::SeqVisitor<Error = E>,
- E: de::Error,
+ E: de::Error
{
type Error = E;
@@ -587,7 +568,7 @@ pub struct MapDeserializer<I, E>
I::Item: private::Pair,
<I::Item as private::Pair>::First: ValueDeserializer<E>,
<I::Item as private::Pair>::Second: ValueDeserializer<E>,
- E: de::Error,
+ E: de::Error
{
iter: iter::Fuse<I>,
value: Option<<I::Item as private::Pair>::Second>,
@@ -600,7 +581,7 @@ impl<I, E> MapDeserializer<I, E>
I::Item: private::Pair,
<I::Item as private::Pair>::First: ValueDeserializer<E>,
<I::Item as private::Pair>::Second: ValueDeserializer<E>,
- E: de::Error,
+ E: de::Error
{
/// Construct a new `MapDeserializer<I, K, V, E>`.
pub fn new(iter: I) -> Self {
@@ -628,7 +609,9 @@ impl<I, E> MapDeserializer<I, E>
}
}
- fn next_pair(&mut self) -> Option<(<I::Item as private::Pair>::First, <I::Item as private::Pair>::Second)> {
+ fn next_pair
+ (&mut self)
+ -> Option<(<I::Item as private::Pair>::First, <I::Item as private::Pair>::Second)> {
match self.iter.next() {
Some(kv) => {
self.count += 1;
@@ -644,12 +627,12 @@ impl<I, E> de::Deserializer for MapDeserializer<I, E>
I::Item: private::Pair,
<I::Item as private::Pair>::First: ValueDeserializer<E>,
<I::Item as private::Pair>::Second: ValueDeserializer<E>,
- E: de::Error,
+ E: de::Error
{
type Error = E;
fn deserialize<V_>(mut self, visitor: V_) -> Result<V_::Value, Self::Error>
- where V_: de::Visitor,
+ where V_: de::Visitor
{
let value = try!(visitor.visit_map(&mut self));
try!(self.end());
@@ -657,15 +640,18 @@ impl<I, E> de::Deserializer for MapDeserializer<I, E>
}
fn deserialize_seq<V_>(mut self, visitor: V_) -> Result<V_::Value, Self::Error>
- where V_: de::Visitor,
+ where V_: de::Visitor
{
let value = try!(visitor.visit_seq(&mut self));
try!(self.end());
Ok(value)
}
- fn deserialize_seq_fixed_size<V_>(self, _len: usize, visitor: V_) -> Result<V_::Value, Self::Error>
- where V_: de::Visitor,
+ fn deserialize_seq_fixed_size<V_>(self,
+ _len: usize,
+ visitor: V_)
+ -> Result<V_::Value, Self::Error>
+ where V_: de::Visitor
{
self.deserialize_seq(visitor)
}
@@ -682,12 +668,12 @@ impl<I, E> de::MapVisitor for MapDeserializer<I, E>
I::Item: private::Pair,
<I::Item as private::Pair>::First: ValueDeserializer<E>,
<I::Item as private::Pair>::Second: ValueDeserializer<E>,
- E: de::Error,
+ E: de::Error
{
type Error = E;
fn visit_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
- where T: de::DeserializeSeed,
+ where T: de::DeserializeSeed
{
match self.next_pair() {
Some((key, value)) => {
@@ -699,7 +685,7 @@ impl<I, E> de::MapVisitor for MapDeserializer<I, E>
}
fn visit_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
- where T: de::DeserializeSeed,
+ where T: de::DeserializeSeed
{
let value = self.value.take();
// Panic because this indicates a bug in the program rather than an
@@ -708,7 +694,10 @@ impl<I, E> de::MapVisitor for MapDeserializer<I, E>
seed.deserialize(value.into_deserializer())
}
- fn visit_seed<TK, TV>(&mut self, kseed: TK, vseed: TV) -> Result<Option<(TK::Value, TV::Value)>, Self::Error>
+ fn visit_seed<TK, TV>(&mut self,
+ kseed: TK,
+ vseed: TV)
+ -> Result<Option<(TK::Value, TV::Value)>, Self::Error>
where TK: de::DeserializeSeed,
TV: de::DeserializeSeed
{
@@ -718,7 +707,7 @@ impl<I, E> de::MapVisitor for MapDeserializer<I, E>
let value = try!(vseed.deserialize(value.into_deserializer()));
Ok(Some((key, value)))
}
- None => Ok(None)
+ None => Ok(None),
}
}
@@ -732,12 +721,12 @@ impl<I, E> de::SeqVisitor for MapDeserializer<I, E>
I::Item: private::Pair,
<I::Item as private::Pair>::First: ValueDeserializer<E>,
<I::Item as private::Pair>::Second: ValueDeserializer<E>,
- E: de::Error,
+ E: de::Error
{
type Error = E;
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
- where T: de::DeserializeSeed,
+ where T: de::DeserializeSeed
{
match self.next_pair() {
Some((k, v)) => {
@@ -771,13 +760,13 @@ impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E>
}
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
+ where V: de::Visitor
{
self.deserialize_seq(visitor)
}
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
+ where V: de::Visitor
{
let mut pair_visitor = PairVisitor(Some(self.0), Some(self.1), PhantomData);
let pair = try!(visitor.visit_seq(&mut pair_visitor));
@@ -792,7 +781,7 @@ impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E>
}
fn deserialize_seq_fixed_size<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
+ where V: de::Visitor
{
if len == 2 {
self.deserialize_seq(visitor)
@@ -809,12 +798,12 @@ struct PairVisitor<A, B, E>(Option<A>, Option<B>, PhantomData<E>);
impl<A, B, E> de::SeqVisitor for PairVisitor<A, B, E>
where A: ValueDeserializer<E>,
B: ValueDeserializer<E>,
- E: de::Error,
+ E: de::Error
{
type Error = E;
fn visit_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
- where T: de::DeserializeSeed,
+ where T: de::DeserializeSeed
{
if let Some(k) = self.0.take() {
seed.deserialize(k.into_deserializer()).map(Some)
@@ -855,7 +844,7 @@ impl Expected for ExpectedInMap {
impl<K, V, E> ValueDeserializer<E> for BTreeMap<K, V>
where K: ValueDeserializer<E> + Eq + Ord,
V: ValueDeserializer<E>,
- E: de::Error,
+ E: de::Error
{
type Deserializer = MapDeserializer<btree_map::IntoIter<K, V>, E>;
@@ -868,7 +857,7 @@ impl<K, V, E> ValueDeserializer<E> for BTreeMap<K, V>
impl<K, V, E> ValueDeserializer<E> for HashMap<K, V>
where K: ValueDeserializer<E> + Eq + Hash,
V: ValueDeserializer<E>,
- E: de::Error,
+ E: de::Error
{
type Deserializer = MapDeserializer<hash_map::IntoIter<K, V>, E>;
@@ -887,20 +876,20 @@ pub struct MapVisitorDeserializer<V_, E> {
impl<V_, E> MapVisitorDeserializer<V_, E>
where V_: de::MapVisitor<Error = E>,
- E: de::Error,
+ E: de::Error
{
/// Construct a new `MapVisitorDeserializer<V_, E>`.
pub fn new(visitor: V_) -> Self {
- MapVisitorDeserializer{
+ MapVisitorDeserializer {
visitor: visitor,
- marker: PhantomData
+ marker: PhantomData,
}
}
}
impl<V_, E> de::Deserializer for MapVisitorDeserializer<V_, E>
where V_: de::MapVisitor<Error = E>,
- E: de::Error,
+ E: de::Error
{
type Error = E;
@@ -918,7 +907,7 @@ impl<V_, E> de::Deserializer for MapVisitorDeserializer<V_, E>
///////////////////////////////////////////////////////////////////////////////
impl<'a, E> ValueDeserializer<E> for bytes::Bytes<'a>
- where E: de::Error,
+ where E: de::Error
{
type Deserializer = BytesDeserializer<'a, E>;
@@ -942,7 +931,7 @@ impl<'a, E> de::Deserializer for BytesDeserializer<'a, E>
type Error = E;
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
+ where V: de::Visitor
{
visitor.visit_bytes(self.value)
}
@@ -958,7 +947,7 @@ impl<'a, E> de::Deserializer for BytesDeserializer<'a, E>
#[cfg(any(feature = "std", feature = "collections"))]
impl<E> ValueDeserializer<E> for bytes::ByteBuf
- where E: de::Error,
+ where E: de::Error
{
type Deserializer = ByteBufDeserializer<E>;
@@ -979,12 +968,12 @@ pub struct ByteBufDeserializer<E> {
#[cfg(any(feature = "std", feature = "collections"))]
impl<E> de::Deserializer for ByteBufDeserializer<E>
- where E: de::Error,
+ where E: de::Error
{
type Error = E;
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
- where V: de::Visitor,
+ where V: de::Visitor
{
visitor.visit_byte_buf(self.value)
}
@@ -1020,14 +1009,12 @@ mod private {
}
fn visit_newtype_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
- where T: de::DeserializeSeed,
+ where T: de::DeserializeSeed
{
Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant"))
}
- fn visit_tuple<V>(self,
- _len: usize,
- _visitor: V) -> Result<V::Value, Self::Error>
+ fn visit_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor
{
Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"))
@@ -1035,7 +1022,8 @@ mod private {
fn visit_struct<V>(self,
_fields: &'static [&'static str],
- _visitor: V) -> Result<V::Value, Self::Error>
+ _visitor: V)
+ -> Result<V::Value, Self::Error>
where V: de::Visitor
{
Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant"))
@@ -1053,6 +1041,8 @@ mod private {
impl<A, B> Pair for (A, B) {
type First = A;
type Second = B;
- fn split(self) -> (A, B) { self }
+ fn split(self) -> (A, B) {
+ self
+ }
}
}
diff --git a/serde/src/error.rs b/serde/src/error.rs
index 6c411f847..fe91c28f7 100644
--- a/serde/src/error.rs
+++ b/serde/src/error.rs
@@ -11,5 +11,7 @@ pub trait Error: Debug + Display {
fn description(&self) -> &str;
/// The lower-level cause of this error, if any.
- fn cause(&self) -> Option<&Error> { None }
+ fn cause(&self) -> Option<&Error> {
+ None
+ }
}
diff --git a/serde/src/iter.rs b/serde/src/iter.rs
index 24a6bf307..784fe9bcf 100644
--- a/serde/src/iter.rs
+++ b/serde/src/iter.rs
@@ -4,13 +4,13 @@ use std::io;
use std::iter::Peekable;
/// Iterator over a byte stream that tracks the current position's line and column.
-pub struct LineColIterator<Iter: Iterator<Item=io::Result<u8>>> {
+pub struct LineColIterator<Iter: Iterator<Item = io::Result<u8>>> {
iter: Iter,
line: usize,
col: usize,
}
-impl<Iter: Iterator<Item=io::Result<u8>>> LineColIterator<Iter> {
+impl<Iter: Iterator<Item = io::Result<u8>>> LineColIterator<Iter> {
/// Construct a new `LineColIterator<Iter>`.
pub fn new(iter: Iter) -> LineColIterator<Iter> {
LineColIterator {
@@ -21,27 +21,39 @@ impl<Iter: Iterator<Item=io::Result<u8>>> LineColIterator<Iter> {
}
/// Report the current line inside the iterator.
- pub fn line(&self) -> usize { self.line }
+ pub fn line(&self) -> usize {
+ self.line
+ }
/// Report the current column inside the iterator.
- pub fn col(&self) -> usize { self.col }
+ pub fn col(&self) -> usize {
+ self.col
+ }
/// Gets a reference to the underlying iterator.
- pub fn get_ref(&self) -> &Iter { &self.iter }
+ pub fn get_ref(&self) -> &Iter {
+ &self.iter
+ }
/// Gets a mutable reference to the underlying iterator.
- pub fn get_mut(&mut self) -> &mut Iter { &mut self.iter }
+ pub fn get_mut(&mut self) -> &mut Iter {
+ &mut self.iter
+ }
/// Unwraps this `LineColIterator`, returning the underlying iterator.
- pub fn into_inner(self) -> Iter { self.iter }
+ pub fn into_inner(self) -> Iter {
+ self.iter
+ }
}
-impl<Iter: Iterator<Item=io::Result<u8>>> LineColIterator<Peekable<Iter>> {
+impl<Iter: Iterator<Item = io::Result<u8>>> LineColIterator<Peekable<Iter>> {
/// peeks at the next value
- pub fn peek(&mut self) -> Option<&io::Result<u8>> { self.iter.peek() }
+ pub fn peek(&mut self) -> Option<&io::Result<u8>> {
+ self.iter.peek()
+ }
}
-impl<Iter: Iterator<Item=io::Result<u8>>> Iterator for LineColIterator<Iter> {
+impl<Iter: Iterator<Item = io::Result<u8>>> Iterator for LineColIterator<Iter> {
type Item = io::Result<u8>;
fn next(&mut self) -> Option<io::Result<u8>> {
match self.iter.next() {
@@ -50,11 +62,11 @@ impl<Iter: Iterator<Item=io::Result<u8>>> Iterator for LineColIterator<Iter> {
self.line += 1;
self.col = 0;
Some(Ok(b'\n'))
- },
+ }
Some(Ok(c)) => {
self.col += 1;
Some(Ok(c))
- },
+ }
Some(Err(e)) => Some(Err(e)),
}
}
diff --git a/serde/src/lib.rs b/serde/src/lib.rs
index 467a22669..9560ecb6e 100644
--- a/serde/src/lib.rs
+++ b/serde/src/lib.rs
@@ -79,7 +79,7 @@ extern crate core as actual_core;
#[cfg(feature = "std")]
mod core {
pub use std::{ops, hash, fmt, cmp, marker, mem, i8, i16, i32, i64, u8, u16, u32, u64, isize,
- usize, f32, f64, char, str, num, slice, iter, cell, default, result, option};
+ usize, f32, f64, char, str, num, slice, iter, cell, default, result, option};
#[cfg(feature = "unstable")]
pub use actual_core::nonzero;
}
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index f54161fac..745903fae 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -4,25 +4,9 @@ use std::borrow::Cow;
use collections::borrow::Cow;
#[cfg(feature = "std")]
-use std::collections::{
- BinaryHeap,
- BTreeMap,
- BTreeSet,
- LinkedList,
- HashMap,
- HashSet,
- VecDeque,
-};
+use std::collections::{BinaryHeap, BTreeMap, BTreeSet, LinkedList, HashMap, HashSet, VecDeque};
#[cfg(all(feature = "collections", not(feature = "std")))]
-use collections::{
- BinaryHeap,
- BTreeMap,
- BTreeSet,
- LinkedList,
- VecDeque,
- String,
- Vec,
-};
+use collections::{BinaryHeap, BTreeMap, BTreeSet, LinkedList, VecDeque, String, Vec};
#[cfg(feature = "collections")]
use collections::borrow::ToOwned;
@@ -57,12 +41,7 @@ use core::marker::PhantomData;
#[cfg(feature = "unstable")]
use core::nonzero::{NonZero, Zeroable};
-use super::{
- Serialize,
- SerializeSeq,
- SerializeTuple,
- Serializer,
-};
+use super::{Serialize, SerializeSeq, SerializeTuple, Serializer};
#[cfg(feature = "std")]
use super::Error;
@@ -101,7 +80,7 @@ impl_visit!(char, serialize_char);
impl Serialize for str {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
serializer.serialize_str(self)
}
@@ -111,7 +90,7 @@ impl Serialize for str {
impl Serialize for String {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
(&self[..]).serialize(serializer)
}
@@ -124,7 +103,7 @@ impl<T> Serialize for Option<T>
{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
match *self {
Some(ref value) => serializer.serialize_some(value),
@@ -138,7 +117,7 @@ impl<T> Serialize for Option<T>
impl<T> Serialize for PhantomData<T> {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
serializer.serialize_unit_struct("PhantomData")
}
@@ -211,7 +190,7 @@ macro_rules! serialize_seq {
}
impl<T> Serialize for [T]
- where T: Serialize,
+ where T: Serialize
{
serialize_seq!();
}
@@ -225,7 +204,7 @@ impl<T> Serialize for BinaryHeap<T>
#[cfg(any(feature = "std", feature = "collections"))]
impl<T> Serialize for BTreeSet<T>
- where T: Serialize + Ord,
+ where T: Serialize + Ord
{
serialize_seq!();
}
@@ -233,14 +212,14 @@ impl<T> Serialize for BTreeSet<T>
#[cfg(feature = "std")]
impl<T, H> Serialize for HashSet<T, H>
where T: Serialize + Eq + Hash,
- H: BuildHasher,
+ H: BuildHasher
{
serialize_seq!();
}
#[cfg(any(feature = "std", feature = "collections"))]
impl<T> Serialize for LinkedList<T>
- where T: Serialize,
+ where T: Serialize
{
serialize_seq!();
}
@@ -262,11 +241,11 @@ impl<T> Serialize for VecDeque<T>
#[cfg(feature = "unstable")]
impl<A> Serialize for ops::Range<A>
where ops::Range<A>: ExactSizeIterator + iter::Iterator<Item = A> + Clone,
- A: Serialize,
+ A: Serialize
{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
for e in self.clone() {
@@ -279,11 +258,11 @@ impl<A> Serialize for ops::Range<A>
#[cfg(feature = "unstable")]
impl<A> Serialize for ops::RangeInclusive<A>
where ops::RangeInclusive<A>: ExactSizeIterator + iter::Iterator<Item = A> + Clone,
- A: Serialize,
+ A: Serialize
{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
for e in self.clone() {
@@ -298,7 +277,7 @@ impl<A> Serialize for ops::RangeInclusive<A>
impl Serialize for () {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
serializer.serialize_unit()
}
@@ -518,7 +497,7 @@ macro_rules! serialize_map {
#[cfg(any(feature = "std", feature = "collections"))]
impl<K, V> Serialize for BTreeMap<K, V>
where K: Serialize + Ord,
- V: Serialize,
+ V: Serialize
{
serialize_map!();
}
@@ -527,26 +506,30 @@ impl<K, V> Serialize for BTreeMap<K, V>
impl<K, V, H> Serialize for HashMap<K, V, H>
where K: Serialize + Eq + Hash,
V: Serialize,
- H: BuildHasher,
+ H: BuildHasher
{
serialize_map!();
}
///////////////////////////////////////////////////////////////////////////////
-impl<'a, T: ?Sized> Serialize for &'a T where T: Serialize {
+impl<'a, T: ?Sized> Serialize for &'a T
+ where T: Serialize
+{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
(**self).serialize(serializer)
}
}
-impl<'a, T: ?Sized> Serialize for &'a mut T where T: Serialize {
+impl<'a, T: ?Sized> Serialize for &'a mut T
+ where T: Serialize
+{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
(**self).serialize(serializer)
}
@@ -558,7 +541,7 @@ impl<T: ?Sized> Serialize for Box<T>
{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
(**self).serialize(serializer)
}
@@ -570,7 +553,7 @@ impl<T> Serialize for Rc<T>
{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
(**self).serialize(serializer)
}
@@ -582,7 +565,7 @@ impl<T> Serialize for Arc<T>
{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
(**self).serialize(serializer)
}
@@ -594,7 +577,7 @@ impl<'a, T: ?Sized> Serialize for Cow<'a, T>
{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
(**self).serialize(serializer)
}
@@ -610,9 +593,7 @@ impl<T, E> Serialize for Result<T, E>
where S: Serializer
{
match *self {
- Result::Ok(ref value) => {
- serializer.serialize_newtype_variant("Result", 0, "Ok", value)
- }
+ Result::Ok(ref value) => serializer.serialize_newtype_variant("Result", 0, "Ok", value),
Result::Err(ref value) => {
serializer.serialize_newtype_variant("Result", 1, "Err", value)
}
@@ -625,7 +606,7 @@ impl<T, E> Serialize for Result<T, E>
#[cfg(feature = "std")]
impl Serialize for Duration {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
use super::SerializeStruct;
let mut state = try!(serializer.serialize_struct("Duration", 2));
@@ -640,7 +621,7 @@ impl Serialize for Duration {
#[cfg(feature = "std")]
impl Serialize for net::IpAddr {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
self.to_string().serialize(serializer)
}
@@ -649,7 +630,7 @@ impl Serialize for net::IpAddr {
#[cfg(feature = "std")]
impl Serialize for net::Ipv4Addr {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
self.to_string().serialize(serializer)
}
@@ -658,7 +639,7 @@ impl Serialize for net::Ipv4Addr {
#[cfg(feature = "std")]
impl Serialize for net::Ipv6Addr {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
self.to_string().serialize(serializer)
}
@@ -669,7 +650,7 @@ impl Serialize for net::Ipv6Addr {
#[cfg(feature = "std")]
impl Serialize for net::SocketAddr {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
match *self {
net::SocketAddr::V4(ref addr) => addr.serialize(serializer),
@@ -681,7 +662,7 @@ impl Serialize for net::SocketAddr {
#[cfg(feature = "std")]
impl Serialize for net::SocketAddrV4 {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
self.to_string().serialize(serializer)
}
@@ -690,7 +671,7 @@ impl Serialize for net::SocketAddrV4 {
#[cfg(feature = "std")]
impl Serialize for net::SocketAddrV6 {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
self.to_string().serialize(serializer)
}
@@ -701,7 +682,7 @@ impl Serialize for net::SocketAddrV6 {
#[cfg(feature = "std")]
impl Serialize for path::Path {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
match self.to_str() {
Some(s) => s.serialize(serializer),
@@ -713,7 +694,7 @@ impl Serialize for path::Path {
#[cfg(feature = "std")]
impl Serialize for path::PathBuf {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where S: Serializer
{
self.as_path().serialize(serializer)
}
diff --git a/serde/src/ser/impossible.rs b/serde/src/ser/impossible.rs
index 8c9bf40d6..6b8e7c28b 100644
--- a/serde/src/ser/impossible.rs
+++ b/serde/src/ser/impossible.rs
@@ -2,17 +2,8 @@
use core::marker::PhantomData;
-use ser::{
- self,
- Serialize,
- SerializeSeq,
- SerializeTuple,
- SerializeTupleStruct,
- SerializeTupleVariant,
- SerializeMap,
- SerializeStruct,
- SerializeStructVariant,
-};
+use ser::{self, Serialize, SerializeSeq, SerializeTuple, SerializeTupleStruct,
+ SerializeTupleVariant, SerializeMap, SerializeStruct, SerializeStructVariant};
/// Helper type for implementing a `Serializer` that does not support
/// serializing one of the compound types.
@@ -50,14 +41,12 @@ pub struct Impossible<Ok, E> {
enum Void {}
impl<Ok, E> SerializeSeq for Impossible<Ok, E>
- where E: ser::Error,
+ where E: ser::Error
{
type Ok = Ok;
type Error = E;
- fn serialize_element<T: ?Sized + Serialize>(&mut self,
- _value: &T)
- -> Result<(), E> {
+ fn serialize_element<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
match self.void {}
}
@@ -67,14 +56,12 @@ impl<Ok, E> SerializeSeq for Impossible<Ok, E>
}
impl<Ok, E> SerializeTuple for Impossible<Ok, E>
- where E: ser::Error,
+ where E: ser::Error
{
type Ok = Ok;
type Error = E;
- fn serialize_element<T: ?Sized + Serialize>(&mut self,
- _value: &T)
- -> Result<(), E> {
+ fn serialize_element<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
match self.void {}
}
@@ -84,14 +71,12 @@ impl<Ok, E> SerializeTuple for Impossible<Ok, E>
}
impl<Ok, E> SerializeTupleStruct for Impossible<Ok, E>
- where E: ser::Error,
+ where E: ser::Error
{
type Ok = Ok;
type Error = E;
- fn serialize_field<T: ?Sized + Serialize>(&mut self,
- _value: &T)
- -> Result<(), E> {
+ fn serialize_field<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
match self.void {}
}
@@ -101,14 +86,12 @@ impl<Ok, E> SerializeTupleStruct for Impossible<Ok, E>
}
impl<Ok, E> SerializeTupleVariant for Impossible<Ok, E>
- where E: ser::Error,
+ where E: ser::Error
{
type Ok = Ok;
type Error = E;
- fn serialize_field<T: ?Sized + Serialize>(&mut self,
- _value: &T)
- -> Result<(), E> {
+ fn serialize_field<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
match self.void {}
}
@@ -118,20 +101,16 @@ impl<Ok, E> SerializeTupleVariant for Impossible<Ok, E>
}
impl<Ok, E> SerializeMap for Impossible<Ok, E>
- where E: ser::Error,
+ where E: ser::Error
{
type Ok = Ok;
type Error = E;
- fn serialize_key<T: ?Sized + Serialize>(&mut self,
- _key: &T)
- -> Result<(), E> {
+ fn serialize_key<T: ?Sized + Serialize>(&mut self, _key: &T) -> Result<(), E> {
match self.void {}
}
- fn serialize_value<T: ?Sized + Serialize>(&mut self,
- _value: &T)
- -> Result<(), E> {
+ fn serialize_value<T: ?Sized + Serialize>(&mut self, _value: &T) -> Result<(), E> {
match self.void {}
}
@@ -141,13 +120,13 @@ impl<Ok, E> SerializeMap for Impossible<Ok, E>
}
impl<Ok, E> SerializeStruct for Impossible<Ok, E>
- where E: ser::Error,
+ where E: ser::Error
{
type Ok = Ok;
type Error = E;
fn serialize_field<T: ?Sized + Serialize>(&mut self,
- _key: &'static str,
+ _key: &'static str,
_value: &T)
-> Result<(), E> {
match self.void {}
@@ -159,13 +138,13 @@ impl<Ok, E> SerializeStruct for Impossible<Ok, E>
}
impl<Ok, E> SerializeStructVariant for Impossible<Ok, E>
- where E: ser::Error,
+ where E: ser::Error
{
type Ok = Ok;
type Error = E;
fn serialize_field<T: ?Sized + Serialize>(&mut self,
- _key: &'static str,
+ _key: &'static str,
_value: &T)
-> Result<(), E> {
match self.void {}
diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs
index 331928a36..369d68b6c 100644
--- a/serde/src/ser/mod.rs
+++ b/serde/src/ser/mod.rs
@@ -174,8 +174,7 @@ pub trait Serialize {
/// for more information about how to implement this method.
///
/// [impl-serialize]: https://serde.rs/impl-serialize.html
- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer;
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer;
}
///////////////////////////////////////////////////////////////////////////////
@@ -254,31 +253,31 @@ pub trait Serializer: Sized {
/// Type returned from `serialize_seq` and `serialize_seq_fixed_size` for
/// serializing the content of the sequence.
- type SerializeSeq: SerializeSeq<Ok=Self::Ok, Error=Self::Error>;
+ type SerializeSeq: SerializeSeq<Ok = Self::Ok, Error = Self::Error>;
/// Type returned from `serialize_tuple` for serializing the content of the
/// tuple.
- type SerializeTuple: SerializeTuple<Ok=Self::Ok, Error=Self::Error>;
+ type SerializeTuple: SerializeTuple<Ok = Self::Ok, Error = Self::Error>;
/// Type returned from `serialize_tuple_struct` for serializing the content
/// of the tuple struct.
- type SerializeTupleStruct: SerializeTupleStruct<Ok=Self::Ok, Error=Self::Error>;
+ type SerializeTupleStruct: SerializeTupleStruct<Ok = Self::Ok, Error = Self::Error>;
/// Type returned from `serialize_tuple_variant` for serializing the content
/// of the tuple variant.
- type SerializeTupleVariant: SerializeTupleVariant<Ok=Self::Ok, Error=Self::Error>;
+ type SerializeTupleVariant: SerializeTupleVariant<Ok = Self::Ok, Error = Self::Error>;
/// Type returned from `serialize_map` for serializing the content of the
/// map.
- type SerializeMap: SerializeMap<Ok=Self::Ok, Error=Self::Error>;
+ type SerializeMap: SerializeMap<Ok = Self::Ok, Error = Self::Error>;
/// Type returned from `serialize_struct` for serializing the content of the
/// struct.
- type SerializeStruct: SerializeStruct<Ok=Self::Ok, Error=Self::Error>;
+ type SerializeStruct: SerializeStruct<Ok = Self::Ok, Error = Self::Error>;
/// Type returned from `serialize_struct_variant` for serializing the
/// content of the struct variant.
- type SerializeStructVariant: SerializeStructVariant<Ok=Self::Ok, Error=Self::Error>;
+ type SerializeStructVariant: SerializeStructVariant<Ok = Self::Ok, Error = Self::Error>;
/// Serialize a `bool` value.
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>;
@@ -371,10 +370,7 @@ pub trait Serializer: Sized {
fn serialize_none(self) -> Result<Self::Ok, Self::Error>;
/// Serialize a `Some(T)` value.
- fn serialize_some<T: ?Sized + Serialize>(
- self,
- value: &T,
- ) -> Result<Self::Ok, Self::Error>;
+ fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<Self::Ok, Self::Error>;
/// Serialize a `()` value.
fn serialize_unit(self) -> Result<Self::Ok, Self::Error>;
@@ -382,10 +378,7 @@ pub trait Serializer: Sized {
/// Serialize a unit struct like `struct Unit` or `PhantomData<T>`.
///
/// A reasonable implementation would be to forward to `serialize_unit`.
- fn serialize_unit_struct(
- self,
- name: &'static str,
- ) -> Result<Self::Ok, Self::Error>;
+ fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error>;
/// Serialize a unit variant like `E::A` in `enum E { A, B }`.
///
@@ -401,12 +394,11 @@ pub trait Serializer: Sized {
/// E::B => serializer.serialize_unit_variant("E", 1, "B"),
/// }
/// ```
- fn serialize_unit_variant(
- self,
- name: &'static str,
- variant_index: usize,
- variant: &'static str,
- ) -> Result<Self::Ok, Self::Error>;
+ fn serialize_unit_variant(self,
+ name: &'static str,
+ variant_index: usize,
+ variant: &'static str)
+ -> Result<Self::Ok, Self::Error>;
/// Serialize a newtype struct like `struct Millimeters(u8)`.
///
@@ -417,11 +409,10 @@ pub trait Serializer: Sized {
/// ```rust,ignore
/// serializer.serialize_newtype_struct("Millimeters", &self.0)
/// ```
- fn serialize_newtype_struct<T: ?Sized + Serialize>(
- self,
- name: &'static str,
- value: &T,
- ) -> Result<Self::Ok, Self::Error>;
+ fn serialize_newtype_struct<T: ?Sized + Serialize>(self,
+ name: &'static str,
+ value: &T)
+ -> Result<Self::Ok, Self::Error>;
/// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`.
///
@@ -434,13 +425,12 @@ pub trait Serializer: Sized {
/// E::N(ref n) => serializer.serialize_newtype_variant("E", 0, "N", n),
/// }
/// ```
- fn serialize_newtype_variant<T: ?Sized + Serialize>(
- self,
- name: &'static str,
- variant_index: usize,
- variant: &'static str,
- value: &T,
- ) -> Result<Self::Ok, Self::Error>;
+ fn serialize_newtype_variant<T: ?Sized + Serialize>(self,
+ name: &'static str,
+ variant_index: usize,
+ variant: &'static str,
+ value: &T)
+ -> Result<Self::Ok, Self::Error>;
/// Begin to serialize a dynamically sized sequence. This call must be
/// followed by zero or more calls to `serialize_element`, then a call to
@@ -457,10 +447,7 @@ pub trait Serializer: Sized {
/// }
/// seq.end()
/// ```
- fn serialize_seq(
- self,
- len: Option<usize>,
- ) -> Result<Self::SerializeSeq, Self::Error>;
+ fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>;
/// Begin to serialize a statically sized sequence whose length will be
/// known at deserialization time without looking at the serialized data.
@@ -474,10 +461,7 @@ pub trait Serializer: Sized {
/// }
/// seq.end()
/// ```
- fn serialize_seq_fixed_size(
- self,
- size: usize,
- ) -> Result<Self::SerializeSeq, Self::Error>;
+ fn serialize_seq_fixed_size(self, size: usize) -> Result<Self::SerializeSeq, Self::Error>;
/// Begin to serialize a tuple. This call must be followed by zero or more
/// calls to `serialize_field`, then a call to `end`.
@@ -489,10 +473,7 @@ pub trait Serializer: Sized {
/// tup.serialize_field(&self.2)?;
/// tup.end()
/// ```
- fn serialize_tuple(
- self,
- len: usize,
- ) -> Result<Self::SerializeTuple, Self::Error>;
+ fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error>;
/// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This
/// call must be followed by zero or more calls to `serialize_field`, then a
@@ -508,11 +489,10 @@ pub trait Serializer: Sized {
/// ts.serialize_field(&self.2)?;
/// ts.end()
/// ```
- fn serialize_tuple_struct(
- self,
- name: &'static str,
- len: usize,
- ) -> Result<Self::SerializeTupleStruct, Self::Error>;
+ fn serialize_tuple_struct(self,
+ name: &'static str,
+ len: usize)
+ -> Result<Self::SerializeTupleStruct, Self::Error>;
/// Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8)
/// }`. This call must be followed by zero or more calls to
@@ -532,13 +512,12 @@ pub trait Serializer: Sized {
/// }
/// }
/// ```
- fn serialize_tuple_variant(
- self,
- name: &'static str,
- variant_index: usize,
- variant: &'static str,
- len: usize,
- ) -> Result<Self::SerializeTupleVariant, Self::Error>;
+ fn serialize_tuple_variant(self,
+ name: &'static str,
+ variant_index: usize,
+ variant: &'static str,
+ len: usize)
+ -> Result<Self::SerializeTupleVariant, Self::Error>;
/// Begin to serialize a map. This call must be followed by zero or more
/// calls to `serialize_key` and `serialize_value`, then a call to `end`.
@@ -554,10 +533,7 @@ pub trait Serializer: Sized {
/// }
/// map.end()
/// ```
- fn serialize_map(
- self,
- len: Option<usize>,
- ) -> Result<Self::SerializeMap, Self::Error>;
+ fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>;
/// Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`.
/// This call must be followed by zero or more calls to `serialize_field`,
@@ -573,11 +549,10 @@ pub trait Serializer: Sized {
/// struc.serialize_field("b", &self.b)?;
/// struc.end()
/// ```
- fn serialize_struct(
- self,
- name: &'static str,
- len: usize,
- ) -> Result<Self::SerializeStruct, Self::Error>;
+ fn serialize_struct(self,
+ name: &'static str,
+ len: usize)
+ -> Result<Self::SerializeStruct, Self::Error>;
/// Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8,
/// g: u8, b: u8 } }`. This call must be followed by zero or more calls to
@@ -598,13 +573,12 @@ pub trait Serializer: Sized {
/// }
/// }
/// ```
- fn serialize_struct_variant(
- self,
- name: &'static str,
- variant_index: usize,
- variant: &'static str,
- len: usize,
- ) -> Result<Self::SerializeStructVariant, Self::Error>;
+ fn serialize_struct_variant(self,
+ name: &'static str,
+ variant_index: usize,
+ variant: &'static str,
+ len: usize)
+ -> Result<Self::SerializeStructVariant, Self::Error>;
/// Collect an iterator as a sequence.
///
@@ -613,7 +587,7 @@ pub trait Serializer: Sized {
/// this method.
fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error>
where I: IntoIterator,
- <I as IntoIterator>::Item: Serialize,
+ <I as IntoIterator>::Item: Serialize
{
let iter = iter.into_iter();
let mut serializer = try!(self.serialize_seq(iter.len_hint()));
@@ -631,7 +605,7 @@ pub trait Serializer: Sized {
fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>
where K: Serialize,
V: Serialize,
- I: IntoIterator<Item = (K, V)>,
+ I: IntoIterator<Item = (K, V)>
{
let iter = iter.into_iter();
let mut serializer = try!(self.serialize_map(iter.len_hint()));
@@ -773,11 +747,10 @@ pub trait SerializeMap {
/// `serialize_value`. This is appropriate for serializers that do not care
/// about performance or are not able to optimize `serialize_entry` any
/// better than this.
- fn serialize_entry<K: ?Sized + Serialize, V: ?Sized + Serialize>(
- &mut self,
- key: &K,
- value: &V,
- ) -> Result<(), Self::Error> {
+ fn serialize_entry<K: ?Sized + Serialize, V: ?Sized + Serialize>(&mut self,
+ key: &K,
+ value: &V)
+ -> Result<(), Self::Error> {
try!(self.serialize_key(key));
self.serialize_value(value)
}
@@ -803,7 +776,10 @@ pub trait SerializeStruct {
type Error: Error;
/// Serialize a struct field.
- fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>;
+ fn serialize_field<T: ?Sized + Serialize>(&mut self,
+ key: &'static str,
+ value: &T)
+ -> Result<(), Self::Error>;
/// Finish serializing a struct.
fn end(self) -> Result<Self::Ok, Self::Error>;
@@ -830,7 +806,10 @@ pub trait SerializeStructVariant {
type Error: Error;
/// Serialize a struct variant field.
- fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>;
+ fn serialize_field<T: ?Sized + Serialize>(&mut self,
+ key: &'static str,
+ value: &T)
+ -> Result<(), Self::Error>;
/// Finish serializing a struct variant.
fn end(self) -> Result<Self::Ok, Self::Error>;
diff --git a/serde/src/ser/private.rs b/serde/src/ser/private.rs
index 9d17ec789..9ee926840 100644
--- a/serde/src/ser/private.rs
+++ b/serde/src/ser/private.rs
@@ -3,14 +3,13 @@ use core::fmt::{self, Display};
use ser::{self, Serialize, Serializer, SerializeMap, SerializeStruct};
/// Not public API.
-pub fn serialize_tagged_newtype<S, T>(
- serializer: S,
- type_ident: &'static str,
- variant_ident: &'static str,
- tag: &'static str,
- variant_name: &'static str,
- value: T,
-) -> Result<S::Ok, S::Error>
+pub fn serialize_tagged_newtype<S, T>(serializer: S,
+ type_ident: &'static str,
+ variant_ident: &'static str,
+ tag: &'static str,
+ variant_name: &'static str,
+ value: T)
+ -> Result<S::Ok, S::Error>
where S: Serializer,
T: Serialize
{
@@ -181,17 +180,29 @@ impl<S> Serializer for TaggedSerializer<S>
Err(self.bad_type(Unsupported::UnitStruct))
}
- fn serialize_unit_variant(self, _: &'static str, _: usize, _: &'static str) -> Result<Self::Ok, Self::Error> {
+ fn serialize_unit_variant(self,
+ _: &'static str,
+ _: usize,
+ _: &'static str)
+ -> Result<Self::Ok, Self::Error> {
Err(self.bad_type(Unsupported::Enum))
}
- fn serialize_newtype_struct<T: ?Sized>(self, _: &'static str, value: &T) -> Result<Self::Ok, Self::Error>
+ fn serialize_newtype_struct<T: ?Sized>(self,
+ _: &'static str,
+ value: &T)
+ -> Result<Self::Ok, Self::Error>
where T: Serialize
{
value.serialize(self)
}
- fn serialize_newtype_variant<T: ?Sized>(self, _: &'static str, _: usize, _: &'static str, _: &T) -> Result<Self::Ok, Self::Error>
+ fn serialize_newtype_variant<T: ?Sized>(self,
+ _: &'static str,
+ _: usize,
+ _: &'static str,
+ _: &T)
+ -> Result<Self::Ok, Self::Error>
where T: Serialize
{
Err(self.bad_type(Unsupported::Enum))
@@ -209,11 +220,19 @@ impl<S> Serializer for TaggedSerializer<S>
Err(self.bad_type(Unsupported::Tuple))
}
- fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Result<Self::SerializeTupleStruct, Self::Error> {
+ fn serialize_tuple_struct(self,
+ _: &'static str,
+ _: usize)
+ -> Result<Self::SerializeTupleStruct, Self::Error> {
Err(self.bad_type(Unsupported::TupleStruct))
}
- fn serialize_tuple_variant(self, _: &'static str, _: usize, _: &'static str, _: usize) -> Result<Self::SerializeTupleVariant, Self::Error> {
+ fn serialize_tuple_variant(self,
+ _: &'static str,
+ _: usize,
+ _: &'static str,
+ _: usize)
+ -> Result<Self::SerializeTupleVariant, Self::Error> {
Err(self.bad_type(Unsupported::Enum))
}
@@ -223,13 +242,21 @@ impl<S> Serializer for TaggedSerializer<S>
Ok(map)
}
- fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct, Self::Error> {
+ fn serialize_struct(self,
+ name: &'static str,
+ len: usize)
+ -> Result<Self::SerializeStruct, Self::Error> {
let mut state = try!(self.delegate.serialize_struct(name, len + 1));
try!(state.serialize_field(self.tag, self.variant_name));
Ok(state)
}
- fn serialize_struct_variant(self, _: &'static str, _: usize, _: &'static str, _: usize) -> Result<Self::SerializeStructVariant, Self::Error> {
+ fn serialize_struct_variant(self,
+ _: &'static str,
+ _: usize,
+ _: &'static str,
+ _: usize)
+ -> Result<Self::SerializeStructVariant, Self::Error> {
Err(self.bad_type(Unsupported::Enum))
}
}
diff --git a/serde/src/utils.rs b/serde/src/utils.rs
index 708eb4274..7df7b6cf2 100644
--- a/serde/src/utils.rs
+++ b/serde/src/utils.rs
@@ -1,12 +1,12 @@
//! Private utility functions
-const TAG_CONT: u8 = 0b1000_0000;
-const TAG_TWO_B: u8 = 0b1100_0000;
+const TAG_CONT: u8 = 0b1000_0000;
+const TAG_TWO_B: u8 = 0b1100_0000;
const TAG_THREE_B: u8 = 0b1110_0000;
-const TAG_FOUR_B: u8 = 0b1111_0000;
-const MAX_ONE_B: u32 = 0x80;
-const MAX_TWO_B: u32 = 0x800;
-const MAX_THREE_B: u32 = 0x10000;
+const TAG_FOUR_B: u8 = 0b1111_0000;
+const MAX_ONE_B: u32 = 0x80;
+const MAX_TWO_B: u32 = 0x800;
+const MAX_THREE_B: u32 = 0x10000;
#[inline]
pub fn encode_utf8(c: char) -> EncodeUtf8 {
@@ -21,17 +21,20 @@ pub fn encode_utf8(c: char) -> EncodeUtf8 {
2
} else if code < MAX_THREE_B {
buf[1] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
- buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
+ buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
1
} else {
buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT;
- buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
+ buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
0
};
- EncodeUtf8 { buf: buf, pos: pos }
+ EncodeUtf8 {
+ buf: buf,
+ pos: pos,
+ }
}
pub struct EncodeUtf8 {
@@ -47,23 +50,22 @@ impl EncodeUtf8 {
}
#[allow(non_upper_case_globals)]
-const Pattern_White_Space_table: &'static [(char, char)] = &[
- ('\u{9}', '\u{d}'), ('\u{20}', '\u{20}'), ('\u{85}', '\u{85}'), ('\u{200e}', '\u{200f}'),
- ('\u{2028}', '\u{2029}')
-];
+const Pattern_White_Space_table: &'static [(char, char)] = &[('\u{9}', '\u{d}'),
+ ('\u{20}', '\u{20}'),
+ ('\u{85}', '\u{85}'),
+ ('\u{200e}', '\u{200f}'),
+ ('\u{2028}', '\u{2029}')];
fn bsearch_range_table(c: char, r: &'static [(char, char)]) -> bool {
use core::cmp::Ordering::{Equal, Less, Greater};
- r.binary_search_by(|&(lo, hi)| {
- if c < lo {
+ r.binary_search_by(|&(lo, hi)| if c < lo {
Greater
} else if hi < c {
Less
} else {
Equal
- }
- })
- .is_ok()
+ })
+ .is_ok()
}
#[allow(non_snake_case)]
diff --git a/serde_codegen_internals/src/ast.rs b/serde_codegen_internals/src/ast.rs
index 2941c1641..ea598d80a 100644
--- a/serde_codegen_internals/src/ast.rs
+++ b/serde_codegen_internals/src/ast.rs
@@ -39,9 +39,7 @@ impl<'a> Item<'a> {
let attrs = attr::Item::from_ast(cx, item);
let body = match item.body {
- syn::Body::Enum(ref variants) => {
- Body::Enum(enum_from_ast(cx, variants))
- }
+ syn::Body::Enum(ref variants) => Body::Enum(enum_from_ast(cx, variants)),
syn::Body::Struct(ref variant_data) => {
let (style, fields) = struct_from_ast(cx, variant_data);
Body::Struct(style, fields)
@@ -58,15 +56,13 @@ impl<'a> Item<'a> {
}
impl<'a> Body<'a> {
- pub fn all_fields(&'a self) -> Box<Iterator<Item=&'a Field<'a>> + 'a> {
+ pub fn all_fields(&'a self) -> Box<Iterator<Item = &'a Field<'a>> + 'a> {
match *self {
Body::Enum(ref variants) => {
Box::new(variants.iter()
- .flat_map(|variant| variant.fields.iter()))
- }
- Body::Struct(_, ref fields) => {
- Box::new(fields.iter())
+ .flat_map(|variant| variant.fields.iter()))
}
+ Body::Struct(_, ref fields) => Box::new(fields.iter()),
}
}
}
@@ -87,18 +83,12 @@ fn enum_from_ast<'a>(cx: &Ctxt, variants: &'a [syn::Variant]) -> Vec<Variant<'a>
fn struct_from_ast<'a>(cx: &Ctxt, data: &'a syn::VariantData) -> (Style, Vec<Field<'a>>) {
match *data {
- syn::VariantData::Struct(ref fields) => {
- (Style::Struct, fields_from_ast(cx, fields))
- }
+ syn::VariantData::Struct(ref fields) => (Style::Struct, fields_from_ast(cx, fields)),
syn::VariantData::Tuple(ref fields) if fields.len() == 1 => {
(Style::Newtype, fields_from_ast(cx, fields))
}
- syn::VariantData::Tuple(ref fields) => {
- (Style::Tuple, fields_from_ast(cx, fields))
- }
- syn::VariantData::Unit => {
- (Style::Unit, Vec::new())
- }
+ syn::VariantData::Tuple(ref fields) => (Style::Tuple, fields_from_ast(cx, fields)),
+ syn::VariantData::Unit => (Style::Unit, Vec::new()),
}
}
diff --git a/serde_codegen_internals/src/attr.rs b/serde_codegen_internals/src/attr.rs
index 97fa4650b..224bb9398 100644
--- a/serde_codegen_internals/src/attr.rs
+++ b/serde_codegen_internals/src/attr.rs
@@ -157,7 +157,8 @@ impl Item {
// Parse `#[serde(bound="D: Serialize")]`
MetaItem(NameValue(ref name, ref lit)) if name == "bound" => {
- if let Ok(where_predicates) = parse_lit_into_where(cx, name.as_ref(), name.as_ref(), lit) {
+ if let Ok(where_predicates) =
+ parse_lit_into_where(cx, name.as_ref(), name.as_ref(), lit) {
ser_bound.set(where_predicates.clone());
de_bound.set(where_predicates);
}
@@ -217,10 +218,12 @@ impl Item {
if let syn::Body::Enum(ref variants) = item.body {
for variant in variants {
match variant.data {
- syn::VariantData::Struct(_) | syn::VariantData::Unit => {}
+ syn::VariantData::Struct(_) |
+ syn::VariantData::Unit => {}
syn::VariantData::Tuple(ref fields) => {
if fields.len() != 1 {
- cx.error("#[serde(tag = \"...\")] cannot be used with tuple variants");
+ cx.error("#[serde(tag = \"...\")] cannot be used with tuple \
+ variants");
break;
}
}
@@ -311,8 +314,7 @@ impl Variant {
}
MetaItem(ref meta_item) => {
- cx.error(format!("unknown serde variant attribute `{}`",
- meta_item.name()));
+ cx.error(format!("unknown serde variant attribute `{}`", meta_item.name()));
}
Literal(_) => {
@@ -372,9 +374,7 @@ pub enum FieldDefault {
impl Field {
/// Extract out the `#[serde(...)]` attributes from a struct field.
- pub fn from_ast(cx: &Ctxt,
- index: usize,
- field: &syn::Field) -> Self {
+ pub fn from_ast(cx: &Ctxt, index: usize, field: &syn::Field) -> Self {
let mut ser_name = Attr::none(cx, "rename");
let mut de_name = Attr::none(cx, "rename");
let mut skip_serializing = BoolAttr::none(cx, "skip_serializing");
@@ -455,7 +455,8 @@ impl Field {
// Parse `#[serde(bound="D: Serialize")]`
MetaItem(NameValue(ref name, ref lit)) if name == "bound" => {
- if let Ok(where_predicates) = parse_lit_into_where(cx, name.as_ref(), name.as_ref(), lit) {
+ if let Ok(where_predicates) =
+ parse_lit_into_where(cx, name.as_ref(), name.as_ref(), lit) {
ser_bound.set(where_predicates.clone());
de_bound.set(where_predicates);
}
@@ -470,8 +471,7 @@ impl Field {
}
MetaItem(ref meta_item) => {
- cx.error(format!("unknown serde field attribute `{}`",
- meta_item.name()));
+ cx.error(format!("unknown serde field attribute `{}`", meta_item.name()));
}
Literal(_) => {
@@ -542,13 +542,12 @@ impl Field {
type SerAndDe<T> = (Option<T>, Option<T>);
-fn get_ser_and_de<T, F>(
- cx: &Ctxt,
- attr_name: &'static str,
- items: &[syn::NestedMetaItem],
- f: F
-) -> Result<SerAndDe<T>, ()>
- where F: Fn(&Ctxt, &str, &str, &syn::Lit) -> Result<T, ()>,
+fn get_ser_and_de<T, F>(cx: &Ctxt,
+ attr_name: &'static str,
+ items: &[syn::NestedMetaItem],
+ f: F)
+ -> Result<SerAndDe<T>, ()>
+ where F: Fn(&Ctxt, &str, &str, &syn::Lit) -> Result<T, ()>
{
let mut ser_item = Attr::none(cx, attr_name);
let mut de_item = Attr::none(cx, attr_name);
@@ -568,7 +567,8 @@ fn get_ser_and_de<T, F>(
}
_ => {
- cx.error(format!("malformed {0} attribute, expected `{0}(serialize = ..., deserialize = ...)`",
+ cx.error(format!("malformed {0} attribute, expected `{0}(serialize = ..., \
+ deserialize = ...)`",
attr_name));
return Err(());
}
@@ -578,35 +578,34 @@ fn get_ser_and_de<T, F>(
Ok((ser_item.get(), de_item.get()))
}
-fn get_renames(
- cx: &Ctxt,
- items: &[syn::NestedMetaItem],
-) -> Result<SerAndDe<String>, ()> {
+fn get_renames(cx: &Ctxt, items: &[syn::NestedMetaItem]) -> Result<SerAndDe<String>, ()> {
get_ser_and_de(cx, "rename", items, get_string_from_lit)
}
-fn get_where_predicates(
- cx: &Ctxt,
- items: &[syn::NestedMetaItem],
-) -> Result<SerAndDe<Vec<syn::WherePredicate>>, ()> {
+fn get_where_predicates(cx: &Ctxt,
+ items: &[syn::NestedMetaItem])
+ -> Result<SerAndDe<Vec<syn::WherePredicate>>, ()> {
get_ser_and_de(cx, "bound", items, parse_lit_into_where)
}
pub fn get_serde_meta_items(attr: &syn::Attribute) -> Option<Vec<syn::NestedMetaItem>> {
match attr.value {
- List(ref name, ref items) if name == "serde" => {
- Some(items.iter().cloned().collect())
- }
- _ => None
+ List(ref name, ref items) if name == "serde" => Some(items.iter().cloned().collect()),
+ _ => None,
}
}
-fn get_string_from_lit(cx: &Ctxt, attr_name: &str, meta_item_name: &str, lit: &syn::Lit) -> Result<String, ()> {
+fn get_string_from_lit(cx: &Ctxt,
+ attr_name: &str,
+ meta_item_name: &str,
+ lit: &syn::Lit)
+ -> Result<String, ()> {
if let syn::Lit::Str(ref s, _) = *lit {
Ok(s.clone())
} else {
cx.error(format!("expected serde {} attribute to be a string: `{} = \"...\"`",
- attr_name, meta_item_name));
+ attr_name,
+ meta_item_name));
Err(())
}
}
@@ -616,7 +615,11 @@ fn parse_lit_into_path(cx: &Ctxt, attr_name: &str, lit: &syn::Lit) -> Result<syn
syn::parse_path(&string).map_err(|err| cx.error(err))
}
-fn parse_lit_into_where(cx: &Ctxt, attr_name: &str, meta_item_name: &str, lit: &syn::Lit) -> Result<Vec<syn::WherePredicate>, ()> {
+fn parse_lit_into_where(cx: &Ctxt,
+ attr_name: &str,
+ meta_item_name: &str,
+ lit: &syn::Lit)
+ -> Result<Vec<syn::WherePredicate>, ()> {
let string = try!(get_string_from_lit(cx, attr_name, meta_item_name, lit));
if string.is_empty() {
return Ok(Vec::new());
diff --git a/serde_codegen_internals/src/ctxt.rs b/serde_codegen_internals/src/ctxt.rs
index a1455332c..a112c7e96 100644
--- a/serde_codegen_internals/src/ctxt.rs
+++ b/serde_codegen_internals/src/ctxt.rs
@@ -8,9 +8,7 @@ pub struct Ctxt {
impl Ctxt {
pub fn new() -> Self {
- Ctxt {
- errors: RefCell::new(Some(Vec::new())),
- }
+ Ctxt { errors: RefCell::new(Some(Vec::new())) }
}
pub fn error<T: Display>(&self, msg: T) {
diff --git a/serde_derive/src/bound.rs b/serde_derive/src/bound.rs
index fef77ba38..e386e2a31 100644
--- a/serde_derive/src/bound.rs
+++ b/serde_derive/src/bound.rs
@@ -10,36 +10,33 @@ use internals::attr;
// allowed here".
pub fn without_defaults(generics: &syn::Generics) -> syn::Generics {
syn::Generics {
- ty_params: generics.ty_params.iter().map(|ty_param| {
- syn::TyParam {
- default: None,
- .. ty_param.clone()
- }}).collect(),
- .. generics.clone()
+ ty_params: generics.ty_params
+ .iter()
+ .map(|ty_param| syn::TyParam { default: None, ..ty_param.clone() })
+ .collect(),
+ ..generics.clone()
}
}
-pub fn with_where_predicates(
- generics: &syn::Generics,
- predicates: &[syn::WherePredicate],
-) -> syn::Generics {
+pub fn with_where_predicates(generics: &syn::Generics,
+ predicates: &[syn::WherePredicate])
+ -> syn::Generics {
aster::from_generics(generics.clone())
.with_predicates(predicates.to_vec())
.build()
}
-pub fn with_where_predicates_from_fields<F>(
- item: &Item,
- generics: &syn::Generics,
- from_field: F,
-) -> syn::Generics
- where F: Fn(&attr::Field) -> Option<&[syn::WherePredicate]>,
+pub fn with_where_predicates_from_fields<F>(item: &Item,
+ generics: &syn::Generics,
+ from_field: F)
+ -> syn::Generics
+ where F: Fn(&attr::Field) -> Option<&[syn::WherePredicate]>
{
aster::from_generics(generics.clone())
- .with_predicates(
- item.body.all_fields()
- .flat_map(|field| from_field(&field.attrs))
- .flat_map(|predicates| predicates.to_vec()))
+ .with_predicates(item.body
+ .all_fields()
+ .flat_map(|field| from_field(&field.attrs))
+ .flat_map(|predicates| predicates.to_vec()))
.build()
}
@@ -54,13 +51,12 @@ pub fn with_where_predicates_from_fields<F>(
// #[serde(skip_serializing)]
// c: C,
// }
-pub fn with_bound<F>(
- item: &Item,
- generics: &syn::Generics,
- filter: F,
- bound: &syn::Path,
-) -> syn::Generics
- where F: Fn(&attr::Field) -> bool,
+pub fn with_bound<F>(item: &Item,
+ generics: &syn::Generics,
+ filter: F,
+ bound: &syn::Path)
+ -> syn::Generics
+ where F: Fn(&attr::Field) -> bool
{
struct FindTyParams {
// Set of all generic type parameters on the current struct (A, B, C in
@@ -90,11 +86,13 @@ pub fn with_bound<F>(
}
}
- let all_ty_params: HashSet<_> = generics.ty_params.iter()
+ let all_ty_params: HashSet<_> = generics.ty_params
+ .iter()
.map(|ty_param| ty_param.ident.clone())
.collect();
- let relevant_tys = item.body.all_fields()
+ let relevant_tys = item.body
+ .all_fields()
.filter(|&field| filter(&field.attrs))
.map(|field| &field.ty);
@@ -107,15 +105,17 @@ pub fn with_bound<F>(
}
aster::from_generics(generics.clone())
- .with_predicates(
- generics.ty_params.iter()
- .map(|ty_param| ty_param.ident.clone())
- .filter(|id| visitor.relevant_ty_params.contains(id))
- .map(|id| aster::where_predicate()
+ .with_predicates(generics.ty_params
+ .iter()
+ .map(|ty_param| ty_param.ident.clone())
+ .filter(|id| visitor.relevant_ty_params.contains(id))
+ .map(|id| {
+ aster::where_predicate()
// the type parameter that is being bounded e.g. T
.bound().build(aster::ty().id(id))
// the bound e.g. Serialize
.bound().trait_(bound.clone()).build()
- .build()))
+ .build()
+ }))
.build()
}
diff --git a/serde_derive/src/de.rs b/serde_derive/src/de.rs
index 95abd5f0c..9e203ec98 100644
--- a/serde_derive/src/de.rs
+++ b/serde_derive/src/de.rs
@@ -18,13 +18,14 @@ pub fn expand_derive_deserialize(item: &syn::DeriveInput) -> Result<Tokens, Stri
let impl_generics = build_impl_generics(&item);
- let ty = aster::ty().path()
- .segment(item.ident.clone()).with_generics(impl_generics.clone()).build()
+ let ty = aster::ty()
+ .path()
+ .segment(item.ident.clone())
+ .with_generics(impl_generics.clone())
+ .build()
.build();
- let body = deserialize_body(&item,
- &impl_generics,
- ty.clone());
+ let body = deserialize_body(&item, &impl_generics, ty.clone());
let where_clause = &impl_generics.where_clause;
@@ -50,21 +51,21 @@ pub fn expand_derive_deserialize(item: &syn::DeriveInput) -> Result<Tokens, Stri
fn build_impl_generics(item: &Item) -> syn::Generics {
let generics = bound::without_defaults(item.generics);
- let generics = bound::with_where_predicates_from_fields(
- item, &generics,
- |attrs| attrs.de_bound());
+ let generics =
+ bound::with_where_predicates_from_fields(item, &generics, |attrs| attrs.de_bound());
match item.attrs.de_bound() {
- Some(predicates) => {
- bound::with_where_predicates(&generics, predicates)
- }
+ Some(predicates) => bound::with_where_predicates(&generics, predicates),
None => {
- let generics = bound::with_bound(item, &generics,
- needs_deserialize_bound,
- &aster::path().ids(&["_serde", "Deserialize"]).build());
- bound::with_bound(item, &generics,
- requires_default,
- &aster::path().global().ids(&["std", "default", "Default"]).build())
+ let generics =
+ bound::with_bound(item,
+ &generics,
+ needs_deserialize_bound,
+ &aster::path().ids(&["_serde", "Deserialize"]).build());
+ bound::with_bound(item,
+ &generics,
+ requires_default,
+ &aster::path().global().ids(&["std", "default", "Default"]).build())
}
}
}
@@ -74,9 +75,7 @@ fn build_impl_generics(item: &Item) -> syn::Generics {
// attribute specify their own bound so we do not generate one. All other fields
// may need a `T: Deserialize` bound where T is the type of the field.
fn needs_deserialize_bound(attrs: &attr::Field) -> bool {
- !attrs.skip_deserializing()
- && attrs.deserialize_with().is_none()
- && attrs.de_bound().is_none()
+ !attrs.skip_deserializing() && attrs.deserialize_with().is_none() && attrs.de_bound().is_none()
}
// Fields with a `default` attribute (not `default=...`), and fields with a
@@ -85,33 +84,23 @@ fn requires_default(attrs: &attr::Field) -> bool {
attrs.default() == &attr::FieldDefault::Default
}
-fn deserialize_body(
- item: &Item,
- impl_generics: &syn::Generics,
- ty: syn::Ty,
-) -> Tokens {
+fn deserialize_body(item: &Item, impl_generics: &syn::Generics, ty: syn::Ty) -> Tokens {
match item.body {
Body::Enum(ref variants) => {
- deserialize_item_enum(
- &item.ident,
- impl_generics,
- ty,
- variants,
- &item.attrs)
+ deserialize_item_enum(&item.ident, impl_generics, ty, variants, &item.attrs)
}
Body::Struct(Style::Struct, ref fields) => {
if fields.iter().any(|field| field.ident.is_none()) {
panic!("struct has unnamed fields");
}
- deserialize_struct(
- &item.ident,
- None,
- impl_generics,
- ty,
- fields,
- &item.attrs,
- None)
+ deserialize_struct(&item.ident,
+ None,
+ impl_generics,
+ ty,
+ fields,
+ &item.attrs,
+ None)
}
Body::Struct(Style::Tuple, ref fields) |
Body::Struct(Style::Newtype, ref fields) => {
@@ -119,20 +108,15 @@ fn deserialize_body(
panic!("tuple struct has named fields");
}
- deserialize_tuple(
- &item.ident,
- None,
- impl_generics,
- ty,
- fields,
- &item.attrs,
- None)
- }
- Body::Struct(Style::Unit, _) => {
- deserialize_unit_struct(
- &item.ident,
- &item.attrs)
+ deserialize_tuple(&item.ident,
+ None,
+ impl_generics,
+ ty,
+ fields,
+ &item.attrs,
+ None)
}
+ Body::Struct(Style::Unit, _) => deserialize_unit_struct(&item.ident, &item.attrs),
}
}
@@ -145,33 +129,37 @@ fn deserialize_body(
// 3. the expression for instantiating the visitor
fn deserialize_visitor(generics: &syn::Generics) -> (Tokens, Tokens, Tokens) {
if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
- (
- quote! {
+ (quote! {
struct __Visitor;
},
- quote!(__Visitor),
- quote!(__Visitor),
- )
+ quote!(__Visitor),
+ quote!(__Visitor))
} else {
let where_clause = &generics.where_clause;
let num_phantoms = generics.lifetimes.len() + generics.ty_params.len();
- let phantom_types = generics.lifetimes.iter()
+ let phantom_types = generics.lifetimes
+ .iter()
.map(|lifetime_def| {
let lifetime = &lifetime_def.lifetime;
quote!(_serde::export::PhantomData<& #lifetime ()>)
- }).chain(generics.ty_params.iter()
+ })
+ .chain(generics.ty_params
+ .iter()
.map(|ty_param| {
let ident = &ty_param.ident;
quote!(_serde::export::PhantomData<#ident>)
}));
- let all_params = generics.lifetimes.iter()
+ let all_params = generics.lifetimes
+ .iter()
.map(|lifetime_def| {
let lifetime = &lifetime_def.lifetime;
quote!(#lifetime)
- }).chain(generics.ty_params.iter()
+ })
+ .chain(generics.ty_params
+ .iter()
.map(|ty_param| {
let ident = &ty_param.ident;
quote!(#ident)
@@ -186,20 +174,15 @@ fn deserialize_visitor(generics: &syn::Generics) -> (Tokens, Tokens, Tokens) {
let phantom_exprs = iter::repeat(quote!(_serde::export::PhantomData)).take(num_phantoms);
- (
- quote! {
+ (quote! {
struct __Visitor #generics ( #(#phantom_types),* ) #where_clause;
},
- quote!(__Visitor <#(#all_params),*> ),
- quote!(__Visitor #ty_param_idents ( #(#phantom_exprs),* )),
- )
+ quote!(__Visitor <#(#all_params),*> ),
+ quote!(__Visitor #ty_param_idents ( #(#phantom_exprs),* )))
}
}
-fn deserialize_unit_struct(
- type_ident: &syn::Ident,
- item_attrs: &attr::Item,
-) -> Tokens {
+fn deserialize_unit_struct(type_ident: &syn::Ident, item_attrs: &attr::Item) -> Tokens {
let type_name = item_attrs.name().deserialize_name();
let expecting = format!("unit struct {}", type_ident);
@@ -233,15 +216,14 @@ fn deserialize_unit_struct(
})
}
-fn deserialize_tuple(
- type_ident: &syn::Ident,
- variant_ident: Option<&syn::Ident>,
- impl_generics: &syn::Generics,
- ty: syn::Ty,
- fields: &[Field],
- item_attrs: &attr::Item,
- deserializer: Option<Tokens>,
-) -> Tokens {
+fn deserialize_tuple(type_ident: &syn::Ident,
+ variant_ident: Option<&syn::Ident>,
+ impl_generics: &syn::Generics,
+ ty: syn::Ty,
+ fields: &[Field],
+ item_attrs: &attr::Item,
+ deserializer: Option<Tokens>)
+ -> Tokens {
let where_clause = &impl_generics.where_clause;
let (visitor_item, visitor_ty, visitor_expr) = deserialize_visitor(impl_generics);
@@ -259,23 +241,12 @@ fn deserialize_tuple(
let nfields = fields.len();
let visit_newtype_struct = if !is_enum && nfields == 1 {
- Some(deserialize_newtype_struct(
- type_ident,
- &type_path,
- impl_generics,
- &fields[0],
- ))
+ Some(deserialize_newtype_struct(type_ident, &type_path, impl_generics, &fields[0]))
} else {
None
};
- let visit_seq = deserialize_seq(
- type_ident,
- &type_path,
- impl_generics,
- fields,
- false,
- );
+ let visit_seq = deserialize_seq(type_ident, &type_path, impl_generics, fields, false);
let dispatch = if let Some(deserializer) = deserializer {
quote!(_serde::Deserializer::deserialize(#deserializer, #visitor_expr))
@@ -320,13 +291,12 @@ fn deserialize_tuple(
})
}
-fn deserialize_seq(
- type_ident: &syn::Ident,
- type_path: &Tokens,
- impl_generics: &syn::Generics,
- fields: &[Field],
- is_struct: bool,
-) -> Tokens {
+fn deserialize_seq(type_ident: &syn::Ident,
+ type_path: &Tokens,
+ impl_generics: &syn::Generics,
+ fields: &[Field],
+ is_struct: bool)
+ -> Tokens {
let vars = (0..fields.len()).map(field_i as fn(_) -> _);
let deserialized_count = fields.iter()
@@ -389,12 +359,11 @@ fn deserialize_seq(
}
}
-fn deserialize_newtype_struct(
- type_ident: &syn::Ident,
- type_path: &Tokens,
- impl_generics: &syn::Generics,
- field: &Field,
-) -> Tokens {
+fn deserialize_newtype_struct(type_ident: &syn::Ident,
+ type_path: &Tokens,
+ impl_generics: &syn::Generics,
+ field: &Field)
+ -> Tokens {
let value = match field.attrs.deserialize_with() {
None => {
let field_ty = &field.ty;
@@ -403,8 +372,8 @@ fn deserialize_newtype_struct(
}
}
Some(path) => {
- let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
- type_ident, impl_generics, field.ty, path);
+ let (wrapper, wrapper_impl, wrapper_ty) =
+ wrap_deserialize_with(type_ident, impl_generics, field.ty, path);
quote!({
#wrapper
#wrapper_impl
@@ -422,15 +391,14 @@ fn deserialize_newtype_struct(
}
}
-fn deserialize_struct(
- type_ident: &syn::Ident,
- variant_ident: Option<&syn::Ident>,
- impl_generics: &syn::Generics,
- ty: syn::Ty,
- fields: &[Field],
- item_attrs: &attr::Item,
- deserializer: Option<Tokens>,
-) -> Tokens {
+fn deserialize_struct(type_ident: &syn::Ident,
+ variant_ident: Option<&syn::Ident>,
+ impl_generics: &syn::Generics,
+ ty: syn::Ty,
+ fields: &[Field],
+ item_attrs: &attr::Item,
+ deserializer: Option<Tokens>)
+ -> Tokens {
let is_enum = variant_ident.is_some();
let is_untagged = deserializer.is_some();
@@ -447,21 +415,10 @@ fn deserialize_struct(
None => format!("struct {}", type_ident),
};
- let visit_seq = deserialize_seq(
- type_ident,
- &type_path,
- impl_generics,
- fields,
- true,
- );
-
- let (field_visitor, fields_stmt, visit_map) = deserialize_struct_visitor(
- type_ident,
- type_path,
- impl_generics,
- fields,
- item_attrs,
- );
+ let visit_seq = deserialize_seq(type_ident, &type_path, impl_generics, fields, true);
+
+ let (field_visitor, fields_stmt, visit_map) =
+ deserialize_struct_visitor(type_ident, type_path, impl_generics, fields, item_attrs);
let dispatch = if let Some(deserializer) = deserializer {
quote! {
@@ -527,52 +484,36 @@ fn deserialize_struct(
})
}
-fn deserialize_item_enum(
- type_ident: &syn::Ident,
- impl_generics: &syn::Generics,
- ty: syn::Ty,
- variants: &[Variant],
- item_attrs: &attr::Item
-) -> Tokens {
+fn deserialize_item_enum(type_ident: &syn::Ident,
+ impl_generics: &syn::Generics,
+ ty: syn::Ty,
+ variants: &[Variant],
+ item_attrs: &attr::Item)
+ -> Tokens {
match *item_attrs.tag() {
attr::EnumTag::External => {
- deserialize_externally_tagged_enum(
- type_ident,
- impl_generics,
- ty,
- variants,
- item_attrs,
- )
+ deserialize_externally_tagged_enum(type_ident, impl_generics, ty, variants, item_attrs)
}
attr::EnumTag::Internal(ref tag) => {
- deserialize_internally_tagged_enum(
- type_ident,
- impl_generics,
- ty,
- variants,
- item_attrs,
- tag,
- )
+ deserialize_internally_tagged_enum(type_ident,
+ impl_generics,
+ ty,
+ variants,
+ item_attrs,
+ tag)
}
attr::EnumTag::None => {
- deserialize_untagged_enum(
- type_ident,
- impl_generics,
- ty,
- variants,
- item_attrs,
- )
+ deserialize_untagged_enum(type_ident, impl_generics, ty, variants, item_attrs)
}
}
}
-fn deserialize_externally_tagged_enum(
- type_ident: &syn::Ident,
- impl_generics: &syn::Generics,
- ty: syn::Ty,
- variants: &[Variant],
- item_attrs: &attr::Item,
-) -> Tokens {
+fn deserialize_externally_tagged_enum(type_ident: &syn::Ident,
+ impl_generics: &syn::Generics,
+ ty: syn::Ty,
+ variants: &[Variant],
+ item_attrs: &attr::Item)
+ -> Tokens {
let where_clause = &impl_generics.where_clause;
let type_name = item_attrs.name().deserialize_name();
@@ -592,11 +533,7 @@ fn deserialize_externally_tagged_enum(
}
};
- let variant_visitor = deserialize_field_visitor(
- variant_names_idents,
- item_attrs,
- true,
- );
+ let variant_visitor = deserialize_field_visitor(variant_names_idents, item_attrs, true);
// Match arms to extract a variant from a string
let variant_arms = variants.iter()
@@ -605,13 +542,11 @@ fn deserialize_externally_tagged_enum(
.map(|(i, variant)| {
let variant_name = field_i(i);
- let block = deserialize_externally_tagged_variant(
- type_ident,
- impl_generics,
- ty.clone(),
- variant,
- item_attrs,
- );
+ let block = deserialize_externally_tagged_variant(type_ident,
+ impl_generics,
+ ty.clone(),
+ variant,
+ item_attrs);
quote! {
(__Field::#variant_name, visitor) => #block
@@ -664,14 +599,13 @@ fn deserialize_externally_tagged_enum(
})
}
-fn deserialize_internally_tagged_enum(
- type_ident: &syn::Ident,
- impl_generics: &syn::Generics,
- ty: syn::Ty,
- variants: &[Variant],
- item_attrs: &attr::Item,
- tag: &str,
-) -> Tokens {
+fn deserialize_internally_tagged_enum(type_ident: &syn::Ident,
+ impl_generics: &syn::Generics,
+ ty: syn::Ty,
+ variants: &[Variant],
+ item_attrs: &attr::Item,
+ tag: &str)
+ -> Tokens {
let variant_names_idents: Vec<_> = variants.iter()
.enumerate()
.filter(|&(_, variant)| !variant.attrs.skip_deserializing())
@@ -685,11 +619,7 @@ fn deserialize_internally_tagged_enum(
}
};
- let variant_visitor = deserialize_field_visitor(
- variant_names_idents,
- item_attrs,
- true,
- );
+ let variant_visitor = deserialize_field_visitor(variant_names_idents, item_attrs, true);
// Match arms to extract a variant from a string
let variant_arms = variants.iter()
@@ -727,13 +657,12 @@ fn deserialize_internally_tagged_enum(
})
}
-fn deserialize_untagged_enum(
- type_ident: &syn::Ident,
- impl_generics: &syn::Generics,
- ty: syn::Ty,
- variants: &[Variant],
- item_attrs: &attr::Item,
-) -> Tokens {
+fn deserialize_untagged_enum(type_ident: &syn::Ident,
+ impl_generics: &syn::Generics,
+ ty: syn::Ty,
+ variants: &[Variant],
+ item_attrs: &attr::Item)
+ -> Tokens {
let attempts = variants.iter()
.filter(|variant| !variant.attrs.skip_deserializing())
.map(|variant| {
@@ -768,13 +697,12 @@ fn deserialize_untagged_enum(
})
}
-fn deserialize_externally_tagged_variant(
- type_ident: &syn::Ident,
- generics: &syn::Generics,
- ty: syn::Ty,
- variant: &Variant,
- item_attrs: &attr::Item,
-) -> Tokens {
+fn deserialize_externally_tagged_variant(type_ident: &syn::Ident,
+ generics: &syn::Generics,
+ ty: syn::Ty,
+ variant: &Variant,
+ item_attrs: &attr::Item)
+ -> Tokens {
let variant_ident = &variant.ident;
match variant.style {
@@ -785,46 +713,39 @@ fn deserialize_externally_tagged_variant(
})
}
Style::Newtype => {
- deserialize_externally_tagged_newtype_variant(
- type_ident,
- variant_ident,
- generics,
- &variant.fields[0],
- )
+ deserialize_externally_tagged_newtype_variant(type_ident,
+ variant_ident,
+ generics,
+ &variant.fields[0])
}
Style::Tuple => {
- deserialize_tuple(
- type_ident,
- Some(variant_ident),
- generics,
- ty,
- &variant.fields,
- item_attrs,
- None,
- )
+ deserialize_tuple(type_ident,
+ Some(variant_ident),
+ generics,
+ ty,
+ &variant.fields,
+ item_attrs,
+ None)
}
Style::Struct => {
- deserialize_struct(
- type_ident,
- Some(variant_ident),
- generics,
- ty,
- &variant.fields,
- item_attrs,
- None,
- )
+ deserialize_struct(type_ident,
+ Some(variant_ident),
+ generics,
+ ty,
+ &variant.fields,
+ item_attrs,
+ None)
}
}
}
-fn deserialize_internally_tagged_variant(
- type_ident: &syn::Ident,
- generics: &syn::Generics,
- ty: syn::Ty,
- variant: &Variant,
- item_attrs: &attr::Item,
- deserializer: Tokens,
-) -> Tokens {
+fn deserialize_internally_tagged_variant(type_ident: &syn::Ident,
+ generics: &syn::Generics,
+ ty: syn::Ty,
+ variant: &Variant,
+ item_attrs: &attr::Item,
+ deserializer: Tokens)
+ -> Tokens {
let variant_ident = &variant.ident;
match variant.style {
@@ -837,27 +758,24 @@ fn deserialize_internally_tagged_variant(
})
}
Style::Newtype | Style::Struct => {
- deserialize_untagged_variant(
- type_ident,
- generics,
- ty,
- variant,
- item_attrs,
- deserializer,
- )
+ deserialize_untagged_variant(type_ident,
+ generics,
+ ty,
+ variant,
+ item_attrs,
+ deserializer)
}
Style::Tuple => unreachable!("checked in serde_codegen_internals"),
}
}
-fn deserialize_untagged_variant(
- type_ident: &syn::Ident,
- generics: &syn::Generics,
- ty: syn::Ty,
- variant: &Variant,
- item_attrs: &attr::Item,
- deserializer: Tokens,
-) -> Tokens {
+fn deserialize_untagged_variant(type_ident: &syn::Ident,
+ generics: &syn::Generics,
+ ty: syn::Ty,
+ variant: &Variant,
+ item_attrs: &attr::Item,
+ deserializer: Tokens)
+ -> Tokens {
let variant_ident = &variant.ident;
match variant.style {
@@ -874,45 +792,38 @@ fn deserialize_untagged_variant(
}
}
Style::Newtype => {
- deserialize_untagged_newtype_variant(
- type_ident,
- variant_ident,
- generics,
- &variant.fields[0],
- deserializer,
- )
+ deserialize_untagged_newtype_variant(type_ident,
+ variant_ident,
+ generics,
+ &variant.fields[0],
+ deserializer)
}
Style::Tuple => {
- deserialize_tuple(
- type_ident,
- Some(variant_ident),
- generics,
- ty,
- &variant.fields,
- item_attrs,
- Some(deserializer),
- )
+ deserialize_tuple(type_ident,
+ Some(variant_ident),
+ generics,
+ ty,
+ &variant.fields,
+ item_attrs,
+ Some(deserializer))
}
Style::Struct => {
- deserialize_struct(
- type_ident,
- Some(variant_ident),
- generics,
- ty,
- &variant.fields,
- item_attrs,
- Some(deserializer),
- )
+ deserialize_struct(type_ident,
+ Some(variant_ident),
+ generics,
+ ty,
+ &variant.fields,
+ item_attrs,
+ Some(deserializer))
}
}
}
-fn deserialize_externally_tagged_newtype_variant(
- type_ident: &syn::Ident,
- variant_ident: &syn::Ident,
- impl_generics: &syn::Generics,
- field: &Field,
-) -> Tokens {
+fn deserialize_externally_tagged_newtype_variant(type_ident: &syn::Ident,
+ variant_ident: &syn::Ident,
+ impl_generics: &syn::Generics,
+ field: &Field)
+ -> Tokens {
match field.attrs.deserialize_with() {
None => {
let field_ty = &field.ty;
@@ -923,8 +834,8 @@ fn deserialize_externally_tagged_newtype_variant(
}
}
Some(path) => {
- let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
- type_ident, impl_generics, field.ty, path);
+ let (wrapper, wrapper_impl, wrapper_ty) =
+ wrap_deserialize_with(type_ident, impl_generics, field.ty, path);
quote!({
#wrapper
#wrapper_impl
@@ -936,13 +847,12 @@ fn deserialize_externally_tagged_newtype_variant(
}
}
-fn deserialize_untagged_newtype_variant(
- type_ident: &syn::Ident,
- variant_ident: &syn::Ident,
- impl_generics: &syn::Generics,
- field: &Field,
- deserializer: Tokens,
-) -> Tokens {
+fn deserialize_untagged_newtype_variant(type_ident: &syn::Ident,
+ variant_ident: &syn::Ident,
+ impl_generics: &syn::Generics,
+ field: &Field,
+ deserializer: Tokens)
+ -> Tokens {
match field.attrs.deserialize_with() {
None => {
let field_ty = &field.ty;
@@ -953,8 +863,8 @@ fn deserialize_untagged_newtype_variant(
})
}
Some(path) => {
- let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
- type_ident, impl_generics, field.ty, path);
+ let (wrapper, wrapper_impl, wrapper_ty) =
+ wrap_deserialize_with(type_ident, impl_generics, field.ty, path);
quote!({
#wrapper
#wrapper_impl
@@ -966,11 +876,10 @@ fn deserialize_untagged_newtype_variant(
}
}
-fn deserialize_field_visitor(
- fields: Vec<(String, Ident)>,
- item_attrs: &attr::Item,
- is_variant: bool,
-) -> Tokens {
+fn deserialize_field_visitor(fields: Vec<(String, Ident)>,
+ item_attrs: &attr::Item,
+ is_variant: bool)
+ -> Tokens {
let field_strs = fields.iter().map(|&(ref name, _)| name);
let field_bytes = fields.iter().map(|&(ref name, _)| quote::ByteStr(name));
let field_idents: &Vec<_> = &fields.iter().map(|&(_, ref ident)| ident).collect();
@@ -1081,13 +990,12 @@ fn deserialize_field_visitor(
}
}
-fn deserialize_struct_visitor(
- type_ident: &syn::Ident,
- struct_path: Tokens,
- impl_generics: &syn::Generics,
- fields: &[Field],
- item_attrs: &attr::Item,
-) -> (Tokens, Tokens, Tokens) {
+fn deserialize_struct_visitor(type_ident: &syn::Ident,
+ struct_path: Tokens,
+ impl_generics: &syn::Generics,
+ fields: &[Field],
+ item_attrs: &attr::Item)
+ -> (Tokens, Tokens, Tokens) {
let field_names_idents: Vec<_> = fields.iter()
.enumerate()
.filter(|&(_, field)| !field.attrs.skip_deserializing())
@@ -1101,30 +1009,19 @@ fn deserialize_struct_visitor(
}
};
- let field_visitor = deserialize_field_visitor(
- field_names_idents,
- item_attrs,
- false,
- );
+ let field_visitor = deserialize_field_visitor(field_names_idents, item_attrs, false);
- let visit_map = deserialize_map(
- type_ident,
- struct_path,
- impl_generics,
- fields,
- item_attrs,
- );
+ let visit_map = deserialize_map(type_ident, struct_path, impl_generics, fields, item_attrs);
(field_visitor, fields_stmt, visit_map)
}
-fn deserialize_map(
- type_ident: &syn::Ident,
- struct_path: Tokens,
- impl_generics: &syn::Generics,
- fields: &[Field],
- item_attrs: &attr::Item,
-) -> Tokens {
+fn deserialize_map(type_ident: &syn::Ident,
+ struct_path: Tokens,
+ impl_generics: &syn::Generics,
+ fields: &[Field],
+ item_attrs: &attr::Item)
+ -> Tokens {
// Create the field names for the fields.
let fields_names: Vec<_> = fields.iter()
.enumerate()
@@ -1243,38 +1140,36 @@ fn field_i(i: usize) -> Ident {
/// This function wraps the expression in `#[serde(deserialize_with="...")]` in
/// a trait to prevent it from accessing the internal `Deserialize` state.
-fn wrap_deserialize_with(
- type_ident: &syn::Ident,
- impl_generics: &syn::Generics,
- field_ty: &syn::Ty,
- deserialize_with: &syn::Path,
-) -> (Tokens, Tokens, syn::Path) {
+fn wrap_deserialize_with(type_ident: &syn::Ident,
+ impl_generics: &syn::Generics,
+ field_ty: &syn::Ty,
+ deserialize_with: &syn::Path)
+ -> (Tokens, Tokens, syn::Path) {
// Quasi-quoting doesn't do a great job of expanding generics into paths,
// so manually build it.
let wrapper_ty = aster::path()
.segment("__SerdeDeserializeWithStruct")
- .with_generics(impl_generics.clone())
- .build()
+ .with_generics(impl_generics.clone())
+ .build()
.build();
let where_clause = &impl_generics.where_clause;
let phantom_ty = aster::path()
.segment(type_ident)
- .with_generics(aster::from_generics(impl_generics.clone())
- .strip_ty_params()
- .build())
- .build()
+ .with_generics(aster::from_generics(impl_generics.clone())
+ .strip_ty_params()
+ .build())
+ .build()
.build();
- (
- quote! {
+ (quote! {
struct __SerdeDeserializeWithStruct #impl_generics #where_clause {
value: #field_ty,
phantom: _serde::export::PhantomData<#phantom_ty>,
}
},
- quote! {
+ quote! {
impl #impl_generics _serde::Deserialize for #wrapper_ty #where_clause {
fn deserialize<__D>(__d: __D) -> _serde::export::Result<Self, __D::Error>
where __D: _serde::Deserializer
@@ -1287,8 +1182,7 @@ fn wrap_deserialize_with(
}
}
},
- wrapper_ty,
- )
+ wrapper_ty)
}
fn expr_is_missing(attrs: &attr::Field) -> Tokens {
@@ -1319,14 +1213,14 @@ fn expr_is_missing(attrs: &attr::Field) -> Tokens {
fn check_no_str(cx: &internals::Ctxt, item: &Item) {
let fail = || {
- cx.error(
- "Serde does not support deserializing fields of type &str; \
- consider using String instead");
+ cx.error("Serde does not support deserializing fields of type &str; consider using \
+ String instead");
};
for field in item.body.all_fields() {
- if field.attrs.skip_deserializing()
- || field.attrs.deserialize_with().is_some() { continue }
+ if field.attrs.skip_deserializing() || field.attrs.deserialize_with().is_some() {
+ continue;
+ }
if let syn::Ty::Rptr(_, ref inner) = *field.ty {
if let syn::Ty::Path(_, ref path) = inner.ty {
diff --git a/serde_derive/src/ser.rs b/serde_derive/src/ser.rs
index 52c86c7e7..62786f33b 100644
--- a/serde_derive/src/ser.rs
+++ b/serde_derive/src/ser.rs
@@ -12,13 +12,14 @@ pub fn expand_derive_serialize(item: &syn::DeriveInput) -> Result<Tokens, String
let impl_generics = build_impl_generics(&item);
- let ty = aster::ty().path()
- .segment(item.ident.clone()).with_generics(impl_generics.clone()).build()
+ let ty = aster::ty()
+ .path()
+ .segment(item.ident.clone())
+ .with_generics(impl_generics.clone())
+ .build()
.build();
- let body = serialize_body(&item,
- &impl_generics,
- ty.clone());
+ let body = serialize_body(&item, &impl_generics, ty.clone());
let where_clause = &impl_generics.where_clause;
@@ -45,18 +46,16 @@ pub fn expand_derive_serialize(item: &syn::DeriveInput) -> Result<Tokens, String
fn build_impl_generics(item: &Item) -> syn::Generics {
let generics = bound::without_defaults(item.generics);
- let generics = bound::with_where_predicates_from_fields(
- item, &generics,
- |attrs| attrs.ser_bound());
+ let generics =
+ bound::with_where_predicates_from_fields(item, &generics, |attrs| attrs.ser_bound());
match item.attrs.ser_bound() {
- Some(predicates) => {
- bound::with_where_predicates(&generics, predicates)
- }
+ Some(predicates) => bound::with_where_predicates(&generics, predicates),
None => {
- bound::with_bound(item, &generics,
- needs_serialize_bound,
- &aster::path().ids(&["_serde", "Serialize"]).build())
+ bound::with_bound(item,
+ &generics,
+ needs_serialize_bound,
+ &aster::path().ids(&["_serde", "Serialize"]).build())
}
}
}
@@ -66,58 +65,32 @@ fn build_impl_generics(item: &Item) -> syn::Generics {
// attribute specify their own bound so we do not generate one. All other fields
// may need a `T: Serialize` bound where T is the type of the field.
fn needs_serialize_bound(attrs: &attr::Field) -> bool {
- !attrs.skip_serializing()
- && attrs.serialize_with().is_none()
- && attrs.ser_bound().is_none()
+ !attrs.skip_serializing() && attrs.serialize_with().is_none() && attrs.ser_bound().is_none()
}
-fn serialize_body(
- item: &Item,
- impl_generics: &syn::Generics,
- ty: syn::Ty,
-) -> Tokens {
+fn serialize_body(item: &Item, impl_generics: &syn::Generics, ty: syn::Ty) -> Tokens {
match item.body {
Body::Enum(ref variants) => {
- serialize_item_enum(
- &item.ident,
- impl_generics,
- ty,
- variants,
- &item.attrs)
+ serialize_item_enum(&item.ident, impl_generics, ty, variants, &item.attrs)
}
Body::Struct(Style::Struct, ref fields) => {
if fields.iter().any(|field| field.ident.is_none()) {
panic!("struct has unnamed fields");
}
- serialize_struct(
- impl_generics,
- ty,
- fields,
- &item.attrs)
+ serialize_struct(impl_generics, ty, fields, &item.attrs)
}
Body::Struct(Style::Tuple, ref fields) => {
if fields.iter().any(|field| field.ident.is_some()) {
panic!("tuple struct has named fields");
}
- serialize_tuple_struct(
- impl_generics,
- ty,
- fields,
- &item.attrs)
+ serialize_tuple_struct(impl_generics, ty, fields, &item.attrs)
}
Body::Struct(Style::Newtype, ref fields) => {
- serialize_newtype_struct(
- impl_generics,
- ty,
- &fields[0],
- &item.attrs)
- }
- Body::Struct(Style::Unit, _) => {
- serialize_unit_struct(
- &item.attrs)
+ serialize_newtype_struct(impl_generics, ty, &fields[0], &item.attrs)
}
+ Body::Struct(Style::Unit, _) => serialize_unit_struct(&item.attrs),
}
}
@@ -129,18 +102,16 @@ fn serialize_unit_struct(item_attrs: &attr::Item) -> Tokens {
}
}
-fn serialize_newtype_struct(
- impl_generics: &syn::Generics,
- item_ty: syn::Ty,
- field: &Field,
- item_attrs: &attr::Item,
-) -> Tokens {
+fn serialize_newtype_struct(impl_generics: &syn::Generics,
+ item_ty: syn::Ty,
+ field: &Field,
+ item_attrs: &attr::Item)
+ -> Tokens {
let type_name = item_attrs.name().serialize_name();
let mut field_expr = quote!(&self.0);
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(
- &item_ty, impl_generics, field.ty, path, field_expr);
+ field_expr = wrap_serialize_with(&item_ty, impl_generics, field.ty, path, field_expr);
}
quote! {
@@ -148,19 +119,17 @@ fn serialize_newtype_struct(
}
}
-fn serialize_tuple_struct(
- impl_generics: &syn::Generics,
- ty: syn::Ty,
- fields: &[Field],
- item_attrs: &attr::Item,
-) -> Tokens {
- let serialize_stmts = serialize_tuple_struct_visitor(
- ty.clone(),
- fields,
- impl_generics,
- false,
- quote!(_serde::ser::SerializeTupleStruct::serialize_field),
- );
+fn serialize_tuple_struct(impl_generics: &syn::Generics,
+ ty: syn::Ty,
+ fields: &[Field],
+ item_attrs: &attr::Item)
+ -> Tokens {
+ let serialize_stmts =
+ serialize_tuple_struct_visitor(ty.clone(),
+ fields,
+ impl_generics,
+ false,
+ quote!(_serde::ser::SerializeTupleStruct::serialize_field));
let type_name = item_attrs.name().serialize_name();
let len = serialize_stmts.len();
@@ -173,19 +142,17 @@ fn serialize_tuple_struct(
}
}
-fn serialize_struct(
- impl_generics: &syn::Generics,
- ty: syn::Ty,
- fields: &[Field],
- item_attrs: &attr::Item,
-) -> Tokens {
- let serialize_fields = serialize_struct_visitor(
- ty.clone(),
- fields,
- impl_generics,
- false,
- quote!(_serde::ser::SerializeStruct::serialize_field),
- );
+fn serialize_struct(impl_generics: &syn::Generics,
+ ty: syn::Ty,
+ fields: &[Field],
+ item_attrs: &attr::Item)
+ -> Tokens {
+ let serialize_fields =
+ serialize_struct_visitor(ty.clone(),
+ fields,
+ impl_generics,
+ false,
+ quote!(_serde::ser::SerializeStruct::serialize_field));
let type_name = item_attrs.name().serialize_name();
@@ -195,8 +162,7 @@ fn serialize_struct(
let let_mut = mut_if(serialized_fields.peek().is_some());
- let len = serialized_fields
- .map(|field| {
+ let len = serialized_fields.map(|field| {
let ident = field.ident.clone().expect("struct has unnamed fields");
let field_expr = quote!(&self.#ident);
@@ -204,7 +170,7 @@ fn serialize_struct(
Some(path) => quote!(if #path(#field_expr) { 0 } else { 1 }),
None => quote!(1),
}
- })
+ })
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
quote! {
@@ -214,27 +180,23 @@ fn serialize_struct(
}
}
-fn serialize_item_enum(
- type_ident: &syn::Ident,
- impl_generics: &syn::Generics,
- ty: syn::Ty,
- variants: &[Variant],
- item_attrs: &attr::Item,
-) -> Tokens {
- let arms: Vec<_> =
- variants.iter()
- .enumerate()
- .map(|(variant_index, variant)| {
- serialize_variant(
- type_ident,
- impl_generics,
- ty.clone(),
- variant,
- variant_index,
- item_attrs,
- )
- })
- .collect();
+fn serialize_item_enum(type_ident: &syn::Ident,
+ impl_generics: &syn::Generics,
+ ty: syn::Ty,
+ variants: &[Variant],
+ item_attrs: &attr::Item)
+ -> Tokens {
+ let arms: Vec<_> = variants.iter()
+ .enumerate()
+ .map(|(variant_index, variant)| {
+ serialize_variant(type_ident,
+ impl_generics,
+ ty.clone(),
+ variant,
+ variant_index,
+ item_attrs)
+ })
+ .collect();
quote! {
match *self {
@@ -243,14 +205,13 @@ fn serialize_item_enum(
}
}
-fn serialize_variant(
- type_ident: &syn::Ident,
- generics: &syn::Generics,
- ty: syn::Ty,
- variant: &Variant,
- variant_index: usize,
- item_attrs: &attr::Item,
-) -> Tokens {
+fn serialize_variant(type_ident: &syn::Ident,
+ generics: &syn::Generics,
+ ty: syn::Ty,
+ variant: &Variant,
+ variant_index: usize,
+ item_attrs: &attr::Item)
+ -> Tokens {
let variant_ident = variant.ident.clone();
if variant.attrs.skip_serializing() {
@@ -267,7 +228,8 @@ fn serialize_variant(
quote! {
#type_ident::#variant_ident #fields_pat => #skipped_err,
}
- } else { // variant wasn't skipped
+ } else {
+ // variant wasn't skipped
let case = match variant.style {
Style::Unit => {
quote! {
@@ -280,14 +242,15 @@ fn serialize_variant(
}
}
Style::Tuple => {
- let field_names = (0 .. variant.fields.len())
+ let field_names = (0..variant.fields.len())
.map(|i| Ident::new(format!("__field{}", i)));
quote! {
#type_ident::#variant_ident(#(ref #field_names),*)
}
}
Style::Struct => {
- let fields = variant.fields.iter()
+ let fields = variant.fields
+ .iter()
.map(|f| f.ident.clone().expect("struct variant has unnamed fields"));
quote! {
#type_ident::#variant_ident { #(ref #fields),* }
@@ -297,33 +260,22 @@ fn serialize_variant(
let body = match *item_attrs.tag() {
attr::EnumTag::External => {
- serialize_externally_tagged_variant(
- generics,
- ty,
- variant,
- variant_index,
- item_attrs,
- )
+ serialize_externally_tagged_variant(generics,
+ ty,
+ variant,
+ variant_index,
+ item_attrs)
}
attr::EnumTag::Internal(ref tag) => {
- serialize_internally_tagged_variant(
- type_ident.as_ref(),
- variant_ident.as_ref(),
- generics,
- ty,
- variant,
- item_attrs,
- tag,
- )
- }
- attr::EnumTag::None => {
- serialize_untagged_variant(
- generics,
- ty,
- variant,
- item_attrs,
- )
- }
+ serialize_internally_tagged_variant(type_ident.as_ref(),
+ variant_ident.as_ref(),
+ generics,
+ ty,
+ variant,
+ item_attrs,
+ tag)
+ }
+ attr::EnumTag::None => serialize_untagged_variant(generics, ty, variant, item_attrs),
};
quote! {
@@ -332,13 +284,12 @@ fn serialize_variant(
}
}
-fn serialize_externally_tagged_variant(
- generics: &syn::Generics,
- ty: syn::Ty,
- variant: &Variant,
- variant_index: usize,
- item_attrs: &attr::Item,
-) -> Tokens {
+fn serialize_externally_tagged_variant(generics: &syn::Generics,
+ ty: syn::Ty,
+ variant: &Variant,
+ variant_index: usize,
+ item_attrs: &attr::Item)
+ -> Tokens {
let type_name = item_attrs.name().serialize_name();
let variant_name = variant.attrs.name().serialize_name();
@@ -357,8 +308,7 @@ fn serialize_externally_tagged_variant(
let field = &variant.fields[0];
let mut field_expr = quote!(__simple_value);
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(
- &ty, generics, field.ty, path, field_expr);
+ field_expr = wrap_serialize_with(&ty, generics, field.ty, path, field_expr);
}
quote! {
@@ -372,32 +322,28 @@ fn serialize_externally_tagged_variant(
}
}
Style::Tuple => {
- let block = serialize_tuple_variant(
- TupleVariant::ExternallyTagged {
- type_name: type_name,
- variant_index: variant_index,
- variant_name: variant_name,
- },
- generics,
- ty,
- &variant.fields,
- );
+ let block = serialize_tuple_variant(TupleVariant::ExternallyTagged {
+ type_name: type_name,
+ variant_index: variant_index,
+ variant_name: variant_name,
+ },
+ generics,
+ ty,
+ &variant.fields);
quote! {
{ #block }
}
}
Style::Struct => {
- let block = serialize_struct_variant(
- StructVariant::ExternallyTagged {
- variant_index: variant_index,
- variant_name: variant_name,
- },
- generics,
- ty,
- &variant.fields,
- item_attrs,
- );
+ let block = serialize_struct_variant(StructVariant::ExternallyTagged {
+ variant_index: variant_index,
+ variant_name: variant_name,
+ },
+ generics,
+ ty,
+ &variant.fields,
+ item_attrs);
quote! {
{ #block }
@@ -406,15 +352,14 @@ fn serialize_externally_tagged_variant(
}
}
-fn serialize_internally_tagged_variant(
- type_ident: &str,
- variant_ident: &str,
- generics: &syn::Generics,
- ty: syn::Ty,
- variant: &Variant,
- item_attrs: &attr::Item,
- tag: &str,
-) -> Tokens {
+fn serialize_internally_tagged_variant(type_ident: &str,
+ variant_ident: &str,
+ generics: &syn::Generics,
+ ty: syn::Ty,
+ variant: &Variant,
+ item_attrs: &attr::Item,
+ tag: &str)
+ -> Tokens {
let type_name = item_attrs.name().serialize_name();
let variant_name = variant.attrs.name().serialize_name();
@@ -432,8 +377,7 @@ fn serialize_internally_tagged_variant(
let field = &variant.fields[0];
let mut field_expr = quote!(__simple_value);
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(
- &ty, generics, field.ty, path, field_expr);
+ field_expr = wrap_serialize_with(&ty, generics, field.ty, path, field_expr);
}
quote! {
@@ -448,16 +392,14 @@ fn serialize_internally_tagged_variant(
}
}
Style::Struct => {
- let block = serialize_struct_variant(
- StructVariant::InternallyTagged {
- tag: tag,
- variant_name: variant_name,
- },
- generics,
- ty,
- &variant.fields,
- item_attrs,
- );
+ let block = serialize_struct_variant(StructVariant::InternallyTagged {
+ tag: tag,
+ variant_name: variant_name,
+ },
+ generics,
+ ty,
+ &variant.fields,
+ item_attrs);
quote! {
{ #block }
@@ -467,12 +409,11 @@ fn serialize_internally_tagged_variant(
}
}
-fn serialize_untagged_variant(
- generics: &syn::Generics,
- ty: syn::Ty,
- variant: &Variant,
- item_attrs: &attr::Item,
-) -> Tokens {
+fn serialize_untagged_variant(generics: &syn::Generics,
+ ty: syn::Ty,
+ variant: &Variant,
+ item_attrs: &attr::Item)
+ -> Tokens {
match variant.style {
Style::Unit => {
quote! {
@@ -483,8 +424,7 @@ fn serialize_untagged_variant(
let field = &variant.fields[0];
let mut field_expr = quote!(__simple_value);
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(
- &ty, generics, field.ty, path, field_expr);
+ field_expr = wrap_serialize_with(&ty, generics, field.ty, path, field_expr);
}
quote! {
@@ -492,25 +432,19 @@ fn serialize_untagged_variant(
}
}
Style::Tuple => {
- let block = serialize_tuple_variant(
- TupleVariant::Untagged,
- generics,
- ty,
- &variant.fields,
- );
+ let block =
+ serialize_tuple_variant(TupleVariant::Untagged, generics, ty, &variant.fields);
quote! {
{ #block }
}
}
Style::Struct => {
- let block = serialize_struct_variant(
- StructVariant::Untagged,
- generics,
- ty,
- &variant.fields,
- item_attrs,
- );
+ let block = serialize_struct_variant(StructVariant::Untagged,
+ generics,
+ ty,
+ &variant.fields,
+ item_attrs);
quote! {
{ #block }
@@ -528,28 +462,20 @@ enum TupleVariant {
Untagged,
}
-fn serialize_tuple_variant(
- context: TupleVariant,
- generics: &syn::Generics,
- structure_ty: syn::Ty,
- fields: &[Field],
-) -> Tokens {
+fn serialize_tuple_variant(context: TupleVariant,
+ generics: &syn::Generics,
+ structure_ty: syn::Ty,
+ fields: &[Field])
+ -> Tokens {
let method = match context {
- TupleVariant::ExternallyTagged{..} => {
+ TupleVariant::ExternallyTagged { .. } => {
quote!(_serde::ser::SerializeTupleVariant::serialize_field)
}
- TupleVariant::Untagged => {
- quote!(_serde::ser::SerializeTuple::serialize_element)
- }
+ TupleVariant::Untagged => quote!(_serde::ser::SerializeTuple::serialize_element),
};
- let serialize_stmts = serialize_tuple_struct_visitor(
- structure_ty,
- fields,
- generics,
- true,
- method,
- );
+ let serialize_stmts =
+ serialize_tuple_struct_visitor(structure_ty, fields, generics, true, method);
let len = serialize_stmts.len();
let let_mut = mut_if(len > 0);
@@ -584,36 +510,25 @@ enum StructVariant<'a> {
variant_index: usize,
variant_name: String,
},
- InternallyTagged {
- tag: &'a str,
- variant_name: String,
- },
+ InternallyTagged { tag: &'a str, variant_name: String },
Untagged,
}
-fn serialize_struct_variant<'a>(
- context: StructVariant<'a>,
- generics: &syn::Generics,
- ty: syn::Ty,
- fields: &[Field],
- item_attrs: &attr::Item,
-) -> Tokens {
+fn serialize_struct_variant<'a>(context: StructVariant<'a>,
+ generics: &syn::Generics,
+ ty: syn::Ty,
+ fields: &[Field],
+ item_attrs: &attr::Item)
+ -> Tokens {
let method = match context {
- StructVariant::ExternallyTagged{..} => {
+ StructVariant::ExternallyTagged { .. } => {
quote!(_serde::ser::SerializeStructVariant::serialize_field)
}
- StructVariant::InternallyTagged{..} | StructVariant::Untagged => {
- quote!(_serde::ser::SerializeStruct::serialize_field)
- }
+ StructVariant::InternallyTagged { .. } |
+ StructVariant::Untagged => quote!(_serde::ser::SerializeStruct::serialize_field),
};
- let serialize_fields = serialize_struct_visitor(
- ty.clone(),
- fields,
- generics,
- true,
- method,
- );
+ let serialize_fields = serialize_struct_visitor(ty.clone(), fields, generics, true, method);
let item_name = item_attrs.name().serialize_name();
@@ -623,15 +538,14 @@ fn serialize_struct_variant<'a>(
let let_mut = mut_if(serialized_fields.peek().is_some());
- let len = serialized_fields
- .map(|field| {
+ let len = serialized_fields.map(|field| {
let ident = field.ident.clone().expect("struct has unnamed fields");
match field.attrs.skip_serializing_if() {
Some(path) => quote!(if #path(#ident) { 0 } else { 1 }),
None => quote!(1),
}
- })
+ })
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
match context {
@@ -678,13 +592,12 @@ fn serialize_struct_variant<'a>(
}
}
-fn serialize_tuple_struct_visitor(
- structure_ty: syn::Ty,
- fields: &[Field],
- generics: &syn::Generics,
- is_enum: bool,
- func: Tokens,
-) -> Vec<Tokens> {
+fn serialize_tuple_struct_visitor(structure_ty: syn::Ty,
+ fields: &[Field],
+ generics: &syn::Generics,
+ is_enum: bool,
+ func: Tokens)
+ -> Vec<Tokens> {
fields.iter()
.enumerate()
.map(|(i, field)| {
@@ -696,12 +609,13 @@ fn serialize_tuple_struct_visitor(
quote!(&self.#i)
};
- let skip = field.attrs.skip_serializing_if()
+ let skip = field.attrs
+ .skip_serializing_if()
.map(|path| quote!(#path(#field_expr)));
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(
- &structure_ty, generics, field.ty, path, field_expr);
+ field_expr =
+ wrap_serialize_with(&structure_ty, generics, field.ty, path, field_expr);
}
let ser = quote! {
@@ -716,13 +630,12 @@ fn serialize_tuple_struct_visitor(
.collect()
}
-fn serialize_struct_visitor(
- structure_ty: syn::Ty,
- fields: &[Field],
- generics: &syn::Generics,
- is_enum: bool,
- func: Tokens,
-) -> Vec<Tokens> {
+fn serialize_struct_visitor(structure_ty: syn::Ty,
+ fields: &[Field],
+ generics: &syn::Generics,
+ is_enum: bool,
+ func: Tokens)
+ -> Vec<Tokens> {
fields.iter()
.filter(|&field| !field.attrs.skip_serializing())
.map(|field| {
@@ -735,12 +648,13 @@ fn serialize_struct_visitor(
let key_expr = field.attrs.name().serialize_name();
- let skip = field.attrs.skip_serializing_if()
+ let skip = field.attrs
+ .skip_serializing_if()
.map(|path| quote!(#path(#field_expr)));
if let Some(path) = field.attrs.serialize_with() {
- field_expr = wrap_serialize_with(
- &structure_ty, generics, field.ty, path, field_expr)
+ field_expr =
+ wrap_serialize_with(&structure_ty, generics, field.ty, path, field_expr)
}
let ser = quote! {
@@ -755,13 +669,12 @@ fn serialize_struct_visitor(
.collect()
}
-fn wrap_serialize_with(
- item_ty: &syn::Ty,
- generics: &syn::Generics,
- field_ty: &syn::Ty,
- path: &syn::Path,
- value: Tokens,
-) -> Tokens {
+fn wrap_serialize_with(item_ty: &syn::Ty,
+ generics: &syn::Generics,
+ field_ty: &syn::Ty,
+ path: &syn::Path,
+ value: Tokens)
+ -> Tokens {
let where_clause = &generics.where_clause;
let wrapper_generics = aster::from_generics(generics.clone())
@@ -771,8 +684,8 @@ fn wrap_serialize_with(
let wrapper_ty = aster::path()
.segment("__SerializeWith")
- .with_generics(wrapper_generics.clone())
- .build()
+ .with_generics(wrapper_generics.clone())
+ .build()
.build();
quote!({
@@ -803,9 +716,5 @@ fn wrap_serialize_with(
//
// where we want to omit the `mut` to avoid a warning.
fn mut_if(is_mut: bool) -> Option<Tokens> {
- if is_mut {
- Some(quote!(mut))
- } else {
- None
- }
+ if is_mut { Some(quote!(mut)) } else { None }
}
| serde-rs/serde | 2017-02-13T06:17:21Z | Overall I am very happy with the formatting in #439. There are a few bugs to iron out and maybe we need to develop new idioms around chained aster builders but I think rustfmt will be a net benefit.
| 739ad64c7cc79afc9acbe81f745671d9bfd0ff47 |
322 | diff --git a/serde_tests/benches/bench_enum.rs b/serde_tests/benches/bench_enum.rs
index e5deaad77..8badbb494 100644
--- a/serde_tests/benches/bench_enum.rs
+++ b/serde_tests/benches/bench_enum.rs
@@ -1,9 +1,9 @@
use test::Bencher;
use std::error;
use std::fmt;
-use rustc_serialize::{Decoder, Decodable};
+use rustc_serialize::Decodable;
use serde;
-use serde::de::{Deserializer, Deserialize};
+use serde::de::Deserialize;
//////////////////////////////////////////////////////////////////////////////
diff --git a/serde_tests/benches/bench_struct.rs b/serde_tests/benches/bench_struct.rs
index 402230d40..82b189e1e 100644
--- a/serde_tests/benches/bench_struct.rs
+++ b/serde_tests/benches/bench_struct.rs
@@ -3,10 +3,10 @@ use test::Bencher;
use std::fmt;
use std::error;
-use rustc_serialize::{Decoder, Decodable};
+use rustc_serialize::Decodable;
use serde;
-use serde::de::{Deserializer, Deserialize};
+use serde::de::Deserialize;
//////////////////////////////////////////////////////////////////////////////
diff --git a/serde_tests/tests/test_de.rs b/serde_tests/tests/test_de.rs
index 27794aeb7..932b4b10b 100644
--- a/serde_tests/tests/test_de.rs
+++ b/serde_tests/tests/test_de.rs
@@ -2,9 +2,6 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::net;
use std::path::PathBuf;
-extern crate serde;
-use self::serde::de::Deserializer;
-
use token::{
Error,
Token,
| [
"321"
] | serde-rs__serde-322 | Unused imports and needless borrows
I noticed these warnings in a Travis build:
```
/home/travis/build/serde-rs/serde/serde_codegen/src/de.rs:12:5: 12:35 warning: unused import, #[warn(unused_imports)] on by default
/home/travis/build/serde-rs/serde/serde_codegen/src/de.rs:12 use syntax::ext::build::AstBuilder;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/travis/build/serde-rs/serde/serde_codegen/src/de.rs:12:5: 12:35 note: in this expansion of include!
/home/travis/build/serde-rs/serde/serde/src/bytes.rs:35:20: 35:26 warning: this expression borrows a reference that is immediately dereferenced by the compiler, #[warn(needless_borrow)] on by default
/home/travis/build/serde-rs/serde/serde/src/bytes.rs:35 bytes: &bytes,
^~~~~~
/home/travis/build/serde-rs/serde/serde/src/bytes.rs:35:20: 35:26 help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#needless_borrow
/home/travis/build/serde-rs/serde/serde/src/bytes.rs:143:36: 143:41 warning: this expression borrows a reference that is immediately dereferenced by the compiler, #[warn(needless_borrow)] on by default
/home/travis/build/serde-rs/serde/serde/src/bytes.rs:143 serializer.serialize_bytes(&self)
^~~~~
/home/travis/build/serde-rs/serde/serde/src/bytes.rs:143:36: 143:41 help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#needless_borrow
tests/../../serde_tests/tests/test_de.rs:6:5: 6:34 warning: unused import, #[warn(unused_imports)] on by default
tests/../../serde_tests/tests/test_de.rs:6 use self::serde::de::Deserializer;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```
| 0.7 | 74eb2f52b8f6c8c865f49c222c3ea5d74ef8fb61 | diff --git a/serde/src/bytes.rs b/serde/src/bytes.rs
index f83ab8dd6..67f8ce85b 100644
--- a/serde/src/bytes.rs
+++ b/serde/src/bytes.rs
@@ -41,7 +41,7 @@ impl<'a> From<&'a [u8]> for Bytes<'a> {
impl<'a> From<&'a Vec<u8>> for Bytes<'a> {
fn from(bytes: &'a Vec<u8>) -> Self {
Bytes {
- bytes: &bytes,
+ bytes: bytes,
}
}
}
@@ -165,7 +165,7 @@ mod bytebuf {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: ser::Serializer
{
- serializer.serialize_bytes(&self)
+ serializer.serialize_bytes(self)
}
}
diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index df9c75e40..ed727aa23 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -118,7 +118,7 @@ impl Visitor for BoolVisitor {
fn visit_str<E>(&mut self, s: &str) -> Result<bool, E>
where E: Error,
{
- match s.trim_matches(|c| ::utils::Pattern_White_Space(c)) {
+ match s.trim_matches(::utils::Pattern_White_Space) {
"true" => Ok(true),
"false" => Ok(false),
_ => Err(Error::invalid_type(Type::Bool)),
diff --git a/serde_codegen/src/de.rs b/serde_codegen/src/de.rs
index 3de00dbe1..78cc0c85d 100644
--- a/serde_codegen/src/de.rs
+++ b/serde_codegen/src/de.rs
@@ -9,7 +9,6 @@ use syntax::ast::{
};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtxt};
-use syntax::ext::build::AstBuilder;
use syntax::parse::token::InternedString;
use syntax::ptr::P;
| serde-rs/serde | 2016-05-13T17:47:56Z | More:
```
benches/../../serde_tests/benches/bench_enum.rs:4:23: 4:30 warning: unused import, #[warn(unused_imports)] on by default
benches/../../serde_tests/benches/bench_enum.rs:4 use rustc_serialize::{Decoder, Decodable};
^~~~~~~
benches/../../serde_tests/benches/bench_enum.rs:4:23: 4:30 note: in this expansion of include!
benches/../../serde_tests/benches/bench_enum.rs:6:17: 6:29 warning: unused import, #[warn(unused_imports)] on by default
benches/../../serde_tests/benches/bench_enum.rs:6 use serde::de::{Deserializer, Deserialize};
^~~~~~~~~~~~
benches/../../serde_tests/benches/bench_enum.rs:6:17: 6:29 note: in this expansion of include!
benches/../../serde_tests/benches/bench_struct.rs:6:23: 6:30 warning: unused import, #[warn(unused_imports)] on by default
benches/../../serde_tests/benches/bench_struct.rs:6 use rustc_serialize::{Decoder, Decodable};
^~~~~~~
benches/../../serde_tests/benches/bench_struct.rs:6:23: 6:30 note: in this expansion of include!
benches/../../serde_tests/benches/bench_struct.rs:9:17: 9:29 warning: unused import, #[warn(unused_imports)] on by default
benches/../../serde_tests/benches/bench_struct.rs:9 use serde::de::{Deserializer, Deserialize};
^~~~~~~~~~~~
benches/../../serde_tests/benches/bench_struct.rs:9:17: 9:29 note: in this expansion of include!
```
| ed603d4580154bc09af94964c2aca8b42f268274 |
308 | diff --git a/serde_tests/tests/test.rs.in b/serde_tests/tests/test.rs.in
index 89a1b3456..f64b84c18 100644
--- a/serde_tests/tests/test.rs.in
+++ b/serde_tests/tests/test.rs.in
@@ -6,5 +6,6 @@ mod token;
mod test_annotations;
mod test_bytes;
mod test_de;
+mod test_gen;
mod test_macros;
mod test_ser;
diff --git a/serde_tests/tests/test_de.rs b/serde_tests/tests/test_de.rs
index 1859cee98..601710adb 100644
--- a/serde_tests/tests/test_de.rs
+++ b/serde_tests/tests/test_de.rs
@@ -3,7 +3,7 @@ use std::net;
use std::path::PathBuf;
extern crate serde;
-use self::serde::de::{Deserializer, Visitor};
+use self::serde::de::Deserializer;
use token::{
Error,
diff --git a/serde_tests/tests/test_gen.rs b/serde_tests/tests/test_gen.rs
new file mode 100644
index 000000000..805c100db
--- /dev/null
+++ b/serde_tests/tests/test_gen.rs
@@ -0,0 +1,56 @@
+// These just test that serde_codegen is able to produce code that compiles
+// successfully when there are a variety of generics involved.
+
+extern crate serde;
+use self::serde::ser::{Serialize, Serializer};
+use self::serde::de::{Deserialize, Deserializer};
+
+//////////////////////////////////////////////////////////////////////////
+
+#[derive(Serialize, Deserialize)]
+struct With<T> {
+ t: T,
+ #[serde(serialize_with="ser_i32", deserialize_with="de_i32")]
+ i: i32,
+}
+
+#[derive(Serialize, Deserialize)]
+struct WithRef<'a, T: 'a> {
+ #[serde(skip_deserializing)]
+ t: Option<&'a T>,
+ #[serde(serialize_with="ser_i32", deserialize_with="de_i32")]
+ i: i32,
+}
+
+#[derive(Serialize, Deserialize)]
+struct Bounds<T: Serialize + Deserialize> {
+ t: T,
+ option: Option<T>,
+ boxed: Box<T>,
+ option_boxed: Option<Box<T>>,
+}
+
+#[derive(Serialize, Deserialize)]
+struct NoBounds<T> {
+ t: T,
+ option: Option<T>,
+ boxed: Box<T>,
+ option_boxed: Option<Box<T>>,
+}
+
+#[derive(Serialize, Deserialize)]
+enum EnumWith<T> {
+ A(
+ #[serde(serialize_with="ser_i32", deserialize_with="de_i32")]
+ i32),
+ B {
+ t: T,
+ #[serde(serialize_with="ser_i32", deserialize_with="de_i32")]
+ i: i32 },
+}
+
+//////////////////////////////////////////////////////////////////////////
+
+fn ser_i32<S: Serializer>(_: &i32, _: &mut S) -> Result<(), S::Error> { panic!() }
+
+fn de_i32<D: Deserializer>(_: &mut D) -> Result<i32, D::Error> { panic!() }
| [
"307"
] | serde-rs__serde-308 | Deserialize_with generates code that does not compile
``` rust
#[derive(Deserialize)]
struct S<T> {
t: T,
#[serde(deserialize_with="dw")]
d: i32,
}
```
The implementation of `deserialize_with` turns this into a field deserializer:
``` rust
struct __SerdeDeserializeWithStruct<T> where T: Deserialize
value: i32,
}
```
... which does not compile because the type parameter `T` is unused. It incorrectly uses all of the generic type parameters without filtering for ones relevant to the specific field.
Filtering is hard so a quick fix would be:
``` rust
struct __SerdeDeserializeWithStruct<T> where T: Deserialize
value: i32,
phantom: PhantomData<S<T>>,
}
```
| 0.7 | 8378267b9bcba853a5cd837cd0450f29f8a36efd | diff --git a/serde_codegen/src/attr.rs b/serde_codegen/src/attr.rs
index 00ff5069c..c9ff9e809 100644
--- a/serde_codegen/src/attr.rs
+++ b/serde_codegen/src/attr.rs
@@ -180,7 +180,7 @@ pub struct FieldAttrs {
skip_serializing_field_if: Option<P<ast::Expr>>,
default_expr_if_missing: Option<P<ast::Expr>>,
serialize_with: Option<P<ast::Expr>>,
- deserialize_with: P<ast::Expr>,
+ deserialize_with: Option<ast::Path>,
}
impl FieldAttrs {
@@ -197,8 +197,6 @@ impl FieldAttrs {
None => { cx.span_bug(field.span, "struct field has no name?") }
};
- let identity = quote_expr!(cx, |x| x);
-
let mut field_attrs = FieldAttrs {
name: Name::new(field_ident),
skip_serializing_field: false,
@@ -206,7 +204,7 @@ impl FieldAttrs {
skip_serializing_field_if: None,
default_expr_if_missing: None,
serialize_with: None,
- deserialize_with: identity,
+ deserialize_with: None,
};
for meta_items in field.attrs.iter().filter_map(get_serde_meta_items) {
@@ -287,14 +285,8 @@ impl FieldAttrs {
// Parse `#[serde(deserialize_with="...")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"deserialize_with" => {
- let expr = wrap_deserialize_with(
- cx,
- &field.ty,
- generics,
- try!(parse_lit_into_path(cx, name, lit)),
- );
-
- field_attrs.deserialize_with = expr;
+ let path = try!(parse_lit_into_path(cx, name, lit));
+ field_attrs.deserialize_with = Some(path);
}
_ => {
@@ -348,8 +340,8 @@ impl FieldAttrs {
self.serialize_with.as_ref()
}
- pub fn deserialize_with(&self) -> &P<ast::Expr> {
- &self.deserialize_with
+ pub fn deserialize_with(&self) -> Option<&ast::Path> {
+ self.deserialize_with.as_ref()
}
}
@@ -612,36 +604,3 @@ fn wrap_serialize_with(cx: &ExtCtxt,
}
})
}
-
-/// This function wraps the expression in `#[serde(deserialize_with="...")]` in a trait to prevent
-/// it from accessing the internal `Deserialize` state.
-fn wrap_deserialize_with(cx: &ExtCtxt,
- field_ty: &P<ast::Ty>,
- generics: &ast::Generics,
- path: ast::Path) -> P<ast::Expr> {
- // Quasi-quoting doesn't do a great job of expanding generics into paths, so manually build it.
- let ty_path = AstBuilder::new().path()
- .segment("__SerdeDeserializeWithStruct")
- .with_generics(generics.clone())
- .build()
- .build();
-
- let where_clause = &generics.where_clause;
-
- quote_expr!(cx, ({
- struct __SerdeDeserializeWithStruct $generics $where_clause {
- value: $field_ty,
- }
-
- impl $generics _serde::de::Deserialize for $ty_path $where_clause {
- fn deserialize<D>(deserializer: &mut D) -> ::std::result::Result<Self, D::Error>
- where D: _serde::de::Deserializer
- {
- let value = try!($path(deserializer));
- Ok(__SerdeDeserializeWithStruct { value: value })
- }
- }
-
- |visit: $ty_path| visit.value
- }))
-}
diff --git a/serde_codegen/src/de.rs b/serde_codegen/src/de.rs
index 366fb6680..f98fe7658 100644
--- a/serde_codegen/src/de.rs
+++ b/serde_codegen/src/de.rs
@@ -509,12 +509,14 @@ fn deserialize_seq(
fn deserialize_struct_as_seq(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
+ type_ident: Ident,
struct_path: ast::Path,
+ impl_generics: &ast::Generics,
fields: &[(&ast::StructField, attr::FieldAttrs)],
) -> Result<P<ast::Expr>, Error> {
let let_values: Vec<_> = fields.iter()
.enumerate()
- .map(|(i, &(_, ref attrs))| {
+ .map(|(i, &(field, ref attrs))| {
let name = builder.id(format!("__field{}", i));
if attrs.skip_deserializing_field() {
let default = attrs.expr_is_missing();
@@ -522,10 +524,24 @@ fn deserialize_struct_as_seq(
let $name = $default;
).unwrap()
} else {
- let deserialize_with = attrs.deserialize_with();
+ let visit = match attrs.deserialize_with() {
+ None => {
+ let field_ty = &field.ty;
+ quote_expr!(cx, try!(visitor.visit::<$field_ty>()))
+ }
+ Some(path) => {
+ let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
+ cx, builder, type_ident, impl_generics, &field.ty, path);
+ quote_expr!(cx, {
+ $wrapper
+ $wrapper_impl
+ try!(visitor.visit::<$wrapper_ty>()).map(|wrap| wrap.value)
+ })
+ }
+ };
quote_stmt!(cx,
- let $name = match try!(visitor.visit()) {
- Some(value) => { $deserialize_with(value) },
+ let $name = match $visit {
+ Some(value) => { value },
None => {
return Err(_serde::de::Error::end_of_stream());
}
@@ -587,14 +603,18 @@ fn deserialize_struct(
let visit_seq_expr = try!(deserialize_struct_as_seq(
cx,
builder,
+ type_ident,
type_path.clone(),
+ impl_generics,
&fields_with_attrs,
));
let (field_visitor, fields_stmt, visit_map_expr) = try!(deserialize_struct_visitor(
cx,
builder,
+ type_ident,
type_path.clone(),
+ impl_generics,
&fields_with_attrs,
container_attrs,
));
@@ -843,14 +863,18 @@ fn deserialize_struct_variant(
let visit_seq_expr = try!(deserialize_struct_as_seq(
cx,
builder,
+ type_ident,
type_path.clone(),
+ generics,
&fields_with_attrs,
));
let (field_visitor, fields_stmt, field_expr) = try!(deserialize_struct_visitor(
cx,
builder,
+ type_ident,
type_path,
+ generics,
&fields_with_attrs,
container_attrs,
));
@@ -1011,10 +1035,8 @@ fn deserialize_field_visitor(
fn deserialize<D>(deserializer: &mut D) -> ::std::result::Result<__Field, D::Error>
where D: _serde::de::Deserializer,
{
- use std::marker::PhantomData;
-
struct __FieldVisitor<D> {
- phantom: PhantomData<D>
+ phantom: ::std::marker::PhantomData<D>
}
impl<__D> _serde::de::Visitor for __FieldVisitor<__D>
@@ -1041,7 +1063,11 @@ fn deserialize_field_visitor(
}
}
- deserializer.deserialize_struct_field(__FieldVisitor::<D>{ phantom: PhantomData })
+ deserializer.deserialize_struct_field(
+ __FieldVisitor::<D>{
+ phantom: ::std::marker::PhantomData
+ }
+ )
}
}
).unwrap();
@@ -1052,7 +1078,9 @@ fn deserialize_field_visitor(
fn deserialize_struct_visitor(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
+ type_ident: Ident,
struct_path: ast::Path,
+ impl_generics: &ast::Generics,
fields: &[(&ast::StructField, attr::FieldAttrs)],
container_attrs: &attr::ContainerAttrs,
) -> Result<(Vec<P<ast::Item>>, ast::Stmt, P<ast::Expr>), Error> {
@@ -1071,7 +1099,9 @@ fn deserialize_struct_visitor(
let visit_map_expr = try!(deserialize_map(
cx,
builder,
+ type_ident,
struct_path,
+ impl_generics,
fields,
container_attrs,
));
@@ -1100,7 +1130,9 @@ fn deserialize_struct_visitor(
fn deserialize_map(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
+ type_ident: Ident,
struct_path: ast::Path,
+ impl_generics: &ast::Generics,
fields: &[(&ast::StructField, attr::FieldAttrs)],
container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
@@ -1114,17 +1146,34 @@ fn deserialize_map(
// Declare each field that will be deserialized.
let let_values: Vec<ast::Stmt> = fields_attrs_names.iter()
.filter(|&&(_, ref attrs, _)| !attrs.skip_deserializing_field())
- .map(|&(_, _, name)| quote_stmt!(cx, let mut $name = None;).unwrap())
+ .map(|&(field, _, name)| {
+ let field_ty = &field.ty;
+ quote_stmt!(cx, let mut $name: Option<$field_ty> = None;).unwrap()
+ })
.collect();
// Match arms to extract a value for a field.
let value_arms = fields_attrs_names.iter()
.filter(|&&(_, ref attrs, _)| !attrs.skip_deserializing_field())
- .map(|&(_, ref attrs, name)| {
- let deserialize_with = attrs.deserialize_with();
+ .map(|&(field, ref attrs, name)| {
+ let visit = match attrs.deserialize_with() {
+ None => {
+ let field_ty = &field.ty;
+ quote_expr!(cx, try!(visitor.visit_value::<$field_ty>()))
+ }
+ Some(path) => {
+ let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
+ cx, builder, type_ident, impl_generics, &field.ty, path);
+ quote_expr!(cx, ({
+ $wrapper
+ $wrapper_impl
+ try!(visitor.visit_value::<$wrapper_ty>()).value
+ }))
+ }
+ };
quote_arm!(cx,
__Field::$name => {
- $name = Some($deserialize_with(try!(visitor.visit_value())));
+ $name = Some($visit);
}
)
})
@@ -1192,7 +1241,7 @@ fn deserialize_map(
Ok(quote_expr!(cx, {
$let_values
- while let Some(key) = try!(visitor.visit_key()) {
+ while let Some(key) = try!(visitor.visit_key::<__Field>()) {
match key {
$value_arms
$skipped_arms
@@ -1222,3 +1271,55 @@ fn fields_with_attrs<'a>(
})
.collect()
}
+
+/// This function wraps the expression in `#[serde(deserialize_with="...")]` in
+/// a trait to prevent it from accessing the internal `Deserialize` state.
+fn wrap_deserialize_with(
+ cx: &ExtCtxt,
+ builder: &aster::AstBuilder,
+ type_ident: Ident,
+ impl_generics: &ast::Generics,
+ field_ty: &P<ast::Ty>,
+ deserialize_with: &ast::Path,
+) -> (ast::Stmt, ast::Stmt, ast::Path) {
+ // Quasi-quoting doesn't do a great job of expanding generics into paths,
+ // so manually build it.
+ let wrapper_ty = builder.path()
+ .segment("__SerdeDeserializeWithStruct")
+ .with_generics(impl_generics.clone())
+ .build()
+ .build();
+
+ let where_clause = &impl_generics.where_clause;
+
+ let phantom_ty = builder.path()
+ .segment(type_ident)
+ .with_generics(builder.from_generics(impl_generics.clone())
+ .strip_ty_params()
+ .build())
+ .build()
+ .build();
+
+ (
+ quote_stmt!(cx,
+ struct __SerdeDeserializeWithStruct $impl_generics $where_clause {
+ value: $field_ty,
+ phantom: ::std::marker::PhantomData<$phantom_ty>,
+ }
+ ).unwrap(),
+ quote_stmt!(cx,
+ impl $impl_generics _serde::de::Deserialize for $wrapper_ty $where_clause {
+ fn deserialize<D>(__d: &mut D) -> ::std::result::Result<Self, D::Error>
+ where D: _serde::de::Deserializer
+ {
+ let value = try!($deserialize_with(__d));
+ Ok(__SerdeDeserializeWithStruct {
+ value: value,
+ phantom: ::std::marker::PhantomData,
+ })
+ }
+ }
+ ).unwrap(),
+ wrapper_ty,
+ )
+}
| serde-rs/serde | 2016-05-07T22:31:54Z | ed603d4580154bc09af94964c2aca8b42f268274 | |
249 | diff --git a/serde_tests/benches/bench_enum.rs b/serde_tests/benches/bench_enum.rs
index ecd3114ba..220f0de36 100644
--- a/serde_tests/benches/bench_enum.rs
+++ b/serde_tests/benches/bench_enum.rs
@@ -17,18 +17,18 @@ pub enum Animal {
#[derive(Debug)]
pub enum Error {
- EndOfStreamError,
- SyntaxError,
+ EndOfStream,
+ Syntax,
}
impl serde::de::Error for Error {
- fn syntax(_: &str) -> Error { Error::SyntaxError }
+ fn custom(_: String) -> Error { Error::Syntax }
- fn end_of_stream() -> Error { Error::EndOfStreamError }
+ fn end_of_stream() -> Error { Error::EndOfStream }
- fn unknown_field(_: &str) -> Error { Error::SyntaxError }
+ fn unknown_field(_: &str) -> Error { Error::Syntax }
- fn missing_field(_: &'static str) -> Error { Error::SyntaxError }
+ fn missing_field(_: &'static str) -> Error { Error::Syntax }
}
impl fmt::Display for Error {
@@ -54,12 +54,11 @@ mod decoder {
use super::{Animal, Error};
use super::Animal::{Dog, Frog};
- use self::State::{AnimalState, IsizeState, StringState};
enum State {
- AnimalState(Animal),
- IsizeState(isize),
- StringState(String),
+ Animal(Animal),
+ Isize(isize),
+ String(String),
}
pub struct AnimalDecoder {
@@ -71,7 +70,7 @@ mod decoder {
#[inline]
pub fn new(animal: Animal) -> AnimalDecoder {
AnimalDecoder {
- stack: vec!(AnimalState(animal)),
+ stack: vec!(State::Animal(animal)),
}
}
}
@@ -79,35 +78,35 @@ mod decoder {
impl Decoder for AnimalDecoder {
type Error = Error;
- fn error(&mut self, _: &str) -> Error { Error::SyntaxError }
+ fn error(&mut self, _: &str) -> Error { Error::Syntax }
// Primitive types:
- fn read_nil(&mut self) -> Result<(), Error> { Err(Error::SyntaxError) }
- fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::SyntaxError) }
- fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) }
- fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) }
- fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) }
- fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::SyntaxError) }
+ fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
+ fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::Syntax) }
+ fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
+ fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
+ fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
+ fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
#[inline]
fn read_isize(&mut self) -> Result<isize, Error> {
match self.stack.pop() {
- Some(IsizeState(x)) => Ok(x),
- _ => Err(Error::SyntaxError),
+ Some(State::Isize(x)) => Ok(x),
+ _ => Err(Error::Syntax),
}
}
- fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) }
- fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) }
- fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) }
- fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) }
- fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) }
- fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) }
- fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) }
- fn read_char(&mut self) -> Result<char, Error> { Err(Error::SyntaxError) }
+ fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
+ fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
+ fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
+ fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
+ fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
+ fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
+ fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
+ fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
#[inline]
fn read_str(&mut self) -> Result<String, Error> {
match self.stack.pop() {
- Some(StringState(x)) => Ok(x),
- _ => Err(Error::SyntaxError),
+ Some(State::String(x)) => Ok(x),
+ _ => Err(Error::Syntax),
}
}
@@ -117,15 +116,15 @@ mod decoder {
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
match self.stack.pop() {
- Some(AnimalState(animal)) => {
- self.stack.push(AnimalState(animal));
+ Some(State::Animal(animal)) => {
+ self.stack.push(State::Animal(animal));
if name == "Animal" {
f(self)
} else {
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
}
- _ => Err(Error::SyntaxError)
+ _ => Err(Error::Syntax)
}
}
@@ -134,18 +133,18 @@ mod decoder {
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
{
let name = match self.stack.pop() {
- Some(AnimalState(Dog)) => "Dog",
- Some(AnimalState(Frog(x0, x1))) => {
- self.stack.push(IsizeState(x1));
- self.stack.push(StringState(x0));
+ Some(State::Animal(Dog)) => "Dog",
+ Some(State::Animal(Frog(x0, x1))) => {
+ self.stack.push(State::Isize(x1));
+ self.stack.push(State::String(x0));
"Frog"
}
- _ => { return Err(Error::SyntaxError); }
+ _ => { return Err(Error::Syntax); }
};
let idx = match names.iter().position(|n| *n == name) {
Some(idx) => idx,
- None => { return Err(Error::SyntaxError); }
+ None => { return Err(Error::Syntax); }
};
f(self, idx)
@@ -161,56 +160,56 @@ mod decoder {
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
// Specialized types:
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder, bool) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
#[inline]
@@ -230,19 +229,19 @@ mod decoder {
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
}
}
@@ -256,10 +255,10 @@ mod deserializer {
#[derive(Debug)]
enum State {
- AnimalState(Animal),
- IsizeState(isize),
- StrState(&'static str),
- StringState(String),
+ Animal(Animal),
+ Isize(isize),
+ Str(&'static str),
+ String(String),
UnitState,
}
@@ -271,7 +270,7 @@ mod deserializer {
#[inline]
pub fn new(animal: Animal) -> AnimalDeserializer {
AnimalDeserializer {
- stack: vec!(State::AnimalState(animal)),
+ stack: vec!(State::Animal(animal)),
}
}
}
@@ -284,23 +283,23 @@ mod deserializer {
where V: de::Visitor,
{
match self.stack.pop() {
- Some(State::IsizeState(value)) => {
+ Some(State::Isize(value)) => {
visitor.visit_isize(value)
}
- Some(State::StringState(value)) => {
+ Some(State::String(value)) => {
visitor.visit_string(value)
}
- Some(State::StrState(value)) => {
+ Some(State::Str(value)) => {
visitor.visit_str(value)
}
Some(State::UnitState) => {
visitor.visit_unit()
}
Some(_) => {
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
None => {
- Err(Error::EndOfStreamError)
+ Err(Error::EndOfStream)
}
}
}
@@ -313,27 +312,27 @@ mod deserializer {
where V: de::EnumVisitor,
{
match self.stack.pop() {
- Some(State::AnimalState(Animal::Dog)) => {
+ Some(State::Animal(Animal::Dog)) => {
self.stack.push(State::UnitState);
- self.stack.push(State::StrState("Dog"));
+ self.stack.push(State::Str("Dog"));
visitor.visit(DogVisitor {
de: self,
})
}
- Some(State::AnimalState(Animal::Frog(x0, x1))) => {
- self.stack.push(State::IsizeState(x1));
- self.stack.push(State::StringState(x0));
- self.stack.push(State::StrState("Frog"));
+ Some(State::Animal(Animal::Frog(x0, x1))) => {
+ self.stack.push(State::Isize(x1));
+ self.stack.push(State::String(x0));
+ self.stack.push(State::Str("Frog"));
visitor.visit(FrogVisitor {
de: self,
state: 0,
})
}
Some(_) => {
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
None => {
- Err(Error::EndOfStreamError)
+ Err(Error::EndOfStream)
}
}
}
@@ -405,7 +404,7 @@ mod deserializer {
if self.state == 2 {
Ok(())
} else {
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
}
diff --git a/serde_tests/benches/bench_map.rs b/serde_tests/benches/bench_map.rs
index ce25f3f1a..beab38f8d 100644
--- a/serde_tests/benches/bench_map.rs
+++ b/serde_tests/benches/bench_map.rs
@@ -14,16 +14,16 @@ use serde::de::{Deserializer, Deserialize};
#[derive(PartialEq, Debug)]
pub enum Error {
EndOfStream,
- SyntaxError,
+ Syntax,
MissingField,
}
impl serde::de::Error for Error {
- fn syntax(_: &str) -> Error { Error::SyntaxError }
+ fn custom(_: String) -> Error { Error::Syntax }
fn end_of_stream() -> Error { Error::EndOfStream }
- fn unknown_field(_: &str) -> Error { Error::SyntaxError }
+ fn unknown_field(_: &str) -> Error { Error::Syntax }
fn missing_field(_: &'static str) -> Error {
Error::MissingField
@@ -53,11 +53,10 @@ mod decoder {
use rustc_serialize;
use super::Error;
- use self::Value::{StringValue, IsizeValue};
enum Value {
- StringValue(String),
- IsizeValue(isize),
+ String(String),
+ Isize(isize),
}
pub struct IsizeDecoder {
@@ -81,37 +80,37 @@ mod decoder {
type Error = Error;
fn error(&mut self, _msg: &str) -> Error {
- Error::SyntaxError
+ Error::Syntax
}
// Primitive types:
- fn read_nil(&mut self) -> Result<(), Error> { Err(Error::SyntaxError) }
- fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::SyntaxError) }
- fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) }
- fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) }
- fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) }
- fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::SyntaxError) }
+ fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
+ fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::Syntax) }
+ fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
+ fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
+ fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
+ fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
#[inline]
fn read_isize(&mut self) -> Result<isize, Error> {
match self.stack.pop() {
- Some(IsizeValue(x)) => Ok(x),
- Some(_) => Err(Error::SyntaxError),
+ Some(Value::Isize(x)) => Ok(x),
+ Some(_) => Err(Error::Syntax),
None => Err(Error::EndOfStream),
}
}
- fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) }
- fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) }
- fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) }
- fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) }
- fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) }
- fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) }
- fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) }
- fn read_char(&mut self) -> Result<char, Error> { Err(Error::SyntaxError) }
+ fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
+ fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
+ fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
+ fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
+ fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
+ fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
+ fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
+ fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
#[inline]
fn read_str(&mut self) -> Result<String, Error> {
match self.stack.pop() {
- Some(StringValue(x)) => Ok(x),
- Some(_) => Err(Error::SyntaxError),
+ Some(Value::String(x)) => Ok(x),
+ Some(_) => Err(Error::Syntax),
None => Err(Error::EndOfStream),
}
}
@@ -120,86 +119,86 @@ mod decoder {
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
// Specialized types:
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder, bool) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_seq<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_seq_elt<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
#[inline]
@@ -215,12 +214,12 @@ mod decoder {
{
match self.iter.next() {
Some((key, value)) => {
- self.stack.push(IsizeValue(value));
- self.stack.push(StringValue(key));
+ self.stack.push(Value::Isize(value));
+ self.stack.push(Value::String(key));
f(self)
}
None => {
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
}
}
@@ -247,8 +246,8 @@ mod deserializer {
#[derive(PartialEq, Debug)]
enum State {
StartState,
- KeyState(String),
- ValueState(isize),
+ Key(String),
+ Value(isize),
}
pub struct IsizeDeserializer {
@@ -276,10 +275,10 @@ mod deserializer {
Some(State::StartState) => {
visitor.visit_map(self)
}
- Some(State::KeyState(key)) => {
+ Some(State::Key(key)) => {
visitor.visit_string(key)
}
- Some(State::ValueState(value)) => {
+ Some(State::Value(value)) => {
visitor.visit_isize(value)
}
None => {
@@ -297,8 +296,8 @@ mod deserializer {
{
match self.iter.next() {
Some((key, value)) => {
- self.stack.push(State::ValueState(value));
- self.stack.push(State::KeyState(key));
+ self.stack.push(State::Value(value));
+ self.stack.push(State::Key(key));
Ok(Some(try!(de::Deserialize::deserialize(self))))
}
None => {
@@ -315,7 +314,7 @@ mod deserializer {
fn end(&mut self) -> Result<(), Error> {
match self.iter.next() {
- Some(_) => Err(Error::SyntaxError),
+ Some(_) => Err(Error::Syntax),
None => Ok(()),
}
}
@@ -332,14 +331,14 @@ mod deserializer {
#[inline]
fn next(&mut self) -> Option<Result<de::Token, Error>> {
match self.stack.pop() {
- Some(StartState) => {
+ Some(State::StartState) => {
self.stack.push(KeyOrEndState);
Some(Ok(de::Token::MapStart(self.len)))
}
- Some(KeyOrEndState) => {
+ Some(State::KeyOrEndState) => {
match self.iter.next() {
Some((key, value)) => {
- self.stack.push(ValueState(value));
+ self.stack.push(Value(value));
Some(Ok(de::Token::String(key)))
}
None => {
@@ -348,7 +347,7 @@ mod deserializer {
}
}
}
- Some(ValueState(x)) => {
+ Some(State::Value(x)) => {
self.stack.push(KeyOrEndState);
Some(Ok(de::Token::Isize(x)))
}
@@ -370,24 +369,24 @@ mod deserializer {
#[inline]
fn syntax(&mut self, _token: de::Token, _expected: &[de::TokenKind]) -> Error {
- SyntaxError
+ Syntax
}
#[inline]
fn unexpected_name(&mut self, _token: de::Token) -> Error {
- SyntaxError
+ Syntax
}
#[inline]
fn conversion_error(&mut self, _token: de::Token) -> Error {
- SyntaxError
+ Syntax
}
#[inline]
fn missing_field<
T: de::Deserialize<IsizeDeserializer, Error>
>(&mut self, _field: &'static str) -> Result<T, Error> {
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
}
*/
diff --git a/serde_tests/benches/bench_struct.rs b/serde_tests/benches/bench_struct.rs
index 03ae4310e..7ad311f7d 100644
--- a/serde_tests/benches/bench_struct.rs
+++ b/serde_tests/benches/bench_struct.rs
@@ -29,17 +29,17 @@ pub struct Outer {
#[derive(Debug, PartialEq)]
pub enum Error {
EndOfStream,
- SyntaxError,
+ Syntax,
MissingField,
OtherError,
}
impl serde::de::Error for Error {
- fn syntax(_: &str) -> Error { Error::SyntaxError }
+ fn custom(_: String) -> Error { Error::Syntax }
fn end_of_stream() -> Error { Error::EndOfStream }
- fn unknown_field(_: &str) -> Error { Error::SyntaxError }
+ fn unknown_field(_: &str) -> Error { Error::Syntax }
fn missing_field(_: &'static str) -> Error {
Error::MissingField
@@ -68,31 +68,18 @@ mod decoder {
use super::{Outer, Inner, Error};
- use self::State::{
- OuterState,
- InnerState,
- NullState,
- UsizeState,
- CharState,
- StringState,
- FieldState,
- VecState,
- MapState,
- OptionState,
- };
-
#[derive(Debug)]
enum State {
- OuterState(Outer),
- InnerState(Inner),
- NullState,
- UsizeState(usize),
- CharState(char),
- StringState(String),
- FieldState(&'static str),
- VecState(Vec<Inner>),
- MapState(HashMap<String, Option<char>>),
- OptionState(bool),
+ Outer(Outer),
+ Inner(Inner),
+ Null,
+ Usize(usize),
+ Char(char),
+ String(String),
+ Field(&'static str),
+ Vec(Vec<Inner>),
+ Map(HashMap<String, Option<char>>),
+ Option(bool),
}
pub struct OuterDecoder {
@@ -104,7 +91,7 @@ mod decoder {
#[inline]
pub fn new(animal: Outer) -> OuterDecoder {
OuterDecoder {
- stack: vec!(OuterState(animal)),
+ stack: vec!(State::Outer(animal)),
}
}
}
@@ -120,41 +107,41 @@ mod decoder {
#[inline]
fn read_nil(&mut self) -> Result<(), Error> {
match self.stack.pop() {
- Some(NullState) => Ok(()),
- _ => Err(Error::SyntaxError),
+ Some(State::Null) => Ok(()),
+ _ => Err(Error::Syntax),
}
}
#[inline]
fn read_usize(&mut self) -> Result<usize, Error> {
match self.stack.pop() {
- Some(UsizeState(value)) => Ok(value),
- _ => Err(Error::SyntaxError),
+ Some(State::Usize(value)) => Ok(value),
+ _ => Err(Error::Syntax),
}
}
- fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) }
- fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) }
- fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) }
- fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::SyntaxError) }
- fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::SyntaxError) }
- fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) }
- fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) }
- fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) }
- fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) }
- fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) }
- fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) }
- fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) }
+ fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
+ fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
+ fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
+ fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
+ fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::Syntax) }
+ fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
+ fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
+ fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
+ fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
+ fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
+ fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
+ fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
#[inline]
fn read_char(&mut self) -> Result<char, Error> {
match self.stack.pop() {
- Some(CharState(c)) => Ok(c),
- _ => Err(Error::SyntaxError),
+ Some(State::Char(c)) => Ok(c),
+ _ => Err(Error::Syntax),
}
}
#[inline]
fn read_str(&mut self) -> Result<String, Error> {
match self.stack.pop() {
- Some(StringState(value)) => Ok(value),
- _ => Err(Error::SyntaxError),
+ Some(State::String(value)) => Ok(value),
+ _ => Err(Error::Syntax),
}
}
@@ -162,31 +149,31 @@ mod decoder {
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
#[inline]
@@ -194,31 +181,31 @@ mod decoder {
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
match self.stack.pop() {
- Some(OuterState(Outer { inner })) => {
+ Some(State::Outer(Outer { inner })) => {
if s_name == "Outer" {
- self.stack.push(VecState(inner));
- self.stack.push(FieldState("inner"));
+ self.stack.push(State::Vec(inner));
+ self.stack.push(State::Field("inner"));
f(self)
} else {
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
}
- Some(InnerState(Inner { a: (), b, c })) => {
+ Some(State::Inner(Inner { a: (), b, c })) => {
if s_name == "Inner" {
- self.stack.push(MapState(c));
- self.stack.push(FieldState("c"));
+ self.stack.push(State::Map(c));
+ self.stack.push(State::Field("c"));
- self.stack.push(UsizeState(b));
- self.stack.push(FieldState("b"));
+ self.stack.push(State::Usize(b));
+ self.stack.push(State::Field("b"));
- self.stack.push(NullState);
- self.stack.push(FieldState("a"));
+ self.stack.push(State::Null);
+ self.stack.push(State::Field("a"));
f(self)
} else {
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
}
- _ => Err(Error::SyntaxError),
+ _ => Err(Error::Syntax),
}
}
#[inline]
@@ -226,39 +213,39 @@ mod decoder {
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
match self.stack.pop() {
- Some(FieldState(name)) => {
+ Some(State::Field(name)) => {
if f_name == name {
f(self)
} else {
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
}
- _ => Err(Error::SyntaxError)
+ _ => Err(Error::Syntax)
}
}
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
// Specialized types:
@@ -267,8 +254,8 @@ mod decoder {
F: FnOnce(&mut OuterDecoder, bool) -> Result<T, Error>,
{
match self.stack.pop() {
- Some(OptionState(b)) => f(self, b),
- _ => Err(Error::SyntaxError),
+ Some(State::Option(b)) => f(self, b),
+ _ => Err(Error::Syntax),
}
}
@@ -277,14 +264,14 @@ mod decoder {
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
{
match self.stack.pop() {
- Some(VecState(value)) => {
+ Some(State::Vec(value)) => {
let len = value.len();
for inner in value.into_iter().rev() {
- self.stack.push(InnerState(inner));
+ self.stack.push(State::Inner(inner));
}
f(self, len)
}
- _ => Err(Error::SyntaxError)
+ _ => Err(Error::Syntax)
}
}
#[inline]
@@ -299,23 +286,23 @@ mod decoder {
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
{
match self.stack.pop() {
- Some(MapState(map)) => {
+ Some(State::Map(map)) => {
let len = map.len();
for (key, value) in map {
match value {
Some(c) => {
- self.stack.push(CharState(c));
- self.stack.push(OptionState(true));
+ self.stack.push(State::Char(c));
+ self.stack.push(State::Option(true));
}
None => {
- self.stack.push(OptionState(false));
+ self.stack.push(State::Option(false));
}
}
- self.stack.push(StringState(key));
+ self.stack.push(State::String(key));
}
f(self, len)
}
- _ => Err(Error::SyntaxError),
+ _ => Err(Error::Syntax),
}
}
#[inline]
@@ -346,16 +333,16 @@ mod deserializer {
#[derive(Debug)]
enum State {
- OuterState(Outer),
- InnerState(Inner),
- StrState(&'static str),
- NullState,
- UsizeState(usize),
- CharState(char),
- StringState(String),
- OptionState(bool),
- VecState(Vec<Inner>),
- MapState(HashMap<String, Option<char>>),
+ Outer(Outer),
+ Inner(Inner),
+ Str(&'static str),
+ Null,
+ Usize(usize),
+ Char(char),
+ String(String),
+ Option(bool),
+ Vec(Vec<Inner>),
+ Map(HashMap<String, Option<char>>),
}
pub struct OuterDeserializer {
@@ -366,7 +353,7 @@ mod deserializer {
#[inline]
pub fn new(outer: Outer) -> OuterDeserializer {
OuterDeserializer {
- stack: vec!(State::OuterState(outer)),
+ stack: vec!(State::Outer(outer)),
}
}
}
@@ -378,40 +365,40 @@ mod deserializer {
where V: de::Visitor,
{
match self.stack.pop() {
- Some(State::VecState(value)) => {
+ Some(State::Vec(value)) => {
visitor.visit_seq(OuterSeqVisitor {
de: self,
iter: value.into_iter(),
})
}
- Some(State::MapState(value)) => {
+ Some(State::Map(value)) => {
visitor.visit_map(MapVisitor {
de: self,
iter: value.into_iter(),
})
}
- Some(State::NullState) => {
+ Some(State::Null) => {
visitor.visit_unit()
}
- Some(State::UsizeState(x)) => {
+ Some(State::Usize(x)) => {
visitor.visit_usize(x)
}
- Some(State::CharState(x)) => {
+ Some(State::Char(x)) => {
visitor.visit_char(x)
}
- Some(State::StrState(x)) => {
+ Some(State::Str(x)) => {
visitor.visit_str(x)
}
- Some(State::StringState(x)) => {
+ Some(State::String(x)) => {
visitor.visit_string(x)
}
- Some(State::OptionState(false)) => {
+ Some(State::Option(false)) => {
visitor.visit_none()
}
- Some(State::OptionState(true)) => {
+ Some(State::Option(true)) => {
visitor.visit_some(self)
}
- Some(_) => Err(Error::SyntaxError),
+ Some(_) => Err(Error::Syntax),
None => Err(Error::EndOfStream),
}
}
@@ -423,32 +410,32 @@ mod deserializer {
where V: de::Visitor,
{
match self.stack.pop() {
- Some(State::OuterState(Outer { inner })) => {
+ Some(State::Outer(Outer { inner })) => {
if name != "Outer" {
- return Err(Error::SyntaxError);
+ return Err(Error::Syntax);
}
- self.stack.push(State::VecState(inner));
- self.stack.push(State::StrState("inner"));
+ self.stack.push(State::Vec(inner));
+ self.stack.push(State::Str("inner"));
visitor.visit_map(OuterMapVisitor {
de: self,
state: 0,
})
}
- Some(State::InnerState(Inner { a: (), b, c })) => {
+ Some(State::Inner(Inner { a: (), b, c })) => {
if name != "Inner" {
- return Err(Error::SyntaxError);
+ return Err(Error::Syntax);
}
- self.stack.push(State::MapState(c));
- self.stack.push(State::StrState("c"));
+ self.stack.push(State::Map(c));
+ self.stack.push(State::Str("c"));
- self.stack.push(State::UsizeState(b));
- self.stack.push(State::StrState("b"));
+ self.stack.push(State::Usize(b));
+ self.stack.push(State::Str("b"));
- self.stack.push(State::NullState);
- self.stack.push(State::StrState("a"));
+ self.stack.push(State::Null);
+ self.stack.push(State::Str("a"));
visitor.visit_map(InnerMapVisitor {
de: self,
@@ -456,7 +443,7 @@ mod deserializer {
})
}
_ => {
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
}
}
@@ -494,7 +481,7 @@ mod deserializer {
if self.state == 1 {
Ok(())
} else {
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
}
@@ -517,7 +504,7 @@ mod deserializer {
{
match self.iter.next() {
Some(value) => {
- self.de.stack.push(State::InnerState(value));
+ self.de.stack.push(State::Inner(value));
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
}
None => {
@@ -528,7 +515,7 @@ mod deserializer {
fn end(&mut self) -> Result<(), Error> {
match self.iter.next() {
- Some(_) => Err(Error::SyntaxError),
+ Some(_) => Err(Error::Syntax),
None => Ok(()),
}
}
@@ -570,7 +557,7 @@ mod deserializer {
if self.state == 3 {
Ok(())
} else {
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
}
@@ -593,14 +580,14 @@ mod deserializer {
{
match self.iter.next() {
Some((key, Some(value))) => {
- self.de.stack.push(State::CharState(value));
- self.de.stack.push(State::OptionState(true));
- self.de.stack.push(State::StringState(key));
+ self.de.stack.push(State::Char(value));
+ self.de.stack.push(State::Option(true));
+ self.de.stack.push(State::String(key));
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
}
Some((key, None)) => {
- self.de.stack.push(State::OptionState(false));
- self.de.stack.push(State::StringState(key));
+ self.de.stack.push(State::Option(false));
+ self.de.stack.push(State::String(key));
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
}
None => {
@@ -617,7 +604,7 @@ mod deserializer {
fn end(&mut self) -> Result<(), Error> {
match self.iter.next() {
- Some(_) => Err(Error::SyntaxError),
+ Some(_) => Err(Error::Syntax),
None => Ok(()),
}
}
diff --git a/serde_tests/benches/bench_vec.rs b/serde_tests/benches/bench_vec.rs
index 3ce1cc320..01edcf09e 100644
--- a/serde_tests/benches/bench_vec.rs
+++ b/serde_tests/benches/bench_vec.rs
@@ -12,18 +12,18 @@ use serde::de::{Deserializer, Deserialize};
#[derive(PartialEq, Debug)]
pub enum Error {
- EndOfStreamError,
- SyntaxError,
+ EndOfStream,
+ Syntax,
}
impl serde::de::Error for Error {
- fn syntax(_: &str) -> Error { Error::SyntaxError }
+ fn custom(_: String) -> Error { Error::Syntax }
- fn end_of_stream() -> Error { Error::EndOfStreamError }
+ fn end_of_stream() -> Error { Error::EndOfStream }
- fn unknown_field(_: &str) -> Error { Error::SyntaxError }
+ fn unknown_field(_: &str) -> Error { Error::Syntax }
- fn missing_field(_: &'static str) -> Error { Error::SyntaxError }
+ fn missing_field(_: &'static str) -> Error { Error::Syntax }
}
impl fmt::Display for Error {
@@ -67,104 +67,104 @@ mod decoder {
impl rustc_serialize::Decoder for UsizeDecoder {
type Error = Error;
- fn error(&mut self, _: &str) -> Error { Error::SyntaxError }
+ fn error(&mut self, _: &str) -> Error { Error::Syntax }
// Primitive types:
- fn read_nil(&mut self) -> Result<(), Error> { Err(Error::SyntaxError) }
+ fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
#[inline]
fn read_usize(&mut self) -> Result<usize, Error> {
match self.iter.next() {
Some(value) => Ok(value),
- None => Err(Error::EndOfStreamError),
+ None => Err(Error::EndOfStream),
}
}
- fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) }
- fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) }
- fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) }
- fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::SyntaxError) }
- fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::SyntaxError) }
- fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) }
- fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) }
- fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) }
- fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) }
- fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) }
- fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) }
- fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) }
- fn read_char(&mut self) -> Result<char, Error> { Err(Error::SyntaxError) }
- fn read_str(&mut self) -> Result<String, Error> { Err(Error::SyntaxError) }
+ fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
+ fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
+ fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
+ fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
+ fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::Syntax) }
+ fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
+ fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
+ fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
+ fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
+ fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
+ fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
+ fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
+ fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
+ fn read_str(&mut self) -> Result<String, Error> { Err(Error::Syntax) }
// Compound types:
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
// Specialized types:
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder, bool) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
#[inline]
@@ -184,19 +184,19 @@ mod decoder {
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
}
@@ -219,105 +219,105 @@ mod decoder {
impl rustc_serialize::Decoder for U8Decoder {
type Error = Error;
- fn error(&mut self, _: &str) -> Error { Error::SyntaxError }
+ fn error(&mut self, _: &str) -> Error { Error::Syntax }
// Primitive types:
- fn read_nil(&mut self) -> Result<(), Error> { Err(Error::SyntaxError) }
- fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::SyntaxError) }
- fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::SyntaxError) }
- fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::SyntaxError) }
- fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::SyntaxError) }
+ fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
+ fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::Syntax) }
+ fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
+ fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
+ fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
#[inline]
fn read_u8(&mut self) -> Result<u8, Error> {
match self.iter.next() {
Some(value) => Ok(value),
- None => Err(Error::EndOfStreamError),
+ None => Err(Error::EndOfStream),
}
}
#[inline]
- fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::SyntaxError) }
- fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::SyntaxError) }
- fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::SyntaxError) }
- fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::SyntaxError) }
- fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::SyntaxError) }
- fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::SyntaxError) }
- fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::SyntaxError) }
- fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::SyntaxError) }
- fn read_char(&mut self) -> Result<char, Error> { Err(Error::SyntaxError) }
- fn read_str(&mut self) -> Result<String, Error> { Err(Error::SyntaxError) }
+ fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::Syntax) }
+ fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
+ fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
+ fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
+ fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
+ fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
+ fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
+ fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
+ fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
+ fn read_str(&mut self) -> Result<String, Error> { Err(Error::Syntax) }
// Compound types:
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
// Specialized types:
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder, bool) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
#[inline]
@@ -337,19 +337,19 @@ mod decoder {
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
- Err(Error::SyntaxError)
+ Err(Error::Syntax)
}
}
}
@@ -366,9 +366,9 @@ mod deserializer {
#[derive(PartialEq, Debug)]
enum State {
- StartState,
- SepOrEndState,
- EndState,
+ Start,
+ SepOrEnd,
+ End,
}
pub struct Deserializer<A> {
@@ -383,7 +383,7 @@ mod deserializer {
pub fn new(values: Vec<A>) -> Deserializer<A> {
let len = values.len();
Deserializer {
- state: State::StartState,
+ state: State::Start,
iter: values.into_iter(),
len: len,
value: None,
@@ -399,15 +399,15 @@ mod deserializer {
where V: de::Visitor,
{
match self.state {
- State::StartState => {
- self.state = State::SepOrEndState;
+ State::Start => {
+ self.state = State::SepOrEnd;
visitor.visit_seq(self)
}
- State::SepOrEndState => {
+ State::SepOrEnd => {
visitor.visit_usize(self.value.take().unwrap())
}
- State::EndState => {
- Err(Error::EndOfStreamError)
+ State::End => {
+ Err(Error::EndOfStream)
}
}
}
@@ -427,7 +427,7 @@ mod deserializer {
Ok(Some(try!(de::Deserialize::deserialize(self))))
}
None => {
- self.state = State::EndState;
+ self.state = State::End;
Ok(None)
}
}
@@ -436,9 +436,9 @@ mod deserializer {
#[inline]
fn end(&mut self) -> Result<(), Error> {
match self.iter.next() {
- Some(_) => Err(Error::SyntaxError),
+ Some(_) => Err(Error::Syntax),
None => {
- self.state = State::EndState;
+ self.state = State::End;
Ok(())
}
}
@@ -458,15 +458,15 @@ mod deserializer {
where V: de::Visitor,
{
match self.state {
- State::StartState => {
- self.state = State::SepOrEndState;
+ State::Start => {
+ self.state = State::SepOrEnd;
visitor.visit_seq(self)
}
- State::SepOrEndState => {
+ State::SepOrEnd => {
visitor.visit_u8(self.value.take().unwrap())
}
- State::EndState => {
- Err(Error::EndOfStreamError)
+ State::End => {
+ Err(Error::EndOfStream)
}
}
}
@@ -486,7 +486,7 @@ mod deserializer {
Ok(Some(try!(de::Deserialize::deserialize(self))))
}
None => {
- self.state = State::EndState;
+ self.state = State::End;
Ok(None)
}
}
@@ -495,9 +495,9 @@ mod deserializer {
#[inline]
fn end(&mut self) -> Result<(), Error> {
match self.iter.next() {
- Some(_) => Err(Error::SyntaxError),
+ Some(_) => Err(Error::Syntax),
None => {
- self.state = State::EndState;
+ self.state = State::End;
Ok(())
}
}
diff --git a/serde_tests/tests/test_bytes.rs b/serde_tests/tests/test_bytes.rs
index 785ff5503..93fe97057 100644
--- a/serde_tests/tests/test_bytes.rs
+++ b/serde_tests/tests/test_bytes.rs
@@ -10,19 +10,13 @@ use serde::bytes::{ByteBuf, Bytes};
struct Error;
impl serde::ser::Error for Error {
- fn syntax(_: &str) -> Error { Error }
-
- fn invalid_value(_field: &str) -> Error { Error }
+ fn custom(_: String) -> Error { Error }
}
impl serde::de::Error for Error {
- fn syntax(_: &str) -> Error { Error }
+ fn custom(_: String) -> Error { Error }
fn end_of_stream() -> Error { Error }
-
- fn unknown_field(_field: &str) -> Error { Error }
-
- fn missing_field(_field: &'static str) -> Error { Error }
}
impl fmt::Display for Error {
diff --git a/serde_tests/tests/token.rs b/serde_tests/tests/token.rs
index 11c0dc8ea..16be21b14 100644
--- a/serde_tests/tests/token.rs
+++ b/serde_tests/tests/token.rs
@@ -416,7 +416,7 @@ pub enum Error {
}
impl ser::Error for Error {
- fn syntax(_: &str) -> Error { Error::SyntaxError }
+ fn custom(_: String) -> Error { Error::SyntaxError }
fn invalid_value(msg: &str) -> Error {
Error::InvalidValue(msg.to_owned())
@@ -424,7 +424,7 @@ impl ser::Error for Error {
}
impl de::Error for Error {
- fn syntax(_: &str) -> Error { Error::SyntaxError }
+ fn custom(_: String) -> Error { Error::SyntaxError }
fn end_of_stream() -> Error { Error::EndOfStreamError }
| [
"247"
] | serde-rs__serde-249 | fix(error): Report `UnknownVariant`
Don't unify it with syntax errors.
| 0.7 | 96483ee54f5078c7a632dc43332911a1df9241ad | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 7bb024915..c30400da0 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -88,7 +88,7 @@ impl Visitor for BoolVisitor {
match s.trim() {
"true" => Ok(true),
"false" => Ok(false),
- _ => Err(Error::type_mismatch(Type::Bool)),
+ _ => Err(Error::invalid_type(Type::Bool)),
}
}
}
@@ -111,30 +111,30 @@ macro_rules! impl_deserialize_num_method {
{
match FromPrimitive::$from_method(v) {
Some(v) => Ok(v),
- None => Err(Error::type_mismatch($ty)),
+ None => Err(Error::invalid_type($ty)),
}
}
}
}
/// A visitor that produces a primitive type.
-pub struct PrimitiveVisitor<T> {
+struct PrimitiveVisitor<T> {
marker: PhantomData<T>,
}
impl<T> PrimitiveVisitor<T> {
/// Construct a new `PrimitiveVisitor`.
#[inline]
- pub fn new() -> Self {
+ fn new() -> Self {
PrimitiveVisitor {
marker: PhantomData,
}
}
}
-impl<
- T: Deserialize + FromPrimitive + str::FromStr
-> Visitor for PrimitiveVisitor<T> {
+impl<T> Visitor for PrimitiveVisitor<T>
+ where T: Deserialize + FromPrimitive + str::FromStr
+{
type Value = T;
impl_deserialize_num_method!(isize, visit_isize, from_isize, Type::Isize);
@@ -155,7 +155,7 @@ impl<
where E: Error,
{
str::FromStr::from_str(v.trim()).or_else(|_| {
- Err(Error::type_mismatch(Type::Str))
+ Err(Error::invalid_type(Type::Str))
})
}
}
@@ -207,7 +207,7 @@ impl Visitor for CharVisitor {
let mut iter = v.chars();
if let Some(v) = iter.next() {
if iter.next().is_some() {
- Err(Error::type_mismatch(Type::Char))
+ Err(Error::invalid_type(Type::Char))
} else {
Ok(v)
}
@@ -250,7 +250,7 @@ impl Visitor for StringVisitor {
{
match str::from_utf8(v) {
Ok(s) => Ok(s.to_owned()),
- Err(_) => Err(Error::type_mismatch(Type::String)),
+ Err(_) => Err(Error::invalid_type(Type::String)),
}
}
@@ -259,7 +259,7 @@ impl Visitor for StringVisitor {
{
match String::from_utf8(v) {
Ok(s) => Ok(s),
- Err(_) => Err(Error::type_mismatch(Type::String)),
+ Err(_) => Err(Error::invalid_type(Type::String)),
}
}
}
@@ -889,7 +889,7 @@ impl<T> Deserialize for NonZero<T> where T: Deserialize + PartialEq + Zeroable +
fn deserialize<D>(deserializer: &mut D) -> Result<NonZero<T>, D::Error> where D: Deserializer {
let value = try!(Deserialize::deserialize(deserializer));
if value == Zero::zero() {
- return Err(Error::syntax("expected a non-zero value"))
+ return Err(Error::invalid_value("expected a non-zero value"))
}
unsafe {
Ok(NonZero::new(value))
@@ -941,7 +941,7 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
_ => {
match str::from_utf8(value) {
Ok(value) => Err(Error::unknown_field(value)),
- Err(_) => Err(Error::type_mismatch(Type::String)),
+ Err(_) => Err(Error::invalid_type(Type::String)),
}
}
}
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index d45930e4e..ef7baedca 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -12,44 +12,44 @@ mod from_primitive;
/// `Deserializer` error.
pub trait Error: Sized + error::Error {
/// Raised when there is general error when deserializing a type.
- fn syntax(msg: &str) -> Self;
+ fn custom(msg: String) -> Self;
- /// Raised when a fixed sized sequence or map was passed in the wrong amount of arguments.
- fn length_mismatch(_len: usize) -> Self {
- Error::syntax("incorrect length")
- }
+ /// Raised when a `Deserialize` type unexpectedly hit the end of the stream.
+ fn end_of_stream() -> Self;
/// Raised when a `Deserialize` was passed an incorrect type.
- fn type_mismatch(_type: Type) -> Self {
- Error::syntax("incorrect type")
+ fn invalid_type(ty: Type) -> Self {
+ Error::custom(format!("Invalid type. Expected `{:?}`", ty))
}
/// Raised when a `Deserialize` was passed an incorrect value.
fn invalid_value(msg: &str) -> Self {
- Error::syntax(msg)
+ Error::custom(format!("Invalid value: {}", msg))
}
- /// Raised when a `Deserialize` type unexpectedly hit the end of the stream.
- fn end_of_stream() -> Self;
-
- /// Raised when a `Deserialize` struct type received an unexpected struct field.
- fn unknown_field(field: &str) -> Self {
- Error::syntax(&format!("Unknown field `{}`", field))
+ /// Raised when a fixed sized sequence or map was passed in the wrong amount of arguments.
+ fn invalid_length(len: usize) -> Self {
+ Error::custom(format!("Invalid length: {}", len))
}
/// Raised when a `Deserialize` enum type received an unexpected variant.
fn unknown_variant(field: &str) -> Self {
- Error::syntax(&format!("Unknown variant `{}`", field))
+ Error::custom(format!("Unknown variant `{}`", field))
+ }
+
+ /// Raised when a `Deserialize` struct type received an unexpected struct field.
+ fn unknown_field(field: &str) -> Self {
+ Error::custom(format!("Unknown field `{}`", field))
}
/// raised when a `deserialize` struct type did not receive a field.
fn missing_field(field: &'static str) -> Self {
- Error::syntax(&format!("Missing field `{}`", field))
+ Error::custom(format!("Missing field `{}`", field))
}
}
/// `Type` represents all the primitive types that can be deserialized. This is used by
-/// `Error::kind_mismatch`.
+/// `Error::invalid_type`.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Type {
/// Represents a `bool` type.
@@ -124,12 +124,18 @@ pub enum Type {
/// Represents a struct type.
Struct,
+ /// Represents a struct field name.
+ FieldName,
+
/// Represents a tuple type.
Tuple,
/// Represents an `enum` type.
Enum,
+ /// Represents an enum variant name.
+ VariantName,
+
/// Represents a struct variant.
StructVariant,
@@ -416,7 +422,7 @@ pub trait Deserializer {
_visitor: V) -> Result<V::Value, Self::Error>
where V: EnumVisitor,
{
- Err(Error::syntax("expected an enum"))
+ Err(Error::invalid_type(Type::Enum))
}
/// This method hints that the `Deserialize` type is expecting a `Vec<u8>`. This allows
@@ -460,7 +466,7 @@ pub trait Visitor {
fn visit_bool<E>(&mut self, _v: bool) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::type_mismatch(Type::Bool))
+ Err(Error::invalid_type(Type::Bool))
}
/// `visit_isize` deserializes a `isize` into a `Value`.
@@ -495,7 +501,7 @@ pub trait Visitor {
fn visit_i64<E>(&mut self, _v: i64) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::type_mismatch(Type::I64))
+ Err(Error::invalid_type(Type::I64))
}
/// `visit_usize` deserializes a `usize` into a `Value`.
@@ -530,7 +536,7 @@ pub trait Visitor {
fn visit_u64<E>(&mut self, _v: u64) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::type_mismatch(Type::U64))
+ Err(Error::invalid_type(Type::U64))
}
/// `visit_f32` deserializes a `f32` into a `Value`.
@@ -544,7 +550,7 @@ pub trait Visitor {
fn visit_f64<E>(&mut self, _v: f64) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::type_mismatch(Type::F64))
+ Err(Error::invalid_type(Type::F64))
}
/// `visit_char` deserializes a `char` into a `Value`.
@@ -561,7 +567,7 @@ pub trait Visitor {
fn visit_str<E>(&mut self, _v: &str) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::type_mismatch(Type::Str))
+ Err(Error::invalid_type(Type::Str))
}
/// `visit_string` deserializes a `String` into a `Value`. This allows a deserializer to avoid
@@ -578,7 +584,7 @@ pub trait Visitor {
fn visit_unit<E>(&mut self) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::type_mismatch(Type::Unit))
+ Err(Error::invalid_type(Type::Unit))
}
/// `visit_unit_struct` deserializes a unit struct into a `Value`.
@@ -593,42 +599,42 @@ pub trait Visitor {
fn visit_none<E>(&mut self) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::type_mismatch(Type::Option))
+ Err(Error::invalid_type(Type::Option))
}
/// `visit_some` deserializes a value into a `Value`.
fn visit_some<D>(&mut self, _deserializer: &mut D) -> Result<Self::Value, D::Error>
where D: Deserializer,
{
- Err(Error::type_mismatch(Type::Option))
+ Err(Error::invalid_type(Type::Option))
}
/// `visit_newtype_struct` deserializes a value into a `Value`.
fn visit_newtype_struct<D>(&mut self, _deserializer: &mut D) -> Result<Self::Value, D::Error>
where D: Deserializer,
{
- Err(Error::type_mismatch(Type::NewtypeStruct))
+ Err(Error::invalid_type(Type::NewtypeStruct))
}
/// `visit_bool` deserializes a `SeqVisitor` into a `Value`.
fn visit_seq<V>(&mut self, _visitor: V) -> Result<Self::Value, V::Error>
where V: SeqVisitor,
{
- Err(Error::type_mismatch(Type::Seq))
+ Err(Error::invalid_type(Type::Seq))
}
/// `visit_map` deserializes a `MapVisitor` into a `Value`.
fn visit_map<V>(&mut self, _visitor: V) -> Result<Self::Value, V::Error>
where V: MapVisitor,
{
- Err(Error::type_mismatch(Type::Map))
+ Err(Error::invalid_type(Type::Map))
}
/// `visit_bytes` deserializes a `&[u8]` into a `Value`.
fn visit_bytes<E>(&mut self, _v: &[u8]) -> Result<Self::Value, E>
where E: Error,
{
- Err(Error::type_mismatch(Type::Bytes))
+ Err(Error::invalid_type(Type::Bytes))
}
/// `visit_byte_buf` deserializes a `Vec<u8>` into a `Value`.
@@ -799,7 +805,7 @@ pub trait VariantVisitor {
/// `visit_unit` is called when deserializing a variant with no values.
fn visit_unit(&mut self) -> Result<(), Self::Error> {
- Err(Error::type_mismatch(Type::UnitVariant))
+ Err(Error::invalid_type(Type::UnitVariant))
}
/// `visit_newtype` is called when deserializing a variant with a single value. By default this
@@ -818,7 +824,7 @@ pub trait VariantVisitor {
_visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor
{
- Err(Error::type_mismatch(Type::TupleVariant))
+ Err(Error::invalid_type(Type::TupleVariant))
}
/// `visit_struct` is called when deserializing a struct-like variant.
@@ -827,7 +833,7 @@ pub trait VariantVisitor {
_visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor
{
- Err(Error::type_mismatch(Type::StructVariant))
+ Err(Error::invalid_type(Type::StructVariant))
}
}
diff --git a/serde/src/de/value.rs b/serde/src/de/value.rs
index 3f40f39e5..773c19df3 100644
--- a/serde/src/de/value.rs
+++ b/serde/src/de/value.rs
@@ -24,18 +24,24 @@ use bytes;
/// This represents all the possible errors that can occur using the `ValueDeserializer`.
#[derive(Clone, Debug, PartialEq)]
pub enum Error {
- /// The value had some syntatic error.
- Syntax(String),
+ /// The value had some custom error.
+ Custom(String),
/// The value had an incorrect type.
- Type(de::Type),
+ InvalidType(de::Type),
/// The value had an invalid length.
- Length(usize),
+ InvalidLength(usize),
+
+ /// The value is invalid and cannot be deserialized.
+ InvalidValue(String),
/// EOF while deserializing a value.
EndOfStream,
+ /// Unknown variant in enum.
+ UnknownVariant(String),
+
/// Unknown field in struct.
UnknownField(String),
@@ -44,10 +50,12 @@ pub enum Error {
}
impl de::Error for Error {
- fn syntax(msg: &str) -> Self { Error::Syntax(String::from(msg)) }
- fn type_mismatch(type_: de::Type) -> Self { Error::Type(type_) }
- fn length_mismatch(len: usize) -> Self { Error::Length(len) }
+ fn custom(msg: String) -> Self { Error::Custom(msg) }
fn end_of_stream() -> Self { Error::EndOfStream }
+ fn invalid_type(ty: de::Type) -> Self { Error::InvalidType(ty) }
+ fn invalid_value(msg: &str) -> Self { Error::InvalidValue(msg.to_owned()) }
+ fn invalid_length(len: usize) -> Self { Error::InvalidLength(len) }
+ fn unknown_variant(variant: &str) -> Self { Error::UnknownVariant(String::from(variant)) }
fn unknown_field(field: &str) -> Self { Error::UnknownField(String::from(field)) }
fn missing_field(field: &'static str) -> Self { Error::MissingField(field) }
}
@@ -55,10 +63,14 @@ impl de::Error for Error {
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
- Error::Syntax(ref s) => write!(formatter, "Syntax error: {}", s),
- Error::Type(ty) => write!(formatter, "Invalid type: {:?}", ty),
- Error::Length(len) => write!(formatter, "Invalid length: {}", len),
- Error::EndOfStream => formatter.write_str("EndOfStreamError"),
+ Error::Custom(ref s) => write!(formatter, "{}", s),
+ Error::EndOfStream => formatter.write_str("End of stream"),
+ Error::InvalidType(ty) => write!(formatter, "Invalid type, expected `{:?}`", ty),
+ Error::InvalidValue(ref value) => write!(formatter, "Invalid value: {}", value),
+ Error::InvalidLength(len) => write!(formatter, "Invalid length: {}", len),
+ Error::UnknownVariant(ref variant) => {
+ write!(formatter, "Unknown variant: {}", variant)
+ }
Error::UnknownField(ref field) => write!(formatter, "Unknown field: {}", field),
Error::MissingField(ref field) => write!(formatter, "Missing field: {}", field),
}
@@ -338,7 +350,7 @@ impl<I, T, E> de::SeqVisitor for SeqDeserializer<I, E>
if self.len == 0 {
Ok(())
} else {
- Err(de::Error::length_mismatch(self.len))
+ Err(de::Error::invalid_length(self.len))
}
}
@@ -494,7 +506,9 @@ impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
let mut de = value.into_deserializer();
de::Deserialize::deserialize(&mut de)
}
- None => Err(de::Error::syntax("expected a map value"))
+ None => {
+ Err(de::Error::end_of_stream())
+ }
}
}
@@ -502,7 +516,7 @@ impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
if self.len == 0 {
Ok(())
} else {
- Err(de::Error::length_mismatch(self.len))
+ Err(de::Error::invalid_length(self.len))
}
}
diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs
index e700b44fc..01368afb6 100644
--- a/serde/src/ser/mod.rs
+++ b/serde/src/ser/mod.rs
@@ -10,11 +10,11 @@ pub mod impls;
/// `Serializer` error.
pub trait Error: Sized + error::Error {
/// Raised when there is general error when deserializing a type.
- fn syntax(msg: &str) -> Self;
+ fn custom(msg: String) -> Self;
/// Raised when a `Serialize` was passed an incorrect value.
fn invalid_value(msg: &str) -> Self {
- Error::syntax(msg)
+ Error::custom(format!("invalid value: {}", msg))
}
}
diff --git a/serde_codegen/src/attr.rs b/serde_codegen/src/attr.rs
index a082fcbfa..d937f6050 100644
--- a/serde_codegen/src/attr.rs
+++ b/serde_codegen/src/attr.rs
@@ -5,7 +5,7 @@ use syntax::codemap::Span;
use syntax::ext::base::ExtCtxt;
use syntax::fold::Folder;
use syntax::parse::parser::PathParsingMode;
-use syntax::parse::token;
+use syntax::parse::token::{self, InternedString};
use syntax::parse;
use syntax::print::pprust::{lit_to_string, meta_item_to_string};
use syntax::ptr::P;
@@ -14,22 +14,66 @@ use aster::AstBuilder;
use error::Error;
+#[derive(Debug)]
+pub struct Name {
+ ident: ast::Ident,
+ serialize_name: Option<InternedString>,
+ deserialize_name: Option<InternedString>,
+}
+
+impl Name {
+ fn new(ident: ast::Ident) -> Self {
+ Name {
+ ident: ident,
+ serialize_name: None,
+ deserialize_name: None,
+ }
+ }
+
+ /// Return the string expression of the field ident.
+ pub fn ident_expr(&self) -> P<ast::Expr> {
+ AstBuilder::new().expr().str(self.ident)
+ }
+
+ /// Return the container name for the container when serializing.
+ pub fn serialize_name(&self) -> InternedString {
+ match self.serialize_name {
+ Some(ref name) => name.clone(),
+ None => self.ident.name.as_str(),
+ }
+ }
+
+ /// Return the container name expression for the container when deserializing.
+ pub fn serialize_name_expr(&self) -> P<ast::Expr> {
+ AstBuilder::new().expr().str(self.serialize_name())
+ }
+
+ /// Return the container name for the container when deserializing.
+ pub fn deserialize_name(&self) -> InternedString {
+ match self.deserialize_name {
+ Some(ref name) => name.clone(),
+ None => self.ident.name.as_str(),
+ }
+ }
+
+ /// Return the container name expression for the container when deserializing.
+ pub fn deserialize_name_expr(&self) -> P<ast::Expr> {
+ AstBuilder::new().expr().str(self.deserialize_name())
+ }
+}
+
/// Represents container (e.g. struct) attribute information
#[derive(Debug)]
pub struct ContainerAttrs {
- ident: ast::Ident,
- serialize_name: Option<ast::Lit>,
- deserialize_name: Option<ast::Lit>,
+ name: Name,
deny_unknown_fields: bool,
}
impl ContainerAttrs {
/// Extract out the `#[serde(...)]` attributes from an item.
- pub fn from_item(cx: &ExtCtxt, item: &ast::Item) -> Result<ContainerAttrs, Error> {
+ pub fn from_item(cx: &ExtCtxt, item: &ast::Item) -> Result<Self, Error> {
let mut container_attrs = ContainerAttrs {
- ident: item.ident,
- serialize_name: None,
- deserialize_name: None,
+ name: Name::new(item.ident),
deny_unknown_fields: false,
};
@@ -38,15 +82,18 @@ impl ContainerAttrs {
match meta_item.node {
// Parse `#[serde(rename="foo")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
- container_attrs.serialize_name = Some(lit.clone());
- container_attrs.deserialize_name = Some(lit.clone());
+ let s = try!(get_str_from_lit(cx, name, lit));
+
+ container_attrs.name.serialize_name = Some(s.clone());
+ container_attrs.name.deserialize_name = Some(s);
}
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
let (ser_name, de_name) = try!(get_renames(cx, meta_items));
- container_attrs.serialize_name = ser_name;
- container_attrs.deserialize_name = de_name;
+
+ container_attrs.name.serialize_name = ser_name;
+ container_attrs.name.deserialize_name = de_name;
}
// Parse `#[serde(deny_unknown_fields)]`
@@ -69,25 +116,8 @@ impl ContainerAttrs {
Ok(container_attrs)
}
- /// Return the string expression of the field ident.
- pub fn ident_expr(&self) -> P<ast::Expr> {
- AstBuilder::new().expr().str(self.ident)
- }
-
- /// Return the field name for the field when serializing.
- pub fn serialize_name_expr(&self) -> P<ast::Expr> {
- match self.serialize_name {
- Some(ref name) => AstBuilder::new().expr().build_lit(P(name.clone())),
- None => self.ident_expr(),
- }
- }
-
- /// Return the field name for the field when serializing.
- pub fn deserialize_name_expr(&self) -> P<ast::Expr> {
- match self.deserialize_name {
- Some(ref name) => AstBuilder::new().expr().build_lit(P(name.clone())),
- None => self.ident_expr(),
- }
+ pub fn name(&self) -> &Name {
+ &self.name
}
pub fn deny_unknown_fields(&self) -> bool {
@@ -98,17 +128,13 @@ impl ContainerAttrs {
/// Represents variant attribute information
#[derive(Debug)]
pub struct VariantAttrs {
- ident: ast::Ident,
- serialize_name: Option<ast::Lit>,
- deserialize_name: Option<ast::Lit>,
+ name: Name,
}
impl VariantAttrs {
pub fn from_variant(cx: &ExtCtxt, variant: &ast::Variant) -> Result<Self, Error> {
let mut variant_attrs = VariantAttrs {
- ident: variant.node.name,
- serialize_name: None,
- deserialize_name: None,
+ name: Name::new(variant.node.name),
};
for meta_items in variant.node.attrs.iter().filter_map(get_serde_meta_items) {
@@ -116,15 +142,18 @@ impl VariantAttrs {
match meta_item.node {
// Parse `#[serde(rename="foo")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
- variant_attrs.serialize_name = Some(lit.clone());
- variant_attrs.deserialize_name = Some(lit.clone());
+ let s = try!(get_str_from_lit(cx, name, lit));
+
+ variant_attrs.name.serialize_name = Some(s.clone());
+ variant_attrs.name.deserialize_name = Some(s);
}
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
let (ser_name, de_name) = try!(get_renames(cx, meta_items));
- variant_attrs.serialize_name = ser_name;
- variant_attrs.deserialize_name = de_name;
+
+ variant_attrs.name.serialize_name = ser_name;
+ variant_attrs.name.deserialize_name = de_name;
}
_ => {
@@ -142,34 +171,15 @@ impl VariantAttrs {
Ok(variant_attrs)
}
- /// Return the string expression of the field ident.
- pub fn ident_expr(&self) -> P<ast::Expr> {
- AstBuilder::new().expr().str(self.ident)
- }
-
- /// Return the field name for the field when serializing.
- pub fn serialize_name_expr(&self) -> P<ast::Expr> {
- match self.serialize_name {
- Some(ref name) => AstBuilder::new().expr().build_lit(P(name.clone())),
- None => self.ident_expr(),
- }
- }
-
- /// Return the field name for the field when serializing.
- pub fn deserialize_name_expr(&self) -> P<ast::Expr> {
- match self.deserialize_name {
- Some(ref name) => AstBuilder::new().expr().build_lit(P(name.clone())),
- None => self.ident_expr(),
- }
+ pub fn name(&self) -> &Name {
+ &self.name
}
}
/// Represents field attribute information
#[derive(Debug)]
pub struct FieldAttrs {
- ident: ast::Ident,
- serialize_name: Option<ast::Lit>,
- deserialize_name: Option<ast::Lit>,
+ name: Name,
skip_serializing_field: bool,
skip_serializing_field_if: Option<P<ast::Expr>>,
default_expr_if_missing: Option<P<ast::Expr>>,
@@ -192,9 +202,7 @@ impl FieldAttrs {
};
let mut field_attrs = FieldAttrs {
- ident: field_ident,
- serialize_name: None,
- deserialize_name: None,
+ name: Name::new(field_ident),
skip_serializing_field: false,
skip_serializing_field_if: None,
default_expr_if_missing: None,
@@ -207,15 +215,18 @@ impl FieldAttrs {
match meta_item.node {
// Parse `#[serde(rename="foo")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
- field_attrs.serialize_name = Some(lit.clone());
- field_attrs.deserialize_name = Some(lit.clone());
+ let s = try!(get_str_from_lit(cx, name, lit));
+
+ field_attrs.name.serialize_name = Some(s.clone());
+ field_attrs.name.deserialize_name = Some(s);
}
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
let (ser_name, de_name) = try!(get_renames(cx, meta_items));
- field_attrs.serialize_name = ser_name;
- field_attrs.deserialize_name = de_name;
+
+ field_attrs.name.serialize_name = ser_name;
+ field_attrs.name.deserialize_name = de_name;
}
// Parse `#[serde(default)]`
@@ -290,25 +301,8 @@ impl FieldAttrs {
Ok(field_attrs)
}
- /// Return the string expression of the field ident.
- pub fn ident_expr(&self) -> P<ast::Expr> {
- AstBuilder::new().expr().str(self.ident)
- }
-
- /// Return the field name for the field when serializing.
- pub fn serialize_name_expr(&self) -> P<ast::Expr> {
- match self.serialize_name {
- Some(ref name) => AstBuilder::new().expr().build_lit(P(name.clone())),
- None => self.ident_expr(),
- }
- }
-
- /// Return the field name for the field when deserializing.
- pub fn deserialize_name_expr(&self) -> P<ast::Expr> {
- match self.deserialize_name {
- Some(ref name) => AstBuilder::new().expr().build_lit(P(name.clone())),
- None => self.ident_expr(),
- }
+ pub fn name(&self) -> &Name {
+ &self.name
}
/// Predicate for using a field's default value
@@ -316,7 +310,7 @@ impl FieldAttrs {
match self.default_expr_if_missing {
Some(ref expr) => expr.clone(),
None => {
- let name = self.ident_expr();
+ let name = self.name.ident_expr();
AstBuilder::new().expr()
.try()
.method_call("missing_field").id("visitor")
@@ -357,18 +351,21 @@ pub fn get_struct_field_attrs(cx: &ExtCtxt,
}
fn get_renames(cx: &ExtCtxt,
- items: &[P<ast::MetaItem>]) -> Result<(Option<ast::Lit>, Option<ast::Lit>), Error> {
+ items: &[P<ast::MetaItem>],
+ )-> Result<(Option<InternedString>, Option<InternedString>), Error> {
let mut ser_name = None;
let mut de_name = None;
for item in items {
match item.node {
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"serialize" => {
- ser_name = Some(lit.clone());
+ let s = try!(get_str_from_lit(cx, name, lit));
+ ser_name = Some(s);
}
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"deserialize" => {
- de_name = Some(lit.clone());
+ let s = try!(get_str_from_lit(cx, name, lit));
+ de_name = Some(s);
}
_ => {
@@ -442,9 +439,9 @@ impl<'a, 'b> Folder for Respanner<'a, 'b> {
}
}
-fn parse_lit_into_path(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<ast::Path, Error> {
- let source: &str = match lit.node {
- ast::LitKind::Str(ref source, _) => &source,
+fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<InternedString, Error> {
+ match lit.node {
+ ast::LitKind::Str(ref s, _) => Ok(s.clone()),
_ => {
cx.span_err(
lit.span,
@@ -454,7 +451,11 @@ fn parse_lit_into_path(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<ast::
return Err(Error);
}
- };
+ }
+}
+
+fn parse_lit_into_path(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<ast::Path, Error> {
+ let source = try!(get_str_from_lit(cx, name, lit));
// If we just parse the string into an expression, any syntax errors in the source will only
// have spans that point inside the string, and not back to the attribute. So to have better
@@ -463,7 +464,7 @@ fn parse_lit_into_path(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<ast::
// and then finally parse them into an expression.
let tts = parse::parse_tts_from_source_str(
format!("<serde {} expansion>", name),
- source.to_owned(),
+ (*source).to_owned(),
cx.cfg(),
cx.parse_sess());
diff --git a/serde_codegen/src/de.rs b/serde_codegen/src/de.rs
index a94fd02bb..fc9358098 100644
--- a/serde_codegen/src/de.rs
+++ b/serde_codegen/src/de.rs
@@ -10,6 +10,7 @@ use syntax::ast::{
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ext::build::AstBuilder;
+use syntax::parse::token::InternedString;
use syntax::ptr::P;
use attr;
@@ -266,7 +267,7 @@ fn deserialize_unit_struct(
type_ident: Ident,
container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
- let type_name = container_attrs.deserialize_name_expr();
+ let type_name = container_attrs.name().deserialize_name_expr();
Ok(quote_expr!(cx, {
struct __Visitor;
@@ -318,7 +319,7 @@ fn deserialize_newtype_struct(
1,
);
- let type_name = container_attrs.deserialize_name_expr();
+ let type_name = container_attrs.name().deserialize_name_expr();
Ok(quote_expr!(cx, {
$visitor_item
@@ -371,7 +372,7 @@ fn deserialize_tuple_struct(
fields,
);
- let type_name = container_attrs.deserialize_name_expr();
+ let type_name = container_attrs.name().deserialize_name_expr();
Ok(quote_expr!(cx, {
$visitor_item
@@ -510,7 +511,7 @@ fn deserialize_struct(
false,
));
- let type_name = container_attrs.deserialize_name_expr();
+ let type_name = container_attrs.name().deserialize_name_expr();
Ok(quote_expr!(cx, {
$field_visitor
@@ -552,7 +553,7 @@ fn deserialize_item_enum(
) -> Result<P<ast::Expr>, Error> {
let where_clause = &impl_generics.where_clause;
- let type_name = container_attrs.deserialize_name_expr();
+ let type_name = container_attrs.name().deserialize_name_expr();
let variant_visitor = deserialize_field_visitor(
cx,
@@ -561,7 +562,7 @@ fn deserialize_item_enum(
enum_def.variants.iter()
.map(|variant| {
let attrs = try!(attr::VariantAttrs::from_variant(cx, variant));
- Ok(attrs.deserialize_name_expr())
+ Ok(attrs.name().deserialize_name())
})
.collect()
),
@@ -806,12 +807,12 @@ fn deserialize_struct_variant(
fn deserialize_field_visitor(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
- field_names: Vec<P<ast::Expr>>,
+ field_names: Vec<InternedString>,
container_attrs: &attr::ContainerAttrs,
is_variant: bool,
) -> Vec<P<ast::Item>> {
// Create the field names for the fields.
- let field_idents: Vec<ast::Ident> = (0 .. field_names.len())
+ let field_idents: Vec<_> = (0 .. field_names.len())
.map(|i| builder.id(format!("__field{}", i)))
.collect();
@@ -846,22 +847,34 @@ fn deserialize_field_visitor(
(builder.expr().str("expected a field"), builder.id("unknown_field"))
};
+ let fallthrough_index_arm_expr = if !is_variant && !container_attrs.deny_unknown_fields() {
+ quote_expr!(cx, Ok(__Field::__ignore))
+ } else {
+ quote_expr!(cx, {
+ Err(::serde::de::Error::invalid_value($index_error_msg))
+ })
+ };
+
let index_body = quote_expr!(cx,
match value {
$index_field_arms
- _ => { Err(::serde::de::Error::syntax($index_error_msg)) }
+ _ => $fallthrough_index_arm_expr
}
);
+ // Convert the field names into byte strings.
+ let str_field_names: Vec<_> = field_names.iter()
+ .map(|name| builder.expr().lit().str(&name))
+ .collect();
+
// Match arms to extract a field from a string
- let default_field_arms: Vec<_> = field_idents.iter()
- .zip(field_names.iter())
+ let str_field_arms: Vec<_> = field_idents.iter().zip(str_field_names.iter())
.map(|(field_ident, field_name)| {
quote_arm!(cx, $field_name => { Ok(__Field::$field_ident) })
})
.collect();
- let fallthrough_arm_expr = if !is_variant && !container_attrs.deny_unknown_fields() {
+ let fallthrough_str_arm_expr = if !is_variant && !container_attrs.deny_unknown_fields() {
quote_expr!(cx, Ok(__Field::__ignore))
} else {
quote_expr!(cx, Err(::serde::de::Error::$unknown_ident(value)))
@@ -869,8 +882,39 @@ fn deserialize_field_visitor(
let str_body = quote_expr!(cx,
match value {
- $default_field_arms
- _ => $fallthrough_arm_expr
+ $str_field_arms
+ _ => $fallthrough_str_arm_expr
+ }
+ );
+
+ // Convert the field names into byte strings.
+ let bytes_field_names: Vec<_> = field_names.iter()
+ .map(|name| {
+ let name: &str = name;
+ builder.expr().lit().byte_str(name)
+ })
+ .collect();
+
+ // Match arms to extract a field from a string
+ let bytes_field_arms: Vec<_> = field_idents.iter().zip(bytes_field_names.iter())
+ .map(|(field_ident, field_name)| {
+ quote_arm!(cx, $field_name => { Ok(__Field::$field_ident) })
+ })
+ .collect();
+
+ let fallthrough_bytes_arm_expr = if !is_variant && !container_attrs.deny_unknown_fields() {
+ quote_expr!(cx, Ok(__Field::__ignore))
+ } else {
+ quote_expr!(cx, {
+ let value = ::std::string::String::from_utf8_lossy(value);
+ Err(::serde::de::Error::$unknown_ident(&value))
+ })
+ };
+
+ let bytes_body = quote_expr!(cx,
+ match value {
+ $bytes_field_arms
+ _ => $fallthrough_bytes_arm_expr
}
);
@@ -906,17 +950,7 @@ fn deserialize_field_visitor(
fn visit_bytes<E>(&mut self, value: &[u8]) -> ::std::result::Result<__Field, E>
where E: ::serde::de::Error,
{
- // TODO: would be better to generate a byte string literal match
- match ::std::str::from_utf8(value) {
- Ok(s) => self.visit_str(s),
- _ => {
- Err(
- ::serde::de::Error::syntax(
- "could not convert a byte string to a String"
- )
- )
- }
- }
+ $bytes_body
}
}
@@ -947,7 +981,7 @@ fn deserialize_struct_visitor(
field,
is_enum)
);
- Ok(field_attrs.deserialize_name_expr())
+ Ok(field_attrs.name().deserialize_name())
})
.collect();
diff --git a/serde_codegen/src/ser.rs b/serde_codegen/src/ser.rs
index b1e1641ff..cb97640dc 100644
--- a/serde_codegen/src/ser.rs
+++ b/serde_codegen/src/ser.rs
@@ -185,7 +185,7 @@ fn serialize_unit_struct(
cx: &ExtCtxt,
container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
- let type_name = container_attrs.serialize_name_expr();
+ let type_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx,
serializer.serialize_unit_struct($type_name)
@@ -196,7 +196,7 @@ fn serialize_newtype_struct(
cx: &ExtCtxt,
container_attrs: &attr::ContainerAttrs,
) -> Result<P<ast::Expr>, Error> {
- let type_name = container_attrs.serialize_name_expr();
+ let type_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx,
serializer.serialize_newtype_struct($type_name, &self.0)
@@ -224,7 +224,7 @@ fn serialize_tuple_struct(
impl_generics,
);
- let type_name = container_attrs.serialize_name_expr();
+ let type_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx, {
$visitor_struct
@@ -259,7 +259,7 @@ fn serialize_struct(
false,
));
- let type_name = container_attrs.serialize_name_expr();
+ let type_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx, {
$visitor_struct
@@ -316,11 +316,11 @@ fn serialize_variant(
variant_index: usize,
container_attrs: &attr::ContainerAttrs,
) -> Result<ast::Arm, Error> {
- let type_name = container_attrs.serialize_name_expr();
+ let type_name = container_attrs.name().serialize_name_expr();
let variant_ident = variant.node.name;
let variant_attrs = try!(attr::VariantAttrs::from_variant(cx, variant));
- let variant_name = variant_attrs.serialize_name_expr();
+ let variant_name = variant_attrs.name().serialize_name_expr();
match variant.node.data {
ast::VariantData::Unit(_) => {
@@ -551,7 +551,7 @@ fn serialize_struct_variant(
true,
));
- let container_name = container_attrs.serialize_name_expr();
+ let container_name = container_attrs.name().serialize_name_expr();
Ok(quote_expr!(cx, {
$variant_struct
@@ -658,7 +658,7 @@ fn serialize_struct_visitor(
.map(|(i, (ref field, ref field_attr))| {
let name = field.node.ident().expect("struct has unnamed field");
- let key_expr = field_attr.serialize_name_expr();
+ let key_expr = field_attr.name().serialize_name_expr();
let stmt = if let Some(expr) = field_attr.skip_serializing_field_if() {
Some(quote_stmt!(cx, if $expr { continue; }))
| serde-rs/serde | 2016-02-24T04:25:37Z | I will update my PR on https://github.com/serde-rs/json/pull/11 if this one is merged.
Ooh nice catch before I cut the release :)
On serde_json, I've also got 0.7 almost merged in. Give me a moment to do that.
I just saw another method [`invalid_value`](https://github.com/serde-rs/serde/blob/master/serde/src/de/mod.rs#L27) on `de::Error` trait, maybe you want to forward it through `value::Error` also.
@tomprogrammer: I'll take care of it, and the travis build failure.
Meh, the failure is a typo...
Thanks!
| ed603d4580154bc09af94964c2aca8b42f268274 |
245 | diff --git a/serde_tests/tests/test_de.rs b/serde_tests/tests/test_de.rs
index 082d627d3..ab5a79ca2 100644
--- a/serde_tests/tests/test_de.rs
+++ b/serde_tests/tests/test_de.rs
@@ -186,27 +186,27 @@ declare_tests! {
],
TupleStruct(1, 2, 3) => vec![
Token::TupleStructStart("TupleStruct", Some(3)),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(1),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(2),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(3),
- Token::TupleSeqEnd,
+ Token::TupleStructEnd,
],
TupleStruct(1, 2, 3) => vec![
Token::TupleStructStart("TupleStruct", None),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(1),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(2),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(3),
- Token::TupleSeqEnd,
+ Token::TupleStructEnd,
],
}
test_btreeset {
@@ -321,6 +321,10 @@ declare_tests! {
Token::SeqStart(Some(0)),
Token::SeqEnd,
],
+ [0; 0] => vec![
+ Token::SeqArrayStart(0),
+ Token::SeqEnd,
+ ],
([0; 0], [1], [2, 3]) => vec![
Token::SeqStart(Some(3)),
Token::SeqSep,
@@ -343,6 +347,28 @@ declare_tests! {
Token::SeqEnd,
Token::SeqEnd,
],
+ ([0; 0], [1], [2, 3]) => vec![
+ Token::SeqArrayStart(3),
+ Token::SeqSep,
+ Token::SeqArrayStart(0),
+ Token::SeqEnd,
+
+ Token::SeqSep,
+ Token::SeqArrayStart(1),
+ Token::SeqSep,
+ Token::I32(1),
+ Token::SeqEnd,
+
+ Token::SeqSep,
+ Token::SeqArrayStart(2),
+ Token::SeqSep,
+ Token::I32(2),
+
+ Token::SeqSep,
+ Token::I32(3),
+ Token::SeqEnd,
+ Token::SeqEnd,
+ ],
[0; 0] => vec![
Token::UnitStruct("Anything"),
],
@@ -370,6 +396,24 @@ declare_tests! {
Token::I32(3),
Token::SeqEnd,
],
+ (1,) => vec![
+ Token::TupleStart(1),
+ Token::TupleSep,
+ Token::I32(1),
+ Token::TupleEnd,
+ ],
+ (1, 2, 3) => vec![
+ Token::TupleStart(3),
+ Token::TupleSep,
+ Token::I32(1),
+
+ Token::TupleSep,
+ Token::I32(2),
+
+ Token::TupleSep,
+ Token::I32(3),
+ Token::TupleEnd,
+ ],
}
test_btreemap {
BTreeMap::<isize, isize>::new() => vec![
diff --git a/serde_tests/tests/test_macros.rs b/serde_tests/tests/test_macros.rs
index 842fa670e..5feb7252d 100644
--- a/serde_tests/tests/test_macros.rs
+++ b/serde_tests/tests/test_macros.rs
@@ -153,16 +153,16 @@ fn test_ser_named_tuple() {
&SerNamedTuple(&a, &mut b, c),
&[
Token::TupleStructStart("SerNamedTuple", Some(3)),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(5),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(6),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(7),
- Token::TupleSeqEnd,
+ Token::TupleStructEnd,
],
);
}
@@ -190,16 +190,16 @@ fn test_de_named_tuple() {
&DeNamedTuple(5, 6, 7),
vec![
Token::TupleStructStart("DeNamedTuple", Some(3)),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(5),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(6),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(7),
- Token::TupleSeqEnd,
+ Token::TupleStructEnd,
]
);
}
@@ -525,13 +525,13 @@ fn test_generic_tuple_struct() {
vec![
Token::TupleStructStart("GenericTupleStruct", Some(2)),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::U32(5),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::U32(6),
- Token::TupleSeqEnd,
+ Token::TupleStructEnd,
]
);
}
diff --git a/serde_tests/tests/test_ser.rs b/serde_tests/tests/test_ser.rs
index 2edd7c175..a67a69212 100644
--- a/serde_tests/tests/test_ser.rs
+++ b/serde_tests/tests/test_ser.rs
@@ -100,11 +100,11 @@ declare_ser_tests! {
}
test_array {
[0; 0] => &[
- Token::SeqStart(Some(0)),
+ Token::SeqArrayStart(0),
Token::SeqEnd,
],
[1, 2, 3] => &[
- Token::SeqStart(Some(3)),
+ Token::SeqArrayStart(3),
Token::SeqSep,
Token::I32(1),
@@ -146,22 +146,22 @@ declare_ser_tests! {
}
test_tuple {
(1,) => &[
- Token::SeqStart(Some(1)),
- Token::SeqSep,
+ Token::TupleStart(1),
+ Token::TupleSep,
Token::I32(1),
- Token::SeqEnd,
+ Token::TupleEnd,
],
(1, 2, 3) => &[
- Token::SeqStart(Some(3)),
- Token::SeqSep,
+ Token::TupleStart(3),
+ Token::TupleSep,
Token::I32(1),
- Token::SeqSep,
+ Token::TupleSep,
Token::I32(2),
- Token::SeqSep,
+ Token::TupleSep,
Token::I32(3),
- Token::SeqEnd,
+ Token::TupleEnd,
],
}
test_btreemap {
@@ -210,15 +210,15 @@ declare_ser_tests! {
test_tuple_struct {
TupleStruct(1, 2, 3) => &[
Token::TupleStructStart("TupleStruct", Some(3)),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(1),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(2),
- Token::TupleSeqSep,
+ Token::TupleStructSep,
Token::I32(3),
- Token::TupleSeqEnd,
+ Token::TupleStructEnd,
],
}
test_struct {
diff --git a/serde_tests/tests/token.rs b/serde_tests/tests/token.rs
index 30d623be8..11c0dc8ea 100644
--- a/serde_tests/tests/token.rs
+++ b/serde_tests/tests/token.rs
@@ -38,12 +38,17 @@ pub enum Token<'a> {
EnumNewType(&'a str, &'a str),
SeqStart(Option<usize>),
+ SeqArrayStart(usize),
SeqSep,
SeqEnd,
+ TupleStart(usize),
+ TupleSep,
+ TupleEnd,
+
TupleStructStart(&'a str, Option<usize>),
- TupleSeqSep,
- TupleSeqEnd,
+ TupleStructSep,
+ TupleStructEnd,
MapStart(Option<usize>),
MapSep,
@@ -231,6 +236,16 @@ impl<'a, I> ser::Serializer for Serializer<I>
self.visit_sequence(visitor)
}
+ fn serialize_fixed_size_array<V>(&mut self, visitor: V) -> Result<(), Error>
+ where V: ser::SeqVisitor
+ {
+ let len = visitor.len().expect("arrays must have a length");
+
+ assert_eq!(self.tokens.next(), Some(&Token::SeqArrayStart(len)));
+
+ self.visit_sequence(visitor)
+ }
+
fn serialize_seq_elt<T>(&mut self, value: T) -> Result<(), Error>
where T: ser::Serialize
{
@@ -238,6 +253,27 @@ impl<'a, I> ser::Serializer for Serializer<I>
value.serialize(self)
}
+ fn serialize_tuple<V>(&mut self, mut visitor: V) -> Result<(), Error>
+ where V: ser::SeqVisitor
+ {
+ let len = visitor.len().expect("arrays must have a length");
+
+ assert_eq!(self.tokens.next(), Some(&Token::TupleStart(len)));
+
+ while let Some(()) = try!(visitor.visit(self)) { }
+
+ assert_eq!(self.tokens.next(), Some(&Token::TupleEnd));
+
+ Ok(())
+ }
+
+ fn serialize_tuple_elt<T>(&mut self, value: T) -> Result<(), Error>
+ where T: ser::Serialize
+ {
+ assert_eq!(self.tokens.next(), Some(&Token::TupleSep));
+ value.serialize(self)
+ }
+
fn serialize_newtype_struct<T>(&mut self,
name: &'static str,
value: T) -> Result<(), Error>
@@ -256,7 +292,7 @@ impl<'a, I> ser::Serializer for Serializer<I>
while let Some(()) = try!(visitor.visit(self)) { }
- assert_eq!(self.tokens.next(), Some(&Token::TupleSeqEnd));
+ assert_eq!(self.tokens.next(), Some(&Token::TupleStructEnd));
Ok(())
}
@@ -264,7 +300,7 @@ impl<'a, I> ser::Serializer for Serializer<I>
fn serialize_tuple_struct_elt<T>(&mut self, value: T) -> Result<(), Error>
where T: ser::Serialize,
{
- assert_eq!(self.tokens.next(), Some(&Token::TupleSeqSep));
+ assert_eq!(self.tokens.next(), Some(&Token::TupleStructSep));
value.serialize(self)
}
@@ -449,10 +485,28 @@ impl<I> Deserializer<I>
})
}
- fn visit_tuple_seq<V>(&mut self, len: Option<usize>, mut visitor: V) -> Result<V::Value, Error>
+ fn visit_array<V>(&mut self, len: usize, mut visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
- visitor.visit_seq(DeserializerTupleSeqVisitor {
+ visitor.visit_seq(DeserializerArrayVisitor {
+ de: self,
+ len: len,
+ })
+ }
+
+ fn visit_tuple<V>(&mut self, len: usize, mut visitor: V) -> Result<V::Value, Error>
+ where V: de::Visitor,
+ {
+ visitor.visit_seq(DeserializerTupleVisitor {
+ de: self,
+ len: len,
+ })
+ }
+
+ fn visit_tuple_struct<V>(&mut self, len: usize, mut visitor: V) -> Result<V::Value, Error>
+ where V: de::Visitor,
+ {
+ visitor.visit_seq(DeserializerTupleStructVisitor {
de: self,
len: len,
})
@@ -528,6 +582,9 @@ impl<I> de::Deserializer for Deserializer<I>
Some(Token::SeqStart(len)) | Some(Token::TupleStructStart(_, len)) => {
self.visit_seq(len, visitor)
}
+ Some(Token::SeqArrayStart(len)) => {
+ self.visit_seq(Some(len), visitor)
+ }
Some(Token::MapStart(len)) | Some(Token::StructStart(_, len)) => {
self.visit_map(len, visitor)
}
@@ -625,6 +682,56 @@ impl<I> de::Deserializer for Deserializer<I>
}
}
+ fn deserialize_fixed_size_array<V>(&mut self,
+ len: usize,
+ visitor: V) -> Result<V::Value, Error>
+ where V: de::Visitor,
+ {
+ match self.tokens.peek() {
+ Some(&Token::SeqArrayStart(_)) => {
+ self.tokens.next();
+ self.visit_array(len, visitor)
+ }
+ Some(_) => self.deserialize(visitor),
+ None => Err(Error::EndOfStreamError),
+ }
+ }
+
+ fn deserialize_tuple<V>(&mut self,
+ len: usize,
+ mut visitor: V) -> Result<V::Value, Error>
+ where V: de::Visitor,
+ {
+ match self.tokens.peek() {
+ Some(&Token::Unit) => {
+ self.tokens.next();
+ visitor.visit_unit()
+ }
+ Some(&Token::UnitStruct(_)) => {
+ self.tokens.next();
+ visitor.visit_unit()
+ }
+ Some(&Token::SeqStart(_)) => {
+ self.tokens.next();
+ self.visit_seq(Some(len), visitor)
+ }
+ Some(&Token::SeqArrayStart(_)) => {
+ self.tokens.next();
+ self.visit_array(len, visitor)
+ }
+ Some(&Token::TupleStart(_)) => {
+ self.tokens.next();
+ self.visit_tuple(len, visitor)
+ }
+ Some(&Token::TupleStructStart(_, _)) => {
+ self.tokens.next();
+ self.visit_tuple_struct(len, visitor)
+ }
+ Some(_) => self.deserialize(visitor),
+ None => Err(Error::EndOfStreamError),
+ }
+ }
+
fn deserialize_tuple_struct<V>(&mut self,
name: &str,
len: usize,
@@ -632,6 +739,10 @@ impl<I> de::Deserializer for Deserializer<I>
where V: de::Visitor,
{
match self.tokens.peek() {
+ Some(&Token::Unit) => {
+ self.tokens.next();
+ visitor.visit_unit()
+ }
Some(&Token::UnitStruct(n)) => {
self.tokens.next();
if name == n {
@@ -640,18 +751,26 @@ impl<I> de::Deserializer for Deserializer<I>
Err(Error::InvalidName(n))
}
}
+ Some(&Token::SeqStart(_)) => {
+ self.tokens.next();
+ self.visit_seq(Some(len), visitor)
+ }
+ Some(&Token::SeqArrayStart(_)) => {
+ self.tokens.next();
+ self.visit_array(len, visitor)
+ }
+ Some(&Token::TupleStart(_)) => {
+ self.tokens.next();
+ self.visit_tuple(len, visitor)
+ }
Some(&Token::TupleStructStart(n, _)) => {
self.tokens.next();
if name == n {
- self.visit_tuple_seq(Some(len), visitor)
+ self.visit_tuple_struct(len, visitor)
} else {
Err(Error::InvalidName(n))
}
}
- Some(&Token::SeqStart(_)) => {
- self.tokens.next();
- self.visit_seq(Some(len), visitor)
- }
Some(_) => self.deserialize(visitor),
None => Err(Error::EndOfStreamError),
}
@@ -729,12 +848,12 @@ impl<'a, I> de::SeqVisitor for DeserializerSeqVisitor<'a, I>
//////////////////////////////////////////////////////////////////////////
-struct DeserializerTupleSeqVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
+struct DeserializerArrayVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
de: &'a mut Deserializer<I>,
- len: Option<usize>,
+ len: usize,
}
-impl<'a, I> de::SeqVisitor for DeserializerTupleSeqVisitor<'a, I>
+impl<'a, I> de::SeqVisitor for DeserializerArrayVisitor<'a, I>
where I: Iterator<Item=Token<'static>>,
{
type Error = Error;
@@ -743,12 +862,12 @@ impl<'a, I> de::SeqVisitor for DeserializerTupleSeqVisitor<'a, I>
where T: de::Deserialize,
{
match self.de.tokens.peek() {
- Some(&Token::TupleSeqSep) => {
+ Some(&Token::SeqSep) => {
self.de.tokens.next();
- self.len = self.len.map(|len| len - 1);
+ self.len -= 1;
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
}
- Some(&Token::TupleSeqEnd) => Ok(None),
+ Some(&Token::SeqEnd) => Ok(None),
Some(_) => {
let token = self.de.tokens.next().unwrap();
Err(Error::UnexpectedToken(token))
@@ -758,17 +877,104 @@ impl<'a, I> de::SeqVisitor for DeserializerTupleSeqVisitor<'a, I>
}
fn end(&mut self) -> Result<(), Error> {
- //assert_eq!(self.len.unwrap_or(0), 0);
+ assert_eq!(self.len, 0);
match self.de.tokens.next() {
- Some(Token::TupleSeqEnd) => Ok(()),
+ Some(Token::SeqEnd) => Ok(()),
Some(token) => Err(Error::UnexpectedToken(token)),
None => Err(Error::EndOfStreamError),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
- let len = self.len.unwrap_or(0);
- (len, self.len)
+ (self.len, Some(self.len))
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////
+
+struct DeserializerTupleVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
+ de: &'a mut Deserializer<I>,
+ len: usize,
+}
+
+impl<'a, I> de::SeqVisitor for DeserializerTupleVisitor<'a, I>
+ where I: Iterator<Item=Token<'static>>,
+{
+ type Error = Error;
+
+ fn visit<T>(&mut self) -> Result<Option<T>, Error>
+ where T: de::Deserialize,
+ {
+ match self.de.tokens.peek() {
+ Some(&Token::TupleSep) => {
+ self.de.tokens.next();
+ self.len -= 1;
+ Ok(Some(try!(de::Deserialize::deserialize(self.de))))
+ }
+ Some(&Token::TupleEnd) => Ok(None),
+ Some(_) => {
+ let token = self.de.tokens.next().unwrap();
+ Err(Error::UnexpectedToken(token))
+ }
+ None => Err(Error::EndOfStreamError),
+ }
+ }
+
+ fn end(&mut self) -> Result<(), Error> {
+ assert_eq!(self.len, 0);
+ match self.de.tokens.next() {
+ Some(Token::TupleEnd) => Ok(()),
+ Some(token) => Err(Error::UnexpectedToken(token)),
+ None => Err(Error::EndOfStreamError),
+ }
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.len, Some(self.len))
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////
+
+struct DeserializerTupleStructVisitor<'a, I: 'a> where I: Iterator<Item=Token<'static>> {
+ de: &'a mut Deserializer<I>,
+ len: usize,
+}
+
+impl<'a, I> de::SeqVisitor for DeserializerTupleStructVisitor<'a, I>
+ where I: Iterator<Item=Token<'static>>,
+{
+ type Error = Error;
+
+ fn visit<T>(&mut self) -> Result<Option<T>, Error>
+ where T: de::Deserialize,
+ {
+ match self.de.tokens.peek() {
+ Some(&Token::TupleStructSep) => {
+ self.de.tokens.next();
+ self.len -= 1;
+ Ok(Some(try!(de::Deserialize::deserialize(self.de))))
+ }
+ Some(&Token::TupleStructEnd) => Ok(None),
+ Some(_) => {
+ let token = self.de.tokens.next().unwrap();
+ Err(Error::UnexpectedToken(token))
+ }
+ None => Err(Error::EndOfStreamError),
+ }
+ }
+
+ fn end(&mut self) -> Result<(), Error> {
+ assert_eq!(self.len, 0);
+ match self.de.tokens.next() {
+ Some(Token::TupleStructEnd) => Ok(()),
+ Some(token) => Err(Error::UnexpectedToken(token)),
+ None => Err(Error::EndOfStreamError),
+ }
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.len, Some(self.len))
}
}
| [
"244"
] | serde-rs__serde-245 | Figure out if there are sensible hooks for serializing fixed length arrays
Fixed length arrays don't yet have a hook to hint that they're fixed length, so they're serialized like a generic sequence. It might be nice to add one for backends that might want to do something special with them.
One potential challenge here is how do we trust that the `Serialize` is actually serializing the right number of values, but we have the same challenge for tuples.
| 0.6 | d24b2c86f2c9b3f5036289d6c2c5764be57d2127 | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index dbf0042ba..7bb024915 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -529,7 +529,7 @@ macro_rules! array_impls {
fn deserialize<D>(deserializer: &mut D) -> Result<[T; $len], D::Error>
where D: Deserializer,
{
- deserializer.deserialize_seq($visitor::new())
+ deserializer.deserialize_fixed_size_array($len, $visitor::new())
}
}
)+
diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index a69f2701c..d45930e4e 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -329,6 +329,19 @@ pub trait Deserializer {
self.deserialize(visitor)
}
+ /// This method hints that the `Deserialize` type is expecting a fixed size array. This allows
+ /// deserializers to parse arrays that aren't tagged as arrays.
+ ///
+ /// By default, this deserializes arrays from a sequence.
+ #[inline]
+ fn deserialize_fixed_size_array<V>(&mut self,
+ _len: usize,
+ visitor: V) -> Result<V::Value, Self::Error>
+ where V: Visitor,
+ {
+ self.deserialize(visitor)
+ }
+
/// This method hints that the `Deserialize` type is expecting a map of values. This allows
/// deserializers to parse sequences that aren't tagged as maps.
#[inline]
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index e7a2e6018..a2441e429 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -196,6 +196,8 @@ impl<T> Serialize for [T]
}
}
+///////////////////////////////////////////////////////////////////////////////
+
macro_rules! array_impls {
($len:expr) => {
impl<T> Serialize for [T; $len] where T: Serialize {
@@ -203,7 +205,8 @@ macro_rules! array_impls {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: Serializer,
{
- serializer.serialize_seq(SeqIteratorVisitor::new(self.iter(), Some($len)))
+ let visitor = SeqIteratorVisitor::new(self.iter(), Some($len));
+ serializer.serialize_fixed_size_array(visitor)
}
}
}
diff --git a/serde/src/ser/mod.rs b/serde/src/ser/mod.rs
index 16edd953a..e700b44fc 100644
--- a/serde/src/ser/mod.rs
+++ b/serde/src/ser/mod.rs
@@ -220,6 +220,16 @@ pub trait Serializer {
self.serialize_seq_elt(value)
}
+ /// Serializes a fixed-size array.
+ ///
+ /// By default this serializes an array as a sequence.
+ #[inline]
+ fn serialize_fixed_size_array<V>(&mut self, visitor: V) -> Result<(), Self::Error>
+ where V: SeqVisitor,
+ {
+ self.serialize_seq(visitor)
+ }
+
/// Serializes a tuple struct.
///
/// By default, tuple structs are serialized as a tuple.
| serde-rs/serde | 2016-02-23T13:16:33Z | d24b2c86f2c9b3f5036289d6c2c5764be57d2127 | |
242 | diff --git a/serde_tests/tests/test_de.rs b/serde_tests/tests/test_de.rs
index 568bfaea1..88f6a9add 100644
--- a/serde_tests/tests/test_de.rs
+++ b/serde_tests/tests/test_de.rs
@@ -1,4 +1,5 @@
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
+use std::net;
use std::path::PathBuf;
use num::FromPrimitive;
@@ -571,6 +572,17 @@ declare_tests! {
Token::Unit,
],
}
+ test_net_ipv4addr {
+ "1.2.3.4".parse::<net::Ipv4Addr>().unwrap() => vec![Token::Str("1.2.3.4")],
+ }
+ test_net_ipv6addr {
+ "::1".parse::<net::Ipv6Addr>().unwrap() => vec![Token::Str("::1")],
+ }
+ test_net_socketaddr {
+ "1.2.3.4:1234".parse::<net::SocketAddr>().unwrap() => vec![Token::Str("1.2.3.4:1234")],
+ "1.2.3.4:1234".parse::<net::SocketAddrV4>().unwrap() => vec![Token::Str("1.2.3.4:1234")],
+ "[::1]:1234".parse::<net::SocketAddrV6>().unwrap() => vec![Token::Str("[::1]:1234")],
+ }
test_num_bigint {
BigInt::from_i64(123).unwrap() => vec![Token::Str("123")],
BigInt::from_i64(-123).unwrap() => vec![Token::Str("-123")],
@@ -607,6 +619,15 @@ declare_tests! {
}
}
+#[cfg(feature = "nightly")]
+#[test]
+fn test_net_ipaddr() {
+ assert_de_tokens(
+ "1.2.3.4".parse::<net::IpAddr>().unwrap(),
+ vec![Token::Str("1.2.3.4")],
+ );
+}
+
#[test]
fn test_enum_error() {
assert_de_tokens_error::<Enum>(
diff --git a/serde_tests/tests/test_ser.rs b/serde_tests/tests/test_ser.rs
index e08d8c140..bf9bd1ead 100644
--- a/serde_tests/tests/test_ser.rs
+++ b/serde_tests/tests/test_ser.rs
@@ -1,4 +1,5 @@
use std::collections::BTreeMap;
+use std::net;
use std::path::{Path, PathBuf};
use std::str;
@@ -266,6 +267,17 @@ declare_ser_tests! {
Token::EnumMapEnd,
],
}
+ test_net_ipv4addr {
+ "1.2.3.4".parse::<net::Ipv4Addr>().unwrap() => &[Token::Str("1.2.3.4")],
+ }
+ test_net_ipv6addr {
+ "::1".parse::<net::Ipv6Addr>().unwrap() => &[Token::Str("::1")],
+ }
+ test_net_socketaddr {
+ "1.2.3.4:1234".parse::<net::SocketAddr>().unwrap() => &[Token::Str("1.2.3.4:1234")],
+ "1.2.3.4:1234".parse::<net::SocketAddrV4>().unwrap() => &[Token::Str("1.2.3.4:1234")],
+ "[::1]:1234".parse::<net::SocketAddrV6>().unwrap() => &[Token::Str("[::1]:1234")],
+ }
test_num_bigint {
BigInt::from_i64(123).unwrap() => &[Token::Str("123")],
BigInt::from_i64(-123).unwrap() => &[Token::Str("-123")],
@@ -307,6 +319,15 @@ declare_ser_tests! {
}
}
+#[cfg(feature = "nightly")]
+#[test]
+fn test_net_ipaddr() {
+ assert_ser_tokens(
+ "1.2.3.4".parse::<net::IpAddr>().unwrap(),
+ &[Token::Str("1.2.3.4")],
+ );
+}
+
#[test]
fn test_cannot_serialize_paths() {
let path = unsafe {
| [
"181"
] | serde-rs__serde-242 | Consider changing Ipv*Addr serialization to a tuple of integers from a string
Serde is missing support for `Ipv4Addr` and `Ipv6Addr`. It would be nice if we supported it and other `std::net` types. One open question though is how should we actually serialize IP addresses? It would be the most compact by serializing to a `u32` or `(u64, u64)`, or in pieces with `(u8, u8, u8, u8)` and 8 `u16`s, but I'm sure human consumable formats like markdown or JSON would prefer a textual format.
| 0.6 | c03587f0bf82b8c7c9e4b4c24304d5788206dbda | diff --git a/serde/src/de/impls.rs b/serde/src/de/impls.rs
index 4d8b95f89..4db468a88 100644
--- a/serde/src/de/impls.rs
+++ b/serde/src/de/impls.rs
@@ -14,6 +14,7 @@ use std::collections::{
use collections::enum_set::{CLike, EnumSet};
use std::hash::Hash;
use std::marker::PhantomData;
+use std::net;
use std::path;
use std::rc::Rc;
use std::str;
@@ -740,6 +741,83 @@ map_impl!(
///////////////////////////////////////////////////////////////////////////////
+#[cfg(feature = "nightly")]
+impl Deserialize for net::IpAddr {
+ fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+ where D: Deserializer,
+ {
+ let s = try!(String::deserialize(deserializer));
+ match s.parse() {
+ Ok(s) => Ok(s),
+ Err(err) => Err(D::Error::invalid_value(&err.to_string())),
+ }
+ }
+}
+
+impl Deserialize for net::Ipv4Addr {
+ fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+ where D: Deserializer,
+ {
+ let s = try!(String::deserialize(deserializer));
+ match s.parse() {
+ Ok(s) => Ok(s),
+ Err(err) => Err(D::Error::invalid_value(&err.to_string())),
+ }
+ }
+}
+
+impl Deserialize for net::Ipv6Addr {
+ fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+ where D: Deserializer,
+ {
+ let s = try!(String::deserialize(deserializer));
+ match s.parse() {
+ Ok(s) => Ok(s),
+ Err(err) => Err(D::Error::invalid_value(&err.to_string())),
+ }
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+impl Deserialize for net::SocketAddr {
+ fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+ where D: Deserializer,
+ {
+ let s = try!(String::deserialize(deserializer));
+ match s.parse() {
+ Ok(s) => Ok(s),
+ Err(err) => Err(D::Error::invalid_value(&err.to_string())),
+ }
+ }
+}
+
+impl Deserialize for net::SocketAddrV4 {
+ fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+ where D: Deserializer,
+ {
+ let s = try!(String::deserialize(deserializer));
+ match s.parse() {
+ Ok(s) => Ok(s),
+ Err(err) => Err(D::Error::invalid_value(&err.to_string())),
+ }
+ }
+}
+
+impl Deserialize for net::SocketAddrV6 {
+ fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
+ where D: Deserializer,
+ {
+ let s = try!(String::deserialize(deserializer));
+ match s.parse() {
+ Ok(s) => Ok(s),
+ Err(err) => Err(D::Error::invalid_value(&err.to_string())),
+ }
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
struct PathBufVisitor;
impl Visitor for PathBufVisitor {
diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs
index cc20f9b60..ac604936d 100644
--- a/serde/src/ser/impls.rs
+++ b/serde/src/ser/impls.rs
@@ -15,6 +15,7 @@ use collections::enum_set::{CLike, EnumSet};
use std::hash::Hash;
#[cfg(feature = "nightly")]
use std::iter;
+use std::net;
#[cfg(feature = "nightly")]
use std::num;
#[cfg(feature = "nightly")]
@@ -679,6 +680,65 @@ impl<T, E> Serialize for Result<T, E> where T: Serialize, E: Serialize {
///////////////////////////////////////////////////////////////////////////////
+#[cfg(feature = "nightly")]
+impl Serialize for net::IpAddr {
+ fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ where S: Serializer,
+ {
+ match *self {
+ net::IpAddr::V4(ref addr) => addr.serialize(serializer),
+ net::IpAddr::V6(ref addr) => addr.serialize(serializer),
+ }
+ }
+}
+
+impl Serialize for net::Ipv4Addr {
+ fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ where S: Serializer,
+ {
+ self.to_string().serialize(serializer)
+ }
+}
+
+impl Serialize for net::Ipv6Addr {
+ fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ where S: Serializer,
+ {
+ self.to_string().serialize(serializer)
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+impl Serialize for net::SocketAddr {
+ fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ where S: Serializer,
+ {
+ match *self {
+ net::SocketAddr::V4(ref addr) => addr.serialize(serializer),
+ net::SocketAddr::V6(ref addr) => addr.serialize(serializer),
+ }
+ }
+}
+
+impl Serialize for net::SocketAddrV4 {
+ fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ where S: Serializer,
+ {
+ self.to_string().serialize(serializer)
+ }
+}
+
+impl Serialize for net::SocketAddrV6 {
+ fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
+ where S: Serializer,
+ {
+ self.to_string().serialize(serializer)
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
impl Serialize for path::Path {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: Serializer,
| serde-rs/serde | 2016-02-22T03:06:33Z | `[127, 0, 0, 1]` is very human readable imo. As long as it's done with `serialize_tuple` and `serialize_u8` bincode will do the optimal thing (4 bytes) and json will do the readable thing. The same goes for ipv6.
The only issue I see is that some might prefer to output a `String` in the canonical `"127.0.0.1"` form. For deserialization that's a no-brainer, simply offer a deserialization for `String`s. But there's no way to serialize them this way.
I like the octet array version.
Versus text: Once some version of #198 (mapping proxies) lands then serde can add pre-built text mapper proxies that folks can opt in to with annotations.
Versus u32: Octet arrays look better in JSON. Also, arrays have the same endianness universally.
The type I'm really interested in is `Timespec`, which has the same basic requirements as `Ipv*Addr`. Serde could by default offer a mapping that very directly models the native shape `(i64, i32)`, and vend #198 mapping proxies with customizable formats for strings.
| d24b2c86f2c9b3f5036289d6c2c5764be57d2127 |
241 | diff --git a/serde_tests/tests/test_de.rs b/serde_tests/tests/test_de.rs
index dcc6e8f00..568bfaea1 100644
--- a/serde_tests/tests/test_de.rs
+++ b/serde_tests/tests/test_de.rs
@@ -8,7 +8,13 @@ use num::rational::Ratio;
use serde::de::{Deserializer, Visitor};
-use token::{Token, assert_de_tokens, assert_de_tokens_ignore};
+use token::{
+ Error,
+ Token,
+ assert_de_tokens,
+ assert_de_tokens_ignore,
+ assert_de_tokens_error,
+};
//////////////////////////////////////////////////////////////////////////
@@ -600,3 +606,13 @@ declare_tests! {
],
}
}
+
+#[test]
+fn test_enum_error() {
+ assert_de_tokens_error::<Enum>(
+ vec![
+ Token::EnumUnit("Enum", "Foo"),
+ ],
+ Error::UnknownVariantError("Foo".to_owned()),
+ )
+}
diff --git a/serde_tests/tests/token.rs b/serde_tests/tests/token.rs
index 40810d47d..30d623be8 100644
--- a/serde_tests/tests/token.rs
+++ b/serde_tests/tests/token.rs
@@ -371,6 +371,7 @@ pub enum Error {
SyntaxError,
EndOfStreamError,
UnknownFieldError(String),
+ UnknownVariantError(String),
MissingFieldError(&'static str),
InvalidName(&'static str),
InvalidValue(String),
@@ -395,6 +396,10 @@ impl de::Error for Error {
Error::UnknownFieldError(field.to_owned())
}
+ fn unknown_variant(variant: &str) -> Error {
+ Error::UnknownVariantError(variant.to_owned())
+ }
+
fn missing_field(field: &'static str) -> Error {
Error::MissingFieldError(field)
}
| [
"169"
] | serde-rs__serde-241 | Add an `Error::unknown_variant` error
Semantically speaking, it is incorrect for deserializing a variant to error out with an `unknown_field` error. It would be better expressed as an `unknown_variant` error. Without this, certain implementations of #44 may not properly handle unknown variants.
| 0.6 | 4d10eef55df49ba3d5f7b834750592f27800d0f7 | diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs
index 11050648e..142502b77 100644
--- a/serde/src/de/mod.rs
+++ b/serde/src/de/mod.rs
@@ -32,10 +32,19 @@ pub trait Error: Sized + error::Error {
fn end_of_stream() -> Self;
/// Raised when a `Deserialize` struct type received an unexpected struct field.
- fn unknown_field(field: &str) -> Self;
+ fn unknown_field(field: &str) -> Self {
+ Error::syntax(&format!("Unknown field `{}`", field))
+ }
+
+ /// Raised when a `Deserialize` enum type received an unexpected variant.
+ fn unknown_variant(field: &str) -> Self {
+ Error::syntax(&format!("Unknown variant `{}`", field))
+ }
- /// Raised when a `Deserialize` struct type did not receive a field.
- fn missing_field(field: &'static str) -> Self;
+ /// raised when a `deserialize` struct type did not receive a field.
+ fn missing_field(field: &'static str) -> Self {
+ Error::syntax(&format!("Missing field `{}`", field))
+ }
}
/// `Type` represents all the primitive types that can be deserialized. This is used by
diff --git a/serde_codegen/src/de.rs b/serde_codegen/src/de.rs
index bc53153e4..a94fd02bb 100644
--- a/serde_codegen/src/de.rs
+++ b/serde_codegen/src/de.rs
@@ -566,6 +566,7 @@ fn deserialize_item_enum(
.collect()
),
container_attrs,
+ true,
);
let variants_expr = builder.expr().ref_().slice()
@@ -807,6 +808,7 @@ fn deserialize_field_visitor(
builder: &aster::AstBuilder,
field_names: Vec<P<ast::Expr>>,
container_attrs: &attr::ContainerAttrs,
+ is_variant: bool,
) -> Vec<P<ast::Item>> {
// Create the field names for the fields.
let field_idents: Vec<ast::Ident> = (0 .. field_names.len())
@@ -838,10 +840,16 @@ fn deserialize_field_visitor(
})
.collect();
+ let (index_error_msg, unknown_ident) = if is_variant {
+ (builder.expr().str("expected a variant"), builder.id("unknown_variant"))
+ } else {
+ (builder.expr().str("expected a field"), builder.id("unknown_field"))
+ };
+
let index_body = quote_expr!(cx,
match value {
$index_field_arms
- _ => { Err(::serde::de::Error::syntax("expected a field")) }
+ _ => { Err(::serde::de::Error::syntax($index_error_msg)) }
}
);
@@ -853,10 +861,10 @@ fn deserialize_field_visitor(
})
.collect();
- let fallthrough_arm_expr = if !container_attrs.deny_unknown_fields() {
+ let fallthrough_arm_expr = if !is_variant && !container_attrs.deny_unknown_fields() {
quote_expr!(cx, Ok(__Field::__ignore))
} else {
- quote_expr!(cx, Err(::serde::de::Error::unknown_field(value)))
+ quote_expr!(cx, Err(::serde::de::Error::$unknown_ident(value)))
};
let str_body = quote_expr!(cx,
@@ -947,7 +955,8 @@ fn deserialize_struct_visitor(
cx,
builder,
try!(field_exprs),
- container_attrs
+ container_attrs,
+ false,
);
let visit_map_expr = try!(deserialize_map(
| serde-rs/serde | 2016-02-22T00:28:03Z | d24b2c86f2c9b3f5036289d6c2c5764be57d2127 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.