Compare commits

...

132 Commits

Author SHA1 Message Date
David Tolnay c334c1c7b5 Release 0.9.0-rc3 2017-01-23 19:14:02 -08:00
David Tolnay 92668d7061 Serialize T by ref 2017-01-23 17:11:18 -08:00
David Tolnay b9d865d8e7 Merge pull request #715 from serde-rs/nostd
Support serde_derive on no_std
2017-01-23 16:13:25 -08:00
David Tolnay fc4e370ba9 Support serde_derive on no_std 2017-01-23 16:03:06 -08:00
Oliver Schneider a982d27536 Merge pull request #700 from serde-rs/usize
Restore visit_usize and visit_bytes for identifying variants
2017-01-23 11:27:06 +01:00
Oliver Schneider dc87826298 Merge pull request #699 from serde-rs/fields
Remove visit_usize from Duration impl
2017-01-23 11:26:18 +01:00
David Tolnay a09a8a039a All combinations of features compile without warnings 2017-01-23 01:45:54 -08:00
David Tolnay ea702755a2 Merge branch master into origin/usize
Conflicts:
    serde_codegen/src/de.rs
    testing/tests/test_de.rs
2017-01-23 01:36:49 -08:00
David Tolnay d161911c63 Merge branch master into origin/fields
Conflicts:
    serde/src/de/impls.rs
2017-01-23 01:28:01 -08:00
Oliver Schneider e27553d3df Merge pull request #710 from serde-rs/errors
Errors redesign
2017-01-23 10:25:48 +01:00
David Tolnay 48eaf988bc Add free-form option for Unexpected 2017-01-22 05:02:24 -08:00
David Tolnay 73a364d4fd Capture byte value for error message 2017-01-22 04:57:12 -08:00
David Tolnay 6dfdcb6ba1 Merge pull request #713 from serde-rs/zero
Suppress warning about using num::Zero
2017-01-21 19:20:57 -08:00
David Tolnay 089c7eb1d7 Suppress warning about using num::Zero 2017-01-21 19:14:56 -08:00
David Tolnay 1e05fc2145 Release 0.9.0-rc2 2017-01-21 16:30:13 -08:00
David Tolnay 977612d8dd Merge branch origin/missing into origin/errors 2017-01-21 16:28:24 -08:00
David Tolnay 5855078703 Fix backward invalid_length messages in value deserializer 2017-01-21 14:38:33 -08:00
David Tolnay 3c88a93fb2 Fix the filtered error messages 2017-01-21 12:34:04 -08:00
David Tolnay 530c29466e Merge pull request #711 from serde-rs/names
Filter the slice of expected field and variant names
2017-01-21 12:25:43 -08:00
David Tolnay ea99e8b686 Filter the slice of expected field and variant names 2017-01-21 12:18:55 -08:00
David Tolnay 2a148112d4 Fix Box<str> use on no_std 2017-01-21 10:17:48 -08:00
David Tolnay a4126e4c5a Errors 2017-01-21 09:13:01 -08:00
David Tolnay d1325862f7 Merge tag v0.8.23 into master
Conflicts:
    serde/Cargo.toml
    serde_codegen/Cargo.toml
    serde_derive/Cargo.toml
    serde_test/Cargo.toml
    testing/Cargo.toml
2017-01-20 15:29:32 -08:00
David Tolnay 1f65ce75ec Release 0.8.23 2017-01-20 15:25:57 -08:00
Jake Goulding 9536e52aa6 Add categories to Cargo.toml 2017-01-20 15:09:11 -08:00
Oliver Schneider be0c755731 Merge pull request #705 from serde-rs/inlineseed
Inline <PhantomData<T> as DeserializeSeed>::deserialize
2017-01-20 14:34:24 +01:00
David Tolnay 42bc63bed8 Standardize behavior of missing fields 2017-01-20 00:44:43 -08:00
David Tolnay e41b940a3d Inline <PhantomData<T> as DeserializeSeed>::deserialize 2017-01-19 16:17:27 -08:00
David Tolnay 88149fc0c3 Fix key and value seed variable names
Rename fail.
2017-01-19 13:44:18 -08:00
David Tolnay 5ecfb3b388 Update serde_test to use seeds 2017-01-19 01:24:33 -08:00
David Tolnay 13a9f929de Stateful deserialization 2017-01-19 01:17:59 -08:00
David Tolnay e40fbe0767 Restore visit_bytes for Duration impl 2017-01-18 21:13:51 -08:00
David Tolnay 0a10116bf5 Restore visit_bytes for identifying variants and fields 2017-01-18 21:11:51 -08:00
David Tolnay b1fbbfd3ce Restore visit_usize for identifying variants 2017-01-17 23:52:06 -08:00
David Tolnay 984ebcead0 Remove visit_usize and visit_bytes for Duration impl 2017-01-17 23:32:28 -08:00
David Tolnay aa88f01cdc Merge pull request #697 from serde-rs/vanity
cleanup some deprecation warnings
2017-01-17 09:26:44 -08:00
David Tolnay 13794c1b48 Stop testing on rust 1.12.0 2017-01-17 09:19:39 -08:00
Oliver Schneider b5e64abba1 cleanup some deprecation warnings 2017-01-17 14:29:33 +01:00
David Tolnay 503ce310f5 Merge pull request #692 from serde-rs/byte_buf
add missing `Vec<u8>` deserialization hint to `Deserializer`
2017-01-16 08:10:25 -08:00
Oliver Schneider b26f291d93 add missing Vec<u8> deserialization hint to Deserializer 2017-01-16 16:55:13 +01:00
David Tolnay bc6bc9e3f0 Remove LICENSE file in favor of LICENSE-MIT and LICENSE-APACHE
This repo no longer contains bench_log referenced in this file.
2017-01-15 10:16:57 -08:00
David Tolnay 3a52364f3e Release 0.9.0-rc1 2017-01-15 09:26:44 -08:00
David Tolnay 4d1627fc96 Merge pull request #687 from serde-rs/ser
Enforce correct use of Serialize trait
2017-01-15 09:22:30 -08:00
David Tolnay 7c04bf36d9 Merge pull request #686 from serde-rs/de
Enforce correct use of Deserialize trait
2017-01-15 07:30:14 -08:00
David Tolnay 4b06030666 Unabbreviated method naming 2017-01-14 21:39:37 -08:00
David Tolnay a5a04306f2 Update tests for Serializer changes 2017-01-14 16:07:43 -08:00
David Tolnay f9885c4826 Update serde_codegen for Serializer changes 2017-01-14 16:07:34 -08:00
David Tolnay 04f25eb122 Update serde_test for Serializer changes 2017-01-14 16:07:17 -08:00
David Tolnay 2fea5f3e1c Enforce correct use of Serialize trait 2017-01-14 15:21:31 -08:00
David Tolnay 905b2c3cf3 Expose VariantVisitor for the StrDeserializer 2017-01-14 14:17:46 -08:00
David Tolnay d5b428a087 Fix imports for stable compiler 2017-01-14 14:16:01 -08:00
David Tolnay b3b8056d93 Update tests for Deserializer changes 2017-01-14 13:42:49 -08:00
David Tolnay 137cf9bab8 Update serde_codegen for Deserializer changes 2017-01-14 13:42:48 -08:00
David Tolnay 7372f152bd Update serde_test for Deserializer changes 2017-01-14 13:42:45 -08:00
David Tolnay a43da15b74 Merge pull request #685 from mineo/patch-1
Typo: aggrergate -> aggregate
2017-01-14 13:36:49 -08:00
Wieland Hoffmann 212cbbd8bf Typo: aggrergate -> aggregate 2017-01-14 22:33:31 +01:00
David Tolnay 738aa31733 Enforce correct use of Deserialize trait 2017-01-14 12:16:08 -08:00
Oliver Schneider 787ecc6a82 Merge pull request #684 from serde-rs/end
Remove SeqVisitor::end() and MapVisitor::end()
2017-01-14 08:01:53 +01:00
David Tolnay 9fc8a86bcc Exclude serde-syntex-example until serde_json has been updated 2017-01-13 13:34:41 -08:00
David Tolnay 800442a75e Handle visitor that does not need to be mutable 2017-01-13 13:34:39 -08:00
David Tolnay 88debb3fb8 Remove SeqVisitor::end() and MapVisitor::end() 2017-01-13 13:34:38 -08:00
David Tolnay 88a4ed9cd7 Include missing_field in impl MapVisitor for &mut MapVisitor 2017-01-13 13:33:37 -08:00
David Tolnay bdba6fc5b0 Remove the proc_macro feature gate in serde-syntex-example 2017-01-13 10:27:51 -08:00
Oliver Schneider dec116311e Merge pull request #682 from serde-rs/unknown
Treat skipped fields as unknown
2017-01-13 10:46:18 +01:00
David Tolnay 8c49e6d6a5 Resolve conflict between rename changes and skip changes 2017-01-13 01:27:07 -08:00
David Tolnay 7cc24a43fb Merge branch master into unknown
Conflicts:
    serde_codegen/src/de.rs
2017-01-13 01:23:00 -08:00
David Tolnay c008c6d3a8 Merge pull request #681 from serde-rs/deserialize_struct_bug
fix various serde(rename) bugs
2017-01-13 01:21:46 -08:00
David Tolnay c9f5d08ed1 Add test for all variants skipped 2017-01-13 01:14:03 -08:00
David Tolnay fff6c9cb66 Add tests for all fields skipped 2017-01-13 01:12:31 -08:00
David Tolnay cb5e7c6264 Fix case of skipped variant followed by other variants 2017-01-12 23:35:39 -08:00
David Tolnay 4ef1128546 More explicit about argument to deserialize_field_visitor 2017-01-12 23:30:57 -08:00
David Tolnay 227bea1d0b Treat skipped fields as unknown 2017-01-12 23:17:45 -08:00
David Tolnay 766ede965e Eliminate collects in codegen for deserializing map 2017-01-12 21:52:56 -08:00
David Tolnay eb5a49e380 Use helper function to build __field{} 2017-01-12 21:49:20 -08:00
David Tolnay 2df529cac5 Simplify codegen logic in deserializing seq 2017-01-12 21:41:27 -08:00
David Tolnay 4b66463011 Eliminate collect in deserializing seq 2017-01-12 21:29:50 -08:00
David Tolnay b907cfef85 Eliminate collect in visitor generics 2017-01-12 21:28:09 -08:00
David Tolnay 506c8cc087 Simplify the trait paths used in bounds 2017-01-12 21:24:51 -08:00
David Tolnay 3951ef91c0 Don't need aster to construct syn::Ident 2017-01-12 21:15:13 -08:00
David Tolnay b0d20afdfb Merge pull request #680 from serde-rs/oli-obk-patch-1
make `ser::iterator` more general by taking `IntoIterator`
2017-01-12 16:45:39 -08:00
Oliver Schneider 5e6ee523d2 remove duplicate into_iter 2017-01-12 21:52:38 +01:00
Oliver Schneider a07b6bd9e7 also use the renamed variant names during deserialization 2017-01-12 20:21:59 +01:00
Oliver Schneider 8dd06eed2f type inference failure 2017-01-12 20:19:00 +01:00
Oliver Schneider 5b668ed87a attempt to test the field names, but deem it too complex and opt to at least improve the code 2017-01-12 20:17:55 +01:00
Oliver Schneider abe305dbfe fix deserialize_struct passing the original field names instead of the renamed ones 2017-01-12 20:17:02 +01:00
Oliver Schneider 2d1a60c056 Update the Serialize impl, too 2017-01-12 20:06:44 +01:00
Oliver Schneider 5edfdba940 use IntoIterator everywhere 2017-01-12 20:05:26 +01:00
Oliver Schneider 756bff534f make ser::iterator more general by taking IntoIterator 2017-01-12 19:24:35 +01:00
David Tolnay 110d36fa14 Merge pull request #679 from oli-obk/iterators
add wrapper to serde that allows serializing iterators as sequences
2017-01-12 10:19:09 -08:00
Oliver Schneider 8c576fe9fb rename IteratorSerializer to Iterator 2017-01-12 17:29:04 +01:00
Oliver Schneider b860d3cb1f fix tests on stable 2017-01-12 16:06:26 +01:00
Oliver Schneider dced4416a7 add wrapper to serde that allows serializing iterators as sequences 2017-01-12 15:31:40 +01:00
David Tolnay ca47eb929c Merge pull request #678 from serde-rs/empty
Handle various degenerate cases
2017-01-11 11:45:24 -08:00
David Tolnay b01c23b5ee Also provide a smarter alternative for the other impossible case 2017-01-11 11:34:47 -08:00
David Tolnay 3aaf29c846 Remove ref in top-level let pattern
Discouraged by Clippy.
2017-01-11 11:12:53 -08:00
David Tolnay d2eea87001 Handle various degenerate cases 2017-01-11 11:02:24 -08:00
David Tolnay 8242c64152 Merge branch v0.8 into master 2017-01-10 17:16:31 -08:00
David Tolnay 9e45bd8c87 Release 0.8.22 2017-01-10 17:10:26 -08:00
Oliver Schneider 405b534254 Merge pull request #674 from serde-rs/nonascii
Add test for non ascii idents
2017-01-10 11:16:19 +01:00
David Tolnay d34be74dfd Add test for non ascii idents 2017-01-10 01:20:01 -08:00
David Tolnay c475df8320 Encourage GitHub issues 2017-01-09 14:44:36 -08:00
Oliver Schneider 2b8a620807 Merge pull request #671 from serde-rs/fields
Stop generating visit_usize and visit_bytes for FieldVisitor
2017-01-09 13:09:18 +01:00
David Tolnay 1cd6aee562 Merge pull request #670 from serde-rs/error
Stop exporting serde::de::Error as serde::Error
2017-01-09 00:45:04 -08:00
David Tolnay 90d4d7b37b Restore the old FieldVisitor tests as error tests 2017-01-09 00:43:13 -08:00
David Tolnay 1f8b803607 Repetition for field visitor arms 2017-01-09 00:37:37 -08:00
David Tolnay 516cc8b04e Stop generating visit_usize and visit_bytes for FieldVisitor 2017-01-08 01:01:56 -08:00
David Tolnay 0676477cd7 Stop exporting serde::de::Error as serde::Error 2017-01-08 00:50:07 -08:00
David Tolnay 4193122472 Use the more concise paths in generated code 2017-01-08 00:47:44 -08:00
David Tolnay eb6fb1d40e Merge pull request #523 from serde-rs/enum
Enum deserialization API
2017-01-08 00:45:50 -08:00
David Tolnay bf873a7b3f Merge branch origin/master into origin/enum
Conflicts:
    serde/src/de/mod.rs
    serde_codegen/src/de.rs
    testing/tests/test_bytes.rs
2017-01-08 00:31:07 -08:00
David Tolnay fbd4a17467 Merge pull request #664 from serde-rs/visitor-value
Remove the Deserialize trait bound on Visitor::Value
2017-01-08 00:24:53 -08:00
David Tolnay ad34c14c8c Prepare for 0.9 breaking changes 2017-01-08 00:18:53 -08:00
David Tolnay e461a23798 Not intended to be published 2017-01-08 00:18:37 -08:00
David Tolnay 894a21bc1f Remove the proc_macro feature gate 2017-01-08 00:11:11 -08:00
David Tolnay 1ecf3730ee Update to syntex 0.54 2017-01-06 01:26:51 -08:00
David Tolnay 7a0e8f73b4 Remove the Deserialize trait bound on Visitor::Value 2017-01-03 01:50:10 -08:00
Erick Tryzelaar b6e8b58cb2 Stop testing on 1.11 2017-01-02 14:59:00 -08:00
Oliver Schneider a3f556959f Merge pull request #652 from serde-rs/bbstr
Support deserializing ByteBuf from string
2016-12-25 01:09:15 +01:00
David Tolnay 9338c4f1b9 Release 0.8.21 2016-12-24 13:10:24 -05:00
David Tolnay 28d67f4172 Format variant-skip message only if variant is skipped 2016-12-24 13:10:06 -05:00
David Tolnay 2401ae61a8 Update to syntex 0.52 2016-12-24 12:42:23 -05:00
David Tolnay 57d3fce0c6 Further simplify variant serialization patterns 2016-12-24 12:28:46 -05:00
David Tolnay a020cceed8 Simplify variant serialize patterns 2016-12-24 12:22:45 -05:00
David Tolnay 49e985eb90 Update message for skipped enum variant 2016-12-24 12:16:28 -05:00
David Tolnay 63def96c66 Merge pull request #653 from shinglyu/skip_se
Implement skip_serializing for enum variant
2016-12-24 11:40:21 -05:00
Shing Lyu 2fea8c9c28 Implement skip_serializing for enum variant 2016-12-24 22:34:22 +08:00
David Tolnay b7ea213926 Support nostd for ByteBuf from String 2016-12-23 23:30:27 -05:00
David Tolnay 871fb5adee Support deserializing ByteBuf from string 2016-12-23 23:17:42 -05:00
David Tolnay 2c984980a0 Link to release notes from readme 2016-12-22 21:52:37 -05:00
David Tolnay 36f07912b8 Remove no-longer-necessary cfg
This was fixed in Rust, allowing proc macro crates to be tested.
2016-12-17 17:32:11 -08:00
David Tolnay 7222cf7514 Ignore warning from unused enum variant 2016-12-17 17:31:11 -08:00
David Tolnay 85f1bf0259 Enum deserialization API 2016-08-23 22:17:28 -04:00
52 changed files with 3026 additions and 2655 deletions
+4 -4
View File
@@ -1,8 +1,7 @@
sudo: false
language: rust
rust:
- 1.11.0
- 1.12.0
- 1.13.0
- stable
- beta
- nightly
@@ -19,8 +18,9 @@ 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 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_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)
env:
global:
-33
View File
@@ -1,33 +0,0 @@
See LICENSE-APACHE and LICENSE-MIT.
----
bench_log is derived from https://github.com/cloudflare/goser, which has the
following license:
Copyright (c) 2013, CloudFlare, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+4 -4
View File
@@ -11,12 +11,11 @@ You may be looking for:
- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html)
- [Examples](https://serde.rs/examples.html)
- [API documentation](https://docs.serde.rs/serde/)
- [Release notes](https://github.com/serde-rs/serde/releases)
## Serde in action
```rust
#![feature(proc_macro)]
#[macro_use]
extern crate serde_derive;
@@ -50,8 +49,9 @@ fn main() {
Serde developers live in the #serde channel on
[`irc.mozilla.org`](https://wiki.mozilla.org/IRC). The #rust channel is also a
good resource with generally faster response time but less specific knowledge
about Serde. If IRC is not your thing, we are happy to respond to [GitHub
issues](https://github.com/serde-rs/serde/issues/new) as well.
about Serde. If IRC is not your thing or you don't get a good response, we are
happy to respond to [GitHub issues](https://github.com/serde-rs/serde/issues/new)
as well.
## License
+1
View File
@@ -3,6 +3,7 @@ name = "serde-syntex-example"
version = "0.1.0"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
build = "build.rs"
publish = false
[features]
default = ["serde_codegen"]
@@ -1,5 +1,3 @@
#![cfg_attr(feature = "serde_derive", feature(proc_macro))]
#[cfg(feature = "serde_derive")]
#[macro_use]
extern crate serde_derive;
+2 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "serde"
version = "0.8.20"
version = "0.9.0-rc3"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "A generic serialization/deserialization framework"
@@ -9,6 +9,7 @@ repository = "https://github.com/serde-rs/serde"
documentation = "https://docs.serde.rs/serde/"
readme = "../README.md"
keywords = ["serde", "serialization"]
categories = ["encoding"]
include = ["Cargo.toml", "src/**/*.rs"]
[features]
+26 -12
View File
@@ -65,7 +65,7 @@ impl<'a> ops::Deref for Bytes<'a> {
impl<'a> ser::Serialize for Bytes<'a> {
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer
{
serializer.serialize_bytes(self.bytes)
@@ -84,7 +84,7 @@ mod bytebuf {
use de;
#[cfg(feature = "collections")]
use collections::Vec;
use collections::{String, Vec};
/// `ByteBuf` wraps a `Vec<u8>` and serializes as a byte array.
#[derive(Clone, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
@@ -168,7 +168,7 @@ mod bytebuf {
}
impl ser::Serialize for ByteBuf {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer
{
serializer.serialize_bytes(self)
@@ -181,15 +181,19 @@ 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>(&mut self) -> Result<ByteBuf, E>
fn visit_unit<E>(self) -> Result<ByteBuf, E>
where E: de::Error,
{
Ok(ByteBuf::new())
}
#[inline]
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<ByteBuf, V::Error>
fn visit_seq<V>(self, mut visitor: V) -> Result<ByteBuf, V::Error>
where V: de::SeqVisitor,
{
let (len, _) = visitor.size_hint();
@@ -199,20 +203,30 @@ mod bytebuf {
values.push(value);
}
try!(visitor.end());
Ok(ByteBuf::from(values))
}
#[inline]
fn visit_bytes<E>(&mut self, v: &[u8]) -> Result<ByteBuf, E>
fn visit_bytes<E>(self, v: &[u8]) -> Result<ByteBuf, E>
where E: de::Error,
{
self.visit_byte_buf(v.to_vec())
Ok(ByteBuf::from(v))
}
#[inline]
fn visit_byte_buf<E>(&mut self, v: Vec<u8>) -> Result<ByteBuf, E>
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<ByteBuf, E>
where E: de::Error,
{
Ok(ByteBuf::from(v))
}
fn visit_str<E>(self, v: &str) -> Result<ByteBuf, E>
where E: de::Error,
{
Ok(ByteBuf::from(v))
}
fn visit_string<E>(self, v: String) -> Result<ByteBuf, E>
where E: de::Error,
{
Ok(ByteBuf::from(v))
@@ -221,10 +235,10 @@ mod bytebuf {
impl de::Deserialize for ByteBuf {
#[inline]
fn deserialize<D>(deserializer: &mut D) -> Result<ByteBuf, D::Error>
fn deserialize<D>(deserializer: D) -> Result<ByteBuf, D::Error>
where D: de::Deserializer
{
deserializer.deserialize_bytes(ByteBufVisitor)
deserializer.deserialize_byte_buf(ByteBufVisitor)
}
}
}
+225 -214
View File
File diff suppressed because it is too large Load Diff
+781 -331
View File
File diff suppressed because it is too large Load Diff
+40
View File
@@ -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)
}
+337 -397
View File
File diff suppressed because it is too large Load Diff
-29
View File
@@ -1,30 +1,7 @@
//! 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.
#[cfg(feature = "unstable")]
pub trait Error: Debug + Display + ::core::marker::Reflect {
/// A short description of the error.
///
/// The description should not contain newlines or sentence-ending
/// punctuation, to facilitate embedding in larger user-facing
/// strings.
fn description(&self) -> &str;
/// The lower-level cause of this error, if any.
fn cause(&self) -> Option<&Error> { None }
/// Get the `TypeId` of `self`
#[doc(hidden)]
fn type_id(&self) -> TypeId where Self: 'static {
TypeId::of::<Self>()
}
}
/// A stand-in for `std::error::Error`, which requires no allocation.
#[cfg(not(feature = "unstable"))]
pub trait Error: Debug + Display {
/// A short description of the error.
///
@@ -35,10 +12,4 @@ pub trait Error: Debug + Display {
/// The lower-level cause of this error, if any.
fn cause(&self) -> Option<&Error> { None }
/// Stubbed! Returns type_id of `()`
#[doc(hidden)]
fn type_id(&self) -> TypeId where Self: 'static {
TypeId::of::<()>()
}
}
+33
View File
@@ -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}")
}
+16 -18
View File
@@ -11,39 +11,33 @@
#![doc(html_root_url="https://docs.serde.rs")]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "unstable", feature(reflect_marker, unicode, nonzero, plugin, step_trait, zero_one))]
#![cfg_attr(feature = "unstable", feature(nonzero, inclusive_range, zero_one))]
#![cfg_attr(feature = "alloc", feature(alloc))]
#![cfg_attr(feature = "collections", feature(collections, enumset))]
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![cfg_attr(feature = "clippy", allow(linkedlist))]
#![cfg_attr(any(not(feature = "std"), feature = "unstable"), allow(unused_variables, unused_imports, unused_features, dead_code))]
#![cfg_attr(feature = "clippy", allow(linkedlist, type_complexity))]
#![deny(missing_docs)]
#[cfg(all(feature = "unstable", feature = "collections"))]
#[cfg(feature = "collections")]
extern crate collections;
#[cfg(all(feature = "unstable", feature = "alloc"))]
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "unstable")]
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};
usize, f32, f64, char, str, num, slice, iter, cell, default, result};
#[cfg(feature = "unstable")]
extern crate core;
#[cfg(feature = "unstable")]
pub use self::core::nonzero;
pub use actual_core::nonzero;
}
pub use ser::{Serialize, Serializer};
pub use de::{Deserialize, Deserializer, Error};
#[cfg(not(feature = "std"))]
macro_rules! format {
($s:expr, $($rest:tt)*) => ($s)
}
pub use de::{Deserialize, Deserializer};
#[macro_use]
mod macros;
@@ -53,6 +47,10 @@ pub mod de;
#[cfg(feature = "std")]
pub mod iter;
pub mod ser;
#[cfg(not(feature = "std"))]
#[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;
+9 -34
View File
@@ -4,7 +4,7 @@
macro_rules! forward_to_deserialize_method {
($func:ident($($arg:ty),*)) => {
#[inline]
fn $func<__V>(&mut self, $(_: $arg,)* visitor: __V) -> ::std::result::Result<__V::Value, Self::Error>
fn $func<__V>(self, $(_: $arg,)* visitor: __V) -> ::std::result::Result<__V::Value, Self::Error>
where __V: $crate::de::Visitor
{
self.deserialize(visitor)
@@ -18,7 +18,7 @@ macro_rules! forward_to_deserialize_method {
macro_rules! forward_to_deserialize_method {
($func:ident($($arg:ty),*)) => {
#[inline]
fn $func<__V>(&mut self, $(_: $arg,)* visitor: __V) -> ::core::result::Result<__V::Value, Self::Error>
fn $func<__V>(self, $(_: $arg,)* visitor: __V) -> ::core::result::Result<__V::Value, Self::Error>
where __V: $crate::de::Visitor
{
self.deserialize(visitor)
@@ -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 {
@@ -120,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()}
};
@@ -141,12 +116,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`.
@@ -156,7 +131,7 @@ macro_rules! forward_to_deserialize_helper {
///
/// ```rust,ignore
/// impl Deserializer for MyDeserializer {
/// fn deserialize<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
/// fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
/// where V: Visitor
/// {
/// /* ... */
+143 -70
View File
@@ -30,19 +30,18 @@ use collections::{
Vec,
};
#[cfg(all(feature = "unstable", feature = "collections"))]
#[cfg(feature = "collections")]
use collections::enum_set::{CLike, EnumSet};
#[cfg(all(feature = "unstable", feature = "collections"))]
#[cfg(feature = "collections")]
use collections::borrow::ToOwned;
#[cfg(feature = "std")]
use core::hash::{Hash, BuildHasher};
#[cfg(feature = "unstable")]
use core::iter;
#[cfg(feature = "std")]
use std::net;
#[cfg(feature = "unstable")]
use core::num;
#[cfg(feature = "unstable")]
use core::ops;
#[cfg(feature = "std")]
use std::path;
@@ -67,10 +66,16 @@ use core::marker::PhantomData;
use core::nonzero::{NonZero, Zeroable};
use super::{
Error,
Serialize,
SerializeSeq,
SerializeTuple,
Serializer,
};
#[cfg(any(feature = "std", feature = "unstable"))]
use super::Error;
#[cfg(feature = "unstable")]
use super::Iterator;
///////////////////////////////////////////////////////////////////////////////
@@ -78,7 +83,7 @@ macro_rules! impl_visit {
($ty:ty, $method:ident) => {
impl Serialize for $ty {
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
serializer.$method(*self)
@@ -106,7 +111,7 @@ impl_visit!(char, serialize_char);
impl Serialize for str {
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
serializer.serialize_str(self)
@@ -116,7 +121,7 @@ impl Serialize for str {
#[cfg(any(feature = "std", feature = "collections"))]
impl Serialize for String {
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
(&self[..]).serialize(serializer)
@@ -125,9 +130,11 @@ impl Serialize for String {
///////////////////////////////////////////////////////////////////////////////
impl<T> Serialize for Option<T> where T: Serialize {
impl<T> Serialize for Option<T>
where T: Serialize
{
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
match *self {
@@ -141,7 +148,7 @@ impl<T> Serialize for Option<T> where T: Serialize {
impl<T> Serialize for PhantomData<T> {
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
serializer.serialize_unit_struct("PhantomData")
@@ -155,14 +162,14 @@ impl<T> Serialize for [T]
where T: Serialize,
{
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
let mut state = try!(serializer.serialize_seq(Some(self.len())));
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
for e in self {
try!(serializer.serialize_seq_elt(&mut state, e));
try!(seq.serialize_element(e));
}
serializer.serialize_seq_end(state)
seq.end()
}
}
@@ -172,14 +179,14 @@ macro_rules! array_impls {
($len:expr) => {
impl<T> Serialize for [T; $len] where T: Serialize {
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
let mut state = try!(serializer.serialize_seq_fixed_size($len));
let mut seq = try!(serializer.serialize_seq_fixed_size($len));
for e in self {
try!(serializer.serialize_seq_elt(&mut state, e));
try!(seq.serialize_element(e));
}
serializer.serialize_seq_end(state)
seq.end()
}
}
}
@@ -221,17 +228,44 @@ array_impls!(32);
///////////////////////////////////////////////////////////////////////////////
#[cfg(feature = "unstable")]
impl<'a, I> Serialize for Iterator<I>
where I: IntoIterator, <I as IntoIterator>::Item: Serialize
{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
// FIXME: use specialization to prevent invalidating the object in case of clonable iterators?
let iter = match self.0.borrow_mut().take() {
Some(iter) => iter.into_iter(),
None => return Err(Error::custom("Iterator used twice")),
};
let size = match iter.size_hint() {
(lo, Some(hi)) if lo == hi => Some(lo),
_ => None,
};
let mut seq = try!(serializer.serialize_seq(size));
for e in iter {
try!(seq.serialize_element(&e));
}
seq.end()
}
}
///////////////////////////////////////////////////////////////////////////////
macro_rules! serialize_seq {
() => {
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
let mut state = try!(serializer.serialize_seq(Some(self.len())));
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
for e in self {
try!(serializer.serialize_seq_elt(&mut state, e));
try!(seq.serialize_element(&e));
}
serializer.serialize_seq_end(state)
seq.end()
}
}
}
@@ -250,7 +284,7 @@ impl<T> Serialize for BTreeSet<T>
serialize_seq!();
}
#[cfg(all(feature = "unstable", feature = "collections"))]
#[cfg(feature = "collections")]
impl<T> Serialize for EnumSet<T>
where T: Serialize + CLike
{
@@ -273,30 +307,50 @@ impl<T> Serialize for LinkedList<T>
}
#[cfg(any(feature = "std", feature = "collections"))]
impl<T> Serialize for Vec<T> where T: Serialize {
impl<T> Serialize for Vec<T>
where T: Serialize
{
serialize_seq!();
}
#[cfg(any(feature = "std", feature = "collections"))]
impl<T> Serialize for VecDeque<T> where T: Serialize {
impl<T> Serialize for VecDeque<T>
where T: Serialize
{
serialize_seq!();
}
#[cfg(feature = "unstable")]
impl<A> Serialize for ops::Range<A>
where A: Serialize + Clone + iter::Step + num::One,
for<'a> &'a A: ops::Add<&'a A, Output = A>,
where ops::Range<A>: ExactSizeIterator + iter::Iterator<Item = A> + Clone,
A: Serialize,
{
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
let len = iter::Step::steps_between(&self.start, &self.end, &A::one());
let mut state = try!(serializer.serialize_seq(len));
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
for e in self.clone() {
try!(serializer.serialize_seq_elt(&mut state, e));
try!(seq.serialize_element(&e));
}
serializer.serialize_seq_end(state)
seq.end()
}
}
#[cfg(feature = "unstable")]
impl<A> Serialize for ops::RangeInclusive<A>
where ops::RangeInclusive<A>: ExactSizeIterator + iter::Iterator<Item = A> + Clone,
A: Serialize,
{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
let mut seq = try!(serializer.serialize_seq(Some(self.len())));
for e in self.clone() {
try!(seq.serialize_element(&e));
}
seq.end()
}
}
@@ -304,7 +358,7 @@ impl<A> Serialize for ops::Range<A>
impl Serialize for () {
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
serializer.serialize_unit()
@@ -324,14 +378,14 @@ macro_rules! tuple_impls {
where $($T: Serialize),+
{
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
let mut state = try!(serializer.serialize_tuple($len));
let mut tuple = try!(serializer.serialize_tuple($len));
$(
try!(serializer.serialize_tuple_elt(&mut state, &self.$idx));
try!(tuple.serialize_element(&self.$idx));
)+
serializer.serialize_tuple_end(state)
tuple.end()
}
}
)+
@@ -514,15 +568,16 @@ tuple_impls! {
macro_rules! serialize_map {
() => {
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
let mut state = try!(serializer.serialize_map(Some(self.len())));
use super::SerializeMap;
let mut map = try!(serializer.serialize_map(Some(self.len())));
for (k, v) in self {
try!(serializer.serialize_map_key(&mut state, k));
try!(serializer.serialize_map_value(&mut state, v));
try!(map.serialize_key(k));
try!(map.serialize_value(v));
}
serializer.serialize_map_end(state)
map.end()
}
}
}
@@ -548,7 +603,7 @@ impl<K, V, H> Serialize for HashMap<K, V, H>
impl<'a, T: ?Sized> Serialize for &'a T where T: Serialize {
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
(**self).serialize(serializer)
@@ -557,7 +612,7 @@ impl<'a, T: ?Sized> Serialize for &'a T where T: Serialize {
impl<'a, T: ?Sized> Serialize for &'a mut T where T: Serialize {
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
(**self).serialize(serializer)
@@ -565,9 +620,11 @@ impl<'a, T: ?Sized> Serialize for &'a mut T where T: Serialize {
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<T: ?Sized> Serialize for Box<T> where T: Serialize {
impl<T: ?Sized> Serialize for Box<T>
where T: Serialize
{
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
(**self).serialize(serializer)
@@ -575,9 +632,11 @@ impl<T: ?Sized> Serialize for Box<T> where T: Serialize {
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<T> Serialize for Rc<T> where T: Serialize, {
impl<T> Serialize for Rc<T>
where T: Serialize
{
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
(**self).serialize(serializer)
@@ -585,9 +644,11 @@ impl<T> Serialize for Rc<T> where T: Serialize, {
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<T> Serialize for Arc<T> where T: Serialize, {
impl<T> Serialize for Arc<T>
where T: Serialize
{
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
(**self).serialize(serializer)
@@ -595,9 +656,11 @@ impl<T> Serialize for Arc<T> where T: Serialize, {
}
#[cfg(any(feature = "std", feature = "collections"))]
impl<'a, T: ?Sized> Serialize for Cow<'a, T> where T: Serialize + ToOwned, {
impl<'a, T: ?Sized> Serialize for Cow<'a, T>
where T: Serialize + ToOwned
{
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
(**self).serialize(serializer)
@@ -606,8 +669,13 @@ 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 {
impl<T, E> Serialize for Result<T, E>
where T: Serialize,
E: Serialize
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
match *self {
Result::Ok(ref value) => {
serializer.serialize_newtype_variant("Result", 0, "Ok", value)
@@ -623,13 +691,14 @@ 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>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
use super::SerializeStruct;
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)
try!(state.serialize_field("secs", &self.as_secs()));
try!(state.serialize_field("nanos", &self.subsec_nanos()));
state.end()
}
}
@@ -637,7 +706,7 @@ impl Serialize for Duration {
#[cfg(feature = "std")]
impl Serialize for net::IpAddr {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
self.to_string().serialize(serializer)
@@ -646,7 +715,7 @@ impl Serialize for net::IpAddr {
#[cfg(feature = "std")]
impl Serialize for net::Ipv4Addr {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
self.to_string().serialize(serializer)
@@ -655,7 +724,7 @@ impl Serialize for net::Ipv4Addr {
#[cfg(feature = "std")]
impl Serialize for net::Ipv6Addr {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
self.to_string().serialize(serializer)
@@ -666,7 +735,7 @@ impl Serialize for net::Ipv6Addr {
#[cfg(feature = "std")]
impl Serialize for net::SocketAddr {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
match *self {
@@ -678,7 +747,7 @@ impl Serialize for net::SocketAddr {
#[cfg(feature = "std")]
impl Serialize for net::SocketAddrV4 {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
self.to_string().serialize(serializer)
@@ -687,7 +756,7 @@ impl Serialize for net::SocketAddrV4 {
#[cfg(feature = "std")]
impl Serialize for net::SocketAddrV6 {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
self.to_string().serialize(serializer)
@@ -698,19 +767,19 @@ impl Serialize for net::SocketAddrV6 {
#[cfg(feature = "std")]
impl Serialize for path::Path {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
match self.to_str() {
Some(s) => s.serialize(serializer),
None => Err(Error::invalid_value("Path contains invalid UTF-8 characters")),
None => Err(Error::custom("Path contains invalid UTF-8 characters")),
}
}
}
#[cfg(feature = "std")]
impl Serialize for path::PathBuf {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
self.as_path().serialize(serializer)
@@ -718,8 +787,12 @@ impl Serialize for path::PathBuf {
}
#[cfg(feature = "unstable")]
impl<T> Serialize for NonZero<T> where T: Serialize + Zeroable {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer {
impl<T> Serialize for NonZero<T>
where T: Serialize + Zeroable
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
(**self).serialize(serializer)
}
}
+223 -200
View File
@@ -15,8 +15,10 @@ use std::error;
#[cfg(not(feature = "std"))]
use error;
#[cfg(all(feature = "collections", not(feature = "std")))]
use collections::String;
#[cfg(feature = "unstable")]
use core::cell::RefCell;
use core::fmt::Display;
pub mod impls;
@@ -26,17 +28,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;
}
///////////////////////////////////////////////////////////////////////////////
@@ -44,7 +36,7 @@ pub trait Error: Sized + error::Error {
/// A trait that describes a type that can be serialized by a `Serializer`.
pub trait Serialize {
/// Serializes this value into this serializer.
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer;
}
@@ -53,7 +45,7 @@ pub trait Serialize {
/// A trait that describes a type that can serialize a stream of values into the underlying format.
///
/// # For `Serialize` Developers
/// Non-aggrergate types like integers and strings can be serialized directly by calling the
/// Non-aggregate types like integers and strings can be serialized directly by calling the
/// appropriate function. For Aggregate types there's an initial `serialize_T` method that yields
/// a State object that you should not interact with. For each part of the aggregate there's a
/// `serialize_T_elt` method that allows you to pass values or key/value pairs. The types of the
@@ -72,341 +64,372 @@ pub trait Serialize {
/// state object, as it is expected that the user will not modify it. Due to the generic nature
/// of the `Serialize` impls, modifying the object is impossible on stable Rust.
pub trait Serializer {
/// The error type that can be returned if some error occurs during serialization.
/// Trickery to enforce correct use of the `Serialize` trait. Every
/// `Serializer` should set `Ok = ()`.
type Ok;
/// The error type when some error occurs during serialization.
type Error: Error;
/// A state object that is initialized by `serialize_seq`, passed to
/// `serialize_seq_elt`, and consumed by `serialize_seq_end`. Use `()` if no
/// state is required.
type SeqState;
/// A state object that is initialized by `serialize_tuple`, passed to
/// `serialize_tuple_elt`, and consumed by `serialize_tuple_end`. Use `()`
/// if no state is required.
type TupleState;
/// A state object that is initialized by `serialize_tuple_struct`, passed
/// to `serialize_tuple_struct_elt`, and consumed by
/// `serialize_tuple_struct_end`. Use `()` if no state is required.
type TupleStructState;
/// A state object that is initialized by `serialize_tuple_variant`, passed
/// to `serialize_tuple_variant_elt`, and consumed by
/// `serialize_tuple_variant_end`. Use `()` if no state is required.
type TupleVariantState;
/// A state object that is initialized by `serialize_map`, passed to
/// `serialize_map_elt`, and consumed by `serialize_map_end`. Use `()` if no
/// state is required.
type MapState;
/// A state object that is initialized by `serialize_struct`, passed to
/// `serialize_struct_elt`, and consumed by `serialize_struct_end`. Use `()`
/// if no state is required.
type StructState;
/// A state object that is initialized by `serialize_struct_variant`, passed
/// to `serialize_struct_variant_elt`, and consumed by
/// `serialize_struct_variant_end`. Use `()` if no state is required.
type StructVariantState;
/// 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 returned from `serialize_tuple` for serializing the content of the
/// tuple.
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 returned from `serialize_tuple_variant` for serializing the content
/// of the tuple variant.
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 returned from `serialize_struct` for serializing the content of the
/// struct.
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>;
/// Serializes a `bool` value.
fn serialize_bool(&mut self, v: bool) -> Result<(), Self::Error>;
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>;
/// Serializes 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(&mut self, v: isize) -> Result<(), Self::Error>;
fn serialize_isize(self, v: isize) -> Result<Self::Ok, Self::Error>;
/// Serializes an `i8` value. If the format does not differentiate between
/// `i8` and `i64`, a reasonable implementation would be to cast the value
/// to `i64` and forward to `serialize_i64`.
fn serialize_i8(&mut self, v: i8) -> Result<(), Self::Error>;
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error>;
/// Serializes an `i16` value. If the format does not differentiate between
/// `i16` and `i64`, a reasonable implementation would be to cast the value
/// to `i64` and forward to `serialize_i64`.
fn serialize_i16(&mut self, v: i16) -> Result<(), Self::Error>;
fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error>;
/// Serializes an `i32` value. If the format does not differentiate between
/// `i32` and `i64`, a reasonable implementation would be to cast the value
/// to `i64` and forward to `serialize_i64`.
fn serialize_i32(&mut self, v: i32) -> Result<(), Self::Error>;
fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error>;
/// Serializes an `i64` value.
fn serialize_i64(&mut self, v: i64) -> Result<(), Self::Error>;
fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>;
/// Serializes 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(&mut self, v: usize) -> Result<(), Self::Error>;
fn serialize_usize(self, v: usize) -> Result<Self::Ok, Self::Error>;
/// Serializes a `u8` value. If the format does not differentiate between
/// `u8` and `u64`, a reasonable implementation would be to cast the value
/// to `u64` and forward to `serialize_u64`.
fn serialize_u8(&mut self, v: u8) -> Result<(), Self::Error>;
fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error>;
/// Serializes a `u16` value. If the format does not differentiate between
/// `u16` and `u64`, a reasonable implementation would be to cast the value
/// to `u64` and forward to `serialize_u64`.
fn serialize_u16(&mut self, v: u16) -> Result<(), Self::Error>;
fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error>;
/// Serializes a `u32` value. If the format does not differentiate between
/// `u32` and `u64`, a reasonable implementation would be to cast the value
/// to `u64` and forward to `serialize_u64`.
fn serialize_u32(&mut self, v: u32) -> Result<(), Self::Error>;
fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error>;
/// `Serializes a `u64` value.
fn serialize_u64(&mut self, v: u64) -> Result<(), Self::Error>;
fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>;
/// Serializes an `f32` value. If the format does not differentiate between
/// `f32` and `f64`, a reasonable implementation would be to cast the value
/// to `f64` and forward to `serialize_f64`.
fn serialize_f32(&mut self, v: f32) -> Result<(), Self::Error>;
fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error>;
/// Serializes an `f64` value.
fn serialize_f64(&mut self, v: f64) -> Result<(), Self::Error>;
fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error>;
/// Serializes a character. If the format does not support characters,
/// it is reasonable to serialize it as a single element `str` or a `u32`.
fn serialize_char(&mut self, v: char) -> Result<(), Self::Error>;
fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error>;
/// Serializes a `&str`.
fn serialize_str(&mut self, value: &str) -> Result<(), Self::Error>;
fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error>;
/// Enables serializers to serialize byte slices more compactly or more
/// efficiently than other types of slices. If no efficient implementation
/// is available, a reasonable implementation would be to forward to
/// `serialize_seq`. If forwarded, the implementation looks usually just like this:
/// ```rust
/// let mut state = try!(self.serialize_seq(value));
/// let mut seq = self.serialize_seq(Some(value.len()))?;
/// for b in value {
/// try!(self.serialize_seq_elt(&mut state, b));
/// seq.serialize_element(b)?;
/// }
/// self.serialize_seq_end(state)
/// seq.end()
/// ```
fn serialize_bytes(&mut self, value: &[u8]) -> Result<(), Self::Error>;
fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error>;
/// Serializes a `()` value. It's reasonable to just not serialize anything.
fn serialize_unit(&mut self) -> Result<(), Self::Error>;
fn serialize_unit(self) -> Result<Self::Ok, Self::Error>;
/// Serializes a unit struct value. A reasonable implementation would be to
/// forward to `serialize_unit`.
fn serialize_unit_struct(
&mut self,
self,
name: &'static str,
) -> Result<(), Self::Error>;
) -> Result<Self::Ok, Self::Error>;
/// Serializes a unit variant, otherwise known as a variant with no
/// arguments. A reasonable implementation would be to forward to
/// `serialize_unit`.
fn serialize_unit_variant(
&mut self,
self,
name: &'static str,
variant_index: usize,
variant: &'static str,
) -> Result<(), Self::Error>;
) -> Result<Self::Ok, Self::Error>;
/// Allows a tuple struct with a single element, also known as a newtype
/// 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>(
&mut self,
fn serialize_newtype_struct<T: ?Sized + Serialize>(
self,
name: &'static str,
value: T,
) -> Result<(), Self::Error>;
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>(
&mut self,
fn serialize_newtype_variant<T: ?Sized + Serialize>(
self,
name: &'static str,
variant_index: usize,
variant: &'static str,
value: T,
) -> Result<(), Self::Error>;
value: &T,
) -> Result<Self::Ok, Self::Error>;
/// Serializes a `None` value.
fn serialize_none(&mut self) -> Result<(), Self::Error>;
fn serialize_none(self) -> Result<Self::Ok, Self::Error>;
/// Serializes a `Some(...)` value.
fn serialize_some<T: Serialize>(
&mut self,
value: T,
) -> Result<(), Self::Error>;
fn serialize_some<T: ?Sized + Serialize>(
self,
value: &T,
) -> Result<Self::Ok, Self::Error>;
/// Begins to serialize a sequence. This call must be followed by zero or
/// more calls to `serialize_seq_elt`, then a call to `serialize_seq_end`.
fn serialize_seq(
&mut self,
self,
len: Option<usize>,
) -> Result<Self::SeqState, Self::Error>;
/// Serializes a sequence element. Must have previously called
/// `serialize_seq`.
fn serialize_seq_elt<T: Serialize>(
&mut self,
state: &mut Self::SeqState,
value: T,
) -> Result<(), Self::Error>;
/// Finishes serializing a sequence.
fn serialize_seq_end(
&mut self,
state: Self::SeqState,
) -> Result<(), Self::Error>;
) -> Result<Self::SerializeSeq, Self::Error>;
/// Begins to serialize a sequence whose length will be known at
/// deserialization time. This call must be followed by zero or more calls
/// to `serialize_seq_elt`, then a call to `serialize_seq_end`. A reasonable
/// implementation would be to forward to `serialize_seq`.
fn serialize_seq_fixed_size(
&mut self,
self,
size: usize,
) -> Result<Self::SeqState, Self::Error>;
) -> Result<Self::SerializeSeq, Self::Error>;
/// Begins to serialize a tuple. This call must be followed by zero or more
/// calls to `serialize_tuple_elt`, then a call to `serialize_tuple_end`. A
/// reasonable implementation would be to forward to `serialize_seq`.
fn serialize_tuple(
&mut self,
self,
len: usize,
) -> Result<Self::TupleState, Self::Error>;
/// Serializes a tuple element. Must have previously called
/// `serialize_tuple`.
fn serialize_tuple_elt<T: Serialize>(
&mut self,
state: &mut Self::TupleState,
value: T,
) -> Result<(), Self::Error>;
/// Finishes serializing a tuple.
fn serialize_tuple_end(
&mut self,
state: Self::TupleState,
) -> Result<(), Self::Error>;
) -> Result<Self::SerializeTuple, Self::Error>;
/// Begins to serialize a tuple struct. This call must be followed by zero
/// or more calls to `serialize_tuple_struct_elt`, then a call to
/// `serialize_tuple_struct_end`. A reasonable implementation would be to
/// forward to `serialize_tuple`.
fn serialize_tuple_struct(
&mut self,
self,
name: &'static str,
len: usize,
) -> Result<Self::TupleStructState, Self::Error>;
/// Serializes a tuple struct element. Must have previously called
/// `serialize_tuple_struct`.
fn serialize_tuple_struct_elt<T: Serialize>(
&mut self,
state: &mut Self::TupleStructState,
value: T,
) -> Result<(), Self::Error>;
/// Finishes serializing a tuple struct.
fn serialize_tuple_struct_end(
&mut self,
state: Self::TupleStructState,
) -> Result<(), Self::Error>;
) -> Result<Self::SerializeTupleStruct, Self::Error>;
/// Begins to serialize a tuple variant. This call must be followed by zero
/// or more calls to `serialize_tuple_variant_elt`, then a call to
/// `serialize_tuple_variant_end`. A reasonable implementation would be to
/// forward to `serialize_tuple_struct`.
fn serialize_tuple_variant(
&mut self,
self,
name: &'static str,
variant_index: usize,
variant: &'static str,
len: usize,
) -> Result<Self::TupleVariantState, Self::Error>;
/// Serializes a tuple variant element. Must have previously called
/// `serialize_tuple_variant`.
fn serialize_tuple_variant_elt<T: Serialize>(
&mut self,
state: &mut Self::TupleVariantState,
value: T,
) -> Result<(), Self::Error>;
/// Finishes serializing a tuple variant.
fn serialize_tuple_variant_end(
&mut self,
state: Self::TupleVariantState,
) -> Result<(), Self::Error>;
) -> Result<Self::SerializeTupleVariant, Self::Error>;
/// Begins to serialize a map. This call must be followed by zero or more
/// calls to `serialize_map_key` and `serialize_map_value`, then a call to
/// `serialize_map_end`.
fn serialize_map(
&mut self,
self,
len: Option<usize>,
) -> Result<Self::MapState, Self::Error>;
/// Serialize a map key. Must have previously called `serialize_map`.
fn serialize_map_key<T: Serialize>(
&mut self,
state: &mut Self::MapState,
key: T
) -> Result<(), Self::Error>;
/// Serialize a map value. Must have previously called `serialize_map`.
fn serialize_map_value<T: Serialize>(
&mut self,
state: &mut Self::MapState,
value: T
) -> Result<(), Self::Error>;
/// Finishes serializing a map.
fn serialize_map_end(
&mut self,
state: Self::MapState,
) -> Result<(), Self::Error>;
) -> Result<Self::SerializeMap, Self::Error>;
/// Begins to serialize a struct. This call must be followed by zero or more
/// calls to `serialize_struct_elt`, then a call to `serialize_struct_end`.
fn serialize_struct(
&mut self,
self,
name: &'static str,
len: usize,
) -> Result<Self::StructState, Self::Error>;
/// Serializes a struct field. Must have previously called
/// `serialize_struct`.
fn serialize_struct_elt<V: Serialize>(
&mut self,
state: &mut Self::StructState,
key: &'static str,
value: V,
) -> Result<(), Self::Error>;
/// Finishes serializing a struct.
fn serialize_struct_end(
&mut self,
state: Self::StructState,
) -> Result<(), Self::Error>;
) -> Result<Self::SerializeStruct, Self::Error>;
/// Begins to serialize a struct variant. This call must be followed by zero
/// or more calls to `serialize_struct_variant_elt`, then a call to
/// `serialize_struct_variant_end`.
fn serialize_struct_variant(
&mut self,
self,
name: &'static str,
variant_index: usize,
variant: &'static str,
len: usize,
) -> Result<Self::StructVariantState, Self::Error>;
) -> Result<Self::SerializeStructVariant, Self::Error>;
}
/// Serialize a struct variant element. Must have previously called
/// `serialize_struct_variant`.
fn serialize_struct_variant_elt<V: Serialize>(
&mut self,
state: &mut Self::StructVariantState,
key: &'static str,
value: V,
) -> Result<(), Self::Error>;
/// Returned from `Serializer::serialize_seq` and
/// `Serializer::serialize_seq_fixed_size`.
pub trait SerializeSeq {
/// Trickery to enforce correct use of the `Serialize` trait. Every
/// `SerializeSeq` should set `Ok = ()`.
type Ok;
/// The error type when some error occurs during serialization.
type Error: Error;
/// Serializes a sequence element.
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>;
}
/// Returned from `Serializer::serialize_tuple`.
pub trait SerializeTuple {
/// Trickery to enforce correct use of the `Serialize` trait. Every
/// `SerializeTuple` should set `Ok = ()`.
type Ok;
/// The error type when some error occurs during serialization.
type Error: Error;
/// Serializes a tuple element.
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>;
}
/// Returned from `Serializer::serialize_tuple_struct`.
pub trait SerializeTupleStruct {
/// Trickery to enforce correct use of the `Serialize` trait. Every
/// `SerializeTupleStruct` should set `Ok = ()`.
type Ok;
/// The error type when some error occurs during serialization.
type Error: Error;
/// Serializes a tuple struct element.
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>;
}
/// Returned from `Serializer::serialize_tuple_variant`.
pub trait SerializeTupleVariant {
/// Trickery to enforce correct use of the `Serialize` trait. Every
/// `SerializeTupleVariant` should set `Ok = ()`.
type Ok;
/// The error type when some error occurs during serialization.
type Error: Error;
/// Serializes a tuple variant element.
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>;
}
/// Returned from `Serializer::serialize_map`.
pub trait SerializeMap {
/// Trickery to enforce correct use of the `Serialize` trait. Every
/// `SerializeMap` should set `Ok = ()`.
type Ok;
/// The error type when some error occurs during serialization.
type Error: Error;
/// Serialize a map key.
fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), Self::Error>;
/// Serialize a map value.
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>;
}
/// Returned from `Serializer::serialize_struct`.
pub trait SerializeStruct {
/// Trickery to enforce correct use of the `Serialize` trait. Every
/// `SerializeStruct` should set `Ok = ()`.
type Ok;
/// The error type when some error occurs during serialization.
type Error: Error;
/// Serializes a struct field.
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>;
}
/// Returned from `Serializer::serialize_struct_variant`.
pub trait SerializeStructVariant {
/// Trickery to enforce correct use of the `Serialize` trait. Every
/// `SerializeStructVariant` should set `Ok = ()`.
type Ok;
/// The error type when some error occurs during serialization.
type Error: Error;
/// Serialize a struct variant element.
fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>;
/// Finishes serializing a struct variant.
fn serialize_struct_variant_end(
&mut self,
state: Self::StructVariantState,
) -> Result<(), Self::Error>;
fn end(self) -> Result<Self::Ok, Self::Error>;
}
/// A wrapper type for iterators that implements `Serialize` for iterators whose items implement
/// `Serialize`. Don't use multiple times. Create new versions of this with the `iterator` function
/// every time you want to serialize an iterator.
#[cfg(feature = "unstable")]
pub struct Iterator<I>(RefCell<Option<I>>)
where <I as IntoIterator>::Item: Serialize,
I: IntoIterator;
/// Creates a temporary type that can be passed to any function expecting a `Serialize` and will
/// serialize the given iterator as a sequence
#[cfg(feature = "unstable")]
pub fn iterator<I>(iter: I) -> Iterator<I>
where <I as IntoIterator>::Item: Serialize,
I: IntoIterator
{
Iterator(RefCell::new(Some(iter)))
}
+4 -4
View File
@@ -1,6 +1,6 @@
[package]
name = "serde_codegen"
version = "0.8.20"
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"
@@ -23,7 +23,7 @@ with-syn = []
[dependencies]
clippy = { version = "^0.*", optional = true }
quote = "0.3.8"
serde_codegen_internals = { version = "=0.11.2", default-features = false, path = "../serde_codegen_internals" }
serde_codegen_internals = { version = "=0.11.3", default-features = false, path = "../serde_codegen_internals" }
syn = { version = "0.10", features = ["aster", "visit"] }
syntex = { version = "^0.50.0", optional = true }
syntex_syntax = { version = "^0.50.0", optional = true }
syntex = { version = "^0.54.0", optional = true }
syntex_syntax = { version = "^0.54.0", optional = true }
+245 -235
View File
@@ -1,4 +1,4 @@
use syn::{self, aster};
use syn::{self, aster, Ident};
use quote::{self, Tokens};
use bound;
@@ -28,16 +28,16 @@ pub fn expand_derive_deserialize(item: &syn::MacroInput) -> Result<Tokens, Strin
let where_clause = &impl_generics.where_clause;
let dummy_const = aster::id(format!("_IMPL_DESERIALIZE_FOR_{}", item.ident));
let dummy_const = Ident::new(format!("_IMPL_DESERIALIZE_FOR_{}", item.ident));
Ok(quote! {
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
const #dummy_const: () = {
extern crate serde as _serde;
#[automatically_derived]
impl #impl_generics _serde::de::Deserialize for #ty #where_clause {
fn deserialize<__D>(deserializer: &mut __D) -> ::std::result::Result<#ty, __D::Error>
where __D: _serde::de::Deserializer
impl #impl_generics _serde::Deserialize for #ty #where_clause {
fn deserialize<__D>(deserializer: __D) -> _serde::export::Result<#ty, __D::Error>
where __D: _serde::Deserializer
#body
}
};
@@ -61,7 +61,7 @@ fn build_impl_generics(item: &Item) -> syn::Generics {
None => {
let generics = bound::with_bound(item, &generics,
needs_deserialize_bound,
&aster::path().ids(&["_serde", "de", "Deserialize"]).build());
&aster::path().ids(&["_serde", "Deserialize"]).build());
bound::with_bound(item, &generics,
requires_default,
&aster::path().global().ids(&["std", "default", "Default"]).build())
@@ -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()
@@ -175,20 +175,14 @@ fn deserialize_visitor(generics: &syn::Generics) -> (Tokens, Tokens, Tokens) {
quote!(#ident)
}));
let ty_param_idents: Vec<_> = generics.ty_params.iter()
.map(|t| {
let ident = &t.ident;
quote!(#ident)
})
.collect();
let ty_param_idents = if ty_param_idents.is_empty() {
let ty_param_idents = if generics.ty_params.is_empty() {
None
} else {
let ty_param_idents = generics.ty_params.iter().map(|t| &t.ident);
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! {
@@ -206,25 +200,30 @@ 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 _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
formatter.write_str(#expecting)
}
#[inline]
fn visit_unit<__E>(&mut 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>(&mut self, mut visitor: __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,
{
try!(visitor.end());
self.visit_unit()
Ok(#type_ident)
}
}
@@ -249,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();
@@ -272,7 +275,7 @@ fn deserialize_tuple(
);
let dispatch = if is_enum {
quote!(visitor.visit_tuple(#nfields, #visitor_expr))
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))
@@ -281,16 +284,27 @@ fn deserialize_tuple(
quote!(deserializer.deserialize_tuple_struct(#type_name, #nfields, #visitor_expr))
};
let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing());
let visitor_var = if all_skipped {
quote!(_)
} else {
quote!(mut visitor)
};
quote!({
#visitor_item
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
type Value = #ty;
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>(&mut self, mut visitor: __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
@@ -308,15 +322,20 @@ fn deserialize_seq(
fields: &[Field],
is_struct: bool,
) -> 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: Vec<_> = fields.iter()
.enumerate()
.map(|(i, field)| {
let name = aster::id(format!("__field{}", i));
let let_values = vars.clone().zip(fields)
.map(|(var, field)| {
if field.attrs.skip_deserializing() {
let default = expr_is_missing(&field.attrs);
quote! {
let #name = #default;
let #var = #default;
}
} else {
let visit = match field.attrs.deserialize_with() {
@@ -335,43 +354,31 @@ fn deserialize_seq(
}
};
let assign = quote! {
let #name = match #visit {
let #var = match #visit {
Some(value) => { value },
None => {
try!(visitor.end());
return Err(_serde::de::Error::invalid_length(#index_in_seq));
return Err(_serde::de::Error::invalid_length(#index_in_seq, &#expecting));
}
};
};
index_in_seq += 1;
assign
}
})
.collect();
});
let result = if is_struct {
let args = fields.iter()
.enumerate()
.map(|(i, field)| {
let ident = field.ident.clone().expect("struct contains unnamed fields");
let value = aster::id(format!("__field{}", i));
quote!(#ident: #value)
});
let names = fields.iter().map(|f| &f.ident);
quote! {
#type_path { #(#args),* }
#type_path { #( #names: #vars ),* }
}
} else {
let args = (0..fields.len()).map(|i| aster::id(format!("__field{}", i)));
quote! {
#type_path ( #(#args),* )
#type_path ( #(#vars),* )
}
};
quote! {
#(#let_values)*
try!(visitor.end());
Ok(#result)
}
}
@@ -401,8 +408,8 @@ fn deserialize_newtype_struct(
};
quote! {
#[inline]
fn visit_newtype_struct<__E>(&mut self, __e: &mut __E) -> ::std::result::Result<Self::Value, __E::Error>
where __E: _serde::de::Deserializer,
fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::export::Result<Self::Value, __E::Error>
where __E: _serde::Deserializer,
{
Ok(#type_path(#value))
}
@@ -425,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,
@@ -445,7 +456,7 @@ fn deserialize_struct(
let is_enum = variant_ident.is_some();
let dispatch = if is_enum {
quote! {
visitor.visit_struct(FIELDS, #visitor_expr)
_serde::de::VariantVisitor::visit_struct(visitor, FIELDS, #visitor_expr)
}
} else {
let type_name = item_attrs.name().deserialize_name();
@@ -454,6 +465,13 @@ fn deserialize_struct(
}
};
let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing());
let visitor_var = if all_skipped {
quote!(_)
} else {
quote!(mut visitor)
};
quote!({
#field_visitor
@@ -462,15 +480,19 @@ fn deserialize_struct(
impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
type Value = #ty;
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
formatter.write_str(#expecting)
}
#[inline]
fn visit_seq<__V>(&mut self, mut visitor: __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>(&mut 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
@@ -494,49 +516,64 @@ 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())
.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(
variants.iter()
.filter(|variant| !variant.attrs.skip_deserializing())
.map(|variant| variant.attrs.name().deserialize_name())
.collect(),
variant_names_idents,
item_attrs,
true,
);
let variant_names = variants.iter().map(|variant| variant.ident.to_string());
let variants_stmt = quote! {
const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ];
};
let ignored_arm = if item_attrs.deny_unknown_fields() {
None
} else {
Some(quote! {
__Field::__ignore => { Err(_serde::de::Error::end_of_stream()) }
})
};
// Match arms to extract a variant from a string
let mut variant_arms = vec![];
for (i, variant) in variants.iter().filter(|variant| !variant.attrs.skip_deserializing()).enumerate() {
let variant_name = aster::id(format!("__field{}", i));
let variant_name = quote!(__Field::#variant_name);
let variant_arms = variants.iter()
.enumerate()
.filter(|&(_, variant)| !variant.attrs.skip_deserializing())
.map(|(i, variant)| {
let variant_name = field_i(i);
let block = deserialize_variant(
type_ident,
impl_generics,
ty.clone(),
variant,
item_attrs,
);
let block = deserialize_variant(
type_ident,
impl_generics,
ty.clone(),
variant,
item_attrs,
);
let arm = quote! {
#variant_name => #block
};
variant_arms.push(arm);
}
variant_arms.extend(ignored_arm.into_iter());
quote! {
(__Field::#variant_name, visitor) => #block
}
});
let all_skipped = variants.iter().all(|variant| variant.attrs.skip_deserializing());
let match_variant = if all_skipped {
// This is an empty enum like `enum Impossible {}` or an enum in which
// 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 {})
}
} else {
quote! {
match try!(visitor.visit_variant()) {
#(#variant_arms)*
}
}
};
let (visitor_item, visitor_ty, visitor_expr) = deserialize_visitor(impl_generics);
@@ -545,15 +582,17 @@ 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>
where __V: _serde::de::VariantVisitor,
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
formatter.write_str(#expecting)
}
fn visit_enum<__V>(self, visitor: __V) -> _serde::export::Result<#ty, __V::Error>
where __V: _serde::de::EnumVisitor,
{
match try!(visitor.visit_variant()) {
#(#variant_arms)*
}
#match_variant
}
}
@@ -575,7 +614,7 @@ fn deserialize_variant(
match variant.style {
Style::Unit => {
quote!({
try!(visitor.visit_unit());
try!(_serde::de::VariantVisitor::visit_unit(visitor));
Ok(#type_ident::#variant_ident)
})
}
@@ -619,7 +658,9 @@ fn deserialize_newtype_variant(
let visit = match field.attrs.deserialize_with() {
None => {
let field_ty = &field.ty;
quote!(try!(visitor.visit_newtype::<#field_ty>()))
quote! {
try!(_serde::de::VariantVisitor::visit_newtype::<#field_ty>(visitor))
}
}
Some(path) => {
let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
@@ -627,7 +668,7 @@ fn deserialize_newtype_variant(
quote!({
#wrapper
#wrapper_impl
try!(visitor.visit_newtype::<#wrapper_ty>()).value
try!(_serde::de::VariantVisitor::visit_newtype::<#wrapper_ty>(visitor)).value
})
}
};
@@ -637,105 +678,63 @@ fn deserialize_newtype_variant(
}
fn deserialize_field_visitor(
field_names: Vec<String>,
fields: Vec<(String, Ident)>,
item_attrs: &attr::Item,
is_variant: bool,
) -> Tokens {
// Create the field names for the fields.
let field_idents: Vec<_> = (0 .. field_names.len())
.map(|i| aster::id(format!("__field{}", i)))
.collect();
let field_strs = fields.iter().map(|&(ref name, _)| name);
let field_bytes = fields.iter().map(|&(ref name, _)| quote::ByteStr(name));
let field_idents: &Vec<_> = &fields.iter().map(|&(_, ref ident)| ident).collect();
let ignore_variant = if item_attrs.deny_unknown_fields() {
let ignore_variant = if is_variant || item_attrs.deny_unknown_fields() {
None
} else {
Some(quote!(__ignore,))
};
let index_field_arms: Vec<_> = field_idents.iter()
.enumerate()
.map(|(field_index, field_ident)| {
quote! {
#field_index => { Ok(__Field::#field_ident) }
let visit_usize = if is_variant {
let variant_indices = 0usize..;
let fallthrough_msg = format!("variant index 0 <= i < {}", fields.len());
Some(quote! {
fn visit_usize<__E>(self, value: usize) -> _serde::export::Result<__Field, __E>
where __E: _serde::de::Error
{
match value {
#(
#variant_indices => Ok(__Field::#field_idents),
)*
_ => Err(_serde::de::Error::invalid_value(
_serde::de::Unexpected::Unsigned(value as u64),
&#fallthrough_msg))
}
}
})
.collect();
let (index_error_msg, unknown_ident) = if is_variant {
("expected a variant", aster::id("unknown_variant"))
} else {
("expected a field", aster::id("unknown_field"))
None
};
let fallthrough_index_arm_expr = if !is_variant && !item_attrs.deny_unknown_fields() {
let fallthrough_arm = if is_variant {
quote! {
Err(_serde::de::Error::unknown_variant(value, VARIANTS))
}
} else if item_attrs.deny_unknown_fields() {
quote! {
Err(_serde::de::Error::unknown_field(value, FIELDS))
}
} else {
quote! {
Ok(__Field::__ignore)
}
} else {
quote! {
Err(_serde::de::Error::invalid_value(#index_error_msg))
}
};
let index_body = quote! {
match value {
#(#index_field_arms)*
_ => #fallthrough_index_arm_expr
}
};
// Match arms to extract a field from a string
let str_field_arms: Vec<_> = field_idents.iter().zip(field_names.iter())
.map(|(field_ident, field_name)| {
quote! {
#field_name => { Ok(__Field::#field_ident) }
}
let bytes_to_str = if is_variant || item_attrs.deny_unknown_fields() {
Some(quote! {
// TODO https://github.com/serde-rs/serde/issues/666
// update this to use str::from_utf8(value).unwrap_or("") on no_std
let value = &_serde::export::from_utf8_lossy(value);
})
.collect();
let fallthrough_str_arm_expr = if !is_variant && !item_attrs.deny_unknown_fields() {
quote! {
Ok(__Field::__ignore)
}
} else {
quote! {
Err(_serde::de::Error::#unknown_ident(value))
}
};
let str_body = quote! {
match value {
#(#str_field_arms)*
_ => #fallthrough_str_arm_expr
}
};
// Match arms to extract a field from a string
let bytes_field_arms: Vec<_> = field_idents.iter().zip(field_names.iter())
.map(|(field_ident, field_name)| {
let bytes_field_name = quote::ByteStr(field_name);
quote! {
#bytes_field_name => { Ok(__Field::#field_ident) }
}
})
.collect();
let fallthrough_bytes_arm_expr = if !is_variant && !item_attrs.deny_unknown_fields() {
quote! {
Ok(__Field::__ignore)
}
} else {
quote!({
let value = ::std::string::String::from_utf8_lossy(value);
Err(_serde::de::Error::#unknown_ident(&value))
})
};
let bytes_body = quote! {
match value {
#(#bytes_field_arms)*
_ => #fallthrough_bytes_arm_expr
}
None
};
quote! {
@@ -745,32 +744,45 @@ fn deserialize_field_visitor(
#ignore_variant
}
impl _serde::de::Deserialize for __Field {
impl _serde::Deserialize for __Field {
#[inline]
fn deserialize<__D>(deserializer: &mut __D) -> ::std::result::Result<__Field, __D::Error>
where __D: _serde::de::Deserializer,
fn deserialize<__D>(deserializer: __D) -> _serde::export::Result<__Field, __D::Error>
where __D: _serde::Deserializer,
{
struct __FieldVisitor;
impl _serde::de::Visitor for __FieldVisitor {
type Value = __Field;
fn visit_usize<__E>(&mut self, value: usize) -> ::std::result::Result<__Field, __E>
where __E: _serde::de::Error
{
#index_body
fn expecting(&self, formatter: &mut _serde::export::fmt::Formatter) -> _serde::export::fmt::Result {
formatter.write_str("field name")
}
fn visit_str<__E>(&mut self, value: &str) -> ::std::result::Result<__Field, __E>
#visit_usize
fn visit_str<__E>(self, value: &str) -> _serde::export::Result<__Field, __E>
where __E: _serde::de::Error
{
#str_body
match value {
#(
#field_strs => Ok(__Field::#field_idents),
)*
_ => #fallthrough_arm
}
}
fn visit_bytes<__E>(&mut 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
{
#bytes_body
match value {
#(
#field_bytes => Ok(__Field::#field_idents),
)*
_ => {
#bytes_to_str
#fallthrough_arm
}
}
}
}
@@ -787,12 +799,21 @@ fn deserialize_struct_visitor(
fields: &[Field],
item_attrs: &attr::Item,
) -> (Tokens, Tokens, Tokens) {
let field_exprs = fields.iter()
.map(|field| field.attrs.name().deserialize_name())
let field_names_idents: Vec<_> = fields.iter()
.enumerate()
.filter(|&(_, field)| !field.attrs.skip_deserializing())
.map(|(i, field)| (field.attrs.name().deserialize_name(), field_i(i)))
.collect();
let fields_stmt = {
let field_names = field_names_idents.iter().map(|&(ref name, _)| name);
quote! {
const FIELDS: &'static [&'static str] = &[ #(#field_names),* ];
}
};
let field_visitor = deserialize_field_visitor(
field_exprs,
field_names_idents,
item_attrs,
false,
);
@@ -805,14 +826,6 @@ fn deserialize_struct_visitor(
item_attrs,
);
let field_names = fields.iter().map(|field| {
field.ident.clone().expect("struct contains unnamed field").to_string()
});
let fields_stmt = quote! {
const FIELDS: &'static [&'static str] = &[ #(#field_names),* ];
};
(field_visitor, fields_stmt, visit_map)
}
@@ -824,22 +837,20 @@ fn deserialize_map(
item_attrs: &attr::Item,
) -> Tokens {
// Create the field names for the fields.
let fields_names = fields.iter()
let fields_names: Vec<_> = fields.iter()
.enumerate()
.map(|(i, field)|
(field, aster::id(format!("__field{}", i))))
.collect::<Vec<_>>();
.map(|(i, field)| (field, field_i(i)))
.collect();
// Declare each field that will be deserialized.
let let_values: Vec<_> = fields_names.iter()
let let_values = fields_names.iter()
.filter(|&&(field, _)| !field.attrs.skip_deserializing())
.map(|&(field, ref name)| {
let field_ty = &field.ty;
quote! {
let mut #name: Option<#field_ty> = None;
}
})
.collect();
});
// Match arms to extract a value for a field.
let value_arms = fields_names.iter()
@@ -872,21 +883,7 @@ fn deserialize_map(
#name = Some(#visit);
}
}
})
.collect::<Vec<_>>();
// Match arms to ignore value for fields that have `skip_deserializing`.
// Ignored even if `deny_unknown_fields` is set.
let skipped_arms = fields_names.iter()
.filter(|&&(field, _)| field.attrs.skip_deserializing())
.map(|&(_, ref name)| {
quote! {
__Field::#name => {
let _ = try!(visitor.visit_value::<_serde::de::impls::IgnoredAny>());
}
}
})
.collect::<Vec<_>>();
});
// Visit ignored values to consume them
let ignored_arm = if item_attrs.deny_unknown_fields() {
@@ -897,6 +894,24 @@ fn deserialize_map(
})
};
let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing());
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 {});
}
} else {
quote! {
while let Some(key) = try!(visitor.visit_key::<__Field>()) {
match key {
#(#value_arms)*
#ignored_arm
}
}
}
};
let extract_values = fields_names.iter()
.filter(|&&(field, _)| !field.attrs.skip_deserializing())
.map(|&(field, ref name)| {
@@ -908,8 +923,7 @@ fn deserialize_map(
None => #missing_expr
};
}
})
.collect::<Vec<_>>();
});
let result = fields_names.iter()
.map(|&(field, ref name)| {
@@ -925,15 +939,7 @@ fn deserialize_map(
quote! {
#(#let_values)*
while let Some(key) = try!(visitor.visit_key::<__Field>()) {
match key {
#(#value_arms)*
#(#skipped_arms)*
#ignored_arm
}
}
try!(visitor.end());
#match_keys
#(#extract_values)*
@@ -941,6 +947,10 @@ fn deserialize_map(
}
}
fn field_i(i: usize) -> Ident {
Ident::new(format!("__field{}", i))
}
/// 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(
@@ -971,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::de::Deserialize for #wrapper_ty #where_clause {
fn deserialize<__D>(__d: &mut __D) -> ::std::result::Result<Self, __D::Error>
where __D: _serde::de::Deserializer
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
{
let value = try!(#deserialize_with(__d));
Ok(__SerdeDeserializeWithStruct {
value: value,
phantom: ::std::marker::PhantomData,
phantom: _serde::export::PhantomData,
})
}
}
@@ -994,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());
@@ -1006,7 +1016,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(_) => {
+7 -8
View File
@@ -38,11 +38,11 @@ fn syntex_registry() -> syntex::Registry {
impl fold::Folder for StripAttributeFolder {
fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
match attr.node.value.node {
ast::MetaItemKind::List(ref n, _) if n == &"serde" => { return None; }
_ => {}
if attr.value.name == "serde" {
if let ast::MetaItemKind::List(..) = attr.value.node {
return None;
}
}
Some(attr)
}
@@ -116,13 +116,12 @@ macro_rules! shim {
use syntax::{attr, ast, visit};
struct MarkSerdeAttributesUsed;
impl visit::Visitor for MarkSerdeAttributesUsed {
impl<'a> visit::Visitor<'a> for MarkSerdeAttributesUsed {
fn visit_attribute(&mut self, attr: &ast::Attribute) {
match attr.node.value.node {
ast::MetaItemKind::List(ref name, _) if name == "serde" => {
if attr.value.name == "serde" {
if let ast::MetaItemKind::List(..) = attr.value.node {
attr::mark_used(attr);
}
_ => {}
}
}
}
+97 -93
View File
@@ -1,4 +1,4 @@
use syn::{self, aster};
use syn::{self, aster, Ident};
use quote::Tokens;
use bound;
@@ -22,16 +22,16 @@ pub fn expand_derive_serialize(item: &syn::MacroInput) -> Result<Tokens, String>
let where_clause = &impl_generics.where_clause;
let dummy_const = aster::id(format!("_IMPL_SERIALIZE_FOR_{}", item.ident));
let dummy_const = Ident::new(format!("_IMPL_SERIALIZE_FOR_{}", item.ident));
Ok(quote! {
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
const #dummy_const: () = {
extern crate serde as _serde;
#[automatically_derived]
impl #impl_generics _serde::ser::Serialize for #ty #where_clause {
fn serialize<__S>(&self, _serializer: &mut __S) -> ::std::result::Result<(), __S::Error>
where __S: _serde::ser::Serializer
impl #impl_generics _serde::Serialize for #ty #where_clause {
fn serialize<__S>(&self, _serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error>
where __S: _serde::Serializer
{
#body
}
@@ -56,7 +56,7 @@ fn build_impl_generics(item: &Item) -> syn::Generics {
None => {
bound::with_bound(item, &generics,
needs_serialize_bound,
&aster::path().ids(&["_serde", "ser", "Serialize"]).build())
&aster::path().ids(&["_serde", "Serialize"]).build())
}
}
}
@@ -159,7 +159,7 @@ fn serialize_tuple_struct(
fields,
impl_generics,
false,
aster::id("serialize_tuple_struct_elt"),
quote!(_serde::ser::SerializeTupleStruct::serialize_field),
);
let type_name = item_attrs.name().serialize_name();
@@ -169,7 +169,7 @@ fn serialize_tuple_struct(
quote! {
let #let_mut __serde_state = try!(_serializer.serialize_tuple_struct(#type_name, #len));
#(#serialize_stmts)*
_serializer.serialize_tuple_struct_end(__serde_state)
_serde::ser::SerializeTupleStruct::end(__serde_state)
}
}
@@ -184,7 +184,7 @@ fn serialize_struct(
fields,
impl_generics,
false,
aster::id("serialize_struct_elt"),
quote!(_serde::ser::SerializeStruct::serialize_field),
);
let type_name = item_attrs.name().serialize_name();
@@ -210,7 +210,7 @@ fn serialize_struct(
quote! {
let #let_mut __serde_state = try!(_serializer.serialize_struct(#type_name, #len));
#(#serialize_fields)*
_serializer.serialize_struct_end(__serde_state)
_serde::ser::SerializeStruct::end(__serde_state)
}
}
@@ -256,76 +256,80 @@ fn serialize_variant(
let variant_ident = variant.ident.clone();
let variant_name = variant.attrs.name().serialize_name();
match variant.style {
Style::Unit => {
quote! {
#type_ident::#variant_ident =>
_serde::ser::Serializer::serialize_unit_variant(
_serializer,
#type_name,
#variant_index,
#variant_name,
),
}
},
Style::Newtype => {
let block = serialize_newtype_variant(
type_name,
variant_index,
variant_name,
ty,
generics,
&variant.fields[0],
);
quote! {
#type_ident::#variant_ident(ref __simple_value) => #block,
}
},
Style::Tuple => {
let field_names: Vec<Tokens> = (0 .. variant.fields.len())
.map(|i| {
let id = aster::id(format!("__field{}", i));
quote!(ref #id)
})
.collect();
let pat = quote!(#type_ident::#variant_ident(#(#field_names),*));
let block = serialize_tuple_variant(
type_name,
variant_index,
variant_name,
generics,
ty,
&variant.fields,
);
quote! {
#pat => { #block }
}
if variant.attrs.skip_serializing() {
let skipped_msg = format!("the enum variant {}::{} cannot be serialized",
type_ident, variant_ident);
let skipped_err = quote! {
Err(_serde::ser::Error::custom(#skipped_msg))
};
let fields_pat = match variant.style {
Style::Unit => quote!(),
Style::Newtype | Style::Tuple => quote!( (..) ),
Style::Struct => quote!( {..} ),
};
quote! {
#type_ident::#variant_ident #fields_pat => #skipped_err,
}
Style::Struct => {
let fields = variant.fields.iter().map(|field| {
let id = match field.ident {
Some(ref name) => name.clone(),
None => panic!("struct variant has unnamed fields"),
};
quote!(ref #id)
});
let pat = quote!(#type_ident::#variant_ident { #(#fields),* });
} else { // variant wasn't skipped
match variant.style {
Style::Unit => {
quote! {
#type_ident::#variant_ident =>
_serde::Serializer::serialize_unit_variant(
_serializer,
#type_name,
#variant_index,
#variant_name,
),
}
},
Style::Newtype => {
let block = serialize_newtype_variant(
type_name,
variant_index,
variant_name,
ty,
generics,
&variant.fields[0],
);
let block = serialize_struct_variant(
variant_index,
variant_name,
generics,
ty,
&variant.fields,
item_attrs,
);
quote! {
#type_ident::#variant_ident(ref __simple_value) => #block,
}
},
Style::Tuple => {
let field_names = (0 .. variant.fields.len())
.map(|i| Ident::new(format!("__field{}", i)));
quote! {
#pat => { #block }
let block = serialize_tuple_variant(
type_name,
variant_index,
variant_name,
generics,
ty,
&variant.fields,
);
quote! {
#type_ident::#variant_ident(#(ref #field_names),*) => { #block }
}
}
Style::Struct => {
let fields = variant.fields.iter()
.map(|f| f.ident.clone().expect("struct variant has unnamed fields"));
let block = serialize_struct_variant(
variant_index,
variant_name,
generics,
ty,
&variant.fields,
item_attrs,
);
quote! {
#type_ident::#variant_ident { #(ref #fields),* } => { #block }
}
}
}
}
@@ -346,7 +350,7 @@ fn serialize_newtype_variant(
}
quote! {
_serde::ser::Serializer::serialize_newtype_variant(
_serde::Serializer::serialize_newtype_variant(
_serializer,
#type_name,
#variant_index,
@@ -369,7 +373,7 @@ fn serialize_tuple_variant(
fields,
generics,
true,
aster::id("serialize_tuple_variant_elt"),
quote!(_serde::ser::SerializeTupleVariant::serialize_field),
);
let len = serialize_stmts.len();
@@ -382,7 +386,7 @@ fn serialize_tuple_variant(
#variant_name,
#len));
#(#serialize_stmts)*
_serializer.serialize_tuple_variant_end(__serde_state)
_serde::ser::SerializeTupleVariant::end(__serde_state)
}
}
@@ -399,7 +403,7 @@ fn serialize_struct_variant(
fields,
generics,
true,
aster::id("serialize_struct_variant_elt"),
quote!(_serde::ser::SerializeStructVariant::serialize_field),
);
let item_name = item_attrs.name().serialize_name();
@@ -429,7 +433,7 @@ fn serialize_struct_variant(
#len,
));
#(#serialize_fields)*
_serializer.serialize_struct_variant_end(__serde_state)
_serde::ser::SerializeStructVariant::end(__serde_state)
}
}
@@ -438,16 +442,16 @@ fn serialize_tuple_struct_visitor(
fields: &[Field],
generics: &syn::Generics,
is_enum: bool,
func: syn::Ident,
func: Tokens,
) -> Vec<Tokens> {
fields.iter()
.enumerate()
.map(|(i, field)| {
let mut field_expr = if is_enum {
let id = aster::id(format!("__field{}", i));
let id = Ident::new(format!("__field{}", i));
quote!(#id)
} else {
let i = aster::id(i);
let i = Ident::new(i);
quote!(&self.#i)
};
@@ -460,7 +464,7 @@ fn serialize_tuple_struct_visitor(
}
let ser = quote! {
try!(_serializer.#func(&mut __serde_state, #field_expr));
try!(#func(&mut __serde_state, #field_expr));
};
match skip {
@@ -476,7 +480,7 @@ fn serialize_struct_visitor(
fields: &[Field],
generics: &syn::Generics,
is_enum: bool,
func: syn::Ident,
func: Tokens,
) -> Vec<Tokens> {
fields.iter()
.filter(|&field| !field.attrs.skip_serializing())
@@ -499,7 +503,7 @@ fn serialize_struct_visitor(
}
let ser = quote! {
try!(_serializer.#func(&mut __serde_state, #key_expr, #field_expr));
try!(#func(&mut __serde_state, #key_expr, #field_expr));
};
match skip {
@@ -536,15 +540,15 @@ fn wrap_serialize_with(
phantom: ::std::marker::PhantomData<#item_ty>,
}
impl #wrapper_generics _serde::ser::Serialize for #wrapper_ty #where_clause {
fn serialize<__S>(&self, __s: &mut __S) -> ::std::result::Result<(), __S::Error>
where __S: _serde::ser::Serializer
impl #wrapper_generics _serde::Serialize for #wrapper_ty #where_clause {
fn serialize<__S>(&self, __s: __S) -> _serde::export::Result<__S::Ok, __S::Error>
where __S: _serde::Serializer
{
#path(self.value, __s)
}
}
__SerializeWith {
&__SerializeWith {
value: #value,
phantom: ::std::marker::PhantomData::<#item_ty>,
}
@@ -554,7 +558,7 @@ fn wrap_serialize_with(
// Serialization of an empty struct results in code like:
//
// let mut __serde_state = try!(serializer.serialize_struct("S", 0));
// serializer.serialize_struct_end(__serde_state)
// _serde::ser::SerializeStruct::end(__serde_state)
//
// where we want to omit the `mut` to avoid a warning.
fn mut_if(is_mut: bool) -> Option<Tokens> {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "serde_codegen_internals"
version = "0.11.2"
version = "0.11.3"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "AST representation used by Serde codegen. Unstable."
+11
View File
@@ -188,6 +188,7 @@ impl Item {
pub struct Variant {
name: Name,
skip_deserializing: bool,
skip_serializing: bool,
}
impl Variant {
@@ -195,6 +196,7 @@ impl Variant {
let mut ser_name = Attr::none(cx, "rename");
let mut de_name = Attr::none(cx, "rename");
let mut skip_deserializing = BoolAttr::none(cx, "skip_deserializing");
let mut skip_serializing = BoolAttr::none(cx, "skip_serializing");
for meta_items in variant.attrs.iter().filter_map(get_serde_meta_items) {
for meta_item in meta_items {
@@ -218,6 +220,10 @@ impl Variant {
MetaItem(Word(ref name)) if name == "skip_deserializing" => {
skip_deserializing.set_true();
}
// Parse `#[serde(skip_serializing)]`
MetaItem(Word(ref name)) if name == "skip_serializing" => {
skip_serializing.set_true();
}
MetaItem(ref meta_item) => {
cx.error(format!("unknown serde variant attribute `{}`",
@@ -237,6 +243,7 @@ impl Variant {
deserialize: de_name.get().unwrap_or_else(|| variant.ident.to_string()),
},
skip_deserializing: skip_deserializing.get(),
skip_serializing: skip_serializing.get(),
}
}
@@ -247,6 +254,10 @@ impl Variant {
pub fn skip_deserializing(&self) -> bool {
self.skip_deserializing
}
pub fn skip_serializing(&self) -> bool {
self.skip_serializing
}
}
/// Represents field attribute information
+4 -4
View File
@@ -1,6 +1,6 @@
[package]
name = "serde_derive"
version = "0.8.20"
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.8.20"
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.8.20", path = "../serde" }
serde_test = { version = "0.8.20", path = "../serde_test" }
serde = { version = "0.9.0-rc3", path = "../serde" }
serde_test = { version = "0.9.0-rc3", path = "../serde_test" }
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "serde_derive_tests_no_std"
version = "0.9.0-rc3"
publish = false
[dependencies]
serde = { path = "../../serde", default-features = false }
serde_derive = { path = ".." }
+50
View File
@@ -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 },
}
-3
View File
@@ -1,6 +1,3 @@
#![feature(proc_macro, proc_macro_lib)]
#![cfg(not(test))]
extern crate proc_macro;
extern crate serde_codegen;
@@ -1,5 +1,3 @@
#![feature(proc_macro)]
#[macro_use]
extern crate serde_derive;
@@ -1,5 +1,3 @@
#![feature(proc_macro)]
#[macro_use]
extern crate serde_derive;
@@ -1,5 +1,3 @@
#![feature(proc_macro)]
#[macro_use]
extern crate serde_derive;
@@ -1,5 +1,3 @@
#![feature(proc_macro)]
#[macro_use]
extern crate serde_derive;
@@ -1,5 +1,3 @@
#![feature(proc_macro)]
#[macro_use]
extern crate serde_derive;
@@ -1,5 +1,3 @@
#![feature(proc_macro)]
#[macro_use]
extern crate serde_derive;
@@ -1,5 +1,3 @@
#![feature(proc_macro)]
#[macro_use]
extern crate serde_derive;
@@ -1,5 +1,3 @@
#![feature(proc_macro)]
#[macro_use]
extern crate serde_derive;
@@ -1,5 +1,3 @@
#![feature(proc_macro)]
#[macro_use]
extern crate serde_derive;
@@ -1,5 +1,3 @@
#![feature(proc_macro)]
#[macro_use]
extern crate serde_derive;
@@ -1,4 +1,3 @@
#![feature(proc_macro)]
#![deny(identity_op)]
#[macro_use]
+1 -1
View File
@@ -1,4 +1,4 @@
#![feature(test, proc_macro)]
#![feature(test)]
#[macro_use]
extern crate serde_derive;
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "serde_test"
version = "0.8.20"
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.8.20", path = "../serde" }
serde = { version = "0.9.0-rc3", path = "../serde" }
+188 -217
View File
@@ -3,12 +3,14 @@ use std::iter;
use serde::de::{
self,
Deserialize,
DeserializeSeed,
EnumVisitor,
MapVisitor,
SeqVisitor,
VariantVisitor,
Visitor,
};
use serde::de::value::ValueDeserializer;
use error::Error;
use token::Token;
@@ -32,174 +34,207 @@ impl<I> Deserializer<I>
self.tokens.next()
}
fn visit_seq<V>(&mut self, len: Option<usize>, mut visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
visitor.visit_seq(DeserializerSeqVisitor {
de: self,
len: len,
})
pub fn expect_token(&mut self, expected: Token) -> Result<(), Error> {
match self.tokens.next() {
Some(token) => {
if expected == token {
Ok(())
} else {
Err(Error::UnexpectedToken(token))
}
}
None => Err(Error::EndOfTokens),
}
}
fn visit_array<V>(&mut self, len: usize, mut visitor: V) -> Result<V::Value, Error>
fn visit_seq<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
visitor.visit_seq(DeserializerArrayVisitor {
let value = try!(visitor.visit_seq(DeserializerSeqVisitor {
de: self,
len: len,
})
}));
try!(self.expect_token(Token::SeqEnd));
Ok(value)
}
fn visit_tuple<V>(&mut self, len: usize, mut visitor: V) -> Result<V::Value, Error>
fn visit_array<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
visitor.visit_seq(DeserializerTupleVisitor {
let value = try!(visitor.visit_seq(DeserializerArrayVisitor {
de: self,
len: len,
})
}));
try!(self.expect_token(Token::SeqEnd));
Ok(value)
}
fn visit_tuple_struct<V>(&mut self, len: usize, mut visitor: V) -> Result<V::Value, Error>
fn visit_tuple<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
visitor.visit_seq(DeserializerTupleStructVisitor {
let value = try!(visitor.visit_seq(DeserializerTupleVisitor {
de: self,
len: len,
})
}));
try!(self.expect_token(Token::TupleEnd));
Ok(value)
}
fn visit_variant_seq<V>(&mut self, len: Option<usize>, mut visitor: V) -> Result<V::Value, Error>
fn visit_tuple_struct<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
visitor.visit_seq(DeserializerVariantSeqVisitor {
let value = try!(visitor.visit_seq(DeserializerTupleStructVisitor {
de: self,
len: len,
})
}));
try!(self.expect_token(Token::TupleStructEnd));
Ok(value)
}
fn visit_map<V>(&mut self, len: Option<usize>, mut visitor: V) -> Result<V::Value, Error>
fn visit_variant_seq<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
visitor.visit_map(DeserializerMapVisitor {
let value = try!(visitor.visit_seq(DeserializerVariantSeqVisitor {
de: self,
len: len,
})
}));
try!(self.expect_token(Token::EnumSeqEnd));
Ok(value)
}
fn visit_struct<V>(&mut self, len: Option<usize>, mut visitor: V) -> Result<V::Value, Error>
fn visit_map<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
visitor.visit_map(DeserializerStructVisitor {
let value = try!(visitor.visit_map(DeserializerMapVisitor {
de: self,
len: len,
})
}));
try!(self.expect_token(Token::MapEnd));
Ok(value)
}
fn visit_variant_map<V>(&mut self, len: Option<usize>, mut visitor: V) -> Result<V::Value, Error>
fn visit_struct<V>(&mut self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
visitor.visit_map(DeserializerVariantMapVisitor {
let value = try!(visitor.visit_map(DeserializerStructVisitor {
de: self,
len: fields.len(),
}));
try!(self.expect_token(Token::StructEnd));
Ok(value)
}
fn visit_variant_map<V>(&mut self, len: Option<usize>, visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
let value = try!(visitor.visit_map(DeserializerVariantMapVisitor {
de: self,
len: len,
})
}));
try!(self.expect_token(Token::EnumMapEnd));
Ok(value)
}
}
impl<I> de::Deserializer for Deserializer<I>
impl<'a, I> de::Deserializer for &'a mut Deserializer<I>
where I: Iterator<Item=Token<'static>>,
{
type Error = Error;
fn deserialize_seq<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::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>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_struct_field<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_map<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_map<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_unit<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_unit<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_bytes<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_bytes<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_ignored_any<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_byte_buf<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_string<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_ignored_any<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_str<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_string<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_char<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_str<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_i64<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_char<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_i32<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_i64<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_i16<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_i32<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_i8<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_i16<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_u64<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_i8<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_u32<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_u64<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_u16<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_u32<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_u8<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_u16<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_f32<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_u8<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_f64<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_f32<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_bool<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_f64<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_usize<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
fn deserialize_bool<__V>(self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_isize<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
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>(&mut self, mut visitor: V) -> Result<V::Value, Error>
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
match self.tokens.next() {
@@ -220,10 +255,11 @@ impl<I> de::Deserializer for 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(),
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)
}
@@ -237,13 +273,13 @@ impl<I> de::Deserializer for Deserializer<I>
self.visit_map(Some(len), visitor)
}
Some(token) => Err(Error::UnexpectedToken(token)),
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
/// Hook into `Option` deserializing so we can treat `Unit` as a
/// `None`, or a regular value as `Some(value)`.
fn deserialize_option<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
match self.tokens.peek() {
@@ -260,21 +296,21 @@ impl<I> de::Deserializer for Deserializer<I>
visitor.visit_none()
}
Some(_) => visitor.visit_some(self),
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
fn deserialize_enum<V>(&mut self,
fn deserialize_enum<V>(self,
name: &str,
_variants: &'static [&'static str],
mut visitor: V) -> Result<V::Value, Error>
where V: EnumVisitor,
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(DeserializerVariantVisitor {
visitor.visit_enum(DeserializerEnumVisitor {
de: self,
})
}
@@ -282,7 +318,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(DeserializerEnumVisitor {
de: self,
})
}
@@ -290,11 +326,11 @@ impl<I> de::Deserializer for Deserializer<I>
let token = self.tokens.next().unwrap();
Err(Error::UnexpectedToken(token))
}
None => { return Err(Error::EndOfStream); }
None => { return Err(Error::EndOfTokens); }
}
}
fn deserialize_unit_struct<V>(&mut self, name: &str, mut visitor: V) -> Result<V::Value, Error>
fn deserialize_unit_struct<V>(self, name: &str, visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
match self.tokens.peek() {
@@ -307,13 +343,13 @@ impl<I> de::Deserializer for Deserializer<I>
}
}
Some(_) => self.deserialize(visitor),
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
fn deserialize_newtype_struct<V>(&mut self,
fn deserialize_newtype_struct<V>(self,
name: &str,
mut visitor: V) -> Result<V::Value, Error>
visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
match self.tokens.peek() {
@@ -326,11 +362,11 @@ impl<I> de::Deserializer for Deserializer<I>
}
}
Some(_) => self.deserialize(visitor),
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
fn deserialize_seq_fixed_size<V>(&mut self,
fn deserialize_seq_fixed_size<V>(self,
len: usize,
visitor: V) -> Result<V::Value, Error>
where V: Visitor,
@@ -341,13 +377,13 @@ impl<I> de::Deserializer for Deserializer<I>
self.visit_array(len, visitor)
}
Some(_) => self.deserialize(visitor),
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
fn deserialize_tuple<V>(&mut self,
fn deserialize_tuple<V>(self,
len: usize,
mut visitor: V) -> Result<V::Value, Error>
visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
match self.tokens.peek() {
@@ -376,14 +412,14 @@ impl<I> de::Deserializer for Deserializer<I>
self.visit_tuple_struct(len, visitor)
}
Some(_) => self.deserialize(visitor),
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
fn deserialize_tuple_struct<V>(&mut self,
fn deserialize_tuple_struct<V>(self,
name: &str,
len: usize,
mut visitor: V) -> Result<V::Value, Error>
visitor: V) -> Result<V::Value, Error>
where V: Visitor,
{
match self.tokens.peek() {
@@ -420,11 +456,11 @@ impl<I> de::Deserializer for Deserializer<I>
}
}
Some(_) => self.deserialize(visitor),
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
fn deserialize_struct<V>(&mut self,
fn deserialize_struct<V>(self,
name: &str,
fields: &'static [&'static str],
visitor: V) -> Result<V::Value, Error>
@@ -434,7 +470,7 @@ impl<I> de::Deserializer for Deserializer<I>
Some(&Token::StructStart(n, _)) => {
self.tokens.next();
if name == n {
self.visit_struct(Some(fields.len()), visitor)
self.visit_struct(fields, visitor)
} else {
Err(Error::InvalidName(n))
}
@@ -444,7 +480,7 @@ impl<I> de::Deserializer for Deserializer<I>
self.visit_map(Some(fields.len()), visitor)
}
Some(_) => self.deserialize(visitor),
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
}
@@ -461,30 +497,21 @@ 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);
Ok(Some(try!(Deserialize::deserialize(self.de))))
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::EndOfStream),
}
}
fn end(&mut self) -> Result<(), Error> {
//assert_eq!(self.len.unwrap_or(0), 0);
match self.de.tokens.next() {
Some(Token::SeqEnd) => Ok(()),
Some(token) => Err(Error::UnexpectedToken(token)),
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
@@ -506,30 +533,21 @@ 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;
Ok(Some(try!(Deserialize::deserialize(self.de))))
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::EndOfStream),
}
}
fn end(&mut self) -> Result<(), Error> {
assert_eq!(self.len, 0);
match self.de.tokens.next() {
Some(Token::SeqEnd) => Ok(()),
Some(token) => Err(Error::UnexpectedToken(token)),
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
@@ -550,30 +568,21 @@ 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;
Ok(Some(try!(Deserialize::deserialize(self.de))))
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::EndOfStream),
}
}
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::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
@@ -594,30 +603,21 @@ 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;
Ok(Some(try!(Deserialize::deserialize(self.de))))
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::EndOfStream),
}
}
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::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
@@ -638,30 +638,21 @@ 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);
Ok(Some(try!(Deserialize::deserialize(self.de))))
seed.deserialize(&mut *self.de).map(Some)
}
Some(&Token::EnumSeqEnd) => Ok(None),
Some(_) => {
let token = self.de.tokens.next().unwrap();
Err(Error::UnexpectedToken(token))
}
None => Err(Error::EndOfStream),
}
}
fn end(&mut self) -> Result<(), Error> {
//assert_eq!(self.len.unwrap_or(0), 0);
match self.de.tokens.next() {
Some(Token::EnumSeqEnd) => Ok(()),
Some(token) => Err(Error::UnexpectedToken(token)),
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
@@ -683,37 +674,28 @@ 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 });
Ok(Some(try!(Deserialize::deserialize(self.de))))
seed.deserialize(&mut *self.de).map(Some)
}
Some(&Token::MapEnd) => Ok(None),
Some(_) => {
let token = self.de.tokens.next().unwrap();
Err(Error::UnexpectedToken(token))
}
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
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,
{
Ok(try!(Deserialize::deserialize(self.de)))
}
fn end(&mut self) -> Result<(), Error> {
//assert_eq!(self.len.unwrap_or(0), 0);
match self.de.tokens.next() {
Some(Token::MapEnd) => Ok(()),
Some(token) => Err(Error::UnexpectedToken(token)),
None => Err(Error::EndOfStream),
}
seed.deserialize(&mut *self.de)
}
fn size_hint(&self) -> (usize, Option<usize>) {
@@ -726,7 +708,7 @@ 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: Option<usize>,
len: usize,
}
impl<'a, I> MapVisitor for DeserializerStructVisitor<'a, I>
@@ -734,76 +716,74 @@ 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.map(|len| if len > 0 { len - 1} else { 0 });
Ok(Some(try!(Deserialize::deserialize(self.de))))
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::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
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,
{
Ok(try!(Deserialize::deserialize(self.de)))
}
fn end(&mut self) -> Result<(), Error> {
//assert_eq!(self.len.unwrap_or(0), 0);
match self.de.tokens.next() {
Some(Token::StructEnd) => Ok(()),
Some(token) => Err(Error::UnexpectedToken(token)),
None => Err(Error::EndOfStream),
}
seed.deserialize(&mut *self.de)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len.unwrap_or(0);
(len, self.len)
(self.len, Some(self.len))
}
}
//////////////////////////////////////////////////////////////////////////
struct DeserializerVariantVisitor<'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> VariantVisitor for DeserializerVariantVisitor<'a, I>
impl<'a, I> EnumVisitor for DeserializerEnumVisitor<'a, I>
where I: Iterator<Item=Token<'static>>,
{
type Error = Error;
type Variant = Self;
fn visit_variant<V>(&mut self) -> Result<V, 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))
| Some(&Token::EnumNewType(_, v))
| Some(&Token::EnumSeqStart(_, v, _))
| Some(&Token::EnumMapStart(_, v, _)) => {
let mut de = de::value::ValueDeserializer::<Error>::into_deserializer(v);
let value = try!(Deserialize::deserialize(&mut de));
Ok(value)
let de = v.into_deserializer();
let value = try!(seed.deserialize(de));
Ok((value, self))
}
Some(_) => {
Deserialize::deserialize(self.de)
let value = try!(seed.deserialize(&mut *self.de));
Ok((value, self))
}
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
}
fn visit_unit(&mut self) -> Result<(), Error> {
impl<'a, I> VariantVisitor for DeserializerEnumVisitor<'a, I>
where I: Iterator<Item=Token<'static>>
{
type Error = Error;
fn visit_unit(self) -> Result<(), Error> {
match self.de.tokens.peek() {
Some(&Token::EnumUnit(_, _)) => {
self.de.tokens.next();
@@ -812,26 +792,26 @@ impl<'a, I> VariantVisitor for DeserializerVariantVisitor<'a, I>
Some(_) => {
Deserialize::deserialize(self.de)
}
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
fn visit_newtype<T>(&mut 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),
None => Err(Error::EndOfTokens),
}
}
fn visit_tuple<V>(&mut self,
fn visit_tuple<V>(self,
len: usize,
visitor: V) -> Result<V::Value, Error>
where V: Visitor,
@@ -856,13 +836,13 @@ impl<'a, I> VariantVisitor for DeserializerVariantVisitor<'a, I>
}
}
Some(_) => {
Deserialize::deserialize(self.de)
de::Deserializer::deserialize(self.de, visitor)
}
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
fn visit_struct<V>(&mut self,
fn visit_struct<V>(self,
fields: &'static [&'static str],
visitor: V) -> Result<V::Value, Error>
where V: Visitor,
@@ -887,9 +867,9 @@ impl<'a, I> VariantVisitor for DeserializerVariantVisitor<'a, I>
}
}
Some(_) => {
Deserialize::deserialize(self.de)
de::Deserializer::deserialize(self.de, visitor)
}
None => Err(Error::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
}
@@ -906,37 +886,28 @@ 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 });
Ok(Some(try!(Deserialize::deserialize(self.de))))
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::EndOfStream),
None => Err(Error::EndOfTokens),
}
}
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,
{
Ok(try!(Deserialize::deserialize(self.de)))
}
fn end(&mut self) -> Result<(), Error> {
//assert_eq!(self.len.unwrap_or(0), 0);
match self.de.tokens.next() {
Some(Token::EnumMapEnd) => Ok(()),
Some(token) => Err(Error::UnexpectedToken(token)),
None => Err(Error::EndOfStream),
}
seed.deserialize(&mut *self.de)
}
fn size_hint(&self) -> (usize, Option<usize>) {
+21 -60
View File
@@ -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",
}
}
}
+210 -177
View File
@@ -1,9 +1,6 @@
use std::marker::PhantomData;
use serde::ser::{
self,
Serialize,
};
use serde::{ser, Serialize};
use error::Error;
use token::Token;
@@ -30,294 +27,330 @@ impl<'a, I> Serializer<'a, I>
}
}
impl<'a, I> ser::Serializer for Serializer<'a, I>
impl<'s, 'a, I> ser::Serializer for &'s mut Serializer<'a, I>
where I: Iterator<Item=&'a Token<'a>>,
{
type Ok = ();
type Error = Error;
type MapState = ();
type SeqState = ();
type TupleState = ();
type TupleStructState = ();
type TupleVariantState = ();
type StructState = ();
type StructVariantState = ();
fn serialize_unit(&mut self) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::Unit));
Ok(())
}
type SerializeSeq = Self;
type SerializeTuple = Self;
type SerializeTupleStruct = Self;
type SerializeTupleVariant = Self;
type SerializeMap = Self;
type SerializeStruct = Self;
type SerializeStructVariant = Self;
fn serialize_newtype_variant<T>(&mut 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)));
value.serialize(self)
}
fn serialize_unit_struct(&mut self, name: &str) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::UnitStruct(name)));
Ok(())
}
fn serialize_unit_variant(&mut self,
name: &str,
_variant_index: usize,
variant: &str) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::EnumUnit(name, variant)));
Ok(())
}
fn serialize_bool(&mut self, v: bool) -> Result<(), Error> {
fn serialize_bool(self, v: bool) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::Bool(v)));
Ok(())
}
fn serialize_isize(&mut self, v: isize) -> Result<(), Error> {
fn serialize_isize(self, v: isize) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::Isize(v)));
Ok(())
}
fn serialize_i8(&mut self, v: i8) -> Result<(), Error> {
fn serialize_i8(self, v: i8) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::I8(v)));
Ok(())
}
fn serialize_i16(&mut self, v: i16) -> Result<(), Error> {
fn serialize_i16(self, v: i16) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::I16(v)));
Ok(())
}
fn serialize_i32(&mut self, v: i32) -> Result<(), Error> {
fn serialize_i32(self, v: i32) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::I32(v)));
Ok(())
}
fn serialize_i64(&mut self, v: i64) -> Result<(), Error> {
fn serialize_i64(self, v: i64) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::I64(v)));
Ok(())
}
fn serialize_usize(&mut self, v: usize) -> Result<(), Error> {
fn serialize_usize(self, v: usize) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::Usize(v)));
Ok(())
}
fn serialize_u8(&mut self, v: u8) -> Result<(), Error> {
fn serialize_u8(self, v: u8) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::U8(v)));
Ok(())
}
fn serialize_u16(&mut self, v: u16) -> Result<(), Error> {
fn serialize_u16(self, v: u16) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::U16(v)));
Ok(())
}
fn serialize_u32(&mut self, v: u32) -> Result<(), Error> {
fn serialize_u32(self, v: u32) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::U32(v)));
Ok(())
}
fn serialize_u64(&mut self, v: u64) -> Result<(), Error> {
fn serialize_u64(self, v: u64) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::U64(v)));
Ok(())
}
fn serialize_f32(&mut self, v: f32) -> Result<(), Error> {
fn serialize_f32(self, v: f32) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::F32(v)));
Ok(())
}
fn serialize_f64(&mut self, v: f64) -> Result<(), Error> {
fn serialize_f64(self, v: f64) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::F64(v)));
Ok(())
}
fn serialize_char(&mut self, v: char) -> Result<(), Error> {
fn serialize_char(self, v: char) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::Char(v)));
Ok(())
}
fn serialize_str(&mut self, v: &str) -> Result<(), Error> {
fn serialize_str(self, v: &str) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::Str(v)));
Ok(())
}
fn serialize_none(&mut self) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::Option(false)));
fn serialize_bytes(self, value: &[u8]) -> Result<(), Self::Error> {
assert_eq!(self.tokens.next(), Some(&Token::Bytes(value)));
Ok(())
}
fn serialize_some<V>(&mut self, value: V) -> Result<(), Error>
where V: Serialize,
{
assert_eq!(self.tokens.next(), Some(&Token::Option(true)));
value.serialize(self)
}
fn serialize_seq<'b>(&'b mut self, len: Option<usize>) -> Result<(), Error>
{
assert_eq!(self.tokens.next(), Some(&Token::SeqStart(len)));
fn serialize_unit(self) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::Unit));
Ok(())
}
fn serialize_seq_elt<T>(&mut self, _: &mut (), value: T) -> Result<(), Error>
where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::SeqSep));
value.serialize(self)
}
fn serialize_seq_end(&mut self, _: ()) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::SeqEnd));
fn serialize_unit_struct(self, name: &str) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::UnitStruct(name)));
Ok(())
}
fn serialize_seq_fixed_size(&mut self, len: usize) -> Result<(), Error>
{
assert_eq!(self.tokens.next(), Some(&Token::SeqArrayStart(len)));
fn serialize_unit_variant(self,
name: &str,
_variant_index: usize,
variant: &str) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::EnumUnit(name, variant)));
Ok(())
}
fn serialize_tuple(&mut self, len: usize) -> Result<(), Error>
{
assert_eq!(self.tokens.next(), Some(&Token::TupleStart(len)));
Ok(())
}
fn serialize_tuple_elt<T>(&mut self, _: &mut (), value: T) -> Result<(), Error>
where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::TupleSep));
value.serialize(self)
}
fn serialize_tuple_end(&mut self, _: ()) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::TupleEnd));
Ok(())
}
fn serialize_newtype_struct<T>(&mut 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_tuple_struct(&mut self, name: &'static str, len: usize) -> 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::TupleStructStart(name, len)));
Ok(())
}
fn serialize_tuple_struct_elt<T>(&mut self, _: &mut (), value: T) -> Result<(), Error>
where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::TupleStructSep));
assert_eq!(self.tokens.next(), Some(&Token::EnumNewType(name, variant)));
value.serialize(self)
}
fn serialize_tuple_struct_end(&mut self, _: ()) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::TupleStructEnd));
fn serialize_none(self) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::Option(false)));
Ok(())
}
fn serialize_tuple_variant(&mut self,
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)
}
fn serialize_seq(self, len: Option<usize>) -> Result<Self, Error> {
assert_eq!(self.tokens.next(), Some(&Token::SeqStart(len)));
Ok(self)
}
fn serialize_seq_fixed_size(self, len: usize) -> Result<Self, Error> {
assert_eq!(self.tokens.next(), Some(&Token::SeqArrayStart(len)));
Ok(self)
}
fn serialize_tuple(self, len: usize) -> Result<Self, Error> {
assert_eq!(self.tokens.next(), Some(&Token::TupleStart(len)));
Ok(self)
}
fn serialize_tuple_struct(self, name: &'static str, len: usize) -> Result<Self, Error> {
assert_eq!(self.tokens.next(), Some(&Token::TupleStructStart(name, len)));
Ok(self)
}
fn serialize_tuple_variant(self,
name: &str,
_variant_index: usize,
variant: &str,
len: usize) -> Result<(), Error>
len: usize) -> Result<Self, Error>
{
assert_eq!(self.tokens.next(), Some(&Token::EnumSeqStart(name, variant, len)));
Ok(())
Ok(self)
}
fn serialize_tuple_variant_elt<T>(&mut self, _: &mut (), value: T) -> Result<(), Error>
where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::EnumSeqSep));
value.serialize(self)
}
fn serialize_tuple_variant_end(&mut self, _: ()) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::EnumSeqEnd));
Ok(())
}
fn serialize_map(&mut self, len: Option<usize>) -> Result<(), Error>
{
fn serialize_map(self, len: Option<usize>) -> Result<Self, Error> {
assert_eq!(self.tokens.next(), Some(&Token::MapStart(len)));
Ok(())
Ok(self)
}
fn serialize_map_key<T>(&mut self, _: &mut (), key: T) -> Result<(), Self::Error> where T: Serialize {
assert_eq!(self.tokens.next(), Some(&Token::MapSep));
key.serialize(self)
}
fn serialize_map_value<T>(&mut self, _: &mut (), value: T) -> Result<(), Self::Error> where T: Serialize {
value.serialize(self)
}
fn serialize_map_end(&mut self, _: ()) -> Result<(), Self::Error> {
assert_eq!(self.tokens.next(), Some(&Token::MapEnd));
Ok(())
}
fn serialize_struct(&mut self, name: &str, len: usize) -> Result<(), Error>
{
fn serialize_struct(self, name: &str, len: usize) -> Result<Self, Error> {
assert_eq!(self.tokens.next(), Some(&Token::StructStart(name, len)));
Ok(())
Ok(self)
}
fn serialize_struct_elt<V>(&mut self, _: &mut (), key: &'static str, value: V) -> Result<(), Self::Error> where V: Serialize {
assert_eq!(self.tokens.next(), Some(&Token::StructSep));
try!(key.serialize(self));
value.serialize(self)
}
fn serialize_struct_end(&mut self, _: ()) -> Result<(), Self::Error> {
assert_eq!(self.tokens.next(), Some(&Token::StructEnd));
Ok(())
}
fn serialize_struct_variant(&mut self,
fn serialize_struct_variant(self,
name: &str,
_variant_index: usize,
variant: &str,
len: usize) -> Result<(), Error>
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>>,
{
type Ok = ();
type Error = Error;
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::SeqSep));
value.serialize(&mut **self)
}
fn end(self) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::SeqEnd));
Ok(())
}
}
fn serialize_struct_variant_elt<V>(&mut self, _: &mut (), key: &'static str, value: V) -> Result<(), Self::Error> where V: Serialize {
assert_eq!(self.tokens.next(), Some(&Token::EnumMapSep));
try!(key.serialize(self));
value.serialize(self)
impl<'s, 'a, I> ser::SerializeTuple for &'s mut Serializer<'a, I>
where I: Iterator<Item=&'a Token<'a>>,
{
type Ok = ();
type Error = Error;
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::TupleSep));
value.serialize(&mut **self)
}
fn serialize_struct_variant_end(&mut self, _: ()) -> Result<(), Self::Error> {
fn end(self) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::TupleEnd));
Ok(())
}
}
impl<'s, 'a, I> ser::SerializeTupleStruct for &'s mut Serializer<'a, I>
where I: Iterator<Item=&'a Token<'a>>,
{
type Ok = ();
type Error = Error;
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::TupleStructSep));
value.serialize(&mut **self)
}
fn end(self) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::TupleStructEnd));
Ok(())
}
}
impl<'s, 'a, I> ser::SerializeTupleVariant for &'s mut Serializer<'a, I>
where I: Iterator<Item=&'a Token<'a>>,
{
type Ok = ();
type Error = Error;
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where T: Serialize
{
assert_eq!(self.tokens.next(), Some(&Token::EnumSeqSep));
value.serialize(&mut **self)
}
fn end(self) -> Result<(), Error> {
assert_eq!(self.tokens.next(), Some(&Token::EnumSeqEnd));
Ok(())
}
}
impl<'s, 'a, I> ser::SerializeMap for &'s mut Serializer<'a, I>
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 {
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 {
value.serialize(&mut **self)
}
fn end(self) -> Result<(), Self::Error> {
assert_eq!(self.tokens.next(), Some(&Token::MapEnd));
Ok(())
}
}
impl<'s, 'a, I> ser::SerializeStruct for &'s mut Serializer<'a, I>
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 {
assert_eq!(self.tokens.next(), Some(&Token::StructSep));
try!(key.serialize(&mut **self));
value.serialize(&mut **self)
}
fn end(self) -> Result<(), Self::Error> {
assert_eq!(self.tokens.next(), Some(&Token::StructEnd));
Ok(())
}
}
impl<'s, 'a, I> ser::SerializeStructVariant for &'s mut Serializer<'a, I>
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 {
assert_eq!(self.tokens.next(), Some(&Token::EnumMapSep));
try!(key.serialize(&mut **self));
value.serialize(&mut **self)
}
fn end(self) -> Result<(), Self::Error> {
assert_eq!(self.tokens.next(), Some(&Token::EnumMapEnd));
Ok(())
}
fn serialize_bytes(&mut self, value: &[u8]) -> Result<(), Self::Error> {
let mut state = try!(self.serialize_seq(Some(value.len())));
for c in value {
try!(self.serialize_seq_elt(&mut state, c));
}
self.serialize_seq_end(state)
}
}
+1
View File
@@ -17,6 +17,7 @@ pub enum Token<'a> {
Str(&'a str),
String(String),
Bytes(&'a [u8]),
ByteBuf(Vec<u8>),
Option(bool),
+2 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "serde_testing"
version = "0.8.20"
version = "0.9.0-rc3"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "A generic serialization/deserialization framework"
@@ -10,6 +10,7 @@ documentation = "https://docs.serde.rs/serde/"
readme = "README.md"
keywords = ["serialization"]
build = "build.rs"
publish = false
[features]
unstable-testing = ["clippy", "serde/unstable-testing", "serde_codegen/unstable-testing"]
+2
View File
@@ -1,4 +1,6 @@
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![cfg_attr(feature = "unstable-testing", feature(non_ascii_idents))]
include!(concat!(env!("OUT_DIR"), "/test.rs"));
+1
View File
@@ -1,4 +1,5 @@
extern crate serde;
extern crate serde_test;
#[macro_use]
mod macros;
+15 -15
View File
@@ -20,12 +20,12 @@ trait ShouldSkip: Sized {
}
trait SerializeWith: Sized {
fn serialize_with<S>(&self, ser: &mut S) -> Result<(), S::Error>
fn serialize_with<S>(&self, ser: S) -> Result<S::Ok, S::Error>
where S: Serializer;
}
trait DeserializeWith: Sized {
fn deserialize_with<D>(de: &mut D) -> Result<Self, D::Error>
fn deserialize_with<D>(de: D) -> Result<Self, D::Error>
where D: Deserializer;
}
@@ -38,7 +38,7 @@ impl ShouldSkip for i32 {
}
impl SerializeWith for i32 {
fn serialize_with<S>(&self, ser: &mut S) -> Result<(), S::Error>
fn serialize_with<S>(&self, ser: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
if *self == 123 {
@@ -50,7 +50,7 @@ impl SerializeWith for i32 {
}
impl DeserializeWith for i32 {
fn deserialize_with<D>(de: &mut D) -> Result<Self, D::Error>
fn deserialize_with<D>(de: D) -> Result<Self, D::Error>
where D: Deserializer
{
if try!(Deserialize::deserialize(de)) {
@@ -145,7 +145,7 @@ fn test_default_enum() {
assert_de_tokens(
&DefaultEnum::Struct { a1: 1, a2: 2, a3: 3, a4: 0, a5: 123 },
&[
Token::EnumMapStart("DefaultEnum", "Struct", 5),
Token::EnumMapStart("DefaultEnum", "Struct", 3),
Token::EnumMapSep,
Token::Str("a1"),
@@ -174,7 +174,7 @@ fn test_default_enum() {
assert_de_tokens(
&DefaultEnum::Struct { a1: 1, a2: 0, a3: 123, a4: 0, a5: 123 },
&[
Token::EnumMapStart("DefaultEnum", "Struct", 5),
Token::EnumMapStart("DefaultEnum", "Struct", 3),
Token::EnumMapSep,
Token::Str("a1"),
@@ -239,7 +239,7 @@ impl Default for NotDeserializeStruct {
}
impl DeserializeWith for NotDeserializeStruct {
fn deserialize_with<D>(_: &mut D) -> Result<Self, D::Error>
fn deserialize_with<D>(_: D) -> Result<Self, D::Error>
where D: Deserializer
{
panic!()
@@ -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())
);
}
@@ -642,7 +642,7 @@ struct NotSerializeStruct(i8);
enum NotSerializeEnum { Trouble }
impl SerializeWith for NotSerializeEnum {
fn serialize_with<S>(&self, ser: &mut S) -> Result<(), S::Error>
fn serialize_with<S>(&self, ser: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
"trouble".serialize(ser)
@@ -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()),
);
}
+46 -451
View File
@@ -1,460 +1,55 @@
use std::fmt;
use std::error;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
use serde::bytes::{ByteBuf, Bytes};
use serde::ser;
use serde::de;
///////////////////////////////////////////////////////////////////////////////
#[derive(Debug, PartialEq)]
struct Error;
impl ser::Error for Error {
fn custom<T: Into<String>>(_: T) -> Error { Error }
}
impl de::Error for Error {
fn custom<T: Into<String>>(_: T) -> Error { Error }
fn end_of_stream() -> Error { Error }
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
formatter.write_str(format!("{:?}", self).as_ref())
}
}
impl error::Error for Error {
fn description(&self) -> &str {
"Serde Deserialization Error"
}
fn cause(&self) -> Option<&error::Error> {
None
}
}
///////////////////////////////////////////////////////////////////////////////
struct BytesSerializer {
bytes: Vec<u8>,
}
impl BytesSerializer {
fn new(bytes: Vec<u8>) -> Self {
BytesSerializer {
bytes: bytes,
}
}
}
impl Serializer for BytesSerializer {
type Error = Error;
type SeqState = ();
type MapState = ();
type TupleState = ();
type TupleStructState = ();
type TupleVariantState = ();
type StructState = ();
type StructVariantState = ();
fn serialize_unit(&mut self) -> Result<(), Error> {
Err(Error)
}
fn serialize_unit_struct(&mut self, _name: &'static str) -> Result<(), Error> {
Err(Error)
}
fn serialize_unit_variant(&mut self, _: &'static str, _: usize, _: &'static str) -> Result<(), Error> {
Err(Error)
}
fn serialize_bool(&mut self, _v: bool) -> Result<(), Error> {
Err(Error)
}
fn serialize_isize(&mut self, _v: isize) -> Result<(), Error> {
Err(Error)
}
fn serialize_usize(&mut self, _v: usize) -> Result<(), Error> {
Err(Error)
}
fn serialize_i8(&mut self, _v: i8) -> Result<(), Error> {
Err(Error)
}
fn serialize_u8(&mut self, _v: u8) -> Result<(), Error> {
Err(Error)
}
fn serialize_i16(&mut self, _v: i16) -> Result<(), Error> {
Err(Error)
}
fn serialize_u16(&mut self, _v: u16) -> Result<(), Error> {
Err(Error)
}
fn serialize_i32(&mut self, _v: i32) -> Result<(), Error> {
Err(Error)
}
fn serialize_u32(&mut self, _v: u32) -> Result<(), Error> {
Err(Error)
}
fn serialize_i64(&mut self, _v: i64) -> Result<(), Error> {
Err(Error)
}
fn serialize_u64(&mut self, _v: u64) -> Result<(), Error> {
Err(Error)
}
fn serialize_f32(&mut self, _v: f32) -> Result<(), Error> {
Err(Error)
}
fn serialize_f64(&mut self, _v: f64) -> Result<(), Error> {
Err(Error)
}
fn serialize_char(&mut self, _v: char) -> Result<(), Error> {
Err(Error)
}
fn serialize_str(&mut self, _v: &str) -> Result<(), Error> {
Err(Error)
}
fn serialize_none(&mut self) -> Result<(), Error> {
Err(Error)
}
fn serialize_some<V>(&mut self, _value: V) -> Result<(), Error>
where V: Serialize,
{
Err(Error)
}
fn serialize_newtype_struct<V>(&mut self, _: &'static str, _value: V) -> Result<(), Error>
where V: Serialize,
{
Err(Error)
}
fn serialize_newtype_variant<V>(&mut self, _: &'static str, _: usize, _: &'static str, _value: V) -> Result<(), Error>
where V: Serialize,
{
Err(Error)
}
fn serialize_seq(&mut self, _len: Option<usize>) -> Result<(), Error>
{
Err(Error)
}
fn serialize_seq_fixed_size(&mut self, _len: usize) -> Result<(), Error>
{
Err(Error)
}
fn serialize_seq_elt<T>(&mut self, _: &mut (), _value: T) -> Result<(), Error>
where T: Serialize
{
Err(Error)
}
fn serialize_seq_end(&mut self, _: ()) -> Result<(), Error>
{
Err(Error)
}
fn serialize_tuple(&mut self, _len: usize) -> Result<(), Error>
{
Err(Error)
}
fn serialize_tuple_elt<T>(&mut self, _: &mut (), _value: T) -> Result<(), Error>
where T: Serialize
{
Err(Error)
}
fn serialize_tuple_end(&mut self, _: ()) -> Result<(), Error>
{
Err(Error)
}
fn serialize_tuple_struct(&mut self, _: &'static str, _len: usize) -> Result<(), Error>
{
Err(Error)
}
fn serialize_tuple_struct_elt<T>(&mut self, _: &mut (), _value: T) -> Result<(), Error>
where T: Serialize
{
Err(Error)
}
fn serialize_tuple_struct_end(&mut self, _: ()) -> Result<(), Error>
{
Err(Error)
}
fn serialize_tuple_variant(&mut self, _: &'static str, _: usize, _: &'static str, _len: usize) -> Result<(), Error>
{
Err(Error)
}
fn serialize_tuple_variant_elt<T>(&mut self, _: &mut (), _value: T) -> Result<(), Error>
where T: Serialize
{
Err(Error)
}
fn serialize_tuple_variant_end(&mut self, _: ()) -> Result<(), Error>
{
Err(Error)
}
fn serialize_map(&mut self, _: Option<usize>) -> Result<(), Error>
{
Err(Error)
}
fn serialize_map_key<T>(&mut self, _: &mut (), _key: T) -> Result<(), Error>
where T: Serialize
{
Err(Error)
}
fn serialize_map_value<T>(&mut self, _: &mut (), _value: T) -> Result<(), Error>
where T: Serialize
{
Err(Error)
}
fn serialize_map_end(&mut self, _: ()) -> Result<(), Error>
{
Err(Error)
}
fn serialize_struct(&mut self, _: &'static str, _: usize) -> Result<(), Error>
{
Err(Error)
}
fn serialize_struct_elt<V>(&mut self, _: &mut (), _key: &'static str, _value: V) -> Result<(), Error>
where V: Serialize,
{
Err(Error)
}
fn serialize_struct_end(&mut self, _: ()) -> Result<(), Error>
{
Err(Error)
}
fn serialize_struct_variant(&mut self, _: &'static str, _: usize, _: &'static str, _: usize) -> Result<(), Error>
{
Err(Error)
}
fn serialize_struct_variant_elt<V>(&mut self, _: &mut (), _key: &'static str, _value: V) -> Result<(), Error>
where V: Serialize,
{
Err(Error)
}
fn serialize_struct_variant_end(&mut self, _: ()) -> Result<(), Error>
{
Err(Error)
}
fn serialize_bytes(&mut self, bytes: &[u8]) -> Result<(), Error> {
assert_eq!(self.bytes, bytes);
Ok(())
}
}
///////////////////////////////////////////////////////////////////////////////
struct BytesDeserializer {
bytes: Option<Vec<u8>>,
}
impl BytesDeserializer {
fn new(bytes: Vec<u8>) -> Self {
BytesDeserializer {
bytes: Some(bytes),
}
}
}
impl Deserializer for BytesDeserializer {
type Error = Error;
fn deserialize<V>(&mut self, _visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
Err(Error)
}
fn deserialize_bytes<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
visitor.visit_byte_buf(self.bytes.take().unwrap())
}
fn deserialize_seq<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_struct_field<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_map<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_unit<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_ignored_any<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_string<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_str<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_char<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_i64<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_i32<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_i16<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_i8<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_u64<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_u32<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_u16<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_u8<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_f32<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_f64<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_bool<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_usize<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_isize<__V>(&mut self, visitor: __V) -> Result<__V::Value, Self::Error>
where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_option<__V>(&mut self, visitor: __V)
-> Result<__V::Value, Self::Error> where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_seq_fixed_size<__V>(&mut self, _: usize, visitor: __V)
-> Result<__V::Value, Self::Error> where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_unit_struct<__V>(&mut self, _: &str, visitor: __V)
-> Result<__V::Value, Self::Error> where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_newtype_struct<__V>(&mut self, _: &str, visitor: __V)
-> Result<__V::Value, Self::Error> where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_tuple_struct<__V>(&mut self, _: &str, _: usize, visitor: __V)
-> Result<__V::Value, Self::Error> where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_struct<__V>(&mut self, _: &str, _: &[&str], visitor: __V)
-> Result<__V::Value, Self::Error> where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_tuple<__V>(&mut self, _: usize, visitor: __V)
-> Result<__V::Value, Self::Error> where __V: de::Visitor {
self.deserialize(visitor)
}
fn deserialize_enum<__V>(&mut self, _: &str, _: &[&str], _visitor: __V)
-> Result<__V::Value, Self::Error> where __V: de::EnumVisitor {
Err(Error)
}
}
///////////////////////////////////////////////////////////////////////////////
use serde_test::{assert_tokens, assert_ser_tokens, assert_de_tokens, Token};
#[test]
fn test_bytes_ser_bytes() {
let buf = vec![];
let bytes = Bytes::from(&buf);
let mut ser = BytesSerializer::new(vec![]);
bytes.serialize(&mut ser).unwrap();
fn test_bytes() {
let empty = Bytes::new(&[]);
assert_ser_tokens(&empty, &[Token::Bytes(b"")]);
let buf = vec![1, 2, 3];
let bytes = Bytes::from(&buf);
let mut ser = BytesSerializer::new(vec![1, 2, 3]);
bytes.serialize(&mut ser).unwrap();
let buf = vec![65, 66, 67];
let bytes = Bytes::new(&buf);
assert_ser_tokens(&bytes, &[Token::Bytes(b"ABC")]);
}
///////////////////////////////////////////////////////////////////////////////
#[test]
fn test_byte_buf_de_bytes() {
let mut de = BytesDeserializer::new(vec![]);
let bytes = Deserialize::deserialize(&mut de);
assert_eq!(bytes, Ok(ByteBuf::new()));
fn test_byte_buf() {
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, &[
Token::SeqStart(None),
Token::SeqEnd,
]);
assert_de_tokens(&empty, &[
Token::SeqStart(Some(0)),
Token::SeqEnd,
]);
let mut de = BytesDeserializer::new(vec![1, 2, 3]);
let bytes = Deserialize::deserialize(&mut de);
assert_eq!(bytes, Ok(ByteBuf::from(vec![1, 2, 3])));
let buf = ByteBuf::from(vec![65, 66, 67]);
assert_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, &[
Token::SeqStart(None),
Token::SeqSep,
Token::U8(65),
Token::SeqSep,
Token::U8(66),
Token::SeqSep,
Token::U8(67),
Token::SeqEnd,
]);
assert_de_tokens(&buf, &[
Token::SeqStart(Some(3)),
Token::SeqSep,
Token::U8(65),
Token::SeqSep,
Token::U8(66),
Token::SeqSep,
Token::U8(67),
Token::SeqEnd,
]);
}
+98 -4
View File
@@ -32,12 +32,41 @@ struct Struct {
c: i32,
}
#[derive(PartialEq, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct StructDenyUnknown {
a: i32,
#[serde(skip_deserializing)]
b: i32,
}
#[derive(PartialEq, Debug, Deserialize)]
struct StructSkipAll {
#[serde(skip_deserializing)]
a: i32,
}
#[derive(PartialEq, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct StructSkipAllDenyUnknown {
#[serde(skip_deserializing)]
a: i32,
}
#[derive(PartialEq, Debug, Deserialize)]
enum Enum {
#[allow(dead_code)]
#[serde(skip_deserializing)]
Skipped,
Unit,
Simple(i32),
Seq(i32, i32, i32),
Map { a: i32, b: i32, c: i32 },
}
#[derive(PartialEq, Debug, Deserialize)]
enum EnumSkipAll {
#[allow(dead_code)]
#[serde(skip_deserializing)]
Skipped,
}
@@ -680,6 +709,29 @@ declare_tests! {
Token::StructEnd,
],
}
test_struct_skip_all {
StructSkipAll { a: 0 } => &[
Token::StructStart("StructSkipAll", 0),
Token::StructEnd,
],
StructSkipAll { a: 0 } => &[
Token::StructStart("StructSkipAll", 1),
Token::StructSep,
Token::Str("a"),
Token::I32(1),
Token::StructSep,
Token::Str("b"),
Token::I32(2),
Token::StructEnd,
],
}
test_struct_skip_all_deny_unknown {
StructSkipAllDenyUnknown { a: 0 } => &[
Token::StructStart("StructSkipAllDenyUnknown", 0),
Token::StructEnd,
],
}
test_enum_unit {
Enum::Unit => &[
Token::EnumUnit("Enum", "Unit"),
@@ -801,17 +853,51 @@ fn test_net_ipaddr() {
}
declare_error_tests! {
test_unknown_field<StructDenyUnknown> {
&[
Token::StructStart("StructDenyUnknown", 2),
Token::StructSep,
Token::Str("a"),
Token::I32(0),
Token::StructSep,
Token::Str("d"),
],
Error::Message("unknown field `d`, expected `a`".to_owned()),
}
test_skipped_field_is_unknown<StructDenyUnknown> {
&[
Token::StructStart("StructDenyUnknown", 2),
Token::StructSep,
Token::Str("b"),
],
Error::Message("unknown field `b`, expected `a`".to_owned()),
}
test_skip_all_deny_unknown<StructSkipAllDenyUnknown> {
&[
Token::StructStart("StructSkipAllDenyUnknown", 1),
Token::StructSep,
Token::Str("a"),
],
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::Message("unknown variant `Skipped`, there are no variants".to_owned()),
}
test_struct_seq_too_long<Struct> {
&[
@@ -832,7 +918,7 @@ declare_error_tests! {
Token::MapSep,
Token::Str("a"),
],
Error::DuplicateField("a"),
Error::Message("duplicate field `a`".to_owned()),
}
test_duplicate_field_enum<Enum> {
&[
@@ -844,6 +930,14 @@ declare_error_tests! {
Token::EnumMapSep,
Token::Str("a"),
],
Error::DuplicateField("a"),
Error::Message("duplicate field `a`".to_owned()),
}
test_enum_out_of_range<Enum> {
&[
Token::EnumStart("Enum"),
Token::Usize(4),
Token::Unit,
],
Error::Message("invalid value: integer `4`, expected variant index 0 <= i < 4".into()),
}
}
+91 -6
View File
@@ -202,6 +202,91 @@ fn test_gen() {
EmptyStruct {},
}
assert::<EmptyEnumVariant>();
#[cfg(feature = "unstable-testing")]
#[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
struct NonAsciiIdents {
σ: f64
}
#[derive(Serialize, Deserialize)]
struct EmptyBraced {}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct EmptyBracedDenyUnknown {}
#[derive(Serialize, Deserialize)]
struct BracedSkipAll {
#[serde(skip_deserializing)]
f: u8,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct BracedSkipAllDenyUnknown {
#[serde(skip_deserializing)]
f: u8,
}
#[cfg(feature = "unstable-testing")]
#[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
struct EmptyTuple();
#[cfg(feature = "unstable-testing")]
#[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
#[serde(deny_unknown_fields)]
struct EmptyTupleDenyUnknown();
#[derive(Serialize, Deserialize)]
struct TupleSkipAll(#[serde(skip_deserializing)] u8);
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct TupleSkipAllDenyUnknown(#[serde(skip_deserializing)] u8);
#[derive(Serialize, Deserialize)]
enum EmptyEnum {}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
enum EmptyEnumDenyUnknown {}
#[derive(Serialize, Deserialize)]
enum EnumSkipAll {
#[serde(skip_deserializing)]
#[allow(dead_code)]
Variant,
}
#[cfg(feature = "unstable-testing")]
#[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
enum EmptyVariants {
Braced {},
Tuple(),
BracedSkip {
#[serde(skip_deserializing)]
f: u8,
},
TupleSkip(#[serde(skip_deserializing)] u8),
}
#[cfg(feature = "unstable-testing")]
#[cfg_attr(feature = "unstable-testing", derive(Serialize, Deserialize))]
#[serde(deny_unknown_fields)]
enum EmptyVariantsDenyUnknown {
Braced {},
Tuple(),
BracedSkip {
#[serde(skip_deserializing)]
f: u8,
},
TupleSkip(#[serde(skip_deserializing)] u8),
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct UnitDenyUnknown;
}
//////////////////////////////////////////////////////////////////////////
@@ -210,32 +295,32 @@ fn assert<T: Serialize + Deserialize>() {}
fn assert_ser<T: Serialize>() {}
trait SerializeWith {
fn serialize_with<S: Serializer>(_: &Self, _: &mut S) -> StdResult<(), S::Error>;
fn serialize_with<S: Serializer>(_: &Self, _: S) -> StdResult<S::Ok, S::Error>;
}
trait DeserializeWith: Sized {
fn deserialize_with<D: Deserializer>(_: &mut D) -> StdResult<Self, D::Error>;
fn deserialize_with<D: Deserializer>(_: D) -> StdResult<Self, D::Error>;
}
// Implements neither Serialize nor Deserialize
struct X;
fn ser_x<S: Serializer>(_: &X, _: &mut S) -> StdResult<(), S::Error> {
fn ser_x<S: Serializer>(_: &X, _: S) -> StdResult<S::Ok, S::Error> {
unimplemented!()
}
fn de_x<D: Deserializer>(_: &mut D) -> StdResult<X, D::Error> {
fn de_x<D: Deserializer>(_: D) -> StdResult<X, D::Error> {
unimplemented!()
}
impl SerializeWith for X {
fn serialize_with<S: Serializer>(_: &Self, _: &mut S) -> StdResult<(), S::Error> {
fn serialize_with<S: Serializer>(_: &Self, _: S) -> StdResult<S::Ok, S::Error> {
unimplemented!()
}
}
impl DeserializeWith for X {
fn deserialize_with<D: Deserializer>(_: &mut D) -> StdResult<Self, D::Error> {
fn deserialize_with<D: Deserializer>(_: D) -> StdResult<Self, D::Error> {
unimplemented!()
}
}
+77 -3
View File
@@ -15,6 +15,9 @@ use self::serde_test::{
extern crate fnv;
use self::fnv::FnvHasher;
#[cfg(feature = "unstable")]
use serde::ser::iterator;
//////////////////////////////////////////////////////////////////////////
#[derive(Serialize)]
@@ -30,12 +33,20 @@ struct Struct {
c: i32,
}
#[derive(Serialize)]
#[derive(Serialize, PartialEq, Debug)]
enum Enum {
Unit,
One(i32),
Seq(i32, i32),
Map { a: i32, b: i32 },
#[serde(skip_serializing)]
SkippedUnit,
#[serde(skip_serializing)]
SkippedOne(i32),
#[serde(skip_serializing)]
SkippedSeq(i32, i32),
#[serde(skip_serializing)]
SkippedMap { _a: i32, _b: i32 },
}
//////////////////////////////////////////////////////////////////////////
@@ -361,6 +372,49 @@ declare_ser_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() {
@@ -378,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);
@@ -386,5 +440,25 @@ 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]
fn test_enum_skipped() {
assert_ser_tokens_error(
&Enum::SkippedUnit,
&[],
Error::Message("the enum variant Enum::SkippedUnit cannot be serialized".to_owned()));
assert_ser_tokens_error(
&Enum::SkippedOne(42),
&[],
Error::Message("the enum variant Enum::SkippedOne cannot be serialized".to_owned()));
assert_ser_tokens_error(
&Enum::SkippedSeq(1, 2),
&[],
Error::Message("the enum variant Enum::SkippedSeq cannot be serialized".to_owned()));
assert_ser_tokens_error(
&Enum::SkippedMap { _a: 1, _b: 2 },
&[],
Error::Message("the enum variant Enum::SkippedMap cannot be serialized".to_owned()));
}