Compare commits

...

185 Commits

Author SHA1 Message Date
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 08c59a2e0e Release 0.8.20 2016-12-16 07:58:52 -08:00
David Tolnay 4a0bf4de65 Merge pull request #641 from shinglyu/deser_enum
Implemented skip_deserializing for enum
2016-12-16 07:53:34 -08:00
Shing Lyu 95ffca9bbe Implemented skip_deserializing for enum 2016-12-16 20:29:21 +08:00
David Tolnay 5e47c87ba0 Add test for deserializing unit to string 2016-12-01 04:46:29 -08:00
David Tolnay c6d5d9be14 Merge pull request #635 from serde-rs/oli-obk-patch-1
Enable deserializing an empty `String` from a unit value
2016-12-01 07:46:07 -05:00
Oliver Schneider d63d09f4db Enable deserializing an empty String from a unit value 2016-12-01 11:23:12 +01:00
David Tolnay de6d00c306 Merge pull request #628 from serde-rs/str
Do not copy tokens to String after expanding
2016-11-24 17:33:19 -05:00
David Tolnay 5bda95ba81 Do not copy tokens to String after expanding 2016-11-24 13:07:47 -08:00
David Tolnay 36641e7b81 Release 0.8.19 2016-11-23 09:14:03 -08:00
David Tolnay 6eca34c45c Drop libsyntax 2016-11-23 09:13:21 -08:00
David Tolnay 7efa0153b0 Drop testing on rust 1.10 2016-11-19 15:24:40 -08:00
David Tolnay 8dba87661b Bump serde_codegen_internals because it failed to publish somehow 2016-11-19 11:47:19 -08:00
David Tolnay 17fb4cb503 Release 0.8.18 2016-11-19 11:40:00 -08:00
David Tolnay 5bd0386b8e Merge pull request #618 from serde-rs/up
Ask proc_macro_derive to ignore serde attributes
2016-11-19 14:19:15 -05:00
David Tolnay 8b484c9703 Hide the serde_codegen functions from docs 2016-11-15 21:37:19 -05:00
David Tolnay a16f07858b Ask proc_macro_derive to ignore serde attributes 2016-11-15 21:29:34 -05:00
David Tolnay 133d117bf4 Bump post-expansion dependency 2016-11-07 11:16:14 -08:00
David Tolnay e7f3a80867 Update serde codegen to syn 0.10 2016-11-02 22:58:55 -07:00
David Tolnay f8c3d225a3 Shorten the syn meta item matches 2016-11-02 22:56:27 -07:00
David Tolnay 6d40d9e8ec Update codegen internals to syn 0.10 2016-11-02 22:52:20 -07:00
David Tolnay c91fca19e1 Release 0.8.17 2016-11-02 09:26:04 -07:00
David Tolnay f13a805530 Merge pull request #605 from serde-rs/up
Bump syntex to 0.48
2016-11-02 09:24:55 -07:00
David Tolnay 54802983b8 Bump syntex to 0.48 2016-11-02 09:12:22 -07:00
David Tolnay f430d9d1c8 Remove unneeded type ascription 2016-10-23 21:06:50 -07:00
David Tolnay c9612a2f57 Release 0.8.16 2016-10-22 00:07:27 -07:00
David Tolnay 7ffea5a716 Bump syntex to 0.46 2016-10-21 23:38:27 -07:00
David Tolnay c8c9f7d96c Merge pull request #599 from TheCatPlusPlus/master
Explictly discard result of visiting IgnoredAny
2016-10-21 23:36:57 -07:00
Cat Plus Plus f75d286b90 Explictly discard result of visiting IgnoredAny
Makes the code generated by `derive(Deserialize)` compile cleanly when
`unused_results` lint is enabled.
2016-10-22 08:00:44 +02:00
David Tolnay 9acb17ab54 Release 0.8.15 2016-10-20 08:42:40 -07:00
David Tolnay f15ff1868e Merge pull request #597 from serde-rs/cov
Drop coveralls
2016-10-20 00:44:19 -07:00
David Tolnay 86f0d0382f Drop coveralls
Has not been uploading for months.
2016-10-20 00:33:03 -07:00
David Tolnay 8595b25763 Merge pull request #592 from serde-rs/post
Use post-expansion crate to let other custom derives see serde attrs
2016-10-20 00:18:23 -07:00
David Tolnay 49aca521f1 Bump post-expansion dependency 2016-10-20 00:01:14 -07:00
David Tolnay 4c38bd0180 Merge branch origin/master into origin/post 2016-10-19 23:59:53 -07:00
Homu 02c4ff7b7e Auto merge of #594 - serde-rs:expr, r=oli-obk
No longer need `e!`

This compiles all the way back to Rust 1.7.0, and 1.6.0 fails for other reasons so I think we are clear here. The referenced issue https://github.com/rust-lang/rust/issues/19630 is still open so they must have fixed it some other way.
2016-10-19 18:07:10 +09:00
David Tolnay a8d1c0253a Merge pull request #593 from serde-rs/rmbench
Remove benchmarks
2016-10-19 00:48:05 -07:00
David Tolnay bb5370b746 No longer need e! 2016-10-19 00:30:23 -07:00
David Tolnay 536e78a146 Remove benchmarks
Nobody noticed these did not compile for 3 months, so I am guessing nobody
cares. The JSON benchmarks at https://github.com/serde-rs/json-benchmark are
much more relevant.
2016-10-18 22:19:10 -07:00
David Tolnay 21c9446890 Update benchmarks to serde 0.8 2016-10-18 22:15:54 -07:00
David Tolnay 1b42f3f594 Release 0.8.14 2016-10-18 21:42:39 -07:00
David Tolnay cafa02d9b4 Merge pull request #591 from serde-rs/sess
Not safe to share Spans from one ParseSess to another
2016-10-18 21:41:05 -07:00
David Tolnay a9b6cbb8b3 Use post-expansion crate to let other custom derives see serde attrs 2016-10-18 09:00:33 -07:00
David Tolnay 1d719b542c Not safe to share Spans from one ParseSess to another
Spans in the AST returned by `parse_item_from_source_str` and other parsing
functions contain byte offsets into the source code they were parsed from. The
pretty printer uses these Spans [here][1] to preserve the representation of
literals when parsing and printing back out unmodified.

In this bug, the byte offset of a string in the input to
`parse_item_from_source_str` coincidentally matched the byte offset of a totally
different string in the input to `parse_crate_from_file` called [here][2] by
Syntex. The Span from the former triggered the pretty printer to write out the
content of the latter.

By using the same ParseSess, Spans from the two `parse_*` calls never collide.

[1]: https://github.com/rust-lang/rust/blob/1.12.0/src/libsyntax/print/pprust.rs#L628
[2]: https://github.com/serde-rs/syntex/blob/v0.45.0/syntex/src/registry.rs#L134
2016-10-17 23:12:32 -07:00
David Tolnay 532b950971 Release 0.8.13 2016-10-16 10:34:26 -07:00
Erick Tryzelaar f93b4e91e6 Version bump serde_derive to 0.8.13 2016-10-15 15:24:37 -07:00
Erick Tryzelaar 94e2ccc94e Merge pull request #588 from erickt/master
Drop support for rust 1.8.0 and 1.9.0.
2016-10-15 15:12:56 -07:00
Erick Tryzelaar cbe6b4c97c Drop support for rust 1.8.0 and 1.9.0. 2016-10-15 14:43:30 -07:00
Erick Tryzelaar a46a4e27dd Merge pull request #587 from erickt/master
Update syntex version to 0.45.0
2016-10-15 14:43:13 -07:00
Erick Tryzelaar 4919a3184d Update syntex version to 0.45.0 2016-10-15 14:01:14 -07:00
David Tolnay 0b19608d85 Merge pull request #584 from serde-rs/array-tuple
Array and tuple deserialization cleanup
2016-10-14 08:43:08 -07:00
David Tolnay 99bddddd8e Array and tuple deserialization cleanup 2016-10-14 00:15:24 -07:00
David Tolnay 85c95040b3 Release 0.8.12 2016-10-08 15:38:29 -07:00
David Tolnay 339c0f5493 Remove unneeded test feature 2016-10-08 15:36:46 -07:00
David Tolnay b4d5c26f4e Update to latest syn and quote 2016-10-08 15:36:02 -07:00
David Tolnay f4e1ffa2cb Merge pull request #578 from mjroghelia/rename_rustc_macro
Rename rustc_macro to proc_macro
2016-10-08 15:35:15 -07:00
Mark Roghelia ef5d09e144 Rename rustc_macro to proc_macro
Fixes #575
2016-10-08 18:29:36 -04:00
David Tolnay e547a06639 Simplify deserialize_field_visitor 2016-10-03 13:45:11 -07:00
David Tolnay c61b20cceb Release 0.8.11 2016-10-03 13:38:52 -07:00
David Tolnay 42987a5b24 Fix break in quote 0.2.2 2016-10-03 13:37:46 -07:00
David Tolnay 3f28a93240 Update readme to serde_derive 2016-09-29 09:21:01 -07:00
David Tolnay 9970084550 Merge pull request #568 from tbu-/pr_ipaddr_stable
Allow the use of `IpAddr` implementations on stable
2016-09-29 08:58:33 -07:00
Tobias Bucher 3920993370 Allow the use of IpAddr implementations on stable
Also use the same strategy for serialization as for deserialization of
`IpAddr`.

Fixes #551.
2016-09-29 15:48:59 +02:00
David Tolnay 22690cedc2 Merge pull request #566 from serde-rs/del
Delete serde_macros
2016-09-28 13:32:02 -07:00
David Tolnay b27039d34d Compiletest error messages 2016-09-28 12:46:54 -07:00
David Tolnay 1b6fd5a362 Delete serde_macros 2016-09-28 11:59:25 -07:00
David Tolnay 8b7b886036 Test serde_derive instead of serde_macros 2016-09-28 11:19:27 -07:00
David Tolnay 2a2c098eeb Release 0.8.10 2016-09-28 09:56:15 -07:00
David Tolnay f68f32d3ee Merge pull request #564 from serde-rs/cleanup
Clean up syn workarounds
2016-09-28 09:48:45 -07:00
David Tolnay 6ccb6c9130 Clean up syn workarounds 2016-09-28 09:29:12 -07:00
David Tolnay 49d24a1377 Merge pull request #548 from serde-rs/syn
No more syntex for serde_derive
2016-09-28 09:28:48 -07:00
David Tolnay b0eee50947 Merge branch origin/master into origin/syn
Conflicts:
    serde_macros/tests/compile-fail/reject-unknown-attributes.rs
2016-09-28 09:27:04 -07:00
David Tolnay 554b81d636 Fix compiletest error in newest nightly 2016-09-28 09:25:19 -07:00
David Tolnay 9fe16767c5 Use iter::repeat to build phantom exprs 2016-09-28 08:57:53 -07:00
David Tolnay 3a3777a2fb Merge branch origin/master into origin/syn
Conflicts:
    serde_codegen/Cargo.toml
2016-09-27 09:59:36 -07:00
David Tolnay effa298871 Fix differences in the generated code 2016-09-27 09:56:35 -07:00
David Tolnay 9a86e6818f Use push_str to support old compilers 2016-09-27 00:47:54 -07:00
David Tolnay 7d09b1475c Fix clippy lints in serde_codegen 2016-09-27 00:46:03 -07:00
David Tolnay 7e441e5110 Handle various attribute parsing error cases 2016-09-27 00:40:37 -07:00
David Tolnay 40b874214a Update tests to new location of errors 2016-09-27 00:17:00 -07:00
David Tolnay 0c18c151e2 Revamp serde_codegen_internals error handling 2016-09-27 00:11:37 -07:00
David Tolnay 4ad6c4fd56 Include unknown attribute name in error message 2016-09-27 00:02:15 -07:00
David Tolnay 8ee8c07090 Mark all serde attributes as used 2016-09-26 23:17:43 -07:00
David Tolnay 8e77960e3a Remove with-libsyntax feature 2016-09-26 23:17:33 -07:00
David Tolnay 819d47fea2 Merge pull request #560 from serde-rs/up
Bump quasi and aster
2016-09-26 22:23:18 -07:00
David Tolnay 8e865f62c4 Fix conflicts with the __serde_state commit 2016-09-26 22:13:53 -07:00
David Tolnay 6cbf0d32da Merge branch origin/master into origin/syn
Conflicts:
    serde_codegen/src/ser.rs
2016-09-26 22:11:14 -07:00
David Tolnay 20afa85087 Bump quasi and aster 2016-09-26 22:08:21 -07:00
David Tolnay da6d967776 Merge pull request #558 from erickt/fix-serde-state
Make serde state variable unique by naming it __serde_state
2016-09-26 21:58:45 -07:00
Erick Tryzelaar f47a50e996 Make serde state variable unique by naming it __serde_state
Closes #557
2016-09-26 21:44:30 -07:00
David Tolnay 1eca7766ba Bump syn dependency 2016-09-24 09:54:10 -07:00
David Tolnay 51f95575ec Merge branch origin/master into origin/syn
Conflicts:
    serde_codegen/Cargo.toml
    serde_codegen_internals/Cargo.toml
    serde_derive/Cargo.toml
2016-09-24 09:29:21 -07:00
David Tolnay a69b82c7c5 Recursion limit 2016-09-12 01:26:47 -07:00
David Tolnay 55e5f19437 Same for deserialization 2016-09-12 00:50:30 -07:00
David Tolnay c34baa1e5f No more syntex for serde_derive 2016-09-11 19:55:13 -07:00
David Tolnay 85f1bf0259 Enum deserialization API 2016-08-23 22:17:28 -04:00
71 changed files with 2806 additions and 5846 deletions
+6 -14
View File
@@ -1,17 +1,11 @@
sudo: false
language: rust
rust:
- 1.12.0
- 1.13.0
- stable
- nightly
- 1.8.0
- 1.9.0
- beta
addons:
apt:
packages:
- libcurl4-openssl-dev
- libelf-dev
- libdw-dev
- nightly
before_script:
- pip install 'travis-cargo<0.2' --user
- export PATH=$HOME/.local/bin:$PATH
@@ -24,12 +18,10 @@ script:
- (cd serde && travis-cargo --only nightly build -- --no-default-features --features collections)
- (cd testing && travis-cargo --skip nightly test)
- (cd testing && travis-cargo --only nightly test -- --features unstable-testing)
- (cd serde_macros && travis-cargo --only nightly test -- --features unstable-testing)
- (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 && travis-cargo --only nightly test)
#- (cd examples/serde-syntex-example && travis-cargo --skip nightly run)
#- (cd examples/serde-syntex-example && travis-cargo --only nightly run -- --no-default-features --features unstable)
- (cd serde && travis-cargo --only stable doc)
after_success:
- (cd testing && travis-cargo --only stable coveralls --no-sudo)
env:
global:
- TRAVIS_CARGO_NIGHTLY_FEATURE=""
+6 -4
View File
@@ -11,12 +11,13 @@ 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(plugin, custom_derive)]
#![plugin(serde_macros)]
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
@@ -48,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
+3 -2
View File
@@ -3,15 +3,16 @@ name = "serde-syntex-example"
version = "0.1.0"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
build = "build.rs"
publish = false
[features]
default = ["serde_codegen"]
unstable = ["serde_macros"]
unstable = ["serde_derive"]
[build-dependencies]
serde_codegen = { version = "^0.8", optional = true, path = "../../serde_codegen" }
[dependencies]
serde = "^0.8"
serde_derive = { version = "^0.8", optional = true, path = "../../serde_derive" }
serde_json = "^0.8"
serde_macros = { version = "^0.8", optional = true, path = "../../serde_macros" }
+2 -2
View File
@@ -1,4 +1,4 @@
#[cfg(not(feature = "serde_macros"))]
#[cfg(not(feature = "serde_derive"))]
mod inner {
extern crate serde_codegen;
@@ -15,7 +15,7 @@ mod inner {
}
}
#[cfg(feature = "serde_macros")]
#[cfg(feature = "serde_derive")]
mod inner {
pub fn main() {}
}
+5 -4
View File
@@ -1,11 +1,12 @@
#![cfg_attr(feature = "serde_macros", feature(custom_derive, plugin))]
#![cfg_attr(feature = "serde_macros", plugin(serde_macros))]
#[cfg(feature = "serde_derive")]
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
#[cfg(feature = "serde_macros")]
#[cfg(feature = "serde_derive")]
include!("main.rs.in");
#[cfg(not(feature = "serde_macros"))]
#[cfg(not(feature = "serde_derive"))]
include!(concat!(env!("OUT_DIR"), "/main.rs"));
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "serde"
version = "0.8.9"
version = "0.9.0-rc1"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "A generic serialization/deserialization framework"
+21 -11
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)
@@ -182,14 +182,14 @@ mod bytebuf {
type Value = ByteBuf;
#[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 +199,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,7 +231,7 @@ 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)
+163 -209
View File
@@ -83,21 +83,21 @@ pub struct UnitVisitor;
impl Visitor for UnitVisitor {
type Value = ();
fn visit_unit<E>(&mut self) -> Result<(), E>
fn visit_unit<E>(self) -> Result<(), E>
where E: Error,
{
Ok(())
}
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<(), V::Error>
fn visit_seq<V>(self, _: V) -> Result<(), V::Error>
where V: SeqVisitor,
{
visitor.end()
Ok(())
}
}
impl Deserialize for () {
fn deserialize<D>(deserializer: &mut D) -> Result<(), D::Error>
fn deserialize<D>(deserializer: D) -> Result<(), D::Error>
where D: Deserializer,
{
deserializer.deserialize_unit(UnitVisitor)
@@ -112,13 +112,13 @@ pub struct BoolVisitor;
impl Visitor for BoolVisitor {
type Value = bool;
fn visit_bool<E>(&mut self, v: bool) -> Result<bool, E>
fn visit_bool<E>(self, v: bool) -> Result<bool, E>
where E: Error,
{
Ok(v)
}
fn visit_str<E>(&mut self, s: &str) -> Result<bool, E>
fn visit_str<E>(self, s: &str) -> Result<bool, E>
where E: Error,
{
match s.trim_matches(::utils::Pattern_White_Space) {
@@ -130,7 +130,7 @@ impl Visitor for BoolVisitor {
}
impl Deserialize for bool {
fn deserialize<D>(deserializer: &mut D) -> Result<bool, D::Error>
fn deserialize<D>(deserializer: D) -> Result<bool, D::Error>
where D: Deserializer,
{
deserializer.deserialize_bool(BoolVisitor)
@@ -142,7 +142,7 @@ impl Deserialize for bool {
macro_rules! impl_deserialize_num_method {
($src_ty:ty, $method:ident, $from_method:ident, $ty:expr) => {
#[inline]
fn $method<E>(&mut self, v: $src_ty) -> Result<T, E>
fn $method<E>(self, v: $src_ty) -> Result<T, E>
where E: Error,
{
match FromPrimitive::$from_method(v) {
@@ -187,7 +187,7 @@ impl<T> Visitor for PrimitiveVisitor<T>
impl_deserialize_num_method!(f64, visit_f64, from_f64, Type::F64);
#[inline]
fn visit_str<E>(&mut self, s: &str) -> Result<T, E>
fn visit_str<E>(self, s: &str) -> Result<T, E>
where E: Error,
{
str::FromStr::from_str(s.trim_matches(::utils::Pattern_White_Space)).or_else(|_| {
@@ -200,7 +200,7 @@ macro_rules! impl_deserialize_num {
($ty:ty, $method:ident) => {
impl Deserialize for $ty {
#[inline]
fn deserialize<D>(deserializer: &mut D) -> Result<$ty, D::Error>
fn deserialize<D>(deserializer: D) -> Result<$ty, D::Error>
where D: Deserializer,
{
deserializer.$method(PrimitiveVisitor::new())
@@ -230,14 +230,14 @@ impl Visitor for CharVisitor {
type Value = char;
#[inline]
fn visit_char<E>(&mut self, v: char) -> Result<char, E>
fn visit_char<E>(self, v: char) -> Result<char, E>
where E: Error,
{
Ok(v)
}
#[inline]
fn visit_str<E>(&mut self, v: &str) -> Result<char, E>
fn visit_str<E>(self, v: &str) -> Result<char, E>
where E: Error,
{
let mut iter = v.chars();
@@ -255,7 +255,7 @@ impl Visitor for CharVisitor {
impl Deserialize for char {
#[inline]
fn deserialize<D>(deserializer: &mut D) -> Result<char, D::Error>
fn deserialize<D>(deserializer: D) -> Result<char, D::Error>
where D: Deserializer,
{
deserializer.deserialize_char(CharVisitor)
@@ -271,19 +271,25 @@ struct StringVisitor;
impl Visitor for StringVisitor {
type Value = String;
fn visit_str<E>(&mut self, v: &str) -> Result<String, E>
fn visit_str<E>(self, v: &str) -> Result<String, E>
where E: Error,
{
Ok(v.to_owned())
}
fn visit_string<E>(&mut self, v: String) -> Result<String, E>
fn visit_string<E>(self, v: String) -> Result<String, E>
where E: Error,
{
Ok(v)
}
fn visit_bytes<E>(&mut self, v: &[u8]) -> Result<String, E>
fn visit_unit<E>(self) -> Result<String, E>
where E: Error,
{
Ok(String::new())
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<String, E>
where E: Error,
{
match str::from_utf8(v) {
@@ -292,7 +298,7 @@ impl Visitor for StringVisitor {
}
}
fn visit_byte_buf<E>(&mut self, v: Vec<u8>) -> Result<String, E>
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<String, E>
where E: Error,
{
match String::from_utf8(v) {
@@ -304,7 +310,7 @@ impl Visitor for StringVisitor {
#[cfg(any(feature = "std", feature = "collections"))]
impl Deserialize for String {
fn deserialize<D>(deserializer: &mut D) -> Result<String, D::Error>
fn deserialize<D>(deserializer: D) -> Result<String, D::Error>
where D: Deserializer,
{
deserializer.deserialize_string(StringVisitor)
@@ -323,21 +329,21 @@ impl<
type Value = Option<T>;
#[inline]
fn visit_unit<E>(&mut self) -> Result<Option<T>, E>
fn visit_unit<E>(self) -> Result<Option<T>, E>
where E: Error,
{
Ok(None)
}
#[inline]
fn visit_none<E>(&mut self) -> Result<Option<T>, E>
fn visit_none<E>(self) -> Result<Option<T>, E>
where E: Error,
{
Ok(None)
}
#[inline]
fn visit_some<D>(&mut self, deserializer: &mut D) -> Result<Option<T>, D::Error>
fn visit_some<D>(self, deserializer: D) -> Result<Option<T>, D::Error>
where D: Deserializer,
{
Ok(Some(try!(Deserialize::deserialize(deserializer))))
@@ -345,7 +351,7 @@ impl<
}
impl<T> Deserialize for Option<T> where T: Deserialize {
fn deserialize<D>(deserializer: &mut D) -> Result<Option<T>, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Option<T>, D::Error>
where D: Deserializer,
{
deserializer.deserialize_option(OptionVisitor { marker: PhantomData })
@@ -363,7 +369,7 @@ impl<T> Visitor for PhantomDataVisitor<T> {
type Value = PhantomData<T>;
#[inline]
fn visit_unit<E>(&mut self) -> Result<PhantomData<T>, E>
fn visit_unit<E>(self) -> Result<PhantomData<T>, E>
where E: Error,
{
Ok(PhantomData)
@@ -371,7 +377,7 @@ impl<T> Visitor for PhantomDataVisitor<T> {
}
impl<T> Deserialize for PhantomData<T> {
fn deserialize<D>(deserializer: &mut D) -> Result<PhantomData<T>, D::Error>
fn deserialize<D>(deserializer: D) -> Result<PhantomData<T>, D::Error>
where D: Deserializer,
{
let visitor = PhantomDataVisitor { marker: PhantomData };
@@ -412,14 +418,14 @@ macro_rules! seq_impl {
type Value = $ty;
#[inline]
fn visit_unit<E>(&mut self) -> Result<$ty, E>
fn visit_unit<E>(self) -> Result<$ty, E>
where E: Error,
{
Ok($ctor)
}
#[inline]
fn visit_seq<V>(&mut self, mut $visitor: V) -> Result<$ty, V::Error>
fn visit_seq<V>(self, mut $visitor: V) -> Result<$ty, V::Error>
where V: SeqVisitor,
{
let mut values = $with_capacity;
@@ -428,8 +434,6 @@ macro_rules! seq_impl {
$insert(&mut values, value);
}
try!($visitor.end());
Ok(values)
}
}
@@ -437,7 +441,7 @@ macro_rules! seq_impl {
impl<$($typaram),*> Deserialize for $ty
where $($typaram: $bound1 $(+ $bound2)*),*
{
fn deserialize<D>(deserializer: &mut D) -> Result<$ty, D::Error>
fn deserialize<D>(deserializer: D) -> Result<$ty, D::Error>
where D: Deserializer,
{
deserializer.deserialize_seq($visitor_ty::new())
@@ -512,91 +516,74 @@ seq_impl!(
///////////////////////////////////////////////////////////////////////////////
struct ArrayVisitor0<T> {
marker: PhantomData<T>,
struct ArrayVisitor<A> {
marker: PhantomData<A>,
}
impl<T> ArrayVisitor0<T> {
/// Construct a `ArrayVisitor0<T>`.
impl<A> ArrayVisitor<A> {
pub fn new() -> Self {
ArrayVisitor0 {
ArrayVisitor {
marker: PhantomData,
}
}
}
impl<T> Visitor for ArrayVisitor0<T> where T: Deserialize + Default {
impl<T> Visitor for ArrayVisitor<[T; 0]> where T: Deserialize {
type Value = [T; 0];
#[inline]
fn visit_unit<E>(&mut self) -> Result<[T; 0], E>
fn visit_unit<E>(self) -> Result<[T; 0], E>
where E: Error,
{
Ok([T::default(); 0])
Ok([])
}
#[inline]
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<[T; 0], V::Error>
fn visit_seq<V>(self, _: V) -> Result<[T; 0], V::Error>
where V: SeqVisitor,
{
try!(visitor.end());
Ok([T::default(); 0])
Ok([])
}
}
impl<T> Deserialize for [T; 0]
where T: Deserialize + Default
where T: Deserialize
{
fn deserialize<D>(deserializer: &mut D) -> Result<[T; 0], D::Error>
fn deserialize<D>(deserializer: D) -> Result<[T; 0], D::Error>
where D: Deserializer,
{
deserializer.deserialize_seq(ArrayVisitor0::new())
deserializer.deserialize_seq_fixed_size(0, ArrayVisitor::<[T; 0]>::new())
}
}
macro_rules! array_impls {
($($visitor:ident, $len:expr => ($($name:ident),+),)+) => {
($($len:expr => ($($name:ident)+))+) => {
$(
struct $visitor<T> {
marker: PhantomData<T>,
}
impl<T> $visitor<T> {
/// Construct a `ArrayVisitor*<T>`.
pub fn new() -> Self {
$visitor {
marker: PhantomData
}
}
}
impl<T> Visitor for $visitor<T> where T: Deserialize {
impl<T> Visitor for ArrayVisitor<[T; $len]> where T: Deserialize {
type Value = [T; $len];
#[inline]
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<[T; $len], V::Error>
fn visit_seq<V>(self, mut visitor: V) -> Result<[T; $len], V::Error>
where V: SeqVisitor,
{
$(
let $name = match try!(visitor.visit()) {
Some(val) => val,
None => { return Err(Error::end_of_stream()); }
None => return Err(Error::end_of_stream()),
};
)+;
)+
try!(visitor.end());
Ok([$($name,)+])
Ok([$($name),+])
}
}
impl<T> Deserialize for [T; $len]
where T: Deserialize,
{
fn deserialize<D>(deserializer: &mut D) -> Result<[T; $len], D::Error>
fn deserialize<D>(deserializer: D) -> Result<[T; $len], D::Error>
where D: Deserializer,
{
deserializer.deserialize_seq_fixed_size($len, $visitor::new())
deserializer.deserialize_seq_fixed_size($len, ArrayVisitor::<[T; $len]>::new())
}
}
)+
@@ -604,96 +591,79 @@ macro_rules! array_impls {
}
array_impls! {
ArrayVisitor1, 1 => (a),
ArrayVisitor2, 2 => (a, b),
ArrayVisitor3, 3 => (a, b, c),
ArrayVisitor4, 4 => (a, b, c, d),
ArrayVisitor5, 5 => (a, b, c, d, e),
ArrayVisitor6, 6 => (a, b, c, d, e, f),
ArrayVisitor7, 7 => (a, b, c, d, e, f, g),
ArrayVisitor8, 8 => (a, b, c, d, e, f, g, h),
ArrayVisitor9, 9 => (a, b, c, d, e, f, g, h, i),
ArrayVisitor10, 10 => (a, b, c, d, e, f, g, h, i, j),
ArrayVisitor11, 11 => (a, b, c, d, e, f, g, h, i, j, k),
ArrayVisitor12, 12 => (a, b, c, d, e, f, g, h, i, j, k, l),
ArrayVisitor13, 13 => (a, b, c, d, e, f, g, h, i, j, k, l, m),
ArrayVisitor14, 14 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n),
ArrayVisitor15, 15 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o),
ArrayVisitor16, 16 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p),
ArrayVisitor17, 17 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q),
ArrayVisitor18, 18 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r),
ArrayVisitor19, 19 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s),
ArrayVisitor20, 20 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s ,t),
ArrayVisitor21, 21 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u),
ArrayVisitor22, 22 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v),
ArrayVisitor23, 23 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w),
ArrayVisitor24, 24 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x),
ArrayVisitor25, 25 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x,
y),
ArrayVisitor26, 26 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x,
y, z),
ArrayVisitor27, 27 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x,
y, z, aa),
ArrayVisitor28, 28 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x,
y, z, aa, ab),
ArrayVisitor29, 29 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x,
y, z, aa, ab, ac),
ArrayVisitor30, 30 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x,
y, z, aa, ab, ac, ad),
ArrayVisitor31, 31 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x,
y, z, aa, ab, ac, ad, ae),
ArrayVisitor32, 32 => (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x,
y, z, aa, ab, ac, ad, ae, af),
1 => (a)
2 => (a b)
3 => (a b c)
4 => (a b c d)
5 => (a b c d e)
6 => (a b c d e f)
7 => (a b c d e f g)
8 => (a b c d e f g h)
9 => (a b c d e f g h i)
10 => (a b c d e f g h i j)
11 => (a b c d e f g h i j k)
12 => (a b c d e f g h i j k l)
13 => (a b c d e f g h i j k l m)
14 => (a b c d e f g h i j k l m n)
15 => (a b c d e f g h i j k l m n o)
16 => (a b c d e f g h i j k l m n o p)
17 => (a b c d e f g h i j k l m n o p q)
18 => (a b c d e f g h i j k l m n o p q r)
19 => (a b c d e f g h i j k l m n o p q r s)
20 => (a b c d e f g h i j k l m n o p q r s t)
21 => (a b c d e f g h i j k l m n o p q r s t u)
22 => (a b c d e f g h i j k l m n o p q r s t u v)
23 => (a b c d e f g h i j k l m n o p q r s t u v w)
24 => (a b c d e f g h i j k l m n o p q r s t u v w x)
25 => (a b c d e f g h i j k l m n o p q r s t u v w x y)
26 => (a b c d e f g h i j k l m n o p q r s t u v w x y z)
27 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa)
28 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab)
29 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac)
30 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad)
31 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae)
32 => (a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae af)
}
///////////////////////////////////////////////////////////////////////////////
macro_rules! tuple_impls {
($($len:expr => $visitor:ident => ($($name:ident),+),)+) => {
($($len:expr => $visitor:ident => ($($name:ident)+))+) => {
$(
/// Construct a tuple visitor.
pub struct $visitor<$($name,)+> {
marker: PhantomData<($($name,)+)>,
}
impl<
$($name: Deserialize,)+
> $visitor<$($name,)+> {
impl<$($name: Deserialize,)+> $visitor<$($name,)+> {
/// Construct a `TupleVisitor*<T>`.
pub fn new() -> Self {
$visitor { marker: PhantomData }
}
}
impl<
$($name: Deserialize,)+
> Visitor for $visitor<$($name,)+> {
impl<$($name: Deserialize),+> Visitor for $visitor<$($name,)+> {
type Value = ($($name,)+);
#[inline]
#[allow(non_snake_case)]
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<($($name,)+), V::Error>
fn visit_seq<V>(self, mut visitor: V) -> Result<($($name,)+), V::Error>
where V: SeqVisitor,
{
$(
let $name = match try!(visitor.visit()) {
Some(value) => value,
None => { return Err(Error::end_of_stream()); }
None => return Err(Error::end_of_stream()),
};
)+;
try!(visitor.end());
)+
Ok(($($name,)+))
}
}
impl<
$($name: Deserialize),+
> Deserialize for ($($name,)+) {
impl<$($name: Deserialize),+> Deserialize for ($($name,)+) {
#[inline]
fn deserialize<D>(deserializer: &mut D) -> Result<($($name,)+), D::Error>
fn deserialize<D>(deserializer: D) -> Result<($($name,)+), D::Error>
where D: Deserializer,
{
deserializer.deserialize_tuple($len, $visitor::new())
@@ -704,22 +674,22 @@ macro_rules! tuple_impls {
}
tuple_impls! {
1 => TupleVisitor1 => (T0),
2 => TupleVisitor2 => (T0, T1),
3 => TupleVisitor3 => (T0, T1, T2),
4 => TupleVisitor4 => (T0, T1, T2, T3),
5 => TupleVisitor5 => (T0, T1, T2, T3, T4),
6 => TupleVisitor6 => (T0, T1, T2, T3, T4, T5),
7 => TupleVisitor7 => (T0, T1, T2, T3, T4, T5, T6),
8 => TupleVisitor8 => (T0, T1, T2, T3, T4, T5, T6, T7),
9 => TupleVisitor9 => (T0, T1, T2, T3, T4, T5, T6, T7, T8),
10 => TupleVisitor10 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9),
11 => TupleVisitor11 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10),
12 => TupleVisitor12 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11),
13 => TupleVisitor13 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12),
14 => TupleVisitor14 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13),
15 => TupleVisitor15 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14),
16 => TupleVisitor16 => (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15),
1 => TupleVisitor1 => (T0)
2 => TupleVisitor2 => (T0 T1)
3 => TupleVisitor3 => (T0 T1 T2)
4 => TupleVisitor4 => (T0 T1 T2 T3)
5 => TupleVisitor5 => (T0 T1 T2 T3 T4)
6 => TupleVisitor6 => (T0 T1 T2 T3 T4 T5)
7 => TupleVisitor7 => (T0 T1 T2 T3 T4 T5 T6)
8 => TupleVisitor8 => (T0 T1 T2 T3 T4 T5 T6 T7)
9 => TupleVisitor9 => (T0 T1 T2 T3 T4 T5 T6 T7 T8)
10 => TupleVisitor10 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9)
11 => TupleVisitor11 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10)
12 => TupleVisitor12 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11)
13 => TupleVisitor13 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12)
14 => TupleVisitor14 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13)
15 => TupleVisitor15 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14)
16 => TupleVisitor16 => (T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15)
}
///////////////////////////////////////////////////////////////////////////////
@@ -754,14 +724,14 @@ macro_rules! map_impl {
type Value = $ty;
#[inline]
fn visit_unit<E>(&mut self) -> Result<$ty, E>
fn visit_unit<E>(self) -> Result<$ty, E>
where E: Error,
{
Ok($ctor)
}
#[inline]
fn visit_map<Visitor>(&mut self, mut $visitor: Visitor) -> Result<$ty, Visitor::Error>
fn visit_map<Visitor>(self, mut $visitor: Visitor) -> Result<$ty, Visitor::Error>
where Visitor: MapVisitor,
{
let mut values = $with_capacity;
@@ -770,8 +740,6 @@ macro_rules! map_impl {
values.insert(key, value);
}
try!($visitor.end());
Ok(values)
}
}
@@ -779,7 +747,7 @@ macro_rules! map_impl {
impl<$($typaram),*> Deserialize for $ty
where $($typaram: $bound1 $(+ $bound2)*),*
{
fn deserialize<D>(deserializer: &mut D) -> Result<$ty, D::Error>
fn deserialize<D>(deserializer: D) -> Result<$ty, D::Error>
where D: Deserializer,
{
deserializer.deserialize_map($visitor_ty::new())
@@ -809,9 +777,9 @@ map_impl!(
///////////////////////////////////////////////////////////////////////////////
#[cfg(all(feature = "unstable", feature = "std"))]
#[cfg(feature = "std")]
impl Deserialize for net::IpAddr {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer,
{
let s = try!(String::deserialize(deserializer));
@@ -824,7 +792,7 @@ impl Deserialize for net::IpAddr {
#[cfg(feature = "std")]
impl Deserialize for net::Ipv4Addr {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer,
{
let s = try!(String::deserialize(deserializer));
@@ -837,7 +805,7 @@ impl Deserialize for net::Ipv4Addr {
#[cfg(feature = "std")]
impl Deserialize for net::Ipv6Addr {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer,
{
let s = try!(String::deserialize(deserializer));
@@ -852,7 +820,7 @@ impl Deserialize for net::Ipv6Addr {
#[cfg(feature = "std")]
impl Deserialize for net::SocketAddr {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer,
{
let s = try!(String::deserialize(deserializer));
@@ -865,7 +833,7 @@ impl Deserialize for net::SocketAddr {
#[cfg(feature = "std")]
impl Deserialize for net::SocketAddrV4 {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer,
{
let s = try!(String::deserialize(deserializer));
@@ -878,7 +846,7 @@ impl Deserialize for net::SocketAddrV4 {
#[cfg(feature = "std")]
impl Deserialize for net::SocketAddrV6 {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer,
{
let s = try!(String::deserialize(deserializer));
@@ -898,13 +866,13 @@ struct PathBufVisitor;
impl Visitor for PathBufVisitor {
type Value = path::PathBuf;
fn visit_str<E>(&mut self, v: &str) -> Result<path::PathBuf, E>
fn visit_str<E>(self, v: &str) -> Result<path::PathBuf, E>
where E: Error,
{
Ok(From::from(v))
}
fn visit_string<E>(&mut self, v: String) -> Result<path::PathBuf, E>
fn visit_string<E>(self, v: String) -> Result<path::PathBuf, E>
where E: Error,
{
self.visit_str(&v)
@@ -913,7 +881,7 @@ impl Visitor for PathBufVisitor {
#[cfg(feature = "std")]
impl Deserialize for path::PathBuf {
fn deserialize<D>(deserializer: &mut D) -> Result<path::PathBuf, D::Error>
fn deserialize<D>(deserializer: D) -> Result<path::PathBuf, D::Error>
where D: Deserializer,
{
deserializer.deserialize_string(PathBufVisitor)
@@ -924,7 +892,7 @@ impl Deserialize for path::PathBuf {
#[cfg(any(feature = "std", feature = "alloc"))]
impl<T: Deserialize> Deserialize for Box<T> {
fn deserialize<D>(deserializer: &mut D) -> Result<Box<T>, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Box<T>, D::Error>
where D: Deserializer,
{
let val = try!(Deserialize::deserialize(deserializer));
@@ -934,7 +902,7 @@ impl<T: Deserialize> Deserialize for Box<T> {
#[cfg(any(feature = "std", feature = "collections"))]
impl<T: Deserialize> Deserialize for Box<[T]> {
fn deserialize<D>(deserializer: &mut D) -> Result<Box<[T]>, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Box<[T]>, D::Error>
where D: Deserializer,
{
let v: Vec<T> = try!(Deserialize::deserialize(deserializer));
@@ -944,7 +912,7 @@ impl<T: Deserialize> Deserialize for Box<[T]> {
#[cfg(any(feature = "std", feature = "collections"))]
impl Deserialize for Box<str> {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer
{
let s = try!(String::deserialize(deserializer));
@@ -954,7 +922,7 @@ impl Deserialize for Box<str> {
#[cfg(any(feature = "std", feature = "alloc"))]
impl<T: Deserialize> Deserialize for Arc<T> {
fn deserialize<D>(deserializer: &mut D) -> Result<Arc<T>, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Arc<T>, D::Error>
where D: Deserializer,
{
let val = try!(Deserialize::deserialize(deserializer));
@@ -964,7 +932,7 @@ impl<T: Deserialize> Deserialize for Arc<T> {
#[cfg(any(feature = "std", feature = "alloc"))]
impl<T: Deserialize> Deserialize for Rc<T> {
fn deserialize<D>(deserializer: &mut D) -> Result<Rc<T>, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Rc<T>, D::Error>
where D: Deserializer,
{
let val = try!(Deserialize::deserialize(deserializer));
@@ -975,7 +943,7 @@ impl<T: Deserialize> Deserialize for Rc<T> {
#[cfg(any(feature = "std", feature = "collections"))]
impl<'a, T: ?Sized> Deserialize for Cow<'a, T> where T: ToOwned, T::Owned: Deserialize, {
#[inline]
fn deserialize<D>(deserializer: &mut D) -> Result<Cow<'a, T>, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Cow<'a, T>, D::Error>
where D: Deserializer,
{
let val = try!(Deserialize::deserialize(deserializer));
@@ -995,13 +963,13 @@ impl<'a, T: ?Sized> Deserialize for Cow<'a, T> where T: ToOwned, T::Owned: Deser
// }
#[cfg(feature = "std")]
impl Deserialize for Duration {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer,
{
enum Field { Secs, Nanos };
impl Deserialize for Field {
fn deserialize<D>(deserializer: &mut D) -> Result<Field, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
where D: Deserializer,
{
struct FieldVisitor;
@@ -1009,7 +977,7 @@ impl Deserialize for Duration {
impl Visitor for FieldVisitor {
type Value = Field;
fn visit_usize<E>(&mut self, value: usize) -> Result<Field, E>
fn visit_usize<E>(self, value: usize) -> Result<Field, E>
where E: Error,
{
match value {
@@ -1019,7 +987,7 @@ impl Deserialize for Duration {
}
}
fn visit_str<E>(&mut self, value: &str) -> Result<Field, E>
fn visit_str<E>(self, value: &str) -> Result<Field, E>
where E: Error,
{
match value {
@@ -1029,7 +997,7 @@ impl Deserialize for Duration {
}
}
fn visit_bytes<E>(&mut self, value: &[u8]) -> Result<Field, E>
fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E>
where E: Error,
{
match value {
@@ -1052,28 +1020,25 @@ impl Deserialize for Duration {
impl Visitor for DurationVisitor {
type Value = Duration;
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<Duration, V::Error>
fn visit_seq<V>(self, mut visitor: V) -> Result<Duration, V::Error>
where V: SeqVisitor,
{
let secs: u64 = match try!(visitor.visit()) {
Some(value) => value,
None => {
try!(visitor.end());
return Err(Error::invalid_length(0));
}
};
let nanos: u32 = match try!(visitor.visit()) {
Some(value) => value,
None => {
try!(visitor.end());
return Err(Error::invalid_length(1));
}
};
try!(visitor.end());
Ok(Duration::new(secs, nanos))
}
fn visit_map<V>(&mut self, mut visitor: V) -> Result<Duration, V::Error>
fn visit_map<V>(self, mut visitor: V) -> Result<Duration, V::Error>
where V: MapVisitor,
{
let mut secs: Option<u64> = None;
@@ -1094,7 +1059,6 @@ impl Deserialize for Duration {
}
}
}
try!(visitor.end());
let secs = match secs {
Some(secs) => secs,
None => try!(visitor.missing_field("secs")),
@@ -1116,7 +1080,7 @@ impl Deserialize for Duration {
#[cfg(feature = "unstable")]
impl<T> Deserialize for NonZero<T> where T: Deserialize + PartialEq + Zeroable + Zero {
fn deserialize<D>(deserializer: &mut D) -> Result<NonZero<T>, D::Error> where D: Deserializer {
fn deserialize<D>(deserializer: D) -> Result<NonZero<T>, D::Error> where D: Deserializer {
let value = try!(Deserialize::deserialize(deserializer));
if value == Zero::zero() {
return Err(Error::invalid_value("expected a non-zero value"))
@@ -1131,7 +1095,7 @@ impl<T> Deserialize for NonZero<T> where T: Deserialize + PartialEq + Zeroable +
impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
fn deserialize<D>(deserializer: &mut D) -> Result<Result<T, E>, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Result<T, E>, D::Error>
where D: Deserializer {
enum Field {
Ok,
@@ -1140,16 +1104,16 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
impl Deserialize for Field {
#[inline]
fn deserialize<D>(deserializer: &mut D) -> Result<Field, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
where D: Deserializer
{
struct FieldVisitor;
impl ::de::Visitor for FieldVisitor {
impl Visitor for FieldVisitor {
type Value = Field;
#[cfg(any(feature = "std", feature = "collections"))]
fn visit_usize<E>(&mut self, value: usize) -> Result<Field, E> where E: Error {
fn visit_usize<E>(self, value: usize) -> Result<Field, E> where E: Error {
#[cfg(feature = "collections")]
use collections::string::ToString;
match value {
@@ -1160,7 +1124,7 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
}
#[cfg(all(not(feature = "std"), not(feature = "collections")))]
fn visit_usize<E>(&mut self, value: usize) -> Result<Field, E> where E: Error {
fn visit_usize<E>(self, value: usize) -> Result<Field, E> where E: Error {
match value {
0 => Ok(Field::Ok),
1 => Ok(Field::Err),
@@ -1168,7 +1132,7 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
}
}
fn visit_str<E>(&mut self, value: &str) -> Result<Field, E> where E: Error {
fn visit_str<E>(self, value: &str) -> Result<Field, E> where E: Error {
match value {
"Ok" => Ok(Field::Ok),
"Err" => Ok(Field::Err),
@@ -1176,7 +1140,7 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
}
}
fn visit_bytes<E>(&mut self, value: &[u8]) -> Result<Field, E> where E: Error {
fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E> where E: Error {
match value {
b"Ok" => Ok(Field::Ok),
b"Err" => Ok(Field::Err),
@@ -1194,33 +1158,27 @@ impl<T, E> Deserialize for Result<T, E> where T: Deserialize, E: Deserialize {
}
}
struct Visitor<T, E>(PhantomData<Result<T, E>>);
struct ResultVisitor<T, E>(PhantomData<Result<T, E>>);
impl<T, E> EnumVisitor for Visitor<T, E>
impl<T, E> Visitor for ResultVisitor<T, E>
where T: Deserialize,
E: Deserialize
{
type Value = Result<T, E>;
fn visit<V>(&mut self, mut visitor: V) -> Result<Result<T, E>, V::Error>
where V: VariantVisitor
fn visit_enum<V>(self, visitor: V) -> Result<Result<T, E>, V::Error>
where V: EnumVisitor
{
match try!(visitor.visit_variant()) {
Field::Ok => {
let value = try!(visitor.visit_newtype());
Ok(Ok(value))
}
Field::Err => {
let value = try!(visitor.visit_newtype());
Ok(Err(value))
}
(Field::Ok, variant) => variant.visit_newtype().map(Ok),
(Field::Err, variant) => variant.visit_newtype().map(Err),
}
}
}
const VARIANTS: &'static [&'static str] = &["Ok", "Err"];
deserializer.deserialize_enum("Result", VARIANTS, Visitor(PhantomData))
deserializer.deserialize_enum("Result", VARIANTS, ResultVisitor(PhantomData))
}
}
@@ -1232,7 +1190,7 @@ pub struct IgnoredAny;
impl Deserialize for IgnoredAny {
#[inline]
fn deserialize<D>(deserializer: &mut D) -> Result<IgnoredAny, D::Error>
fn deserialize<D>(deserializer: D) -> Result<IgnoredAny, D::Error>
where D: Deserializer,
{
struct IgnoredAnyVisitor;
@@ -1241,82 +1199,78 @@ impl Deserialize for IgnoredAny {
type Value = IgnoredAny;
#[inline]
fn visit_bool<E>(&mut self, _: bool) -> Result<IgnoredAny, E> {
fn visit_bool<E>(self, _: bool) -> Result<IgnoredAny, E> {
Ok(IgnoredAny)
}
#[inline]
fn visit_i64<E>(&mut self, _: i64) -> Result<IgnoredAny, E> {
fn visit_i64<E>(self, _: i64) -> Result<IgnoredAny, E> {
Ok(IgnoredAny)
}
#[inline]
fn visit_u64<E>(&mut self, _: u64) -> Result<IgnoredAny, E> {
fn visit_u64<E>(self, _: u64) -> Result<IgnoredAny, E> {
Ok(IgnoredAny)
}
#[inline]
fn visit_f64<E>(&mut self, _: f64) -> Result<IgnoredAny, E> {
fn visit_f64<E>(self, _: f64) -> Result<IgnoredAny, E> {
Ok(IgnoredAny)
}
#[inline]
fn visit_str<E>(&mut self, _: &str) -> Result<IgnoredAny, E>
fn visit_str<E>(self, _: &str) -> Result<IgnoredAny, E>
where E: Error,
{
Ok(IgnoredAny)
}
#[inline]
fn visit_none<E>(&mut self) -> Result<IgnoredAny, E> {
fn visit_none<E>(self) -> Result<IgnoredAny, E> {
Ok(IgnoredAny)
}
#[inline]
fn visit_some<D>(&mut self, _: &mut D) -> Result<IgnoredAny, D::Error>
fn visit_some<D>(self, _: D) -> Result<IgnoredAny, D::Error>
where D: Deserializer,
{
Ok(IgnoredAny)
}
#[inline]
fn visit_newtype_struct<D>(&mut self, _: &mut D) -> Result<IgnoredAny, D::Error>
fn visit_newtype_struct<D>(self, _: D) -> Result<IgnoredAny, D::Error>
where D: Deserializer,
{
Ok(IgnoredAny)
}
#[inline]
fn visit_unit<E>(&mut self) -> Result<IgnoredAny, E> {
fn visit_unit<E>(self) -> Result<IgnoredAny, E> {
Ok(IgnoredAny)
}
#[inline]
fn visit_seq<V>(&mut self, mut visitor: V) -> Result<IgnoredAny, V::Error>
fn visit_seq<V>(self, mut visitor: V) -> Result<IgnoredAny, V::Error>
where V: SeqVisitor,
{
while let Some(_) = try!(visitor.visit::<IgnoredAny>()) {
// Gobble
}
try!(visitor.end());
Ok(IgnoredAny)
}
#[inline]
fn visit_map<V>(&mut self, mut visitor: V) -> Result<IgnoredAny, V::Error>
fn visit_map<V>(self, mut visitor: V) -> Result<IgnoredAny, V::Error>
where V: MapVisitor,
{
while let Some((_, _)) = try!(visitor.visit::<IgnoredAny, IgnoredAny>()) {
// Gobble
}
try!(visitor.end());
Ok(IgnoredAny)
}
#[inline]
fn visit_bytes<E>(&mut self, _: &[u8]) -> Result<IgnoredAny, E>
fn visit_bytes<E>(self, _: &[u8]) -> Result<IgnoredAny, E>
where E: Error,
{
Ok(IgnoredAny)
+129 -165
View File
@@ -169,6 +169,9 @@ pub enum Type {
/// Represents a unit variant.
UnitVariant,
/// Represents a newtype variant.
NewtypeVariant,
/// Represents a `&[u8]` type.
Bytes,
}
@@ -176,38 +179,39 @@ pub enum Type {
impl fmt::Display for Type {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let display = match *self {
Type::Bool => "bool",
Type::Usize => "usize",
Type::U8 => "u8",
Type::U16 => "u16",
Type::U32 => "u32",
Type::U64 => "u64",
Type::Isize => "isize",
Type::I8 => "i8",
Type::I16 => "i16",
Type::I32 => "i32",
Type::I64 => "i64",
Type::F32 => "f32",
Type::F64 => "f64",
Type::Char => "char",
Type::Str => "str",
Type::String => "string",
Type::Unit => "unit",
Type::Option => "option",
Type::Seq => "seq",
Type::Map => "map",
Type::UnitStruct => "unit struct",
Type::NewtypeStruct => "newtype struct",
Type::TupleStruct => "tuple struct",
Type::Struct => "struct",
Type::FieldName => "field name",
Type::Tuple => "tuple",
Type::Enum => "enum",
Type::VariantName => "variant name",
Type::StructVariant => "struct variant",
Type::TupleVariant => "tuple variant",
Type::UnitVariant => "unit variant",
Type::Bytes => "bytes",
Type::Bool => "bool",
Type::Usize => "usize",
Type::U8 => "u8",
Type::U16 => "u16",
Type::U32 => "u32",
Type::U64 => "u64",
Type::Isize => "isize",
Type::I8 => "i8",
Type::I16 => "i16",
Type::I32 => "i32",
Type::I64 => "i64",
Type::F32 => "f32",
Type::F64 => "f64",
Type::Char => "char",
Type::Str => "str",
Type::String => "string",
Type::Unit => "unit",
Type::Option => "option",
Type::Seq => "seq",
Type::Map => "map",
Type::UnitStruct => "unit struct",
Type::NewtypeStruct => "newtype struct",
Type::TupleStruct => "tuple struct",
Type::Struct => "struct",
Type::FieldName => "field name",
Type::Tuple => "tuple",
Type::Enum => "enum",
Type::VariantName => "variant name",
Type::StructVariant => "struct variant",
Type::TupleVariant => "tuple variant",
Type::UnitVariant => "unit variant",
Type::NewtypeVariant => "newtype variant",
Type::Bytes => "bytes",
};
display.fmt(formatter)
}
@@ -218,7 +222,7 @@ impl fmt::Display for Type {
/// `Deserialize` represents a type that can be deserialized.
pub trait Deserialize: Sized {
/// Deserialize this value given this `Deserializer`.
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer;
}
@@ -241,100 +245,100 @@ pub trait Deserializer {
type Error: Error;
/// This method walks a visitor through a value as it is being deserialized.
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;
/// This method hints that the `Deserialize` type is expecting a `bool` value.
fn deserialize_bool<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting an `usize` value.
/// A reasonable default is to forward to `deserialize_u64`.
fn deserialize_usize<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_usize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting an `u8` value.
/// A reasonable default is to forward to `deserialize_u64`.
fn deserialize_u8<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting an `u16` value.
/// A reasonable default is to forward to `deserialize_u64`.
fn deserialize_u16<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting an `u32` value.
/// A reasonable default is to forward to `deserialize_u64`.
fn deserialize_u32<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting an `u64` value.
fn deserialize_u64<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting an `isize` value.
/// A reasonable default is to forward to `deserialize_i64`.
fn deserialize_isize<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_isize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting an `i8` value.
/// A reasonable default is to forward to `deserialize_i64`.
fn deserialize_i8<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting an `i16` value.
/// A reasonable default is to forward to `deserialize_i64`.
fn deserialize_i16<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting an `i32` value.
/// A reasonable default is to forward to `deserialize_i64`.
fn deserialize_i32<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting an `i64` value.
fn deserialize_i64<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting a `f32` value.
/// A reasonable default is to forward to `deserialize_f64`.
fn deserialize_f32<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting a `f64` value.
fn deserialize_f64<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting a `char` value.
fn deserialize_char<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting a `&str` value.
fn deserialize_str<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting a `String` value.
fn deserialize_string<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting an `unit` value.
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: Visitor;
/// This method hints that the `Deserialize` type is expecting an `Option` value. This allows
/// deserializers that encode an optional value as a nullable value to convert the null value
/// into a `None`, and a regular value as `Some(value)`.
fn deserialize_option<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting a sequence value. This allows
/// deserializers to parse sequences that aren't tagged as sequences.
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: Visitor;
/// This method hints that the `Deserialize` type is expecting a fixed size array. This allows
/// deserializers to parse arrays that aren't tagged as arrays.
fn deserialize_seq_fixed_size<V>(&mut self,
fn deserialize_seq_fixed_size<V>(self,
len: usize,
visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
@@ -342,17 +346,17 @@ pub trait Deserializer {
/// This method hints that the `Deserialize` type is expecting a `Vec<u8>`. This allows
/// deserializers that provide a custom byte vector serialization to properly deserialize the
/// type.
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: Visitor;
/// This method hints that the `Deserialize` type is expecting a map of values. This allows
/// deserializers to parse sequences that aren't tagged as maps.
fn deserialize_map<V>(&mut self, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting a unit struct. This allows
/// deserializers to a unit struct that aren't tagged as a unit struct.
fn deserialize_unit_struct<V>(&mut self,
fn deserialize_unit_struct<V>(self,
name: &'static str,
visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
@@ -360,14 +364,14 @@ pub trait Deserializer {
/// This method hints that the `Deserialize` type is expecting a newtype struct. This allows
/// deserializers to a newtype struct that aren't tagged as a newtype struct.
/// A reasonable default is to simply deserialize the expected value directly.
fn deserialize_newtype_struct<V>(&mut self,
fn deserialize_newtype_struct<V>(self,
name: &'static str,
visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting a tuple struct. This allows
/// deserializers to parse sequences that aren't tagged as sequences.
fn deserialize_tuple_struct<V>(&mut self,
fn deserialize_tuple_struct<V>(self,
name: &'static str,
len: usize,
visitor: V) -> Result<V::Value, Self::Error>
@@ -375,7 +379,7 @@ pub trait Deserializer {
/// This method hints that the `Deserialize` type is expecting a struct. This allows
/// deserializers to parse sequences that aren't tagged as maps.
fn deserialize_struct<V>(&mut self,
fn deserialize_struct<V>(self,
name: &'static str,
fields: &'static [&'static str],
visitor: V) -> Result<V::Value, Self::Error>
@@ -384,38 +388,38 @@ pub trait Deserializer {
/// This method hints that the `Deserialize` type is expecting some sort of struct field
/// name. This allows deserializers to choose between &str, usize, or &[u8] to properly
/// deserialize a struct field.
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: Visitor;
/// This method hints that the `Deserialize` type is expecting a tuple value. This allows
/// deserializers that provide a custom tuple serialization to properly deserialize the type.
fn deserialize_tuple<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
/// This method hints that the `Deserialize` type is expecting an enum value. This allows
/// deserializers that provide a custom enumeration serialization to properly deserialize the
/// type.
fn deserialize_enum<V>(&mut self,
fn deserialize_enum<V>(self,
name: &'static str,
variants: &'static [&'static str],
visitor: V) -> Result<V::Value, Self::Error>
where V: EnumVisitor;
where V: Visitor;
/// This method hints that the `Deserialize` type needs to deserialize a value whose type
/// doesn't matter because it is ignored.
fn deserialize_ignored_any<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: Visitor;
}
///////////////////////////////////////////////////////////////////////////////
/// This trait represents a visitor that walks through a deserializer.
pub trait Visitor {
pub trait Visitor: Sized {
/// The value produced by this visitor.
type Value: Deserialize;
type Value;
/// `visit_bool` deserializes a `bool` into a `Value`.
fn visit_bool<E>(&mut self, v: bool) -> Result<Self::Value, E>
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where E: Error,
{
let _ = v;
@@ -423,35 +427,35 @@ pub trait Visitor {
}
/// `visit_isize` deserializes a `isize` into a `Value`.
fn visit_isize<E>(&mut self, v: isize) -> Result<Self::Value, E>
fn visit_isize<E>(self, v: isize) -> Result<Self::Value, E>
where E: Error,
{
self.visit_i64(v as i64)
}
/// `visit_i8` deserializes a `i8` into a `Value`.
fn visit_i8<E>(&mut self, v: i8) -> Result<Self::Value, E>
fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
where E: Error,
{
self.visit_i64(v as i64)
}
/// `visit_i16` deserializes a `i16` into a `Value`.
fn visit_i16<E>(&mut self, v: i16) -> Result<Self::Value, E>
fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E>
where E: Error,
{
self.visit_i64(v as i64)
}
/// `visit_i32` deserializes a `i32` into a `Value`.
fn visit_i32<E>(&mut self, v: i32) -> Result<Self::Value, E>
fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>
where E: Error,
{
self.visit_i64(v as i64)
}
/// `visit_i64` deserializes a `i64` into a `Value`.
fn visit_i64<E>(&mut self, v: i64) -> Result<Self::Value, E>
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where E: Error,
{
let _ = v;
@@ -459,35 +463,35 @@ pub trait Visitor {
}
/// `visit_usize` deserializes a `usize` into a `Value`.
fn visit_usize<E>(&mut self, v: usize) -> Result<Self::Value, E>
fn visit_usize<E>(self, v: usize) -> Result<Self::Value, E>
where E: Error,
{
self.visit_u64(v as u64)
}
/// `visit_u8` deserializes a `u8` into a `Value`.
fn visit_u8<E>(&mut self, v: u8) -> Result<Self::Value, E>
fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
where E: Error,
{
self.visit_u64(v as u64)
}
/// `visit_u16` deserializes a `u16` into a `Value`.
fn visit_u16<E>(&mut self, v: u16) -> Result<Self::Value, E>
fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E>
where E: Error,
{
self.visit_u64(v as u64)
}
/// `visit_u32` deserializes a `u32` into a `Value`.
fn visit_u32<E>(&mut self, v: u32) -> Result<Self::Value, E>
fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>
where E: Error,
{
self.visit_u64(v as u64)
}
/// `visit_u64` deserializes a `u64` into a `Value`.
fn visit_u64<E>(&mut self, v: u64) -> Result<Self::Value, E>
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
where E: Error,
{
let _ = v;
@@ -495,14 +499,14 @@ pub trait Visitor {
}
/// `visit_f32` deserializes a `f32` into a `Value`.
fn visit_f32<E>(&mut self, v: f32) -> Result<Self::Value, E>
fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
where E: Error,
{
self.visit_f64(v as f64)
}
/// `visit_f64` deserializes a `f64` into a `Value`.
fn visit_f64<E>(&mut self, v: f64) -> Result<Self::Value, E>
fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
where E: Error,
{
let _ = v;
@@ -511,14 +515,14 @@ pub trait Visitor {
/// `visit_char` deserializes a `char` into a `Value`.
#[inline]
fn visit_char<E>(&mut self, v: char) -> Result<Self::Value, E>
fn visit_char<E>(self, v: char) -> Result<Self::Value, E>
where E: Error,
{
self.visit_str(::utils::encode_utf8(v).as_str())
}
/// `visit_str` deserializes a `&str` into a `Value`.
fn visit_str<E>(&mut self, v: &str) -> Result<Self::Value, E>
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where E: Error,
{
let _ = v;
@@ -530,14 +534,14 @@ pub trait Visitor {
/// to the `visit_str` method.
#[inline]
#[cfg(any(feature = "std", feature = "collections"))]
fn visit_string<E>(&mut self, v: String) -> Result<Self::Value, E>
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where E: Error,
{
self.visit_str(&v)
}
/// `visit_unit` deserializes a `()` into a `Value`.
fn visit_unit<E>(&mut self) -> Result<Self::Value, E>
fn visit_unit<E>(self) -> Result<Self::Value, E>
where E: Error,
{
Err(Error::invalid_type(Type::Unit))
@@ -545,7 +549,7 @@ pub trait Visitor {
/// `visit_unit_struct` deserializes a unit struct into a `Value`.
#[inline]
fn visit_unit_struct<E>(&mut self, name: &'static str) -> Result<Self::Value, E>
fn visit_unit_struct<E>(self, name: &'static str) -> Result<Self::Value, E>
where E: Error,
{
let _ = name;
@@ -553,14 +557,14 @@ pub trait Visitor {
}
/// `visit_none` deserializes a none value into a `Value`.
fn visit_none<E>(&mut self) -> Result<Self::Value, E>
fn visit_none<E>(self) -> Result<Self::Value, E>
where E: Error,
{
Err(Error::invalid_type(Type::Option))
}
/// `visit_some` deserializes a value into a `Value`.
fn visit_some<D>(&mut self, deserializer: &mut D) -> Result<Self::Value, D::Error>
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where D: Deserializer,
{
let _ = deserializer;
@@ -568,7 +572,7 @@ pub trait Visitor {
}
/// `visit_newtype_struct` deserializes a value into a `Value`.
fn visit_newtype_struct<D>(&mut self, deserializer: &mut D) -> Result<Self::Value, D::Error>
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where D: Deserializer,
{
let _ = deserializer;
@@ -576,7 +580,7 @@ pub trait Visitor {
}
/// `visit_seq` deserializes a `SeqVisitor` into a `Value`.
fn visit_seq<V>(&mut self, visitor: V) -> Result<Self::Value, V::Error>
fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error>
where V: SeqVisitor,
{
let _ = visitor;
@@ -584,15 +588,23 @@ pub trait Visitor {
}
/// `visit_map` deserializes a `MapVisitor` into a `Value`.
fn visit_map<V>(&mut self, visitor: V) -> Result<Self::Value, V::Error>
fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error>
where V: MapVisitor,
{
let _ = visitor;
Err(Error::invalid_type(Type::Map))
}
/// `visit_enum` deserializes a `EnumVisitor` into a `Value`.
fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error>
where V: EnumVisitor,
{
let _ = visitor;
Err(Error::invalid_type(Type::Enum))
}
/// `visit_bytes` deserializes a `&[u8]` into a `Value`.
fn visit_bytes<E>(&mut self, v: &[u8]) -> Result<Self::Value, E>
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where E: Error,
{
let _ = v;
@@ -601,7 +613,7 @@ pub trait Visitor {
/// `visit_byte_buf` deserializes a `Vec<u8>` into a `Value`.
#[cfg(any(feature = "std", feature = "collections"))]
fn visit_byte_buf<E>(&mut self, v: Vec<u8>) -> Result<Self::Value, E>
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where E: Error,
{
self.visit_bytes(&v)
@@ -623,9 +635,6 @@ pub trait SeqVisitor {
fn visit<T>(&mut self) -> Result<Option<T>, Self::Error>
where T: Deserialize;
/// This signals to the `SeqVisitor` that the `Visitor` does not expect any more items.
fn end(&mut self) -> Result<(), Self::Error>;
/// Return the lower and upper bound of items remaining in the sequence.
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
@@ -643,11 +652,6 @@ impl<'a, V> SeqVisitor for &'a mut V where V: SeqVisitor {
(**self).visit()
}
#[inline]
fn end(&mut self) -> Result<(), V::Error> {
(**self).end()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(**self).size_hint()
@@ -688,9 +692,6 @@ pub trait MapVisitor {
fn visit_value<V>(&mut self) -> Result<V, Self::Error>
where V: Deserialize;
/// This signals to the `MapVisitor` that the `Visitor` does not expect any more items.
fn end(&mut self) -> Result<(), Self::Error>;
/// Return the lower and upper bound of items remaining in the sequence.
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
@@ -730,56 +731,55 @@ impl<'a, V_> MapVisitor for &'a mut V_ where V_: MapVisitor {
(**self).visit_value()
}
#[inline]
fn end(&mut self) -> Result<(), V_::Error> {
(**self).end()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(**self).size_hint()
}
#[inline]
fn missing_field<V>(&mut self, field: &'static str) -> Result<V, Self::Error>
where V: Deserialize
{
(**self).missing_field(field)
}
}
///////////////////////////////////////////////////////////////////////////////
/// `EnumVisitor` is a visitor that is created by the `Deserialize` and passed to the
/// `Deserializer` in order to deserialize enums.
/// `EnumVisitor` is a visitor that is created by the `Deserializer` and passed
/// to the `Deserialize` in order to identify which variant of an enum to
/// deserialize.
pub trait EnumVisitor {
/// The value produced by this visitor.
type Value;
/// The error type that can be returned if some error occurs during deserialization.
type Error: Error;
/// The `Visitor` that will be used to deserialize the content of the enum
/// variant.
type Variant: VariantVisitor<Error=Self::Error>;
/// Visit the specific variant with the `VariantVisitor`.
fn visit<V>(&mut self, visitor: V) -> Result<Self::Value, V::Error>
where V: VariantVisitor;
/// `visit_variant` is called to identify which variant to deserialize.
fn visit_variant<V>(self) -> Result<(V, Self::Variant), Self::Error>
where V: Deserialize;
}
///////////////////////////////////////////////////////////////////////////////
/// `VariantVisitor` is a visitor that is created by the `Deserializer` and passed to the
/// `Deserialize` in order to deserialize a specific enum variant.
/// `VariantVisitor` is a visitor that is created by the `Deserializer` and
/// passed to the `Deserialize` to deserialize the content of a particular enum
/// variant.
pub trait VariantVisitor {
/// The error type that can be returned if some error occurs during deserialization.
type Error: Error;
/// `visit_variant` is called to identify which variant to deserialize.
fn visit_variant<V>(&mut self) -> Result<V, Self::Error>
where V: Deserialize;
/// `visit_unit` is called when deserializing a variant with no values.
fn visit_unit(&mut self) -> Result<(), Self::Error> {
Err(Error::invalid_type(Type::UnitVariant))
}
fn visit_unit(self) -> Result<(), Self::Error>;
/// `visit_newtype` is called when deserializing a variant with a single value.
/// A good default is often to use the `visit_tuple` method to deserialize a `(value,)`.
fn visit_newtype<T>(&mut self) -> Result<T, Self::Error>
fn visit_newtype<T>(self) -> Result<T, Self::Error>
where T: Deserialize;
/// `visit_tuple` is called when deserializing a tuple-like variant.
/// If no tuple variants are expected, yield a
/// `Err(serde::de::Error::invalid_type(serde::de::Type::TupleVariant))`
fn visit_tuple<V>(&mut self,
fn visit_tuple<V>(self,
len: usize,
visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
@@ -787,44 +787,8 @@ pub trait VariantVisitor {
/// `visit_struct` is called when deserializing a struct-like variant.
/// If no struct variants are expected, yield a
/// `Err(serde::de::Error::invalid_type(serde::de::Type::StructVariant))`
fn visit_struct<V>(&mut self,
fn visit_struct<V>(self,
fields: &'static [&'static str],
visitor: V) -> Result<V::Value, Self::Error>
where V: Visitor;
}
impl<'a, T> VariantVisitor for &'a mut T where T: VariantVisitor {
type Error = T::Error;
fn visit_variant<V>(&mut self) -> Result<V, T::Error>
where V: Deserialize
{
(**self).visit_variant()
}
fn visit_unit(&mut self) -> Result<(), T::Error> {
(**self).visit_unit()
}
fn visit_newtype<D>(&mut self) -> Result<D, T::Error>
where D: Deserialize,
{
(**self).visit_newtype()
}
fn visit_tuple<V>(&mut self,
len: usize,
visitor: V) -> Result<V::Value, T::Error>
where V: Visitor,
{
(**self).visit_tuple(len, visitor)
}
fn visit_struct<V>(&mut self,
fields: &'static [&'static str],
visitor: V) -> Result<V::Value, T::Error>
where V: Visitor,
{
(**self).visit_struct(fields, visitor)
}
}
+160 -207
View File
@@ -41,7 +41,7 @@ use error;
use core::fmt;
use core::marker::PhantomData;
use de;
use de::{self, SeqVisitor};
use bytes;
///////////////////////////////////////////////////////////////////////////////
@@ -184,13 +184,13 @@ impl<E> de::Deserializer for UnitDeserializer<E>
tuple_struct struct struct_field tuple enum ignored_any
}
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
visitor.visit_unit()
}
fn deserialize_option<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
visitor.visit_none()
@@ -202,7 +202,7 @@ impl<E> de::Deserializer for UnitDeserializer<E>
macro_rules! primitive_deserializer {
($ty:ty, $name:ident, $method:ident) => {
/// A helper deserializer that deserializes a number.
pub struct $name<E>(Option<$ty>, PhantomData<E>);
pub struct $name<E>($ty, PhantomData<E>);
impl<E> ValueDeserializer<E> for $ty
where E: de::Error,
@@ -210,7 +210,7 @@ macro_rules! primitive_deserializer {
type Deserializer = $name<E>;
fn into_deserializer(self) -> $name<E> {
$name(Some(self), PhantomData)
$name(self, PhantomData)
}
}
@@ -226,13 +226,10 @@ macro_rules! primitive_deserializer {
ignored_any
}
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
match self.0.take() {
Some(v) => visitor.$method(v),
None => Err(de::Error::end_of_stream()),
}
visitor.$method(self.0)
}
}
}
@@ -256,7 +253,7 @@ primitive_deserializer!(char, CharDeserializer, visit_char);
///////////////////////////////////////////////////////////////////////////////
/// A helper deserializer that deserializes a `&str`.
pub struct StrDeserializer<'a, E>(Option<&'a str>, PhantomData<E>);
pub struct StrDeserializer<'a, E>(&'a str, PhantomData<E>);
impl<'a, E> ValueDeserializer<E> for &'a str
where E: de::Error,
@@ -264,7 +261,7 @@ impl<'a, E> ValueDeserializer<E> for &'a str
type Deserializer = StrDeserializer<'a, E>;
fn into_deserializer(self) -> StrDeserializer<'a, E> {
StrDeserializer(Some(self), PhantomData)
StrDeserializer(self, PhantomData)
}
}
@@ -273,22 +270,19 @@ impl<'a, E> de::Deserializer for StrDeserializer<'a, E>
{
type Error = E;
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
match self.0.take() {
Some(v) => visitor.visit_str(v),
None => Err(de::Error::end_of_stream()),
}
visitor.visit_str(self.0)
}
fn deserialize_enum<V>(&mut self,
fn deserialize_enum<V>(self,
_name: &str,
_variants: &'static [&'static str],
mut visitor: V) -> Result<V::Value, Self::Error>
where V: de::EnumVisitor,
visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
visitor.visit(self)
visitor.visit_enum(self)
}
forward_to_deserialize! {
@@ -298,42 +292,16 @@ impl<'a, E> de::Deserializer for StrDeserializer<'a, E>
}
}
impl<'a, E> de::VariantVisitor for StrDeserializer<'a, E>
impl<'a, E> de::EnumVisitor for StrDeserializer<'a, E>
where E: de::Error,
{
type Error = E;
type Variant = private::UnitOnly<E>;
fn visit_variant<T>(&mut self) -> Result<T, Self::Error>
fn visit_variant<T>(self) -> Result<(T, Self::Variant), Self::Error>
where T: de::Deserialize,
{
de::Deserialize::deserialize(self)
}
fn visit_unit(&mut self) -> Result<(), Self::Error> {
Ok(())
}
fn visit_newtype<T>(&mut self) -> Result<T, Self::Error>
where T: super::Deserialize,
{
let (value,) = try!(self.visit_tuple(1, super::impls::TupleVisitor1::new()));
Ok(value)
}
fn visit_tuple<V>(&mut self,
_len: usize,
_visitor: V) -> Result<V::Value, Self::Error>
where V: super::Visitor
{
Err(super::Error::invalid_type(super::Type::TupleVariant))
}
fn visit_struct<V>(&mut self,
_fields: &'static [&'static str],
_visitor: V) -> Result<V::Value, Self::Error>
where V: super::Visitor
{
Err(super::Error::invalid_type(super::Type::StructVariant))
de::Deserialize::deserialize(self).map(private::unit_only)
}
}
@@ -341,7 +309,7 @@ impl<'a, E> de::VariantVisitor for StrDeserializer<'a, E>
/// A helper deserializer that deserializes a `String`.
#[cfg(any(feature = "std", feature = "collections"))]
pub struct StringDeserializer<E>(Option<String>, PhantomData<E>);
pub struct StringDeserializer<E>(String, PhantomData<E>);
#[cfg(any(feature = "std", feature = "collections"))]
impl<E> ValueDeserializer<E> for String
@@ -350,7 +318,7 @@ impl<E> ValueDeserializer<E> for String
type Deserializer = StringDeserializer<E>;
fn into_deserializer(self) -> StringDeserializer<E> {
StringDeserializer(Some(self), PhantomData)
StringDeserializer(self, PhantomData)
}
}
@@ -360,22 +328,19 @@ impl<E> de::Deserializer for StringDeserializer<E>
{
type Error = E;
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
match self.0.take() {
Some(string) => visitor.visit_string(string),
None => Err(de::Error::end_of_stream()),
}
visitor.visit_string(self.0)
}
fn deserialize_enum<V>(&mut self,
fn deserialize_enum<V>(self,
_name: &str,
_variants: &'static [&'static str],
mut visitor: V) -> Result<V::Value, Self::Error>
where V: de::EnumVisitor,
visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
visitor.visit(self)
visitor.visit_enum(self)
}
forward_to_deserialize! {
@@ -386,42 +351,16 @@ impl<E> de::Deserializer for StringDeserializer<E>
}
#[cfg(any(feature = "std", feature = "collections"))]
impl<'a, E> de::VariantVisitor for StringDeserializer<E>
impl<'a, E> de::EnumVisitor for StringDeserializer<E>
where E: de::Error,
{
type Error = E;
type Variant = private::UnitOnly<E>;
fn visit_variant<T>(&mut self) -> Result<T, Self::Error>
fn visit_variant<T>(self) -> Result<(T, Self::Variant), Self::Error>
where T: de::Deserialize,
{
de::Deserialize::deserialize(self)
}
fn visit_unit(&mut self) -> Result<(), Self::Error> {
Ok(())
}
fn visit_newtype<T>(&mut self) -> Result<T, Self::Error>
where T: super::Deserialize,
{
let (value,) = try!(self.visit_tuple(1, super::impls::TupleVisitor1::new()));
Ok(value)
}
fn visit_tuple<V>(&mut self,
_len: usize,
_visitor: V) -> Result<V::Value, Self::Error>
where V: super::Visitor
{
Err(super::Error::invalid_type(super::Type::TupleVariant))
}
fn visit_struct<V>(&mut self,
_fields: &'static [&'static str],
_visitor: V) -> Result<V::Value, Self::Error>
where V: super::Visitor
{
Err(super::Error::invalid_type(super::Type::StructVariant))
de::Deserialize::deserialize(self).map(private::unit_only)
}
}
@@ -429,7 +368,7 @@ impl<'a, E> de::VariantVisitor for StringDeserializer<E>
/// A helper deserializer that deserializes a `String`.
#[cfg(any(feature = "std", feature = "collections"))]
pub struct CowStrDeserializer<'a, E>(Option<Cow<'a, str>>, PhantomData<E>);
pub struct CowStrDeserializer<'a, E>(Cow<'a, str>, PhantomData<E>);
#[cfg(any(feature = "std", feature = "collections"))]
impl<'a, E> ValueDeserializer<E> for Cow<'a, str>
@@ -438,7 +377,7 @@ impl<'a, E> ValueDeserializer<E> for Cow<'a, str>
type Deserializer = CowStrDeserializer<'a, E>;
fn into_deserializer(self) -> CowStrDeserializer<'a, E> {
CowStrDeserializer(Some(self), PhantomData)
CowStrDeserializer(self, PhantomData)
}
}
@@ -448,23 +387,22 @@ impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E>
{
type Error = E;
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
match self.0.take() {
Some(Cow::Borrowed(string)) => visitor.visit_str(string),
Some(Cow::Owned(string)) => visitor.visit_string(string),
None => Err(de::Error::end_of_stream()),
match self.0 {
Cow::Borrowed(string) => visitor.visit_str(string),
Cow::Owned(string) => visitor.visit_string(string),
}
}
fn deserialize_enum<V>(&mut self,
fn deserialize_enum<V>(self,
_name: &str,
_variants: &'static [&'static str],
mut visitor: V) -> Result<V::Value, Self::Error>
where V: de::EnumVisitor,
visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
visitor.visit(self)
visitor.visit_enum(self)
}
forward_to_deserialize! {
@@ -475,42 +413,16 @@ impl<'a, E> de::Deserializer for CowStrDeserializer<'a, E>
}
#[cfg(any(feature = "std", feature = "collections"))]
impl<'a, E> de::VariantVisitor for CowStrDeserializer<'a, E>
impl<'a, E> de::EnumVisitor for CowStrDeserializer<'a, E>
where E: de::Error,
{
type Error = E;
type Variant = private::UnitOnly<E>;
fn visit_variant<T>(&mut self) -> Result<T, Self::Error>
fn visit_variant<T>(self) -> Result<(T, Self::Variant), Self::Error>
where T: de::Deserialize,
{
de::Deserialize::deserialize(self)
}
fn visit_unit(&mut self) -> Result<(), Self::Error> {
Ok(())
}
fn visit_newtype<T>(&mut self) -> Result<T, Self::Error>
where T: super::Deserialize,
{
let (value,) = try!(self.visit_tuple(1, super::impls::TupleVisitor1::new()));
Ok(value)
}
fn visit_tuple<V>(&mut self,
_len: usize,
_visitor: V) -> Result<V::Value, Self::Error>
where V: super::Visitor
{
Err(super::Error::invalid_type(super::Type::TupleVariant))
}
fn visit_struct<V>(&mut self,
_fields: &'static [&'static str],
_visitor: V) -> Result<V::Value, Self::Error>
where V: super::Visitor
{
Err(super::Error::invalid_type(super::Type::StructVariant))
de::Deserialize::deserialize(self).map(private::unit_only)
}
}
@@ -543,10 +455,15 @@ impl<I, T, E> de::Deserializer for SeqDeserializer<I, E>
{
type Error = E;
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
fn deserialize<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
visitor.visit_seq(self)
let v = try!(visitor.visit_seq(&mut self));
if self.len == 0 {
Ok(v)
} else {
Err(de::Error::invalid_length(self.len))
}
}
forward_to_deserialize! {
@@ -569,21 +486,12 @@ impl<I, T, E> de::SeqVisitor for SeqDeserializer<I, E>
match self.iter.next() {
Some(value) => {
self.len -= 1;
let mut de = value.into_deserializer();
Ok(Some(try!(de::Deserialize::deserialize(&mut de))))
de::Deserialize::deserialize(value.into_deserializer()).map(Some)
}
None => Ok(None),
}
}
fn end(&mut self) -> Result<(), Self::Error> {
if self.len == 0 {
Ok(())
} else {
Err(de::Error::invalid_length(self.len))
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
@@ -657,8 +565,8 @@ impl<V_, E> de::Deserializer for SeqVisitorDeserializer<V_, E>
{
type Error = E;
fn deserialize<V: de::Visitor>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error> {
visitor.visit_seq(&mut self.visitor)
fn deserialize<V: de::Visitor>(self, visitor: V) -> Result<V::Value, Self::Error> {
visitor.visit_seq(self.visitor)
}
forward_to_deserialize! {
@@ -718,6 +626,13 @@ impl<I, K, V, E> MapDeserializer<I, K, V, E>
(k, v)
})
}
fn end(&mut self) -> Result<(), E> {
match self.len {
Some(len) if len > 0 => Err(de::Error::invalid_length(len)),
_ => Ok(())
}
}
}
impl<I, K, V, E> de::Deserializer for MapDeserializer<I, K, V, E>
@@ -728,25 +643,32 @@ impl<I, K, V, E> de::Deserializer for MapDeserializer<I, K, V, E>
{
type Error = E;
fn deserialize<V_>(&mut self, mut visitor: V_) -> Result<V_::Value, Self::Error>
fn deserialize<V_>(mut self, visitor: V_) -> Result<V_::Value, Self::Error>
where V_: de::Visitor,
{
visitor.visit_map(self)
let value = try!(visitor.visit_map(&mut self));
try!(self.end());
Ok(value)
}
fn deserialize_seq<V_>(&mut self, mut visitor: V_) -> Result<V_::Value, Self::Error>
fn deserialize_seq<V_>(mut self, visitor: V_) -> Result<V_::Value, Self::Error>
where V_: de::Visitor,
{
visitor.visit_seq(self)
let value = try!(visitor.visit_seq(&mut self));
try!(self.end());
Ok(value)
}
fn deserialize_seq_fixed_size<V_>(&mut self, len: usize, mut visitor: V_) -> Result<V_::Value, Self::Error>
fn deserialize_seq_fixed_size<V_>(mut self, len: usize, visitor: V_) -> Result<V_::Value, Self::Error>
where V_: de::Visitor,
{
match self.len {
Some(map_len) if map_len == len => visitor.visit_seq(self),
Some(_) => Err(de::Error::invalid_length(len)),
None => visitor.visit_seq(self),
Some(map_len) if map_len != len => Err(de::Error::invalid_length(len)),
_ => {
let value = try!(visitor.visit_seq(&mut self));
try!(self.end());
Ok(value)
}
}
}
@@ -771,8 +693,7 @@ impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
match self.next() {
Some((key, value)) => {
self.value = Some(value);
let mut de = key.into_deserializer();
de::Deserialize::deserialize(&mut de).map(Some)
de::Deserialize::deserialize(key.into_deserializer()).map(Some)
}
None => Ok(None),
}
@@ -783,8 +704,7 @@ impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
{
match self.value.take() {
Some(value) => {
let mut de = value.into_deserializer();
de::Deserialize::deserialize(&mut de)
de::Deserialize::deserialize(value.into_deserializer())
}
None => {
Err(de::Error::end_of_stream())
@@ -792,10 +712,17 @@ impl<I, K, V, E> de::MapVisitor for MapDeserializer<I, K, V, E>
}
}
fn end(&mut self) -> Result<(), Self::Error> {
match self.len {
Some(len) if len > 0 => Err(de::Error::invalid_length(len)),
_ => Ok(())
fn visit<TK, TV>(&mut self) -> Result<Option<(TK, TV)>, Self::Error>
where TK: de::Deserialize,
TV: de::Deserialize
{
match self.next() {
Some((key, value)) => {
let key = try!(de::Deserialize::deserialize(key.into_deserializer()));
let value = try!(de::Deserialize::deserialize(value.into_deserializer()));
Ok(Some((key, value)))
}
None => Ok(None)
}
}
@@ -818,18 +745,14 @@ impl<I, K, V, E> de::SeqVisitor for MapDeserializer<I, K, V, E>
where T: de::Deserialize,
{
match self.next() {
Some(kv) => {
let mut de = PairDeserializer(Some(kv), PhantomData);
de::Deserialize::deserialize(&mut de).map(Some)
Some((k, v)) => {
let de = PairDeserializer(k, v, PhantomData);
de::Deserialize::deserialize(de).map(Some)
}
None => Ok(None),
}
}
fn end(&mut self) -> Result<(), Self::Error> {
de::MapVisitor::end(self)
}
fn size_hint(&self) -> (usize, Option<usize>) {
de::MapVisitor::size_hint(self)
}
@@ -837,7 +760,7 @@ impl<I, K, V, E> de::SeqVisitor for MapDeserializer<I, K, V, E>
// Used in the `impl SeqVisitor for MapDeserializer` to visit the map as a
// sequence of pairs.
struct PairDeserializer<A, B, E>(Option<(A, B)>, PhantomData<E>);
struct PairDeserializer<A, B, E>(A, B, PhantomData<E>);
impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E>
where A: ValueDeserializer<E>,
@@ -852,24 +775,25 @@ impl<A, B, E> de::Deserializer for PairDeserializer<A, B, E>
struct_field tuple enum ignored_any
}
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: de::Visitor,
{
self.deserialize_seq(visitor)
}
fn deserialize_seq<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
match self.0.take() {
Some((k, v)) => {
visitor.visit_seq(PairVisitor(Some(k), Some(v), PhantomData))
}
None => Err(de::Error::end_of_stream()),
let mut pair_visitor = PairVisitor(Some(self.0), Some(self.1), PhantomData);
let pair = try!(visitor.visit_seq(&mut pair_visitor));
if pair_visitor.1.is_none() {
Ok(pair)
} else {
Err(de::Error::invalid_length(pair_visitor.size_hint().0))
}
}
fn deserialize_seq_fixed_size<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_seq_fixed_size<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
if len == 2 {
@@ -893,24 +817,14 @@ impl<A, B, E> de::SeqVisitor for PairVisitor<A, B, E>
where T: de::Deserialize,
{
if let Some(k) = self.0.take() {
let mut de = k.into_deserializer();
de::Deserialize::deserialize(&mut de).map(Some)
de::Deserialize::deserialize(k.into_deserializer()).map(Some)
} else if let Some(v) = self.1.take() {
let mut de = v.into_deserializer();
de::Deserialize::deserialize(&mut de).map(Some)
de::Deserialize::deserialize(v.into_deserializer()).map(Some)
} else {
Ok(None)
}
}
fn end(&mut self) -> Result<(), Self::Error> {
if self.1.is_none() {
Ok(())
} else {
Err(de::Error::invalid_length(self.size_hint().0))
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = if self.0.is_some() {
2
@@ -980,8 +894,8 @@ impl<V_, E> de::Deserializer for MapVisitorDeserializer<V_, E>
{
type Error = E;
fn deserialize<V: de::Visitor>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error> {
visitor.visit_map(&mut self.visitor)
fn deserialize<V: de::Visitor>(self, visitor: V) -> Result<V::Value, Self::Error> {
visitor.visit_map(self.visitor)
}
forward_to_deserialize! {
@@ -999,25 +913,22 @@ impl<'a, E> ValueDeserializer<E> for bytes::Bytes<'a>
type Deserializer = BytesDeserializer<'a, E>;
fn into_deserializer(self) -> BytesDeserializer<'a, E> {
BytesDeserializer(Some(self.into()), PhantomData)
BytesDeserializer(self.into(), PhantomData)
}
}
/// A helper deserializer that deserializes a `&[u8]`.
pub struct BytesDeserializer<'a, E> (Option<&'a [u8]>, PhantomData<E>);
pub struct BytesDeserializer<'a, E>(&'a [u8], PhantomData<E>);
impl<'a, E> de::Deserializer for BytesDeserializer<'a, E>
where E: de::Error
{
type Error = E;
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
match self.0.take() {
Some(bytes) => visitor.visit_bytes(bytes),
None => Err(de::Error::end_of_stream()),
}
visitor.visit_bytes(self.0)
}
forward_to_deserialize! {
@@ -1036,13 +947,13 @@ impl<E> ValueDeserializer<E> for bytes::ByteBuf
type Deserializer = ByteBufDeserializer<E>;
fn into_deserializer(self) -> Self::Deserializer {
ByteBufDeserializer(Some(self.into()), PhantomData)
ByteBufDeserializer(self.into(), PhantomData)
}
}
/// A helper deserializer that deserializes a `Vec<u8>`.
#[cfg(any(feature = "std", feature = "collections"))]
pub struct ByteBufDeserializer<E>(Option<Vec<u8>>, PhantomData<E>);
pub struct ByteBufDeserializer<E>(Vec<u8>, PhantomData<E>);
#[cfg(any(feature = "std", feature = "collections"))]
impl<E> de::Deserializer for ByteBufDeserializer<E>
@@ -1050,13 +961,10 @@ impl<E> de::Deserializer for ByteBufDeserializer<E>
{
type Error = E;
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Self::Error>
fn deserialize<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor,
{
match self.0.take() {
Some(bytes) => visitor.visit_byte_buf(bytes),
None => Err(de::Error::end_of_stream()),
}
visitor.visit_byte_buf(self.0)
}
forward_to_deserialize! {
@@ -1065,3 +973,48 @@ impl<E> de::Deserializer for ByteBufDeserializer<E>
tuple_struct struct struct_field tuple enum ignored_any
}
}
///////////////////////////////////////////////////////////////////////////////
mod private {
use de;
use core::marker::PhantomData;
pub struct UnitOnly<E>(PhantomData<E>);
pub fn unit_only<T, E>(t: T) -> (T, UnitOnly<E>) {
(t, UnitOnly(PhantomData))
}
impl<E> de::VariantVisitor for UnitOnly<E>
where E: de::Error
{
type Error = E;
fn visit_unit(self) -> Result<(), Self::Error> {
Ok(())
}
fn visit_newtype<T>(self) -> Result<T, Self::Error>
where T: de::Deserialize,
{
Err(de::Error::invalid_type(de::Type::NewtypeVariant))
}
fn visit_tuple<V>(self,
_len: usize,
_visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor
{
Err(de::Error::invalid_type(de::Type::TupleVariant))
}
fn visit_struct<V>(self,
_fields: &'static [&'static str],
_visitor: V) -> Result<V::Value, Self::Error>
where V: de::Visitor
{
Err(de::Error::invalid_type(de::Type::StructVariant))
}
}
}
+2 -2
View File
@@ -30,7 +30,7 @@ extern crate alloc;
#[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};
#[cfg(feature = "unstable")]
extern crate core;
#[cfg(feature = "unstable")]
@@ -38,7 +38,7 @@ mod core {
}
pub use ser::{Serialize, Serializer};
pub use de::{Deserialize, Deserializer, Error};
pub use de::{Deserialize, Deserializer};
#[cfg(not(feature = "std"))]
macro_rules! format {
+6 -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 {
@@ -141,12 +113,12 @@ macro_rules! forward_to_deserialize_helper {
(tuple) => {
forward_to_deserialize_method!{deserialize_tuple(usize)}
};
(enum) => {
forward_to_deserialize_method!{deserialize_enum(&'static str, &'static [&'static str])}
};
(ignored_any) => {
forward_to_deserialize_method!{deserialize_ignored_any()}
};
(enum) => {
forward_to_deserialize_enum!();
};
}
/// Helper to forward `Deserializer` methods to `Deserializer::deserialize`.
@@ -156,7 +128,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
/// {
/// /* ... */
+119 -70
View File
@@ -69,16 +69,23 @@ use core::nonzero::{NonZero, Zeroable};
use super::{
Error,
Serialize,
SerializeMap,
SerializeSeq,
SerializeStruct,
SerializeTuple,
Serializer,
};
#[cfg(feature = "unstable")]
use super::Iterator;
///////////////////////////////////////////////////////////////////////////////
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 +113,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 +123,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 +132,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 +150,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 +164,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 +181,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 +230,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(S::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()
}
}
}
@@ -273,12 +309,16 @@ 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!();
}
@@ -288,15 +328,15 @@ impl<A> Serialize for ops::Range<A>
for<'a> &'a A: ops::Add<&'a A, Output = 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: 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(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()
}
}
@@ -304,7 +344,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()
@@ -313,11 +353,6 @@ impl Serialize for () {
///////////////////////////////////////////////////////////////////////////////
// FIXME(rust #19630) Remove this work-around
macro_rules! e {
($e:expr) => { $e }
}
macro_rules! tuple_impls {
($(
$TupleVisitor:ident ($len:expr, $($T:ident),+) {
@@ -329,14 +364,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, &e!(self.$idx)));
try!(tuple.serialize_element(&self.$idx));
)+
serializer.serialize_tuple_end(state)
tuple.end()
}
}
)+
@@ -519,15 +554,15 @@ 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())));
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()
}
}
}
@@ -553,7 +588,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)
@@ -562,7 +597,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)
@@ -570,9 +605,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)
@@ -580,9 +617,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)
@@ -590,9 +629,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)
@@ -600,9 +641,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)
@@ -611,8 +654,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)
@@ -628,33 +676,30 @@ 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,
{
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()
}
}
///////////////////////////////////////////////////////////////////////////////
#[cfg(all(feature = "std", feature = "unstable"))]
#[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,
{
match *self {
net::IpAddr::V4(ref addr) => addr.serialize(serializer),
net::IpAddr::V6(ref addr) => addr.serialize(serializer),
}
self.to_string().serialize(serializer)
}
}
#[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)
@@ -663,7 +708,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)
@@ -674,7 +719,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 {
@@ -686,7 +731,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)
@@ -695,7 +740,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)
@@ -706,7 +751,7 @@ 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() {
@@ -718,7 +763,7 @@ impl Serialize for path::Path {
#[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)
@@ -726,8 +771,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)
}
}
+217 -181
View File
@@ -18,6 +18,11 @@ use error;
#[cfg(all(feature = "collections", not(feature = "std")))]
use collections::String;
#[cfg(feature = "unstable")]
use core::marker::PhantomData;
#[cfg(feature = "unstable")]
use core::cell::RefCell;
pub mod impls;
///////////////////////////////////////////////////////////////////////////////
@@ -44,7 +49,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 +58,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 +77,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,
self,
name: &'static str,
value: T,
) -> Result<(), Self::Error>;
) -> 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,
self,
name: &'static str,
variant_index: usize,
variant: &'static str,
value: T,
) -> Result<(), Self::Error>;
) -> 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,
self,
value: T,
) -> Result<(), Self::Error>;
) -> 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: 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: 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: 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: 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: Serialize>(&mut self, key: T) -> Result<(), Self::Error>;
/// Serialize a map value.
fn serialize_value<T: 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<V: Serialize>(&mut self, key: &'static str, value: V) -> 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<V: Serialize>(&mut self, key: &'static str, value: V) -> 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)))
}
+9 -18
View File
@@ -1,6 +1,6 @@
[package]
name = "serde_codegen"
version = "0.8.9"
version = "0.9.0-rc1"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Macros to auto-generate implementations for the serde framework"
@@ -8,31 +8,22 @@ homepage = "https://serde.rs"
repository = "https://github.com/serde-rs/serde"
documentation = "https://serde.rs/codegen.html"
keywords = ["serde", "serialization"]
build = "build.rs"
include = ["Cargo.toml", "build.rs", "src/**/*.rs", "src/lib.rs.in"]
include = ["Cargo.toml", "src/**/*.rs"]
[features]
default = ["with-syntex"]
unstable = ["quasi_macros"]
unstable = []
unstable-testing = ["clippy"]
with-syntex = [
"quasi/with-syntex",
"quasi_codegen",
"quasi_codegen/with-syntex",
"serde_codegen_internals/with-syntex",
"syntex",
"syntex_syntax",
]
[build-dependencies]
quasi_codegen = { version = "^0.20.0", optional = true }
syntex = { version = "^0.44.0", optional = true }
with-syn = []
[dependencies]
aster = { version = "^0.27.0", default-features = false }
clippy = { version = "^0.*", optional = true }
quasi = { version = "^0.20.0", default-features = false }
quasi_macros = { version = "^0.20.0", optional = true }
serde_codegen_internals = { version = "=0.8.9", default-features = false, path = "../serde_codegen_internals" }
syntex = { version = "^0.44.0", optional = true }
syntex_syntax = { version = "^0.44.0", optional = true }
quote = "0.3.8"
serde_codegen_internals = { version = "=0.11.3", default-features = false, path = "../serde_codegen_internals" }
syn = { version = "0.10", features = ["aster", "visit"] }
syntex = { version = "^0.54.0", optional = true }
syntex_syntax = { version = "^0.54.0", optional = true }
-28
View File
@@ -1,28 +0,0 @@
#[cfg(feature = "with-syntex")]
mod inner {
extern crate quasi_codegen;
use std::env;
use std::path::Path;
use std::thread::spawn;
pub fn main() {
// put everything into a thread, so users can use `RUST_MIN_STACK` to increase the amount of stack
spawn(|| {
let out_dir = env::var_os("OUT_DIR").unwrap();
let src = Path::new("src/lib.rs.in");
let dst = Path::new(&out_dir).join("lib.rs");
quasi_codegen::expand(&src, &dst).unwrap();
}).join().unwrap()
}
}
#[cfg(not(feature = "with-syntex"))]
mod inner {
pub fn main() {}
}
fn main() {
inner::main();
}
+25 -31
View File
@@ -1,9 +1,6 @@
use std::collections::HashSet;
use aster::AstBuilder;
use syntax::ast;
use syntax::visit;
use syn::{self, aster, visit};
use internals::ast::Item;
use internals::attr;
@@ -11,10 +8,10 @@ use internals::attr;
// Remove the default from every type parameter because in the generated impls
// they look like associated types: "error: associated type bindings are not
// allowed here".
pub fn without_defaults(generics: &ast::Generics) -> ast::Generics {
ast::Generics {
pub fn without_defaults(generics: &syn::Generics) -> syn::Generics {
syn::Generics {
ty_params: generics.ty_params.iter().map(|ty_param| {
ast::TyParam {
syn::TyParam {
default: None,
.. ty_param.clone()
}}).collect(),
@@ -23,24 +20,22 @@ pub fn without_defaults(generics: &ast::Generics) -> ast::Generics {
}
pub fn with_where_predicates(
builder: &AstBuilder,
generics: &ast::Generics,
predicates: &[ast::WherePredicate],
) -> ast::Generics {
builder.from_generics(generics.clone())
generics: &syn::Generics,
predicates: &[syn::WherePredicate],
) -> syn::Generics {
aster::from_generics(generics.clone())
.with_predicates(predicates.to_vec())
.build()
}
pub fn with_where_predicates_from_fields<F>(
builder: &AstBuilder,
item: &Item,
generics: &ast::Generics,
generics: &syn::Generics,
from_field: F,
) -> ast::Generics
where F: Fn(&attr::Field) -> Option<&[ast::WherePredicate]>,
) -> syn::Generics
where F: Fn(&attr::Field) -> Option<&[syn::WherePredicate]>,
{
builder.from_generics(generics.clone())
aster::from_generics(generics.clone())
.with_predicates(
item.body.all_fields()
.flat_map(|field| from_field(&field.attrs))
@@ -60,34 +55,33 @@ pub fn with_where_predicates_from_fields<F>(
// c: C,
// }
pub fn with_bound<F>(
builder: &AstBuilder,
item: &Item,
generics: &ast::Generics,
generics: &syn::Generics,
filter: F,
bound: &ast::Path,
) -> ast::Generics
bound: &syn::Path,
) -> syn::Generics
where F: Fn(&attr::Field) -> bool,
{
struct FindTyParams {
// Set of all generic type parameters on the current struct (A, B, C in
// the example). Initialized up front.
all_ty_params: HashSet<ast::Name>,
all_ty_params: HashSet<syn::Ident>,
// Set of generic type parameters used in fields for which filter
// returns true (A and B in the example). Filled in as the visitor sees
// them.
relevant_ty_params: HashSet<ast::Name>,
relevant_ty_params: HashSet<syn::Ident>,
}
impl visit::Visitor for FindTyParams {
fn visit_path(&mut self, path: &ast::Path, _id: ast::NodeId) {
fn visit_path(&mut self, path: &syn::Path) {
if let Some(seg) = path.segments.last() {
if seg.identifier.name.as_str() == "PhantomData" {
if seg.ident == "PhantomData" {
// Hardcoded exception, because PhantomData<T> implements
// Serialize and Deserialize whether or not T implements it.
return;
}
}
if !path.global && path.segments.len() == 1 {
let id = path.segments[0].identifier.name;
let id = path.segments[0].ident.clone();
if self.all_ty_params.contains(&id) {
self.relevant_ty_params.insert(id);
}
@@ -97,7 +91,7 @@ pub fn with_bound<F>(
}
let all_ty_params: HashSet<_> = generics.ty_params.iter()
.map(|ty_param| ty_param.ident.name)
.map(|ty_param| ty_param.ident.clone())
.collect();
let relevant_tys = item.body.all_fields()
@@ -112,14 +106,14 @@ pub fn with_bound<F>(
visit::walk_ty(&mut visitor, ty);
}
builder.from_generics(generics.clone())
aster::from_generics(generics.clone())
.with_predicates(
generics.ty_params.iter()
.map(|ty_param| ty_param.ident.name)
.map(|ty_param| ty_param.ident.clone())
.filter(|id| visitor.relevant_ty_params.contains(id))
.map(|id| builder.where_predicate()
.map(|id| aster::where_predicate()
// the type parameter that is being bounded e.g. T
.bound().build(builder.ty().id(id))
.bound().build(aster::ty().id(id))
// the bound e.g. Serialize
.bound().trait_(bound.clone()).build()
.build()))
+472 -679
View File
File diff suppressed because it is too large Load Diff
+88 -34
View File
@@ -2,11 +2,10 @@
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", allow(too_many_arguments))]
#![cfg_attr(feature = "clippy", allow(used_underscore_binding))]
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))]
#![cfg_attr(not(feature = "with-syntex"), plugin(quasi_macros))]
extern crate aster;
extern crate quasi;
// The `quote!` macro requires deep recursion.
#![recursion_limit = "192"]
extern crate serde_codegen_internals as internals;
#[cfg(feature = "with-syntex")]
@@ -16,24 +15,16 @@ extern crate syntex;
#[macro_use]
extern crate syntex_syntax as syntax;
#[cfg(not(feature = "with-syntex"))]
extern crate syn;
#[macro_use]
extern crate syntax;
#[cfg(not(feature = "with-syntex"))]
extern crate rustc_plugin;
extern crate quote;
#[cfg(feature = "with-syntex")]
use std::path::Path;
#[cfg(not(feature = "with-syntex"))]
use syntax::feature_gate::AttributeType;
#[cfg(feature = "with-syntex")]
include!(concat!(env!("OUT_DIR"), "/lib.rs"));
#[cfg(not(feature = "with-syntex"))]
include!("lib.rs.in");
mod bound;
mod de;
mod ser;
#[cfg(feature = "with-syntex")]
fn syntex_registry() -> syntex::Registry {
@@ -47,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)
}
@@ -68,8 +59,8 @@ fn syntex_registry() -> syntex::Registry {
reg.add_attr("feature(custom_derive)");
reg.add_attr("feature(custom_attribute)");
reg.add_decorator("derive_Serialize", ser::expand_derive_serialize);
reg.add_decorator("derive_Deserialize", de::expand_derive_deserialize);
reg.add_decorator("derive_Serialize", shim::expand_derive_serialize);
reg.add_decorator("derive_Deserialize", shim::expand_derive_deserialize);
reg.add_post_expansion_pass(strip_attributes);
@@ -102,17 +93,80 @@ pub fn expand<S, D>(src: S, dst: D) -> Result<(), syntex::Error>
syntex::with_extra_stack(expand_thread)
}
#[cfg(not(feature = "with-syntex"))]
pub fn register(reg: &mut rustc_plugin::Registry) {
reg.register_syntax_extension(
syntax::parse::token::intern("derive_Serialize"),
syntax::ext::base::MultiDecorator(
Box::new(ser::expand_derive_serialize)));
macro_rules! shim {
($name:ident $pkg:ident :: $func:ident) => {
pub fn $func(
cx: &mut ::syntax::ext::base::ExtCtxt,
span: ::syntax::codemap::Span,
meta_item: &::syntax::ast::MetaItem,
annotatable: &::syntax::ext::base::Annotatable,
push: &mut FnMut(::syntax::ext::base::Annotatable)
) {
let item = match *annotatable {
::syntax::ext::base::Annotatable::Item(ref item) => item,
_ => {
cx.span_err(
meta_item.span,
concat!("`#[derive(",
stringify!($name),
")]` may only be applied to structs and enums"));
return;
}
};
reg.register_syntax_extension(
syntax::parse::token::intern("derive_Deserialize"),
syntax::ext::base::MultiDecorator(
Box::new(de::expand_derive_deserialize)));
use syntax::{attr, ast, visit};
struct MarkSerdeAttributesUsed;
impl<'a> visit::Visitor<'a> for MarkSerdeAttributesUsed {
fn visit_attribute(&mut self, attr: &ast::Attribute) {
if attr.value.name == "serde" {
if let ast::MetaItemKind::List(..) = attr.value.node {
attr::mark_used(attr);
}
}
}
}
visit::walk_item(&mut MarkSerdeAttributesUsed, item);
reg.register_attribute("serde".to_owned(), AttributeType::Normal);
use syntax::print::pprust;
let s = pprust::item_to_string(item);
use {syn, $pkg};
let syn_item = syn::parse_macro_input(&s).unwrap();
let expanded = match $pkg::$func(&syn_item) {
Ok(expanded) => expanded.to_string(),
Err(msg) => {
cx.span_err(span, &msg);
return;
}
};
use syntax::parse;
let name = stringify!($name).to_string();
let sess = cx.parse_sess;
let impl_item = parse::parse_item_from_source_str(name, expanded, sess);
push(::syntax::ext::base::Annotatable::Item(impl_item.unwrap().unwrap()));
}
};
}
#[cfg(feature = "with-syntex")]
mod shim {
shim!(Serialize ser::expand_derive_serialize);
shim!(Deserialize de::expand_derive_deserialize);
}
#[cfg(feature = "with-syn")]
#[doc(hidden)]
/// Not public API. Use the serde_derive crate.
pub fn expand_derive_serialize(item: &str) -> Result<quote::Tokens, String> {
let syn_item = syn::parse_macro_input(item).unwrap();
ser::expand_derive_serialize(&syn_item)
}
#[cfg(feature = "with-syn")]
#[doc(hidden)]
/// Not public API. Use the serde_derive crate.
pub fn expand_derive_deserialize(item: &str) -> Result<quote::Tokens, String> {
let syn_item = syn::parse_macro_input(item).unwrap();
de::expand_derive_deserialize(&syn_item)
}
-4
View File
@@ -1,4 +0,0 @@
mod bound;
mod de;
mod ser;
mod span;
+266 -368
View File
@@ -1,103 +1,62 @@
use aster;
use syntax::ast::{self, Ident, MetaItem};
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ptr::P;
use syntax::tokenstream::TokenTree;
use syn::{self, aster, Ident};
use quote::Tokens;
use bound;
use span;
use internals::ast::{Body, Field, Item, Style, Variant};
use internals::{attr, Error};
use internals::{self, attr};
pub fn expand_derive_serialize(
cx: &mut ExtCtxt,
span: Span,
meta_item: &MetaItem,
annotatable: &Annotatable,
push: &mut FnMut(Annotatable)
) {
let item = match *annotatable {
Annotatable::Item(ref item) => item,
_ => {
cx.span_err(
meta_item.span,
"`#[derive(Serialize)]` may only be applied to structs and enums");
return;
}
};
pub fn expand_derive_serialize(item: &syn::MacroInput) -> Result<Tokens, String> {
let ctxt = internals::Ctxt::new();
let item = Item::from_ast(&ctxt, item);
try!(ctxt.check());
let item = match Item::from_ast(cx, item) {
Ok(item) => item,
Err(Error::UnexpectedItemKind) => {
cx.span_err(item.span,
"`#[derive(Serialize)]` may only be applied to structs and enums");
return;
}
};
let impl_generics = build_impl_generics(&item);
let builder = aster::AstBuilder::new().span(span);
let impl_item = serialize_item(cx, &builder, &item);
push(span::record_expansion(cx, impl_item, "Serialize"))
}
fn serialize_item(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
item: &Item,
) -> P<ast::Item> {
let impl_generics = build_impl_generics(builder, &item);
let ty = builder.ty().path()
.segment(item.ident).with_generics(impl_generics.clone()).build()
let ty = aster::ty().path()
.segment(item.ident.clone()).with_generics(impl_generics.clone()).build()
.build();
let body = serialize_body(cx,
builder,
&item,
let body = serialize_body(&item,
&impl_generics,
ty.clone());
let where_clause = &impl_generics.where_clause;
let dummy_const = builder.id(format!("_IMPL_SERIALIZE_FOR_{}", item.ident));
let dummy_const = Ident::new(format!("_IMPL_SERIALIZE_FOR_{}", item.ident));
quote_item!(cx,
Ok(quote! {
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
const $dummy_const: () = {
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
$body
impl #impl_generics _serde::Serialize for #ty #where_clause {
fn serialize<__S>(&self, _serializer: __S) -> ::std::result::Result<__S::Ok, __S::Error>
where __S: _serde::Serializer
{
#body
}
}
};
).unwrap()
})
}
// All the generics in the input, plus a bound `T: Serialize` for each generic
// field type that will be serialized by us.
fn build_impl_generics(
builder: &aster::AstBuilder,
item: &Item,
) -> ast::Generics {
fn build_impl_generics(item: &Item) -> syn::Generics {
let generics = bound::without_defaults(item.generics);
let generics = bound::with_where_predicates_from_fields(
builder, item, &generics,
item, &generics,
|attrs| attrs.ser_bound());
match item.attrs.ser_bound() {
Some(predicates) => {
bound::with_where_predicates(builder, &generics, predicates)
bound::with_where_predicates(&generics, predicates)
}
None => {
bound::with_bound(builder, item, &generics,
bound::with_bound(item, &generics,
needs_serialize_bound,
&builder.path().ids(&["_serde", "ser", "Serialize"]).build())
&aster::path().ids(&["_serde", "Serialize"]).build())
}
}
}
@@ -113,18 +72,14 @@ fn needs_serialize_bound(attrs: &attr::Field) -> bool {
}
fn serialize_body(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
item: &Item,
impl_generics: &ast::Generics,
ty: P<ast::Ty>,
) -> P<ast::Block> {
impl_generics: &syn::Generics,
ty: syn::Ty,
) -> Tokens {
match item.body {
Body::Enum(ref variants) => {
serialize_item_enum(
cx,
builder,
item.ident,
&item.ident,
impl_generics,
ty,
variants,
@@ -132,12 +87,10 @@ fn serialize_body(
}
Body::Struct(Style::Struct, ref fields) => {
if fields.iter().any(|field| field.ident.is_none()) {
cx.span_bug(item.span, "struct has unnamed fields")
panic!("struct has unnamed fields");
}
serialize_struct(
cx,
builder,
impl_generics,
ty,
fields,
@@ -145,12 +98,10 @@ fn serialize_body(
}
Body::Struct(Style::Tuple, ref fields) => {
if fields.iter().any(|field| field.ident.is_some()) {
cx.span_bug(item.span, "tuple struct has named fields")
panic!("tuple struct has named fields");
}
serialize_tuple_struct(
cx,
builder,
impl_generics,
ty,
fields,
@@ -158,8 +109,6 @@ fn serialize_body(
}
Body::Struct(Style::Newtype, ref fields) => {
serialize_newtype_struct(
cx,
builder,
impl_generics,
ty,
&fields[0],
@@ -167,136 +116,116 @@ fn serialize_body(
}
Body::Struct(Style::Unit, _) => {
serialize_unit_struct(
cx,
builder,
&item.attrs)
}
}
}
fn serialize_unit_struct(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
item_attrs: &attr::Item,
) -> P<ast::Block> {
let type_name = name_expr(builder, item_attrs.name());
fn serialize_unit_struct(item_attrs: &attr::Item) -> Tokens {
let type_name = item_attrs.name().serialize_name();
quote_block!(cx, {
_serializer.serialize_unit_struct($type_name)
}).unwrap()
quote! {
_serializer.serialize_unit_struct(#type_name)
}
}
fn serialize_newtype_struct(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
impl_generics: &ast::Generics,
item_ty: P<ast::Ty>,
impl_generics: &syn::Generics,
item_ty: syn::Ty,
field: &Field,
item_attrs: &attr::Item,
) -> P<ast::Block> {
let type_name = name_expr(builder, item_attrs.name());
) -> Tokens {
let type_name = item_attrs.name().serialize_name();
let mut field_expr = quote_expr!(cx, &self.0);
let mut field_expr = quote!(&self.0);
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_with(cx, builder,
&item_ty, impl_generics, &field.ty, path, field_expr);
field_expr = wrap_serialize_with(
&item_ty, impl_generics, field.ty, path, field_expr);
}
quote_block!(cx, {
_serializer.serialize_newtype_struct($type_name, $field_expr)
}).unwrap()
quote! {
_serializer.serialize_newtype_struct(#type_name, #field_expr)
}
}
fn serialize_tuple_struct(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
impl_generics: &ast::Generics,
ty: P<ast::Ty>,
impl_generics: &syn::Generics,
ty: syn::Ty,
fields: &[Field],
item_attrs: &attr::Item,
) -> P<ast::Block> {
) -> Tokens {
let serialize_stmts = serialize_tuple_struct_visitor(
cx,
builder,
ty.clone(),
fields,
impl_generics,
false,
cx.ident_of("serialize_tuple_struct_elt"),
quote!(_serde::ser::SerializeTupleStruct::serialize_field),
);
let type_name = name_expr(builder, item_attrs.name());
let type_name = item_attrs.name().serialize_name();
let len = serialize_stmts.len();
let let_mut = mut_if(cx, len > 0);
let let_mut = mut_if(len > 0);
quote_block!(cx, {
let $let_mut state = try!(_serializer.serialize_tuple_struct($type_name, $len));
$serialize_stmts
_serializer.serialize_tuple_struct_end(state)
}).unwrap()
quote! {
let #let_mut __serde_state = try!(_serializer.serialize_tuple_struct(#type_name, #len));
#(#serialize_stmts)*
_serde::ser::SerializeTupleStruct::end(__serde_state)
}
}
fn serialize_struct(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
impl_generics: &ast::Generics,
ty: P<ast::Ty>,
impl_generics: &syn::Generics,
ty: syn::Ty,
fields: &[Field],
item_attrs: &attr::Item,
) -> P<ast::Block> {
) -> Tokens {
let serialize_fields = serialize_struct_visitor(
cx,
builder,
ty.clone(),
fields,
impl_generics,
false,
cx.ident_of("serialize_struct_elt"),
quote!(_serde::ser::SerializeStruct::serialize_field),
);
let type_name = name_expr(builder, item_attrs.name());
let type_name = item_attrs.name().serialize_name();
let mut serialized_fields = fields.iter()
.filter(|&field| !field.attrs.skip_serializing())
.peekable();
let let_mut = mut_if(cx, serialized_fields.peek().is_some());
let let_mut = mut_if(serialized_fields.peek().is_some());
let len = serialized_fields
.map(|field| {
let ident = field.ident.expect("struct has unnamed fields");
let field_expr = quote_expr!(cx, &self.$ident);
let ident = field.ident.clone().expect("struct has unnamed fields");
let field_expr = quote!(&self.#ident);
match field.attrs.skip_serializing_if() {
Some(path) => quote_expr!(cx, if $path($field_expr) { 0 } else { 1 }),
None => quote_expr!(cx, 1),
Some(path) => quote!(if #path(#field_expr) { 0 } else { 1 }),
None => quote!(1),
}
})
.fold(quote_expr!(cx, 0), |sum, expr| quote_expr!(cx, $sum + $expr));
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
quote_block!(cx, {
let $let_mut state = try!(_serializer.serialize_struct($type_name, $len));
$serialize_fields
_serializer.serialize_struct_end(state)
}).unwrap()
quote! {
let #let_mut __serde_state = try!(_serializer.serialize_struct(#type_name, #len));
#(#serialize_fields)*
_serde::ser::SerializeStruct::end(__serde_state)
}
}
fn serialize_item_enum(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
type_ident: Ident,
impl_generics: &ast::Generics,
ty: P<ast::Ty>,
type_ident: &syn::Ident,
impl_generics: &syn::Generics,
ty: syn::Ty,
variants: &[Variant],
item_attrs: &attr::Item,
) -> P<ast::Block> {
) -> Tokens {
let arms: Vec<_> =
variants.iter()
.enumerate()
.map(|(variant_index, variant)| {
serialize_variant(
cx,
builder,
type_ident,
impl_generics,
ty.clone(),
@@ -307,366 +236,335 @@ fn serialize_item_enum(
})
.collect();
quote_block!(cx, {
quote! {
match *self {
$arms
#(#arms)*
}
}).unwrap()
}
}
fn serialize_variant(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
type_ident: Ident,
generics: &ast::Generics,
ty: P<ast::Ty>,
type_ident: &syn::Ident,
generics: &syn::Generics,
ty: syn::Ty,
variant: &Variant,
variant_index: usize,
item_attrs: &attr::Item,
) -> ast::Arm {
let type_name = name_expr(builder, item_attrs.name());
) -> Tokens {
let type_name = item_attrs.name().serialize_name();
let variant_ident = variant.ident;
let variant_name = name_expr(builder, variant.attrs.name());
let variant_ident = variant.ident.clone();
let variant_name = variant.attrs.name().serialize_name();
match variant.style {
Style::Unit => {
quote_arm!(cx,
$type_ident::$variant_ident =>
_serde::ser::Serializer::serialize_unit_variant(
_serializer,
$type_name,
$variant_index,
$variant_name,
),
)
},
Style::Newtype => {
let block = serialize_newtype_variant(
cx,
builder,
type_name,
variant_index,
variant_name,
ty,
generics,
&variant.fields[0],
);
quote_arm!(cx,
$type_ident::$variant_ident(ref __simple_value) => $block
)
},
Style::Tuple => {
let field_names: Vec<ast::Ident> = (0 .. variant.fields.len())
.map(|i| builder.id(format!("__field{}", i)))
.collect();
let pat = builder.pat().enum_()
.id(type_ident).id(variant_ident).build()
.with_pats(
field_names.iter()
.map(|field| builder.pat().ref_id(field))
)
.build();
let block = serialize_tuple_variant(
cx,
builder,
type_name,
variant_index,
variant_name,
generics,
ty,
&variant.fields,
);
quote_arm!(cx,
$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::invalid_value(#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 mut pat = builder.pat().struct_().id(type_ident).id(variant_ident).build();
for field in &variant.fields {
let name = match field.ident {
Some(name) => name,
None => cx.span_bug(field.span, "struct variant has unnamed fields"),
};
pat = pat.with_field_pat(ast::FieldPat {
ident: name,
pat: builder.pat().ref_id(name),
is_shorthand: true,
});
} 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],
);
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)));
let block = serialize_tuple_variant(
type_name,
variant_index,
variant_name,
generics,
ty,
&variant.fields,
);
quote! {
#type_ident::#variant_ident(#(ref #field_names),*) => { #block }
}
}
let pat = pat.build();
Style::Struct => {
let fields = variant.fields.iter()
.map(|f| f.ident.clone().expect("struct variant has unnamed fields"));
let block = serialize_struct_variant(
cx,
builder,
variant_index,
variant_name,
generics,
ty,
&variant.fields,
item_attrs,
);
let block = serialize_struct_variant(
variant_index,
variant_name,
generics,
ty,
&variant.fields,
item_attrs,
);
quote_arm!(cx,
$pat => $block
)
quote! {
#type_ident::#variant_ident { #(ref #fields),* } => { #block }
}
}
}
}
}
fn serialize_newtype_variant(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
type_name: P<ast::Expr>,
type_name: String,
variant_index: usize,
variant_name: P<ast::Expr>,
item_ty: P<ast::Ty>,
generics: &ast::Generics,
variant_name: String,
item_ty: syn::Ty,
generics: &syn::Generics,
field: &Field,
) -> P<ast::Block> {
let mut field_expr = quote_expr!(cx, __simple_value);
) -> Tokens {
let mut field_expr = quote!(__simple_value);
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_with(cx, builder,
&item_ty, generics, &field.ty, path, field_expr);
field_expr = wrap_serialize_with(
&item_ty, generics, field.ty, path, field_expr);
}
quote_block!(cx, {
_serde::ser::Serializer::serialize_newtype_variant(
quote! {
_serde::Serializer::serialize_newtype_variant(
_serializer,
$type_name,
$variant_index,
$variant_name,
$field_expr,
#type_name,
#variant_index,
#variant_name,
#field_expr,
)
}).unwrap()
}
}
fn serialize_tuple_variant(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
type_name: P<ast::Expr>,
type_name: String,
variant_index: usize,
variant_name: P<ast::Expr>,
generics: &ast::Generics,
structure_ty: P<ast::Ty>,
variant_name: String,
generics: &syn::Generics,
structure_ty: syn::Ty,
fields: &[Field],
) -> P<ast::Block> {
) -> Tokens {
let serialize_stmts = serialize_tuple_struct_visitor(
cx,
builder,
structure_ty,
fields,
generics,
true,
cx.ident_of("serialize_tuple_variant_elt"),
quote!(_serde::ser::SerializeTupleVariant::serialize_field),
);
let len = serialize_stmts.len();
let let_mut = mut_if(cx, len > 0);
let let_mut = mut_if(len > 0);
quote_block!(cx, {
let $let_mut state = try!(_serializer.serialize_tuple_variant($type_name, $variant_index, $variant_name, $len));
$serialize_stmts
_serializer.serialize_tuple_variant_end(state)
}).unwrap()
quote! {
let #let_mut __serde_state = try!(_serializer.serialize_tuple_variant(
#type_name,
#variant_index,
#variant_name,
#len));
#(#serialize_stmts)*
_serde::ser::SerializeTupleVariant::end(__serde_state)
}
}
fn serialize_struct_variant(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
variant_index: usize,
variant_name: P<ast::Expr>,
generics: &ast::Generics,
ty: P<ast::Ty>,
variant_name: String,
generics: &syn::Generics,
ty: syn::Ty,
fields: &[Field],
item_attrs: &attr::Item,
) -> P<ast::Block> {
) -> Tokens {
let serialize_fields = serialize_struct_visitor(
cx,
builder,
ty.clone(),
fields,
&generics,
generics,
true,
cx.ident_of("serialize_struct_variant_elt"),
quote!(_serde::ser::SerializeStructVariant::serialize_field),
);
let item_name = name_expr(builder, item_attrs.name());
let item_name = item_attrs.name().serialize_name();
let mut serialized_fields = fields.iter()
.filter(|&field| !field.attrs.skip_serializing())
.peekable();
let let_mut = mut_if(cx, serialized_fields.peek().is_some());
let let_mut = mut_if(serialized_fields.peek().is_some());
let len = serialized_fields
.map(|field| {
let ident = field.ident.expect("struct has unnamed fields");
let field_expr = quote_expr!(cx, $ident);
let ident = field.ident.clone().expect("struct has unnamed fields");
match field.attrs.skip_serializing_if() {
Some(path) => quote_expr!(cx, if $path($field_expr) { 0 } else { 1 }),
None => quote_expr!(cx, 1),
Some(path) => quote!(if #path(#ident) { 0 } else { 1 }),
None => quote!(1),
}
})
.fold(quote_expr!(cx, 0), |sum, expr| quote_expr!(cx, $sum + $expr));
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
quote_block!(cx, {
let $let_mut state = try!(_serializer.serialize_struct_variant(
$item_name,
$variant_index,
$variant_name,
$len,
quote! {
let #let_mut __serde_state = try!(_serializer.serialize_struct_variant(
#item_name,
#variant_index,
#variant_name,
#len,
));
$serialize_fields
_serializer.serialize_struct_variant_end(state)
}).unwrap()
#(#serialize_fields)*
_serde::ser::SerializeStructVariant::end(__serde_state)
}
}
fn serialize_tuple_struct_visitor(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
structure_ty: P<ast::Ty>,
structure_ty: syn::Ty,
fields: &[Field],
generics: &ast::Generics,
generics: &syn::Generics,
is_enum: bool,
func: ast::Ident,
) -> Vec<ast::Stmt> {
func: Tokens,
) -> Vec<Tokens> {
fields.iter()
.enumerate()
.map(|(i, field)| {
let mut field_expr = if is_enum {
builder.expr().path().id(format!("__field{}", i)).build()
let id = Ident::new(format!("__field{}", i));
quote!(#id)
} else {
builder.expr().ref_().tup_field(i).self_()
let i = Ident::new(i);
quote!(&self.#i)
};
let skip = field.attrs.skip_serializing_if()
.map(|path| quote_expr!(cx, $path($field_expr)));
.map(|path| quote!(#path(#field_expr)));
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_with(cx, builder,
&structure_ty, generics, &field.ty, path, field_expr);
field_expr = wrap_serialize_with(
&structure_ty, generics, field.ty, path, field_expr);
}
let ser = quote_expr!(cx,
try!(_serializer.$func(&mut state, $field_expr));
);
let ser = quote! {
try!(#func(&mut __serde_state, #field_expr));
};
match skip {
None => quote_stmt!(cx, $ser).unwrap(),
Some(skip) => quote_stmt!(cx, if !$skip { $ser }).unwrap(),
None => ser,
Some(skip) => quote!(if !#skip { #ser }),
}
})
.collect()
}
fn serialize_struct_visitor(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
structure_ty: P<ast::Ty>,
structure_ty: syn::Ty,
fields: &[Field],
generics: &ast::Generics,
generics: &syn::Generics,
is_enum: bool,
func: ast::Ident,
) -> Vec<ast::Stmt> {
func: Tokens,
) -> Vec<Tokens> {
fields.iter()
.filter(|&field| !field.attrs.skip_serializing())
.map(|field| {
let ident = field.ident.expect("struct has unnamed field");
let ident = field.ident.clone().expect("struct has unnamed field");
let mut field_expr = if is_enum {
quote_expr!(cx, $ident)
quote!(#ident)
} else {
quote_expr!(cx, &self.$ident)
quote!(&self.#ident)
};
let key_expr = name_expr(builder, field.attrs.name());
let key_expr = field.attrs.name().serialize_name();
let skip = field.attrs.skip_serializing_if()
.map(|path| quote_expr!(cx, $path($field_expr)));
.map(|path| quote!(#path(#field_expr)));
if let Some(path) = field.attrs.serialize_with() {
field_expr = wrap_serialize_with(cx, builder,
&structure_ty, generics, &field.ty, path, field_expr)
field_expr = wrap_serialize_with(
&structure_ty, generics, field.ty, path, field_expr)
}
let ser = quote_expr!(cx,
try!(_serializer.$func(&mut state, $key_expr, $field_expr));
);
let ser = quote! {
try!(#func(&mut __serde_state, #key_expr, #field_expr));
};
match skip {
None => quote_stmt!(cx, $ser).unwrap(),
Some(skip) => quote_stmt!(cx, if !$skip { $ser }).unwrap(),
None => ser,
Some(skip) => quote!(if !#skip { #ser }),
}
})
.collect()
}
fn wrap_serialize_with(
cx: &ExtCtxt,
builder: &aster::AstBuilder,
item_ty: &P<ast::Ty>,
generics: &ast::Generics,
field_ty: &P<ast::Ty>,
path: &ast::Path,
value: P<ast::Expr>,
) -> P<ast::Expr> {
item_ty: &syn::Ty,
generics: &syn::Generics,
field_ty: &syn::Ty,
path: &syn::Path,
value: Tokens,
) -> Tokens {
let where_clause = &generics.where_clause;
let wrapper_generics = builder.from_generics(generics.clone())
let wrapper_generics = aster::from_generics(generics.clone())
.add_lifetime_bound("'__a")
.lifetime_name("'__a")
.build();
let wrapper_ty = builder.path()
let wrapper_ty = aster::path()
.segment("__SerializeWith")
.with_generics(wrapper_generics.clone())
.build()
.build();
quote_expr!(cx, {
struct __SerializeWith $wrapper_generics $where_clause {
value: &'__a $field_ty,
phantom: ::std::marker::PhantomData<$item_ty>,
quote!({
struct __SerializeWith #wrapper_generics #where_clause {
value: &'__a #field_ty,
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) -> ::std::result::Result<__S::Ok, __S::Error>
where __S: _serde::Serializer
{
$path(self.value, __s)
#path(self.value, __s)
}
}
__SerializeWith {
value: $value,
phantom: ::std::marker::PhantomData::<$item_ty>,
value: #value,
phantom: ::std::marker::PhantomData::<#item_ty>,
}
})
}
fn name_expr(
builder: &aster::AstBuilder,
name: &attr::Name,
) -> P<ast::Expr> {
builder.expr().str(name.serialize_name())
}
// Serialization of an empty struct results in code like:
//
// let mut state = try!(serializer.serialize_struct("S", 0));
// serializer.serialize_struct_end(state)
// let mut __serde_state = try!(serializer.serialize_struct("S", 0));
// _serde::ser::SerializeStruct::end(__serde_state)
//
// where we want to omit the `mut` to avoid a warning.
fn mut_if(cx: &ExtCtxt, is_mut: bool) -> Vec<TokenTree> {
fn mut_if(is_mut: bool) -> Option<Tokens> {
if is_mut {
quote_tokens!(cx, mut)
Some(quote!(mut))
} else {
Vec::new()
None
}
}
-43
View File
@@ -1,43 +0,0 @@
use syntax::ast;
use syntax::codemap::{self, ExpnId, Span};
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::fold::{self, Folder};
use syntax::parse::token::intern;
use syntax::ptr::P;
pub fn record_expansion(
cx: &ExtCtxt,
item: P<ast::Item>,
derive: &str,
) -> Annotatable {
let info = codemap::ExpnInfo {
call_site: codemap::DUMMY_SP,
callee: codemap::NameAndSpan {
format: codemap::MacroAttribute(intern(&format!("derive({})", derive))),
span: None,
allow_internal_unstable: false,
},
};
let expn_id = cx.codemap().record_expansion(info);
let mut respanner = Respanner { expn_id: expn_id };
let item = item.map(|item| respanner.fold_item_simple(item));
Annotatable::Item(item)
}
struct Respanner {
expn_id: ExpnId,
}
impl Folder for Respanner {
fn new_span(&mut self, span: Span) -> Span {
Span {
expn_id: self.expn_id,
.. span
}
}
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
fold::noop_fold_mac(mac, self)
}
}
+2 -5
View File
@@ -1,6 +1,6 @@
[package]
name = "serde_codegen_internals"
version = "0.8.9"
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,11 +11,8 @@ keywords = ["serde", "serialization"]
include = ["Cargo.toml", "src/**/*.rs"]
[features]
default = ["with-syntex"]
unstable-testing = ["clippy"]
with-syntex = ["syntex_syntax", "syntex_errors"]
[dependencies]
clippy = { version = "^0.*", optional = true }
syntex_syntax = { version = "^0.44.0", optional = true }
syntex_errors = { version = "^0.44.0", optional = true }
syn = "0.10"
+29 -55
View File
@@ -1,17 +1,12 @@
use syntax::ast;
use syntax::codemap;
use syntax::ext::base::ExtCtxt;
use syntax::ptr::P;
use syn;
use attr;
use Error;
use Ctxt;
pub struct Item<'a> {
pub ident: ast::Ident,
pub span: codemap::Span,
pub ident: syn::Ident,
pub attrs: attr::Item,
pub body: Body<'a>,
pub generics: &'a ast::Generics,
pub generics: &'a syn::Generics,
}
pub enum Body<'a> {
@@ -20,18 +15,16 @@ pub enum Body<'a> {
}
pub struct Variant<'a> {
pub ident: ast::Ident,
pub span: codemap::Span,
pub ident: syn::Ident,
pub attrs: attr::Variant,
pub style: Style,
pub fields: Vec<Field<'a>>,
}
pub struct Field<'a> {
pub ident: Option<ast::Ident>,
pub span: codemap::Span,
pub ident: Option<syn::Ident>,
pub attrs: attr::Field,
pub ty: &'a P<ast::Ty>,
pub ty: &'a syn::Ty,
}
pub enum Style {
@@ -42,33 +35,25 @@ pub enum Style {
}
impl<'a> Item<'a> {
pub fn from_ast(
cx: &ExtCtxt,
item: &'a ast::Item,
) -> Result<Item<'a>, Error> {
pub fn from_ast(cx: &Ctxt, item: &'a syn::MacroInput) -> Item<'a> {
let attrs = attr::Item::from_ast(cx, item);
let (body, generics) = match item.node {
ast::ItemKind::Enum(ref enum_def, ref generics) => {
let variants = enum_from_ast(cx, enum_def);
(Body::Enum(variants), generics)
let body = match item.body {
syn::Body::Enum(ref variants) => {
Body::Enum(enum_from_ast(cx, variants))
}
ast::ItemKind::Struct(ref variant_data, ref generics) => {
syn::Body::Struct(ref variant_data) => {
let (style, fields) = struct_from_ast(cx, variant_data);
(Body::Struct(style, fields), generics)
}
_ => {
return Err(Error::UnexpectedItemKind);
Body::Struct(style, fields)
}
};
Ok(Item {
ident: item.ident,
span: item.span,
Item {
ident: item.ident.clone(),
attrs: attrs,
body: body,
generics: generics,
})
generics: &item.generics,
}
}
}
@@ -86,16 +71,12 @@ impl<'a> Body<'a> {
}
}
fn enum_from_ast<'a>(
cx: &ExtCtxt,
enum_def: &'a ast::EnumDef,
) -> Vec<Variant<'a>> {
enum_def.variants.iter()
fn enum_from_ast<'a>(cx: &Ctxt, variants: &'a [syn::Variant]) -> Vec<Variant<'a>> {
variants.iter()
.map(|variant| {
let (style, fields) = struct_from_ast(cx, &variant.node.data);
let (style, fields) = struct_from_ast(cx, &variant.data);
Variant {
ident: variant.node.name,
span: variant.span,
ident: variant.ident.clone(),
attrs: attr::Variant::from_ast(cx, variant),
style: style,
fields: fields,
@@ -104,36 +85,29 @@ fn enum_from_ast<'a>(
.collect()
}
fn struct_from_ast<'a>(
cx: &ExtCtxt,
variant_data: &'a ast::VariantData,
) -> (Style, Vec<Field<'a>>) {
match *variant_data {
ast::VariantData::Struct(ref fields, _) => {
fn struct_from_ast<'a>(cx: &Ctxt, data: &'a syn::VariantData) -> (Style, Vec<Field<'a>>) {
match *data {
syn::VariantData::Struct(ref fields) => {
(Style::Struct, fields_from_ast(cx, fields))
}
ast::VariantData::Tuple(ref fields, _) if fields.len() == 1 => {
syn::VariantData::Tuple(ref fields) if fields.len() == 1 => {
(Style::Newtype, fields_from_ast(cx, fields))
}
ast::VariantData::Tuple(ref fields, _) => {
syn::VariantData::Tuple(ref fields) => {
(Style::Tuple, fields_from_ast(cx, fields))
}
ast::VariantData::Unit(_) => {
syn::VariantData::Unit => {
(Style::Unit, Vec::new())
}
}
}
fn fields_from_ast<'a>(
cx: &ExtCtxt,
fields: &'a [ast::StructField],
) -> Vec<Field<'a>> {
fn fields_from_ast<'a>(cx: &Ctxt, fields: &'a [syn::Field]) -> Vec<Field<'a>> {
fields.iter()
.enumerate()
.map(|(i, field)| {
Field {
ident: field.ident,
span: field.span,
ident: field.ident.clone(),
attrs: attr::Field::from_ast(cx, i, field),
ty: &field.ty,
}
+192 -309
View File
@@ -1,15 +1,7 @@
use std::rc::Rc;
use syntax::ast;
use syntax::attr::{self, HasAttrs};
use syntax::codemap::{Span, Spanned, respan};
use syntax::ext::base::ExtCtxt;
use syntax::fold::Folder;
use syntax::parse::parser::{Parser, PathStyle};
use syntax::parse::token::{self, InternedString};
use syntax::parse;
use syntax::print::pprust::{lit_to_string, meta_item_to_string, meta_list_item_to_string};
use syntax::tokenstream::{self, TokenTree};
use Ctxt;
use syn;
use syn::MetaItem::{List, NameValue, Word};
use syn::NestedMetaItem::{Literal, MetaItem};
// This module handles parsing of `#[serde(...)]` attributes. The entrypoints
// are `attr::Item::from_ast`, `attr::Variant::from_ast`, and
@@ -19,13 +11,14 @@ use syntax::tokenstream::{self, TokenTree};
// user will see errors simultaneously for all bad attributes in the crate
// rather than just the first.
struct Attr<'a, 'b: 'a, T> {
cx: &'a ExtCtxt<'b>,
struct Attr<'c, T> {
cx: &'c Ctxt,
name: &'static str,
value: Option<Spanned<T>>,
value: Option<T>,
}
impl<'a, 'b, T> Attr<'a, 'b, T> {
fn none(cx: &'a ExtCtxt<'b>, name: &'static str) -> Self {
impl<'c, T> Attr<'c, T> {
fn none(cx: &'c Ctxt, name: &'static str) -> Self {
Attr {
cx: cx,
name: name,
@@ -33,47 +26,40 @@ impl<'a, 'b, T> Attr<'a, 'b, T> {
}
}
fn set(&mut self, span: Span, t: T) {
if let Some(Spanned { span: prev_span, .. }) = self.value {
let mut err = self.cx.struct_span_err(
span,
&format!("duplicate serde attribute `{}`", self.name));
err.span_help(prev_span, "previously set here");
err.emit();
fn set(&mut self, value: T) {
if self.value.is_some() {
self.cx.error(format!("duplicate serde attribute `{}`", self.name));
} else {
self.value = Some(respan(span, t));
self.value = Some(value);
}
}
fn set_opt(&mut self, v: Option<Spanned<T>>) {
if let Some(v) = v {
self.set(v.span, v.node);
fn set_opt(&mut self, value: Option<T>) {
if let Some(value) = value {
self.set(value);
}
}
fn set_if_none(&mut self, span: Span, t: T) {
fn set_if_none(&mut self, value: T) {
if self.value.is_none() {
self.value = Some(respan(span, t));
self.value = Some(value);
}
}
fn get(self) -> Option<T> {
self.value.map(|spanned| spanned.node)
}
fn get_spanned(self) -> Option<Spanned<T>> {
self.value
}
}
struct BoolAttr<'a, 'b: 'a>(Attr<'a, 'b, ()>);
impl<'a, 'b> BoolAttr<'a, 'b> {
fn none(cx: &'a ExtCtxt<'b>, name: &'static str) -> Self {
struct BoolAttr<'c>(Attr<'c, ()>);
impl<'c> BoolAttr<'c> {
fn none(cx: &'c Ctxt, name: &'static str) -> Self {
BoolAttr(Attr::none(cx, name))
}
fn set_true(&mut self, span: Span) {
self.0.set(span, ());
fn set_true(&mut self) {
self.0.set(());
}
fn get(&self) -> bool {
@@ -83,18 +69,18 @@ impl<'a, 'b> BoolAttr<'a, 'b> {
#[derive(Debug)]
pub struct Name {
serialize: InternedString,
deserialize: InternedString,
serialize: String,
deserialize: String,
}
impl Name {
/// Return the container name for the container when serializing.
pub fn serialize_name(&self) -> InternedString {
pub fn serialize_name(&self) -> String {
self.serialize.clone()
}
/// Return the container name for the container when deserializing.
pub fn deserialize_name(&self) -> InternedString {
pub fn deserialize_name(&self) -> String {
self.deserialize.clone()
}
}
@@ -104,35 +90,32 @@ impl Name {
pub struct Item {
name: Name,
deny_unknown_fields: bool,
ser_bound: Option<Vec<ast::WherePredicate>>,
de_bound: Option<Vec<ast::WherePredicate>>,
ser_bound: Option<Vec<syn::WherePredicate>>,
de_bound: Option<Vec<syn::WherePredicate>>,
}
impl Item {
/// Extract out the `#[serde(...)]` attributes from an item.
pub fn from_ast(cx: &ExtCtxt, item: &ast::Item) -> Self {
pub fn from_ast(cx: &Ctxt, item: &syn::MacroInput) -> Self {
let mut ser_name = Attr::none(cx, "rename");
let mut de_name = Attr::none(cx, "rename");
let mut deny_unknown_fields = BoolAttr::none(cx, "deny_unknown_fields");
let mut ser_bound = Attr::none(cx, "bound");
let mut de_bound = Attr::none(cx, "bound");
let ident = item.ident.name.as_str();
for meta_items in item.attrs().iter().filter_map(get_serde_meta_items) {
for meta_items in item.attrs.iter().filter_map(get_serde_meta_items) {
for meta_item in meta_items {
let span = meta_item.span;
match meta_item.node {
match meta_item {
// Parse `#[serde(rename="foo")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
if let Ok(s) = get_str_from_lit(cx, name, lit) {
ser_name.set(span, s.clone());
de_name.set(span, s);
MetaItem(NameValue(ref name, ref lit)) if name == "rename" => {
if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) {
ser_name.set(s.clone());
de_name.set(s);
}
}
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
MetaItem(List(ref name, ref meta_items)) if name == "rename" => {
if let Ok((ser, de)) = get_renames(cx, meta_items) {
ser_name.set_opt(ser);
de_name.set_opt(de);
@@ -140,31 +123,33 @@ impl Item {
}
// Parse `#[serde(deny_unknown_fields)]`
ast::MetaItemKind::Word(ref name) if name == &"deny_unknown_fields" => {
deny_unknown_fields.set_true(span);
MetaItem(Word(ref name)) if name == "deny_unknown_fields" => {
deny_unknown_fields.set_true();
}
// Parse `#[serde(bound="D: Serialize")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"bound" => {
if let Ok(where_predicates) = parse_lit_into_where(cx, name, lit) {
ser_bound.set(span, where_predicates.clone());
de_bound.set(span, where_predicates);
MetaItem(NameValue(ref name, ref lit)) if name == "bound" => {
if let Ok(where_predicates) = parse_lit_into_where(cx, name.as_ref(), name.as_ref(), lit) {
ser_bound.set(where_predicates.clone());
de_bound.set(where_predicates);
}
}
// Parse `#[serde(bound(serialize="D: Serialize", deserialize="D: Deserialize"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"bound" => {
MetaItem(List(ref name, ref meta_items)) if name == "bound" => {
if let Ok((ser, de)) = get_where_predicates(cx, meta_items) {
ser_bound.set_opt(ser);
de_bound.set_opt(de);
}
}
_ => {
cx.span_err(
meta_item.span,
&format!("unknown serde container attribute `{}`",
meta_item_to_string(&meta_item)));
MetaItem(ref meta_item) => {
cx.error(format!("unknown serde container attribute `{}`",
meta_item.name()));
}
Literal(_) => {
cx.error(format!("unexpected literal in serde container attribute"));
}
}
}
@@ -172,8 +157,8 @@ impl Item {
Item {
name: Name {
serialize: ser_name.get().unwrap_or(ident.clone()),
deserialize: de_name.get().unwrap_or(ident),
serialize: ser_name.get().unwrap_or_else(|| item.ident.to_string()),
deserialize: de_name.get().unwrap_or_else(|| item.ident.to_string()),
},
deny_unknown_fields: deny_unknown_fields.get(),
ser_bound: ser_bound.get(),
@@ -189,11 +174,11 @@ impl Item {
self.deny_unknown_fields
}
pub fn ser_bound(&self) -> Option<&[ast::WherePredicate]> {
pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> {
self.ser_bound.as_ref().map(|vec| &vec[..])
}
pub fn de_bound(&self) -> Option<&[ast::WherePredicate]> {
pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
self.de_bound.as_ref().map(|vec| &vec[..])
}
}
@@ -202,40 +187,51 @@ impl Item {
#[derive(Debug)]
pub struct Variant {
name: Name,
skip_deserializing: bool,
skip_serializing: bool,
}
impl Variant {
pub fn from_ast(cx: &ExtCtxt, variant: &ast::Variant) -> Self {
pub fn from_ast(cx: &Ctxt, variant: &syn::Variant) -> Self {
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");
let ident = variant.node.name.name.as_str();
for meta_items in variant.node.attrs.iter().filter_map(get_serde_meta_items) {
for meta_items in variant.attrs.iter().filter_map(get_serde_meta_items) {
for meta_item in meta_items {
let span = meta_item.span;
match meta_item.node {
match meta_item {
// Parse `#[serde(rename="foo")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
if let Ok(s) = get_str_from_lit(cx, name, lit) {
ser_name.set(span, s.clone());
de_name.set(span, s);
MetaItem(NameValue(ref name, ref lit)) if name == "rename" => {
if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) {
ser_name.set(s.clone());
de_name.set(s);
}
}
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
MetaItem(List(ref name, ref meta_items)) if name == "rename" => {
if let Ok((ser, de)) = get_renames(cx, meta_items) {
ser_name.set_opt(ser);
de_name.set_opt(de);
}
}
// Parse `#[serde(skip_deserializing)]`
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();
}
_ => {
cx.span_err(
meta_item.span,
&format!("unknown serde variant attribute `{}`",
meta_item_to_string(&meta_item)));
MetaItem(ref meta_item) => {
cx.error(format!("unknown serde variant attribute `{}`",
meta_item.name()));
}
Literal(_) => {
cx.error(format!("unexpected literal in serde variant attribute"));
}
}
}
@@ -243,15 +239,25 @@ impl Variant {
Variant {
name: Name {
serialize: ser_name.get().unwrap_or(ident.clone()),
deserialize: de_name.get().unwrap_or(ident),
serialize: ser_name.get().unwrap_or_else(|| variant.ident.to_string()),
deserialize: de_name.get().unwrap_or_else(|| variant.ident.to_string()),
},
skip_deserializing: skip_deserializing.get(),
skip_serializing: skip_serializing.get(),
}
}
pub fn name(&self) -> &Name {
&self.name
}
pub fn skip_deserializing(&self) -> bool {
self.skip_deserializing
}
pub fn skip_serializing(&self) -> bool {
self.skip_serializing
}
}
/// Represents field attribute information
@@ -260,12 +266,12 @@ pub struct Field {
name: Name,
skip_serializing: bool,
skip_deserializing: bool,
skip_serializing_if: Option<ast::Path>,
skip_serializing_if: Option<syn::Path>,
default: FieldDefault,
serialize_with: Option<ast::Path>,
deserialize_with: Option<ast::Path>,
ser_bound: Option<Vec<ast::WherePredicate>>,
de_bound: Option<Vec<ast::WherePredicate>>,
serialize_with: Option<syn::Path>,
deserialize_with: Option<syn::Path>,
ser_bound: Option<Vec<syn::WherePredicate>>,
de_bound: Option<Vec<syn::WherePredicate>>,
}
/// Represents the default to use for a field when deserializing.
@@ -276,14 +282,14 @@ pub enum FieldDefault {
/// The default is given by `std::default::Default::default()`.
Default,
/// The default is given by this function.
Path(ast::Path),
Path(syn::Path),
}
impl Field {
/// Extract out the `#[serde(...)]` attributes from a struct field.
pub fn from_ast(cx: &ExtCtxt,
pub fn from_ast(cx: &Ctxt,
index: usize,
field: &ast::StructField) -> Self {
field: &syn::Field) -> Self {
let mut ser_name = Attr::none(cx, "rename");
let mut de_name = Attr::none(cx, "rename");
let mut skip_serializing = BoolAttr::none(cx, "skip_serializing");
@@ -296,24 +302,23 @@ impl Field {
let mut de_bound = Attr::none(cx, "bound");
let ident = match field.ident {
Some(ident) => ident.name.as_str(),
None => token::intern_and_get_ident(&index.to_string()),
Some(ref ident) => ident.to_string(),
None => index.to_string(),
};
for meta_items in field.attrs.iter().filter_map(get_serde_meta_items) {
for meta_item in meta_items {
let span = meta_item.span;
match meta_item.node {
match meta_item {
// Parse `#[serde(rename="foo")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"rename" => {
if let Ok(s) = get_str_from_lit(cx, name, lit) {
ser_name.set(span, s.clone());
de_name.set(span, s);
MetaItem(NameValue(ref name, ref lit)) if name == "rename" => {
if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) {
ser_name.set(s.clone());
de_name.set(s);
}
}
// Parse `#[serde(rename(serialize="foo", deserialize="bar"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"rename" => {
MetaItem(List(ref name, ref meta_items)) if name == "rename" => {
if let Ok((ser, de)) = get_renames(cx, meta_items) {
ser_name.set_opt(ser);
de_name.set_opt(de);
@@ -321,69 +326,71 @@ impl Field {
}
// Parse `#[serde(default)]`
ast::MetaItemKind::Word(ref name) if name == &"default" => {
default.set(span, FieldDefault::Default);
MetaItem(Word(ref name)) if name == "default" => {
default.set(FieldDefault::Default);
}
// Parse `#[serde(default="...")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"default" => {
if let Ok(path) = parse_lit_into_path(cx, name, lit) {
default.set(span, FieldDefault::Path(path));
MetaItem(NameValue(ref name, ref lit)) if name == "default" => {
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
default.set(FieldDefault::Path(path));
}
}
// Parse `#[serde(skip_serializing)]`
ast::MetaItemKind::Word(ref name) if name == &"skip_serializing" => {
skip_serializing.set_true(span);
MetaItem(Word(ref name)) if name == "skip_serializing" => {
skip_serializing.set_true();
}
// Parse `#[serde(skip_deserializing)]`
ast::MetaItemKind::Word(ref name) if name == &"skip_deserializing" => {
skip_deserializing.set_true(span);
MetaItem(Word(ref name)) if name == "skip_deserializing" => {
skip_deserializing.set_true();
}
// Parse `#[serde(skip_serializing_if="...")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"skip_serializing_if" => {
if let Ok(path) = parse_lit_into_path(cx, name, lit) {
skip_serializing_if.set(span, path);
MetaItem(NameValue(ref name, ref lit)) if name == "skip_serializing_if" => {
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
skip_serializing_if.set(path);
}
}
// Parse `#[serde(serialize_with="...")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"serialize_with" => {
if let Ok(path) = parse_lit_into_path(cx, name, lit) {
serialize_with.set(span, path);
MetaItem(NameValue(ref name, ref lit)) if name == "serialize_with" => {
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
serialize_with.set(path);
}
}
// Parse `#[serde(deserialize_with="...")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"deserialize_with" => {
if let Ok(path) = parse_lit_into_path(cx, name, lit) {
deserialize_with.set(span, path);
MetaItem(NameValue(ref name, ref lit)) if name == "deserialize_with" => {
if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) {
deserialize_with.set(path);
}
}
// Parse `#[serde(bound="D: Serialize")]`
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"bound" => {
if let Ok(where_predicates) = parse_lit_into_where(cx, name, lit) {
ser_bound.set(span, where_predicates.clone());
de_bound.set(span, where_predicates);
MetaItem(NameValue(ref name, ref lit)) if name == "bound" => {
if let Ok(where_predicates) = parse_lit_into_where(cx, name.as_ref(), name.as_ref(), lit) {
ser_bound.set(where_predicates.clone());
de_bound.set(where_predicates);
}
}
// Parse `#[serde(bound(serialize="D: Serialize", deserialize="D: Deserialize"))]`
ast::MetaItemKind::List(ref name, ref meta_items) if name == &"bound" => {
MetaItem(List(ref name, ref meta_items)) if name == "bound" => {
if let Ok((ser, de)) = get_where_predicates(cx, meta_items) {
ser_bound.set_opt(ser);
de_bound.set_opt(de);
}
}
_ => {
cx.span_err(
meta_item.span,
&format!("unknown serde field attribute `{}`",
meta_item_to_string(&meta_item)));
MetaItem(ref meta_item) => {
cx.error(format!("unknown serde field attribute `{}`",
meta_item.name()));
}
Literal(_) => {
cx.error(format!("unexpected literal in serde field attribute"));
}
}
}
@@ -391,8 +398,8 @@ impl Field {
// Is skip_deserializing, initialize the field to Default::default()
// unless a different default is specified by `#[serde(default="...")]`
if let Some(Spanned { span, .. }) = skip_deserializing.0.value {
default.set_if_none(span, FieldDefault::Default);
if skip_deserializing.0.value.is_some() {
default.set_if_none(FieldDefault::Default);
}
Field {
@@ -423,7 +430,7 @@ impl Field {
self.skip_deserializing
}
pub fn skip_serializing_if(&self) -> Option<&ast::Path> {
pub fn skip_serializing_if(&self) -> Option<&syn::Path> {
self.skip_serializing_if.as_ref()
}
@@ -431,230 +438,106 @@ impl Field {
&self.default
}
pub fn serialize_with(&self) -> Option<&ast::Path> {
pub fn serialize_with(&self) -> Option<&syn::Path> {
self.serialize_with.as_ref()
}
pub fn deserialize_with(&self) -> Option<&ast::Path> {
pub fn deserialize_with(&self) -> Option<&syn::Path> {
self.deserialize_with.as_ref()
}
pub fn ser_bound(&self) -> Option<&[ast::WherePredicate]> {
pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> {
self.ser_bound.as_ref().map(|vec| &vec[..])
}
pub fn de_bound(&self) -> Option<&[ast::WherePredicate]> {
pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> {
self.de_bound.as_ref().map(|vec| &vec[..])
}
}
type SerAndDe<T> = (Option<Spanned<T>>, Option<Spanned<T>>);
type SerAndDe<T> = (Option<T>, Option<T>);
fn get_ser_and_de<T, F>(
cx: &ExtCtxt,
attribute: &'static str,
items: &[ast::NestedMetaItem],
cx: &Ctxt,
attr_name: &'static str,
items: &[syn::NestedMetaItem],
f: F
) -> Result<SerAndDe<T>, ()>
where F: Fn(&ExtCtxt, &str, &ast::Lit) -> Result<T, ()>,
where F: Fn(&Ctxt, &str, &str, &syn::Lit) -> Result<T, ()>,
{
let mut ser_item = Attr::none(cx, attribute);
let mut de_item = Attr::none(cx, attribute);
let mut ser_item = Attr::none(cx, attr_name);
let mut de_item = Attr::none(cx, attr_name);
for item in items {
match item.node {
ast::NestedMetaItemKind::MetaItem(ref meta_item) => {
match meta_item.node {
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"serialize" => {
if let Ok(v) = f(cx, name, lit) {
ser_item.set(item.span, v);
}
}
match *item {
MetaItem(NameValue(ref name, ref lit)) if name == "serialize" => {
if let Ok(v) = f(cx, attr_name, name.as_ref(), lit) {
ser_item.set(v);
}
}
ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"deserialize" => {
if let Ok(v) = f(cx, name, lit) {
de_item.set(item.span, v);
}
}
_ => {
cx.span_err(
item.span,
&format!("unknown {} attribute `{}`",
attribute,
meta_item_to_string(meta_item)));
return Err(());
}
MetaItem(NameValue(ref name, ref lit)) if name == "deserialize" => {
if let Ok(v) = f(cx, attr_name, name.as_ref(), lit) {
de_item.set(v);
}
}
_ => {
cx.span_err(
item.span,
&format!("unknown {} attribute `{}`",
attribute,
meta_list_item_to_string(item)));
cx.error(format!("malformed {0} attribute, expected `{0}(serialize = ..., deserialize = ...)`",
attr_name));
return Err(());
}
}
}
Ok((ser_item.get_spanned(), de_item.get_spanned()))
Ok((ser_item.get(), de_item.get()))
}
fn get_renames(
cx: &ExtCtxt,
items: &[ast::NestedMetaItem],
) -> Result<SerAndDe<InternedString>, ()> {
get_ser_and_de(cx, "rename", items, get_str_from_lit)
cx: &Ctxt,
items: &[syn::NestedMetaItem],
) -> Result<SerAndDe<String>, ()> {
get_ser_and_de(cx, "rename", items, get_string_from_lit)
}
fn get_where_predicates(
cx: &ExtCtxt,
items: &[ast::NestedMetaItem],
) -> Result<SerAndDe<Vec<ast::WherePredicate>>, ()> {
cx: &Ctxt,
items: &[syn::NestedMetaItem],
) -> Result<SerAndDe<Vec<syn::WherePredicate>>, ()> {
get_ser_and_de(cx, "bound", items, parse_lit_into_where)
}
pub fn get_serde_meta_items(attr: &ast::Attribute) -> Option<Vec<ast::MetaItem>> {
match attr.node.value.node {
ast::MetaItemKind::List(ref name, ref items) if name == &"serde" => {
attr::mark_used(attr);
Some(items.iter().filter_map(|item| {
match item.node {
ast::NestedMetaItemKind::MetaItem(ref meta_item) => {
Some((*meta_item.clone()).clone())
}
_ => None,
}
}).collect())
pub fn get_serde_meta_items(attr: &syn::Attribute) -> Option<Vec<syn::NestedMetaItem>> {
match attr.value {
List(ref name, ref items) if name == "serde" => {
Some(items.iter().cloned().collect())
}
_ => None
}
}
/// This syntax folder rewrites tokens to say their spans are coming from a macro context.
struct Respanner<'a, 'b: 'a> {
cx: &'a ExtCtxt<'b>,
}
impl<'a, 'b> Folder for Respanner<'a, 'b> {
fn fold_tt(&mut self, tt: &TokenTree) -> TokenTree {
match *tt {
TokenTree::Token(span, ref tok) => {
TokenTree::Token(
self.new_span(span),
self.fold_token(tok.clone())
)
}
TokenTree::Delimited(span, ref delimed) => {
TokenTree::Delimited(
self.new_span(span),
Rc::new(tokenstream::Delimited {
delim: delimed.delim,
open_span: delimed.open_span,
tts: self.fold_tts(&delimed.tts),
close_span: delimed.close_span,
})
)
}
TokenTree::Sequence(span, ref seq) => {
TokenTree::Sequence(
self.new_span(span),
Rc::new(tokenstream::SequenceRepetition {
tts: self.fold_tts(&seq.tts),
separator: seq.separator.clone().map(|tok| self.fold_token(tok)),
..**seq
})
)
}
}
}
fn new_span(&mut self, span: Span) -> Span {
Span {
lo: span.lo,
hi: span.hi,
expn_id: self.cx.backtrace(),
}
fn get_string_from_lit(cx: &Ctxt, attr_name: &str, meta_item_name: &str, lit: &syn::Lit) -> Result<String, ()> {
if let syn::Lit::Str(ref s, _) = *lit {
Ok(s.clone())
} else {
cx.error(format!("expected serde {} attribute to be a string: `{} = \"...\"`",
attr_name, meta_item_name));
Err(())
}
}
fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<InternedString, ()> {
match lit.node {
ast::LitKind::Str(ref s, _) => Ok(s.clone()),
_ => {
cx.span_err(
lit.span,
&format!("serde annotation `{}` must be a string, not `{}`",
name,
lit_to_string(lit)));
Err(())
}
}
fn parse_lit_into_path(cx: &Ctxt, attr_name: &str, lit: &syn::Lit) -> Result<syn::Path, ()> {
let string = try!(get_string_from_lit(cx, attr_name, attr_name, lit));
syn::parse_path(&string).map_err(|err| cx.error(err))
}
// If we just parse a string literal from an attibute, any syntax errors in the
// source will only have spans that point inside the string and not back to the
// attribute. So to have better error reporting, we'll first parse the string
// into a token tree. Then we'll update those spans to say they're coming from a
// macro context that originally came from the attribnute, and then finally
// parse them into an expression or where-clause.
fn parse_string_via_tts<T, F>(cx: &ExtCtxt, name: &str, string: String, action: F) -> Result<T, ()>
where F: for<'a> Fn(&'a mut Parser) -> parse::PResult<'a, T>,
{
let tts = panictry!(parse::parse_tts_from_source_str(
format!("<serde {} expansion>", name),
string,
cx.cfg(),
cx.parse_sess()));
// Respan the spans to say they are all coming from this macro.
let tts = Respanner { cx: cx }.fold_tts(&tts);
let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts);
let path = match action(&mut parser) {
Ok(path) => path,
Err(mut e) => {
e.emit();
return Err(());
}
};
// Make sure to error out if there are trailing characters in the stream.
match parser.expect(&token::Eof) {
Ok(()) => { }
Err(mut e) => {
e.emit();
return Err(());
}
}
Ok(path)
}
fn parse_lit_into_path(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<ast::Path, ()> {
let string = try!(get_str_from_lit(cx, name, lit)).to_string();
parse_string_via_tts(cx, name, string, |parser| {
parser.parse_path(PathStyle::Type)
})
}
fn parse_lit_into_where(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result<Vec<ast::WherePredicate>, ()> {
let string = try!(get_str_from_lit(cx, name, lit));
fn parse_lit_into_where(cx: &Ctxt, attr_name: &str, meta_item_name: &str, lit: &syn::Lit) -> Result<Vec<syn::WherePredicate>, ()> {
let string = try!(get_string_from_lit(cx, attr_name, meta_item_name, lit));
if string.is_empty() {
return Ok(Vec::new());
}
let where_string = format!("where {}", string);
parse_string_via_tts(cx, name, where_string, |parser| {
let where_clause = try!(parser.parse_where_clause());
Ok(where_clause.predicates)
})
syn::parse_where_clause(&where_string).map(|wh| wh.predicates).map_err(|err| cx.error(err))
}
+43
View File
@@ -0,0 +1,43 @@
use std::fmt::Display;
use std::cell::RefCell;
#[derive(Default)]
pub struct Ctxt {
errors: RefCell<Option<Vec<String>>>,
}
impl Ctxt {
pub fn new() -> Self {
Ctxt {
errors: RefCell::new(Some(Vec::new())),
}
}
pub fn error<T: Display>(&self, msg: T) {
self.errors.borrow_mut().as_mut().unwrap().push(msg.to_string());
}
pub fn check(self) -> Result<(), String> {
let mut errors = self.errors.borrow_mut().take().unwrap();
match errors.len() {
0 => Ok(()),
1 => Err(errors.pop().unwrap()),
n => {
let mut msg = format!("{} errors:", n);
for err in errors {
msg.push_str("\n\t# ");
msg.push_str(&err);
}
Err(msg)
}
}
}
}
impl Drop for Ctxt {
fn drop(&mut self) {
if self.errors.borrow().is_some() {
panic!("forgot to check for errors");
}
}
}
-19
View File
@@ -1,19 +0,0 @@
use std::error;
use std::fmt;
#[derive(Debug)]
pub enum Error {
UnexpectedItemKind,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "expected a struct or enum")
}
}
impl error::Error for Error {
fn description(&self) -> &str {
"expected a struct or enum"
}
}
+3 -14
View File
@@ -1,21 +1,10 @@
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))]
#[cfg(feature = "with-syntex")]
#[macro_use]
extern crate syntex_syntax as syntax;
#[cfg(feature = "with-syntex")]
extern crate syntex_errors as errors;
#[cfg(not(feature = "with-syntex"))]
#[macro_use]
extern crate syntax;
#[cfg(not(feature = "with-syntex"))]
extern crate rustc_errors as errors;
extern crate syn;
pub mod ast;
pub mod attr;
mod error;
pub use error::Error;
mod ctxt;
pub use ctxt::Ctxt;
+10 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "serde_derive"
version = "0.8.9"
version = "0.9.0-rc1"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]"
@@ -12,12 +12,16 @@ include = ["Cargo.toml", "src/**/*.rs"]
[lib]
name = "serde_derive"
rustc-macro = true
proc-macro = true
[dependencies]
serde_codegen = { version = "=0.8.9", path = "../serde_codegen" }
[dependencies.serde_codegen]
version = "=0.9.0-rc1"
path = "../serde_codegen"
default-features = false
features = ["with-syn"]
[dev-dependencies]
compiletest_rs = "^0.2.0"
fnv = "1.0"
serde = { version = "0.8.9", path = "../serde" }
serde_test = { version = "0.8.9", path = "../serde_test" }
serde = { version = "0.9.0-rc1", path = "../serde" }
serde_test = { version = "0.9.0-rc1", path = "../serde_test" }
+12 -13
View File
@@ -1,21 +1,20 @@
#![feature(rustc_macro, rustc_macro_lib)]
#![cfg(not(test))]
extern crate rustc_macro;
extern crate proc_macro;
extern crate serde_codegen;
use rustc_macro::TokenStream;
use proc_macro::TokenStream;
#[rustc_macro_derive(Serialize)]
#[proc_macro_derive(Serialize, attributes(serde))]
pub fn derive_serialize(input: TokenStream) -> TokenStream {
let item = format!("#[derive(Serialize)]\n{}", input);
let expanded = serde_codegen::expand_str(&item).unwrap();
expanded.parse().unwrap()
match serde_codegen::expand_derive_serialize(&input.to_string()) {
Ok(expanded) => expanded.parse().unwrap(),
Err(msg) => panic!(msg),
}
}
#[rustc_macro_derive(Deserialize)]
#[proc_macro_derive(Deserialize, attributes(serde))]
pub fn derive_deserialize(input: TokenStream) -> TokenStream {
let item = format!("#[derive(Deserialize)]\n{}", input);
let expanded = serde_codegen::expand_str(&item).unwrap();
expanded.parse().unwrap()
match serde_codegen::expand_derive_deserialize(&input.to_string()) {
Ok(expanded) => expanded.parse().unwrap(),
Err(msg) => panic!(msg),
}
}
@@ -0,0 +1,10 @@
#[macro_use]
extern crate serde_derive;
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
struct S {
#[serde(rename="x", serialize="y")] //~^^ HELP: unknown serde field attribute `serialize`
x: (),
}
fn main() {}
@@ -0,0 +1,11 @@
#[macro_use]
extern crate serde_derive;
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
struct S {
#[serde(rename="x")]
#[serde(rename(deserialize="y"))] //~^^^ HELP: duplicate serde attribute `rename`
x: (),
}
fn main() {}
@@ -0,0 +1,10 @@
#[macro_use]
extern crate serde_derive;
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
struct S {
#[serde(rename(serialize="x"), rename(serialize="y"))] //~^^ HELP: duplicate serde attribute `rename`
x: (),
}
fn main() {}
@@ -0,0 +1,11 @@
#[macro_use]
extern crate serde_derive;
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
struct S {
#[serde(rename(serialize="x"))]
#[serde(rename="y")] //~^^^ HELP: duplicate serde attribute `rename`
x: (),
}
fn main() {}
@@ -0,0 +1,10 @@
#[macro_use]
extern crate serde_derive;
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
struct S {
#[serde(rename(serialize="x", serialize="y"))] //~^^ HELP: duplicate serde attribute `rename`
x: (),
}
fn main() {}
@@ -0,0 +1,11 @@
#[macro_use]
extern crate serde_derive;
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
struct S {
#[serde(rename(serialize="x"))]
#[serde(rename(serialize="y"))] //~^^^ HELP: duplicate serde attribute `rename`
x: (),
}
fn main() {}
@@ -0,0 +1,9 @@
#[macro_use]
extern crate serde_derive;
#[derive(Serialize, Deserialize)] //~ ERROR: custom derive attribute panicked
struct Test<'a> {
s: &'a str, //~^^ HELP: Serde does not support deserializing fields of type &str
}
fn main() {}
@@ -0,0 +1,10 @@
#[macro_use]
extern crate serde_derive;
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
#[serde(abc="xyz")] //~^ HELP: unknown serde container attribute `abc`
struct A {
x: u32,
}
fn main() { }
@@ -0,0 +1,10 @@
#[macro_use]
extern crate serde_derive;
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
struct C {
#[serde(abc="xyz")] //~^^ HELP: unknown serde field attribute `abc`
x: u32,
}
fn main() { }
@@ -0,0 +1,10 @@
#[macro_use]
extern crate serde_derive;
#[derive(Serialize)] //~ ERROR: custom derive attribute panicked
enum E {
#[serde(abc="xyz")] //~^^ HELP: unknown serde variant attribute `abc`
V,
}
fn main() { }
@@ -1,8 +1,8 @@
#![feature(custom_derive, plugin)]
#![plugin(serde_macros, clippy)]
#![deny(identity_op)]
#[macro_use]
extern crate serde_derive;
// The derived implementation uses 0+1 to add up the number of fields
// serialized, which Clippy warns about. If the expansion info is registered
// correctly, the Clippy lint is not triggered.
+3 -1
View File
@@ -1,4 +1,4 @@
#![feature(test, rustc_macro, rustc_attrs)]
#![feature(test)]
#[macro_use]
extern crate serde_derive;
@@ -6,3 +6,5 @@ extern crate serde_derive;
extern crate test;
include!("../../testing/tests/test.rs.in");
mod compile_tests;
-2
View File
@@ -1,2 +0,0 @@
# To prevent compiletest from seeing two versions of serde
paths = ["../serde"]
-2
View File
@@ -1,2 +0,0 @@
/target
/Cargo.lock
-41
View File
@@ -1,41 +0,0 @@
[package]
name = "serde_macros"
version = "0.8.9"
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Macros to auto-generate implementations for the serde framework"
homepage = "https://serde.rs"
repository = "https://github.com/serde-rs/serde"
documentation = "https://serde.rs/codegen.html"
keywords = ["serde", "serialization"]
include = ["Cargo.toml", "src/**/*.rs"]
[lib]
name = "serde_macros"
plugin = true
[features]
unstable-testing = [
"clippy",
"serde/unstable-testing",
"serde_codegen/unstable-testing"
]
[dependencies]
clippy = { version = "^0.*", optional = true }
serde_codegen = { version = "=0.8.9", default-features = false, features = ["unstable"], path = "../serde_codegen" }
[dev-dependencies]
compiletest_rs = "^0.2.0"
fnv = "1.0"
rustc-serialize = "^0.3.16"
serde = { version = "0.8.9", path = "../serde" }
serde_test = { version = "0.8.9", path = "../serde_test" }
[[test]]
name = "test"
path = "tests/test.rs"
[[bench]]
name = "bench"
path = "benches/bench.rs"
-9
View File
@@ -1,9 +0,0 @@
#![feature(custom_attribute, custom_derive, plugin, test)]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![plugin(serde_macros)]
extern crate rustc_serialize;
extern crate serde;
extern crate test;
include!("../../testing/benches/bench.rs.in");
-12
View File
@@ -1,12 +0,0 @@
#![feature(plugin_registrar, rustc_private)]
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
extern crate serde_codegen;
extern crate rustc_plugin;
#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(reg: &mut rustc_plugin::Registry) {
serde_codegen::register(reg);
}
@@ -1,32 +0,0 @@
#![feature(custom_attribute, custom_derive, plugin)]
#![plugin(serde_macros)]
#[derive(Serialize)]
struct S {
#[serde(rename(serialize="x"))]
#[serde(rename(serialize="y"))] //~ ERROR: duplicate serde attribute `rename`
a: (),
#[serde(rename(serialize="x"))]
#[serde(rename="y")] //~ ERROR: duplicate serde attribute `rename`
b: (),
#[serde(rename(serialize="x"))]
#[serde(rename(deserialize="y"))] // ok
c: (),
#[serde(rename="x")]
#[serde(rename(deserialize="y"))] //~ ERROR: duplicate serde attribute `rename`
d: (),
#[serde(rename(serialize="x", serialize="y"))] //~ ERROR: duplicate serde attribute `rename`
e: (),
#[serde(rename="x", serialize="y")] //~ ERROR: unknown serde field attribute `serialize = "y"`
f: (),
#[serde(rename(serialize="x"), rename(serialize="y"))] //~ ERROR: duplicate serde attribute `rename`
g: (),
}
fn main() {}
@@ -1,30 +0,0 @@
#![feature(custom_attribute, custom_derive, plugin)]
#![plugin(serde_macros)]
extern crate serde;
#[derive(Serialize)]
#[serde(abc="xyz")] //~ unknown serde container attribute `abc = "xyz"`
struct Foo {
x: u32,
}
#[derive(Deserialize)]
#[serde(abc="xyz")] //~ unknown serde container attribute `abc = "xyz"`
struct Foo {
x: u32,
}
#[derive(Serialize)]
struct Foo {
#[serde(abc="xyz")] //~ unknown serde field attribute `abc = "xyz"`
x: u32,
}
#[derive(Deserialize)]
struct Foo {
#[serde(abc="xyz")] //~ unknown serde field attribute `abc = "xyz"`
x: u32,
}
fn main() { }
@@ -1,9 +0,0 @@
#![feature(custom_attribute, custom_derive, plugin)]
#![plugin(serde_macros)]
#[derive(Serialize, Deserialize)]
struct Test<'a> {
s: &'a str, //~ ERROR: Serde does not support deserializing fields of type &str
}
fn main() {}
-8
View File
@@ -1,8 +0,0 @@
#![feature(test, custom_attribute, custom_derive, plugin)]
#![plugin(serde_macros)]
extern crate test;
include!("../../testing/tests/test.rs.in");
mod compile_tests;
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "serde_test"
version = "0.8.9"
version = "0.9.0-rc1"
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.9", path = "../serde" }
serde = { version = "0.9.0-rc1", path = "../serde" }
+133 -168
View File
@@ -9,6 +9,7 @@ use serde::de::{
VariantVisitor,
Visitor,
};
use serde::de::value::ValueDeserializer;
use error::Error;
use token::Token;
@@ -32,174 +33,203 @@ 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::EndOfStream),
}
}
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_ignored_any<__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_string<__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_str<__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_char<__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_i64<__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_i32<__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_i16<__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_i8<__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_u64<__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_u32<__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_u16<__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_u8<__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_f32<__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_f64<__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_bool<__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_usize<__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_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() {
@@ -243,7 +273,7 @@ impl<I> de::Deserializer for Deserializer<I>
/// Hook into `Option` deserializing so we can treat `Unit` as a
/// `None`, or a regular value as `Some(value)`.
fn deserialize_option<V>(&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() {
@@ -264,17 +294,17 @@ impl<I> de::Deserializer for Deserializer<I>
}
}
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 +312,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,
})
}
@@ -294,7 +324,7 @@ impl<I> de::Deserializer for Deserializer<I>
}
}
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() {
@@ -311,9 +341,9 @@ impl<I> de::Deserializer for Deserializer<I>
}
}
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() {
@@ -330,7 +360,7 @@ impl<I> de::Deserializer for Deserializer<I>
}
}
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,
@@ -345,9 +375,9 @@ impl<I> de::Deserializer for Deserializer<I>
}
}
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() {
@@ -380,10 +410,10 @@ impl<I> de::Deserializer for Deserializer<I>
}
}
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() {
@@ -424,7 +454,7 @@ impl<I> de::Deserializer for Deserializer<I>
}
}
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 +464,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))
}
@@ -468,7 +498,7 @@ impl<'a, I> SeqVisitor for DeserializerSeqVisitor<'a, I>
Some(&Token::SeqSep) => {
self.de.tokens.next();
self.len = self.len.map(|len| len - 1);
Ok(Some(try!(Deserialize::deserialize(self.de))))
Deserialize::deserialize(&mut *self.de).map(Some)
}
Some(&Token::SeqEnd) => Ok(None),
Some(_) => {
@@ -479,15 +509,6 @@ impl<'a, I> SeqVisitor for DeserializerSeqVisitor<'a, I>
}
}
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),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len.unwrap_or(0);
(len, self.len)
@@ -513,7 +534,7 @@ impl<'a, I> SeqVisitor for DeserializerArrayVisitor<'a, I>
Some(&Token::SeqSep) => {
self.de.tokens.next();
self.len -= 1;
Ok(Some(try!(Deserialize::deserialize(self.de))))
Deserialize::deserialize(&mut *self.de).map(Some)
}
Some(&Token::SeqEnd) => Ok(None),
Some(_) => {
@@ -524,15 +545,6 @@ impl<'a, I> SeqVisitor for DeserializerArrayVisitor<'a, I>
}
}
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),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
@@ -557,7 +569,7 @@ impl<'a, I> SeqVisitor for DeserializerTupleVisitor<'a, I>
Some(&Token::TupleSep) => {
self.de.tokens.next();
self.len -= 1;
Ok(Some(try!(Deserialize::deserialize(self.de))))
Deserialize::deserialize(&mut *self.de).map(Some)
}
Some(&Token::TupleEnd) => Ok(None),
Some(_) => {
@@ -568,15 +580,6 @@ impl<'a, I> SeqVisitor for DeserializerTupleVisitor<'a, I>
}
}
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),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
@@ -601,7 +604,7 @@ impl<'a, I> SeqVisitor for DeserializerTupleStructVisitor<'a, I>
Some(&Token::TupleStructSep) => {
self.de.tokens.next();
self.len -= 1;
Ok(Some(try!(Deserialize::deserialize(self.de))))
Deserialize::deserialize(&mut *self.de).map(Some)
}
Some(&Token::TupleStructEnd) => Ok(None),
Some(_) => {
@@ -612,15 +615,6 @@ impl<'a, I> SeqVisitor for DeserializerTupleStructVisitor<'a, I>
}
}
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),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
@@ -645,7 +639,7 @@ impl<'a, I> SeqVisitor for DeserializerVariantSeqVisitor<'a, I>
Some(&Token::EnumSeqSep) => {
self.de.tokens.next();
self.len = self.len.map(|len| len - 1);
Ok(Some(try!(Deserialize::deserialize(self.de))))
Deserialize::deserialize(&mut *self.de).map(Some)
}
Some(&Token::EnumSeqEnd) => Ok(None),
Some(_) => {
@@ -656,15 +650,6 @@ impl<'a, I> SeqVisitor for DeserializerVariantSeqVisitor<'a, I>
}
}
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),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len.unwrap_or(0);
(len, self.len)
@@ -690,7 +675,7 @@ impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
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))))
Deserialize::deserialize(&mut *self.de).map(Some)
}
Some(&Token::MapEnd) => Ok(None),
Some(_) => {
@@ -704,16 +689,7 @@ impl<'a, I> MapVisitor for DeserializerMapVisitor<'a, I>
fn visit_value<V>(&mut self) -> Result<V, Error>
where V: Deserialize,
{
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),
}
Deserialize::deserialize(&mut *self.de)
}
fn size_hint(&self) -> (usize, Option<usize>) {
@@ -726,7 +702,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>
@@ -740,8 +716,8 @@ impl<'a, I> MapVisitor for DeserializerStructVisitor<'a, I>
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);
Deserialize::deserialize(&mut *self.de).map(Some)
}
Some(&Token::StructEnd) => Ok(None),
Some(_) => {
@@ -755,36 +731,27 @@ impl<'a, I> MapVisitor for DeserializerStructVisitor<'a, I>
fn visit_value<V>(&mut self) -> Result<V, Error>
where V: Deserialize,
{
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),
}
Deserialize::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>
fn visit_variant<V>(self) -> Result<(V, Self), Error>
where V: Deserialize,
{
match self.de.tokens.peek() {
@@ -792,18 +759,25 @@ impl<'a, I> VariantVisitor for DeserializerVariantVisitor<'a, I>
| 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!(Deserialize::deserialize(de));
Ok((value, self))
}
Some(_) => {
Deserialize::deserialize(self.de)
let value = try!(Deserialize::deserialize(&mut *self.de));
Ok((value, self))
}
None => Err(Error::EndOfStream),
}
}
}
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();
@@ -816,7 +790,7 @@ impl<'a, I> VariantVisitor for DeserializerVariantVisitor<'a, I>
}
}
fn visit_newtype<T>(&mut self) -> Result<T, Self::Error>
fn visit_newtype<T>(self) -> Result<T, Self::Error>
where T: Deserialize,
{
match self.de.tokens.peek() {
@@ -831,7 +805,7 @@ impl<'a, I> VariantVisitor for DeserializerVariantVisitor<'a, I>
}
}
fn visit_tuple<V>(&mut self,
fn visit_tuple<V>(self,
len: usize,
visitor: V) -> Result<V::Value, Error>
where V: Visitor,
@@ -856,13 +830,13 @@ impl<'a, I> VariantVisitor for DeserializerVariantVisitor<'a, I>
}
}
Some(_) => {
Deserialize::deserialize(self.de)
de::Deserializer::deserialize(self.de, visitor)
}
None => Err(Error::EndOfStream),
}
}
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,7 +861,7 @@ impl<'a, I> VariantVisitor for DeserializerVariantVisitor<'a, I>
}
}
Some(_) => {
Deserialize::deserialize(self.de)
de::Deserializer::deserialize(self.de, visitor)
}
None => Err(Error::EndOfStream),
}
@@ -913,7 +887,7 @@ impl<'a, I> MapVisitor for DeserializerVariantMapVisitor<'a, I>
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))))
Deserialize::deserialize(&mut *self.de).map(Some)
}
Some(&Token::EnumMapEnd) => Ok(None),
Some(_) => {
@@ -927,16 +901,7 @@ impl<'a, I> MapVisitor for DeserializerVariantMapVisitor<'a, I>
fn visit_value<V>(&mut self) -> Result<V, Error>
where V: Deserialize,
{
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),
}
Deserialize::deserialize(&mut *self.de)
}
fn size_hint(&self) -> (usize, Option<usize>) {
+208 -175
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,178 +27,119 @@ 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,
fn serialize_newtype_struct<T>(self,
name: &'static str,
value: T) -> Result<(), Error>
where T: Serialize,
@@ -210,114 +148,209 @@ impl<'a, I> ser::Serializer for Serializer<'a, I>
value.serialize(self)
}
fn serialize_tuple_struct(&mut self, name: &'static str, len: usize) -> Result<(), Error>
fn serialize_newtype_variant<T>(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<V>(self, value: V) -> Result<(), Error>
where V: 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>(&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>(&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>(&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>(&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>(&mut self, key: T) -> Result<(), Self::Error> where T: Serialize {
assert_eq!(self.tokens.next(), Some(&Token::MapSep));
key.serialize(&mut **self)
}
fn serialize_value<T>(&mut self, value: T) -> Result<(), Self::Error> where T: Serialize {
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<V>(&mut self, key: &'static str, value: V) -> Result<(), Self::Error> where V: 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<V>(&mut self, key: &'static str, value: V) -> Result<(), Self::Error> where V: 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)
}
}
+2 -5
View File
@@ -1,6 +1,6 @@
[package]
name = "serde_testing"
version = "0.8.9"
version = "0.9.0-rc1"
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"]
@@ -29,7 +30,3 @@ clippy = { version = "^0.*", optional = true }
[[test]]
name = "test"
path = "tests/test.rs"
[[bench]]
name = "bench"
path = "benches/bench.rs"
-9
View File
@@ -1,9 +0,0 @@
#![feature(test)]
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
extern crate rustc_serialize;
extern crate serde;
extern crate test;
include!(concat!(env!("OUT_DIR"), "/bench.rs"));
-4
View File
@@ -1,4 +0,0 @@
mod bench_enum;
mod bench_map;
mod bench_struct;
mod bench_vec;
-466
View File
@@ -1,466 +0,0 @@
use test::Bencher;
use std::error;
use std::fmt;
use rustc_serialize::Decodable;
use serde;
use serde::de::Deserialize;
//////////////////////////////////////////////////////////////////////////////
#[derive(Clone, PartialEq, Debug, RustcDecodable, Deserialize)]
pub enum Animal {
Dog,
Frog(String, isize)
}
//////////////////////////////////////////////////////////////////////////////
#[derive(Debug)]
pub enum Error {
EndOfStream,
Syntax,
}
impl serde::de::Error for Error {
fn custom<T: Into<String>>(_: T) -> Error { Error::Syntax }
fn end_of_stream() -> Error { Error::EndOfStream }
fn unknown_field(_: &str) -> Error { Error::Syntax }
fn missing_field(_: &'static str) -> Error { Error::Syntax }
}
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
}
}
//////////////////////////////////////////////////////////////////////////////
mod decoder {
use rustc_serialize::Decoder;
use super::{Animal, Error};
use super::Animal::{Dog, Frog};
enum State {
Animal(Animal),
Isize(isize),
String(String),
}
pub struct AnimalDecoder {
stack: Vec<State>,
}
impl AnimalDecoder {
#[inline]
pub fn new(animal: Animal) -> AnimalDecoder {
AnimalDecoder {
stack: vec!(State::Animal(animal)),
}
}
}
impl Decoder for AnimalDecoder {
type Error = Error;
fn error(&mut self, _: &str) -> Error { Error::Syntax }
// Primitive types:
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::Syntax) }
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
#[inline]
fn read_isize(&mut self) -> Result<isize, Error> {
match self.stack.pop() {
Some(State::Isize(x)) => Ok(x),
_ => Err(Error::Syntax),
}
}
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
#[inline]
fn read_str(&mut self) -> Result<String, Error> {
match self.stack.pop() {
Some(State::String(x)) => Ok(x),
_ => Err(Error::Syntax),
}
}
// Compound types:
#[inline]
fn read_enum<T, F>(&mut self, name: &str, f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
match self.stack.pop() {
Some(State::Animal(animal)) => {
self.stack.push(State::Animal(animal));
if name == "Animal" {
f(self)
} else {
Err(Error::Syntax)
}
}
_ => Err(Error::Syntax)
}
}
#[inline]
fn read_enum_variant<T, F>(&mut self, names: &[&str], f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
{
let name = match self.stack.pop() {
Some(State::Animal(Dog)) => "Dog",
Some(State::Animal(Frog(x0, x1))) => {
self.stack.push(State::Isize(x1));
self.stack.push(State::String(x0));
"Frog"
}
_ => { return Err(Error::Syntax); }
};
let idx = match names.iter().position(|n| *n == name) {
Some(idx) => idx,
None => { return Err(Error::Syntax); }
};
f(self, idx)
}
#[inline]
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
f(self)
}
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
// Specialized types:
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder, bool) -> Result<T, Error>,
{
Err(Error::Syntax)
}
#[inline]
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
{
f(self, 3)
}
#[inline]
fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
f(self)
}
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder, usize) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut AnimalDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
}
}
//////////////////////////////////////////////////////////////////////////////
mod deserializer {
use super::{Animal, Error};
use serde::de;
#[derive(Debug)]
enum State {
Animal(Animal),
Isize(isize),
Str(&'static str),
String(String),
UnitState,
}
pub struct AnimalDeserializer {
stack: Vec<State>,
}
impl AnimalDeserializer {
#[inline]
pub fn new(animal: Animal) -> AnimalDeserializer {
AnimalDeserializer {
stack: vec!(State::Animal(animal)),
}
}
}
impl de::Deserializer for AnimalDeserializer {
type Error = Error;
#[inline]
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
match self.stack.pop() {
Some(State::Isize(value)) => {
visitor.visit_isize(value)
}
Some(State::String(value)) => {
visitor.visit_string(value)
}
Some(State::Str(value)) => {
visitor.visit_str(value)
}
Some(State::UnitState) => {
visitor.visit_unit()
}
Some(_) => {
Err(Error::Syntax)
}
None => {
Err(Error::EndOfStream)
}
}
}
#[inline]
fn deserialize_enum<V>(&mut self,
_name: &str,
_variants: &[&str],
mut visitor: V) -> Result<V::Value, Error>
where V: de::EnumVisitor,
{
match self.stack.pop() {
Some(State::Animal(Animal::Dog)) => {
self.stack.push(State::UnitState);
self.stack.push(State::Str("Dog"));
visitor.visit(DogVisitor {
de: self,
})
}
Some(State::Animal(Animal::Frog(x0, x1))) => {
self.stack.push(State::Isize(x1));
self.stack.push(State::String(x0));
self.stack.push(State::Str("Frog"));
visitor.visit(FrogVisitor {
de: self,
state: 0,
})
}
Some(_) => {
Err(Error::Syntax)
}
None => {
Err(Error::EndOfStream)
}
}
}
}
struct DogVisitor<'a> {
de: &'a mut AnimalDeserializer,
}
impl<'a> de::VariantVisitor for DogVisitor<'a> {
type Error = Error;
fn visit_variant<V>(&mut self) -> Result<V, Error>
where V: de::Deserialize
{
de::Deserialize::deserialize(self.de)
}
fn visit_unit(&mut self) -> Result<(), Error> {
de::Deserialize::deserialize(self.de)
}
}
struct FrogVisitor<'a> {
de: &'a mut AnimalDeserializer,
state: usize,
}
impl<'a> de::VariantVisitor for FrogVisitor<'a> {
type Error = Error;
fn visit_variant<V>(&mut self) -> Result<V, Error>
where V: de::Deserialize
{
de::Deserialize::deserialize(self.de)
}
fn visit_tuple<V>(&mut self,
_len: usize,
mut visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
visitor.visit_seq(self)
}
}
impl<'a> de::SeqVisitor for FrogVisitor<'a> {
type Error = Error;
fn visit<T>(&mut self) -> Result<Option<T>, Error>
where T: de::Deserialize,
{
match self.state {
0 => {
self.state += 1;
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
}
1 => {
self.state += 1;
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
}
_ => {
Ok(None)
}
}
}
fn end(&mut self) -> Result<(), Error> {
if self.state == 2 {
Ok(())
} else {
Err(Error::Syntax)
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = 2 - self.state;
(len, Some(len))
}
}
}
//////////////////////////////////////////////////////////////////////////////
#[bench]
fn bench_decoder_dog(b: &mut Bencher) {
b.iter(|| {
let animal = Animal::Dog;
let mut d = decoder::AnimalDecoder::new(animal.clone());
let value: Animal = Decodable::decode(&mut d).unwrap();
assert_eq!(value, animal);
})
}
#[bench]
fn bench_decoder_frog(b: &mut Bencher) {
b.iter(|| {
let animal = Animal::Frog("Henry".to_owned(), 349);
let mut d = decoder::AnimalDecoder::new(animal.clone());
let value: Animal = Decodable::decode(&mut d).unwrap();
assert_eq!(value, animal);
})
}
#[bench]
fn bench_deserializer_dog(b: &mut Bencher) {
b.iter(|| {
let animal = Animal::Dog;
let mut d = deserializer::AnimalDeserializer::new(animal.clone());
let value: Animal = Deserialize::deserialize(&mut d).unwrap();
assert_eq!(value, animal);
})
}
#[bench]
fn bench_deserializer_frog(b: &mut Bencher) {
b.iter(|| {
let animal = Animal::Frog("Henry".to_owned(), 349);
let mut d = deserializer::AnimalDeserializer::new(animal.clone());
let value: Animal = Deserialize::deserialize(&mut d).unwrap();
assert_eq!(value, animal);
})
}
-474
View File
@@ -1,474 +0,0 @@
use std::fmt::Debug;
use std::fmt;
use std::error;
use std::collections::HashMap;
use test::Bencher;
use rustc_serialize::{Decoder, Decodable};
use serde;
use serde::de::{Deserializer, Deserialize};
//////////////////////////////////////////////////////////////////////////////
#[derive(PartialEq, Debug)]
pub enum Error {
EndOfStream,
Syntax,
MissingField,
}
impl serde::de::Error for Error {
fn custom<T: Into<String>>(_: T) -> Error { Error::Syntax }
fn end_of_stream() -> Error { Error::EndOfStream }
fn unknown_field(_: &str) -> Error { Error::Syntax }
fn missing_field(_: &'static str) -> Error {
Error::MissingField
}
}
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
}
}
//////////////////////////////////////////////////////////////////////////////
mod decoder {
use std::collections::HashMap;
use std::collections::hash_map::IntoIter;
use rustc_serialize;
use super::Error;
enum Value {
String(String),
Isize(isize),
}
pub struct IsizeDecoder {
len: usize,
iter: IntoIter<String, isize>,
stack: Vec<Value>,
}
impl IsizeDecoder {
#[inline]
pub fn new(values: HashMap<String, isize>) -> IsizeDecoder {
IsizeDecoder {
len: values.len(),
iter: values.into_iter(),
stack: vec!(),
}
}
}
impl rustc_serialize::Decoder for IsizeDecoder {
type Error = Error;
fn error(&mut self, _msg: &str) -> Error {
Error::Syntax
}
// Primitive types:
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::Syntax) }
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
#[inline]
fn read_isize(&mut self) -> Result<isize, Error> {
match self.stack.pop() {
Some(Value::Isize(x)) => Ok(x),
Some(_) => Err(Error::Syntax),
None => Err(Error::EndOfStream),
}
}
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
#[inline]
fn read_str(&mut self) -> Result<String, Error> {
match self.stack.pop() {
Some(Value::String(x)) => Ok(x),
Some(_) => Err(Error::Syntax),
None => Err(Error::EndOfStream),
}
}
// Compound types:
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
// Specialized types:
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder, bool) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_seq<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_seq_elt<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
#[inline]
fn read_map<T, F>(&mut self, f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder, usize) -> Result<T, Error>,
{
let len = self.len;
f(self, len)
}
#[inline]
fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
match self.iter.next() {
Some((key, value)) => {
self.stack.push(Value::Isize(value));
self.stack.push(Value::String(key));
f(self)
}
None => {
Err(Error::Syntax)
}
}
}
#[inline]
fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
F: FnOnce(&mut IsizeDecoder) -> Result<T, Error>,
{
f(self)
}
}
}
//////////////////////////////////////////////////////////////////////////////
mod deserializer {
use std::collections::HashMap;
use std::collections::hash_map;
use super::Error;
use serde::de;
#[derive(PartialEq, Debug)]
enum State {
StartState,
Key(String),
Value(isize),
}
pub struct IsizeDeserializer {
stack: Vec<State>,
iter: hash_map::IntoIter<String, isize>,
}
impl IsizeDeserializer {
#[inline]
pub fn new(values: HashMap<String, isize>) -> IsizeDeserializer {
IsizeDeserializer {
stack: vec!(State::StartState),
iter: values.into_iter(),
}
}
}
impl de::Deserializer for IsizeDeserializer {
type Error = Error;
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
match self.stack.pop() {
Some(State::StartState) => {
visitor.visit_map(self)
}
Some(State::Key(key)) => {
visitor.visit_string(key)
}
Some(State::Value(value)) => {
visitor.visit_isize(value)
}
None => {
Err(Error::EndOfStream)
}
}
}
}
impl de::MapVisitor for IsizeDeserializer {
type Error = Error;
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
where K: de::Deserialize,
{
match self.iter.next() {
Some((key, value)) => {
self.stack.push(State::Value(value));
self.stack.push(State::Key(key));
Ok(Some(try!(de::Deserialize::deserialize(self))))
}
None => {
Ok(None)
}
}
}
fn visit_value<V>(&mut self) -> Result<V, Error>
where V: de::Deserialize,
{
de::Deserialize::deserialize(self)
}
fn end(&mut self) -> Result<(), Error> {
match self.iter.next() {
Some(_) => Err(Error::Syntax),
None => Ok(()),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
/*
impl Iterator for IsizeDeserializer {
type Item = Result<de::Token, Error>;
#[inline]
fn next(&mut self) -> Option<Result<de::Token, Error>> {
match self.stack.pop() {
Some(State::StartState) => {
self.stack.push(KeyOrEndState);
Some(Ok(de::Token::MapStart(self.len)))
}
Some(State::KeyOrEndState) => {
match self.iter.next() {
Some((key, value)) => {
self.stack.push(Value(value));
Some(Ok(de::Token::String(key)))
}
None => {
self.stack.push(EndState);
Some(Ok(de::Token::End))
}
}
}
Some(State::Value(x)) => {
self.stack.push(KeyOrEndState);
Some(Ok(de::Token::Isize(x)))
}
Some(EndState) => {
None
}
None => {
None
}
}
}
}
impl de::Deserializer<Error> for IsizeDeserializer {
#[inline]
fn end_of_stream(&mut self) -> Error {
EndOfStream
}
#[inline]
fn syntax(&mut self, _token: de::Token, _expected: &[de::TokenKind]) -> Error {
Syntax
}
#[inline]
fn unexpected_name(&mut self, _token: de::Token) -> Error {
Syntax
}
#[inline]
fn conversion_error(&mut self, _token: de::Token) -> Error {
Syntax
}
#[inline]
fn missing_field<
T: de::Deserialize<IsizeDeserializer, Error>
>(&mut self, _field: &'static str) -> Result<T, Error> {
Err(Error::Syntax)
}
}
*/
}
//////////////////////////////////////////////////////////////////////////////
fn run_decoder<
D: Decoder<Error=Error>,
T: Clone + PartialEq + Debug + Decodable
>(mut d: D, value: T) {
let v = Decodable::decode(&mut d);
assert_eq!(Ok(value), v);
}
#[bench]
fn bench_decoder_000(b: &mut Bencher) {
b.iter(|| {
let m: HashMap<String, isize> = HashMap::new();
run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
})
}
#[bench]
fn bench_decoder_003(b: &mut Bencher) {
b.iter(|| {
let mut m: HashMap<String, isize> = HashMap::new();
for i in 0 .. 3 {
m.insert(i.to_string(), i);
}
run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
})
}
#[bench]
fn bench_decoder_100(b: &mut Bencher) {
b.iter(|| {
let mut m: HashMap<String, isize> = HashMap::new();
for i in 0 .. 100 {
m.insert(i.to_string(), i);
}
run_decoder(decoder::IsizeDecoder::new(m.clone()), m)
})
}
fn run_deserializer<D, T>(mut d: D, value: T)
where D: Deserializer,
D::Error: Debug + PartialEq,
T: Clone + PartialEq + Debug + Deserialize
{
let v = T::deserialize(&mut d);
assert_eq!(Ok(value), v);
}
#[bench]
fn bench_deserializer_000(b: &mut Bencher) {
b.iter(|| {
let m: HashMap<String, isize> = HashMap::new();
run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
})
}
#[bench]
fn bench_deserializer_003(b: &mut Bencher) {
b.iter(|| {
let mut m: HashMap<String, isize> = HashMap::new();
for i in 0 .. 3 {
m.insert(i.to_string(), i);
}
run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
})
}
#[bench]
fn bench_deserializer_100(b: &mut Bencher) {
b.iter(|| {
let mut m: HashMap<String, isize> = HashMap::new();
for i in 0 .. 100 {
m.insert(i.to_string(), i);
}
run_deserializer(deserializer::IsizeDeserializer::new(m.clone()), m)
})
}
-745
View File
@@ -1,745 +0,0 @@
use std::collections::HashMap;
use test::Bencher;
use std::fmt;
use std::error;
use rustc_serialize::Decodable;
use serde;
use serde::de::Deserialize;
//////////////////////////////////////////////////////////////////////////////
#[derive(Clone, PartialEq, Debug, RustcDecodable, Deserialize)]
pub struct Inner {
a: (),
b: usize,
c: HashMap<String, Option<char>>,
}
//////////////////////////////////////////////////////////////////////////////
#[derive(Clone, PartialEq, Debug, RustcDecodable, Deserialize)]
pub struct Outer {
inner: Vec<Inner>,
}
//////////////////////////////////////////////////////////////////////////////
#[derive(Debug, PartialEq)]
pub enum Error {
EndOfStream,
Syntax,
MissingField,
OtherError,
}
impl serde::de::Error for Error {
fn custom<T: Into<String>>(_: T) -> Error { Error::Syntax }
fn end_of_stream() -> Error { Error::EndOfStream }
fn unknown_field(_: &str) -> Error { Error::Syntax }
fn missing_field(_: &'static str) -> Error {
Error::MissingField
}
}
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
}
}
mod decoder {
use std::collections::HashMap;
use rustc_serialize::Decoder;
use super::{Outer, Inner, Error};
#[derive(Debug)]
enum State {
Outer(Outer),
Inner(Inner),
Null,
Usize(usize),
Char(char),
String(String),
Field(&'static str),
Vec(Vec<Inner>),
Map(HashMap<String, Option<char>>),
Option(bool),
}
pub struct OuterDecoder {
stack: Vec<State>,
}
impl OuterDecoder {
#[inline]
pub fn new(animal: Outer) -> OuterDecoder {
OuterDecoder {
stack: vec!(State::Outer(animal)),
}
}
}
impl Decoder for OuterDecoder {
type Error = Error;
fn error(&mut self, _msg: &str) -> Error {
Error::OtherError
}
// Primitive types:
#[inline]
fn read_nil(&mut self) -> Result<(), Error> {
match self.stack.pop() {
Some(State::Null) => Ok(()),
_ => Err(Error::Syntax),
}
}
#[inline]
fn read_usize(&mut self) -> Result<usize, Error> {
match self.stack.pop() {
Some(State::Usize(value)) => Ok(value),
_ => Err(Error::Syntax),
}
}
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::Syntax) }
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
#[inline]
fn read_char(&mut self) -> Result<char, Error> {
match self.stack.pop() {
Some(State::Char(c)) => Ok(c),
_ => Err(Error::Syntax),
}
}
#[inline]
fn read_str(&mut self) -> Result<String, Error> {
match self.stack.pop() {
Some(State::String(value)) => Ok(value),
_ => Err(Error::Syntax),
}
}
// Compound types:
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
#[inline]
fn read_struct<T, F>(&mut self, s_name: &str, _len: usize, f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
match self.stack.pop() {
Some(State::Outer(Outer { inner })) => {
if s_name == "Outer" {
self.stack.push(State::Vec(inner));
self.stack.push(State::Field("inner"));
f(self)
} else {
Err(Error::Syntax)
}
}
Some(State::Inner(Inner { a: (), b, c })) => {
if s_name == "Inner" {
self.stack.push(State::Map(c));
self.stack.push(State::Field("c"));
self.stack.push(State::Usize(b));
self.stack.push(State::Field("b"));
self.stack.push(State::Null);
self.stack.push(State::Field("a"));
f(self)
} else {
Err(Error::Syntax)
}
}
_ => Err(Error::Syntax),
}
}
#[inline]
fn read_struct_field<T, F>(&mut self, f_name: &str, _f_idx: usize, f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
match self.stack.pop() {
Some(State::Field(name)) => {
if f_name == name {
f(self)
} else {
Err(Error::Syntax)
}
}
_ => Err(Error::Syntax)
}
}
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
// Specialized types:
#[inline]
fn read_option<T, F>(&mut self, f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder, bool) -> Result<T, Error>,
{
match self.stack.pop() {
Some(State::Option(b)) => f(self, b),
_ => Err(Error::Syntax),
}
}
#[inline]
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
{
match self.stack.pop() {
Some(State::Vec(value)) => {
let len = value.len();
for inner in value.into_iter().rev() {
self.stack.push(State::Inner(inner));
}
f(self, len)
}
_ => Err(Error::Syntax)
}
}
#[inline]
fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
f(self)
}
#[inline]
fn read_map<T, F>(&mut self, f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder, usize) -> Result<T, Error>,
{
match self.stack.pop() {
Some(State::Map(map)) => {
let len = map.len();
for (key, value) in map {
match value {
Some(c) => {
self.stack.push(State::Char(c));
self.stack.push(State::Option(true));
}
None => {
self.stack.push(State::Option(false));
}
}
self.stack.push(State::String(key));
}
f(self, len)
}
_ => Err(Error::Syntax),
}
}
#[inline]
fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
f(self)
}
#[inline]
fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
F: FnOnce(&mut OuterDecoder) -> Result<T, Error>,
{
f(self)
}
}
}
//////////////////////////////////////////////////////////////////////////////
mod deserializer {
use std::collections::HashMap;
use std::collections::hash_map;
use std::vec;
use super::{Outer, Inner};
use super::Error;
use serde::de;
#[derive(Debug)]
enum State {
Outer(Outer),
Inner(Inner),
Str(&'static str),
Null,
Usize(usize),
Char(char),
String(String),
Option(bool),
Vec(Vec<Inner>),
Map(HashMap<String, Option<char>>),
}
pub struct OuterDeserializer {
stack: Vec<State>,
}
impl OuterDeserializer {
#[inline]
pub fn new(outer: Outer) -> OuterDeserializer {
OuterDeserializer {
stack: vec!(State::Outer(outer)),
}
}
}
impl de::Deserializer for OuterDeserializer {
type Error = Error;
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
match self.stack.pop() {
Some(State::Vec(value)) => {
visitor.visit_seq(OuterSeqVisitor {
de: self,
iter: value.into_iter(),
})
}
Some(State::Map(value)) => {
visitor.visit_map(MapVisitor {
de: self,
iter: value.into_iter(),
})
}
Some(State::Null) => {
visitor.visit_unit()
}
Some(State::Usize(x)) => {
visitor.visit_usize(x)
}
Some(State::Char(x)) => {
visitor.visit_char(x)
}
Some(State::Str(x)) => {
visitor.visit_str(x)
}
Some(State::String(x)) => {
visitor.visit_string(x)
}
Some(State::Option(false)) => {
visitor.visit_none()
}
Some(State::Option(true)) => {
visitor.visit_some(self)
}
Some(_) => Err(Error::Syntax),
None => Err(Error::EndOfStream),
}
}
fn deserialize_struct<V>(&mut self,
name: &str,
_fields: &'static [&'static str],
mut visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
match self.stack.pop() {
Some(State::Outer(Outer { inner })) => {
if name != "Outer" {
return Err(Error::Syntax);
}
self.stack.push(State::Vec(inner));
self.stack.push(State::Str("inner"));
visitor.visit_map(OuterMapVisitor {
de: self,
state: 0,
})
}
Some(State::Inner(Inner { a: (), b, c })) => {
if name != "Inner" {
return Err(Error::Syntax);
}
self.stack.push(State::Map(c));
self.stack.push(State::Str("c"));
self.stack.push(State::Usize(b));
self.stack.push(State::Str("b"));
self.stack.push(State::Null);
self.stack.push(State::Str("a"));
visitor.visit_map(InnerMapVisitor {
de: self,
state: 0,
})
}
_ => {
Err(Error::Syntax)
}
}
}
}
struct OuterMapVisitor<'a> {
de: &'a mut OuterDeserializer,
state: usize,
}
impl<'a> de::MapVisitor for OuterMapVisitor<'a> {
type Error = Error;
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
where K: de::Deserialize,
{
match self.state {
0 => {
self.state += 1;
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
}
_ => {
Ok(None)
}
}
}
fn visit_value<V>(&mut self) -> Result<V, Error>
where V: de::Deserialize,
{
de::Deserialize::deserialize(self.de)
}
fn end(&mut self) -> Result<(), Error> {
if self.state == 1 {
Ok(())
} else {
Err(Error::Syntax)
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = 1 - self.state;
(len, Some(len))
}
}
struct OuterSeqVisitor<'a> {
de: &'a mut OuterDeserializer,
iter: vec::IntoIter<Inner>,
}
impl<'a> de::SeqVisitor for OuterSeqVisitor<'a> {
type Error = Error;
fn visit<T>(&mut self) -> Result<Option<T>, Error>
where T: de::Deserialize,
{
match self.iter.next() {
Some(value) => {
self.de.stack.push(State::Inner(value));
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
}
None => {
Ok(None)
}
}
}
fn end(&mut self) -> Result<(), Error> {
match self.iter.next() {
Some(_) => Err(Error::Syntax),
None => Ok(()),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
struct InnerMapVisitor<'a> {
de: &'a mut OuterDeserializer,
state: usize,
}
impl<'a> de::MapVisitor for InnerMapVisitor<'a> {
type Error = Error;
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
where K: de::Deserialize,
{
match self.state {
0 ... 2 => {
self.state += 1;
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
}
_ => {
Ok(None)
}
}
}
fn visit_value<V>(&mut self) -> Result<V, Error>
where V: de::Deserialize,
{
de::Deserialize::deserialize(self.de)
}
fn end(&mut self) -> Result<(), Error> {
if self.state == 3 {
Ok(())
} else {
Err(Error::Syntax)
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = 1 - self.state;
(len, Some(len))
}
}
struct MapVisitor<'a> {
de: &'a mut OuterDeserializer,
iter: hash_map::IntoIter<String, Option<char>>,
}
impl<'a> de::MapVisitor for MapVisitor<'a> {
type Error = Error;
fn visit_key<K>(&mut self) -> Result<Option<K>, Error>
where K: de::Deserialize,
{
match self.iter.next() {
Some((key, Some(value))) => {
self.de.stack.push(State::Char(value));
self.de.stack.push(State::Option(true));
self.de.stack.push(State::String(key));
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
}
Some((key, None)) => {
self.de.stack.push(State::Option(false));
self.de.stack.push(State::String(key));
Ok(Some(try!(de::Deserialize::deserialize(self.de))))
}
None => {
Ok(None)
}
}
}
fn visit_value<V>(&mut self) -> Result<V, Error>
where V: de::Deserialize,
{
de::Deserialize::deserialize(self.de)
}
fn end(&mut self) -> Result<(), Error> {
match self.iter.next() {
Some(_) => Err(Error::Syntax),
None => Ok(()),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
}
#[bench]
fn bench_decoder_0_0(b: &mut Bencher) {
b.iter(|| {
let mut map = HashMap::new();
map.insert("abc".to_owned(), Some('c'));
let outer = Outer {
inner: vec!(),
};
let mut d = decoder::OuterDecoder::new(outer.clone());
let value: Result<Outer, Error> = Decodable::decode(&mut d);
assert_eq!(value, Ok(outer));
})
}
#[bench]
fn bench_decoder_1_0(b: &mut Bencher) {
b.iter(|| {
let map = HashMap::new();
let outer = Outer {
inner: vec!(
Inner {
a: (),
b: 5,
c: map,
},
)
};
let mut d = decoder::OuterDecoder::new(outer.clone());
let value: Result<Outer, Error> = Decodable::decode(&mut d);
assert_eq!(value, Ok(outer));
})
}
#[bench]
fn bench_decoder_1_5(b: &mut Bencher) {
b.iter(|| {
let mut map = HashMap::new();
map.insert("1".to_owned(), Some('a'));
map.insert("2".to_owned(), None);
map.insert("3".to_owned(), Some('b'));
map.insert("4".to_owned(), None);
map.insert("5".to_owned(), Some('c'));
let outer = Outer {
inner: vec!(
Inner {
a: (),
b: 5,
c: map,
},
)
};
let mut d = decoder::OuterDecoder::new(outer.clone());
let value: Result<Outer, Error> = Decodable::decode(&mut d);
assert_eq!(value, Ok(outer));
})
}
#[bench]
fn bench_deserializer_0_0(b: &mut Bencher) {
b.iter(|| {
let outer = Outer {
inner: vec!(),
};
let mut d = deserializer::OuterDeserializer::new(outer.clone());
let value: Result<Outer, Error> = Deserialize::deserialize(&mut d);
assert_eq!(value, Ok(outer));
})
}
#[bench]
fn bench_deserializer_1_0(b: &mut Bencher) {
b.iter(|| {
let map = HashMap::new();
let outer = Outer {
inner: vec!(
Inner {
a: (),
b: 5,
c: map,
},
)
};
let mut d = deserializer::OuterDeserializer::new(outer.clone());
let value: Result<Outer, Error> = Deserialize::deserialize(&mut d);
assert_eq!(value, Ok(outer));
})
}
#[bench]
fn bench_deserializer_1_5(b: &mut Bencher) {
b.iter(|| {
let mut map = HashMap::new();
map.insert("1".to_owned(), Some('a'));
map.insert("2".to_owned(), None);
map.insert("3".to_owned(), Some('b'));
map.insert("4".to_owned(), None);
map.insert("5".to_owned(), Some('c'));
let outer = Outer {
inner: vec!(
Inner {
a: (),
b: 5,
c: map,
},
)
};
let mut d = deserializer::OuterDeserializer::new(outer.clone());
let value: Result<Outer, Error> = Deserialize::deserialize(&mut d);
assert_eq!(value, Ok(outer));
})
}
-628
View File
@@ -1,628 +0,0 @@
use std::fmt::Debug;
use std::fmt;
use std::error;
use test::Bencher;
use rustc_serialize::{Decoder, Decodable};
use serde;
use serde::de::{Deserializer, Deserialize};
//////////////////////////////////////////////////////////////////////////////
#[derive(PartialEq, Debug)]
pub enum Error {
EndOfStream,
Syntax,
}
impl serde::de::Error for Error {
fn custom<T: Into<String>>(_: T) -> Error { Error::Syntax }
fn end_of_stream() -> Error { Error::EndOfStream }
fn unknown_field(_: &str) -> Error { Error::Syntax }
fn missing_field(_: &'static str) -> Error { Error::Syntax }
}
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
}
}
//////////////////////////////////////////////////////////////////////////////
mod decoder {
use std::vec;
use rustc_serialize;
use super::Error;
pub struct UsizeDecoder {
len: usize,
iter: vec::IntoIter<usize>,
}
impl UsizeDecoder {
#[inline]
pub fn new(values: Vec<usize>) -> UsizeDecoder {
UsizeDecoder {
len: values.len(),
iter: values.into_iter(),
}
}
}
impl rustc_serialize::Decoder for UsizeDecoder {
type Error = Error;
fn error(&mut self, _: &str) -> Error { Error::Syntax }
// Primitive types:
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
#[inline]
fn read_usize(&mut self) -> Result<usize, Error> {
match self.iter.next() {
Some(value) => Ok(value),
None => Err(Error::EndOfStream),
}
}
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
fn read_u8(&mut self) -> Result<u8, Error> { Err(Error::Syntax) }
fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::Syntax) }
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
fn read_str(&mut self) -> Result<String, Error> { Err(Error::Syntax) }
// Compound types:
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
// Specialized types:
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder, bool) -> Result<T, Error>,
{
Err(Error::Syntax)
}
#[inline]
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
{
let len = self.len;
f(self, len)
}
#[inline]
fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
f(self)
}
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder, usize) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut UsizeDecoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
}
pub struct U8Decoder {
len: usize,
iter: vec::IntoIter<u8>,
}
impl U8Decoder {
#[inline]
pub fn new(values: Vec<u8>) -> U8Decoder {
U8Decoder {
len: values.len(),
iter: values.into_iter(),
}
}
}
impl rustc_serialize::Decoder for U8Decoder {
type Error = Error;
fn error(&mut self, _: &str) -> Error { Error::Syntax }
// Primitive types:
fn read_nil(&mut self) -> Result<(), Error> { Err(Error::Syntax) }
fn read_usize(&mut self) -> Result<usize, Error> { Err(Error::Syntax) }
fn read_u64(&mut self) -> Result<u64, Error> { Err(Error::Syntax) }
fn read_u32(&mut self) -> Result<u32, Error> { Err(Error::Syntax) }
fn read_u16(&mut self) -> Result<u16, Error> { Err(Error::Syntax) }
#[inline]
fn read_u8(&mut self) -> Result<u8, Error> {
match self.iter.next() {
Some(value) => Ok(value),
None => Err(Error::EndOfStream),
}
}
#[inline]
fn read_isize(&mut self) -> Result<isize, Error> { Err(Error::Syntax) }
fn read_i64(&mut self) -> Result<i64, Error> { Err(Error::Syntax) }
fn read_i32(&mut self) -> Result<i32, Error> { Err(Error::Syntax) }
fn read_i16(&mut self) -> Result<i16, Error> { Err(Error::Syntax) }
fn read_i8(&mut self) -> Result<i8, Error> { Err(Error::Syntax) }
fn read_bool(&mut self) -> Result<bool, Error> { Err(Error::Syntax) }
fn read_f64(&mut self) -> Result<f64, Error> { Err(Error::Syntax) }
fn read_f32(&mut self) -> Result<f32, Error> { Err(Error::Syntax) }
fn read_char(&mut self) -> Result<char, Error> { Err(Error::Syntax) }
fn read_str(&mut self) -> Result<String, Error> { Err(Error::Syntax) }
// Compound types:
fn read_enum<T, F>(&mut self, _name: &str, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_struct_variant<T, F>(&mut self, _names: &[&str], _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple<T, F>(&mut self, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_struct<T, F>(&mut self, _s_name: &str, _len: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_tuple_struct_arg<T, F>(&mut self, _a_idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
// Specialized types:
fn read_option<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder, bool) -> Result<T, Error>,
{
Err(Error::Syntax)
}
#[inline]
fn read_seq<T, F>(&mut self, f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
{
let len = self.len;
f(self, len)
}
#[inline]
fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
f(self)
}
fn read_map<T, F>(&mut self, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder, usize) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_map_elt_key<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
fn read_map_elt_val<T, F>(&mut self, _idx: usize, _f: F) -> Result<T, Error> where
F: FnOnce(&mut U8Decoder) -> Result<T, Error>,
{
Err(Error::Syntax)
}
}
}
//////////////////////////////////////////////////////////////////////////////
mod deserializer {
//use std::num;
use std::vec;
use super::Error;
use serde::de;
#[derive(PartialEq, Debug)]
enum State {
Start,
SepOrEnd,
End,
}
pub struct Deserializer<A> {
state: State,
iter: vec::IntoIter<A>,
len: usize,
value: Option<A>,
}
impl<A> Deserializer<A> {
#[inline]
pub fn new(values: Vec<A>) -> Deserializer<A> {
let len = values.len();
Deserializer {
state: State::Start,
iter: values.into_iter(),
len: len,
value: None,
}
}
}
impl de::Deserializer for Deserializer<usize> {
type Error = Error;
#[inline]
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
match self.state {
State::Start => {
self.state = State::SepOrEnd;
visitor.visit_seq(self)
}
State::SepOrEnd => {
visitor.visit_usize(self.value.take().unwrap())
}
State::End => {
Err(Error::EndOfStream)
}
}
}
}
impl de::SeqVisitor for Deserializer<usize> {
type Error = Error;
#[inline]
fn visit<T>(&mut self) -> Result<Option<T>, Error>
where T: de::Deserialize,
{
match self.iter.next() {
Some(value) => {
self.len -= 1;
self.value = Some(value);
Ok(Some(try!(de::Deserialize::deserialize(self))))
}
None => {
self.state = State::End;
Ok(None)
}
}
}
#[inline]
fn end(&mut self) -> Result<(), Error> {
match self.iter.next() {
Some(_) => Err(Error::Syntax),
None => {
self.state = State::End;
Ok(())
}
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}
impl de::Deserializer for Deserializer<u8> {
type Error = Error;
#[inline]
fn deserialize<V>(&mut self, mut visitor: V) -> Result<V::Value, Error>
where V: de::Visitor,
{
match self.state {
State::Start => {
self.state = State::SepOrEnd;
visitor.visit_seq(self)
}
State::SepOrEnd => {
visitor.visit_u8(self.value.take().unwrap())
}
State::End => {
Err(Error::EndOfStream)
}
}
}
}
impl de::SeqVisitor for Deserializer<u8> {
type Error = Error;
#[inline]
fn visit<T>(&mut self) -> Result<Option<T>, Error>
where T: de::Deserialize,
{
match self.iter.next() {
Some(value) => {
self.len -= 1;
self.value = Some(value);
Ok(Some(try!(de::Deserialize::deserialize(self))))
}
None => {
self.state = State::End;
Ok(None)
}
}
}
#[inline]
fn end(&mut self) -> Result<(), Error> {
match self.iter.next() {
Some(_) => Err(Error::Syntax),
None => {
self.state = State::End;
Ok(())
}
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}
}
//////////////////////////////////////////////////////////////////////////////
fn run_decoder<
D: Decoder<Error=Error>,
T: Clone + PartialEq + Debug + Decodable
>(mut d: D, value: T) {
let v = Decodable::decode(&mut d);
assert_eq!(Ok(value), v);
}
fn run_deserializer<D, T>(mut d: D, value: T)
where D: Deserializer,
D::Error: Debug + PartialEq,
T: Clone + PartialEq + Debug + Deserialize
{
let v = T::deserialize(&mut d);
assert_eq!(Ok(value), v);
}
#[bench]
fn bench_decoder_usize_000(b: &mut Bencher) {
b.iter(|| {
let v: Vec<usize> = vec!();
run_decoder(decoder::UsizeDecoder::new(v.clone()), v)
})
}
#[bench]
fn bench_decoder_usize_003(b: &mut Bencher) {
b.iter(|| {
let v: Vec<usize> = vec!(1, 2, 3);
run_decoder(decoder::UsizeDecoder::new(v.clone()), v)
})
}
#[bench]
fn bench_decoder_usize_100(b: &mut Bencher) {
b.iter(|| {
let v: Vec<usize> = (0 .. 100).collect();
run_decoder(decoder::UsizeDecoder::new(v.clone()), v)
})
}
#[bench]
fn bench_decoder_u8_000(b: &mut Bencher) {
b.iter(|| {
let v: Vec<u8> = vec!();
run_decoder(decoder::U8Decoder::new(v.clone()), v)
})
}
#[bench]
fn bench_decoder_u8_003(b: &mut Bencher) {
b.iter(|| {
let v: Vec<u8> = vec!(1, 2, 3);
run_decoder(decoder::U8Decoder::new(v.clone()), v)
})
}
#[bench]
fn bench_decoder_u8_100(b: &mut Bencher) {
b.iter(|| {
let v: Vec<u8> = (0 .. 100).collect();
run_decoder(decoder::U8Decoder::new(v.clone()), v)
})
}
#[bench]
fn bench_deserializer_usize_000(b: &mut Bencher) {
b.iter(|| {
let v: Vec<usize> = vec!();
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
})
}
#[bench]
fn bench_deserializer_usize_003(b: &mut Bencher) {
b.iter(|| {
let v: Vec<usize> = vec!(1, 2, 3);
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
})
}
#[bench]
fn bench_deserializer_usize_100(b: &mut Bencher) {
b.iter(|| {
let v: Vec<usize> = (0 .. 100).collect();
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
})
}
#[bench]
fn bench_deserializer_u8_000(b: &mut Bencher) {
b.iter(|| {
let v: Vec<u8> = vec!();
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
})
}
#[bench]
fn bench_deserializer_u8_003(b: &mut Bencher) {
b.iter(|| {
let v: Vec<u8> = vec!(1, 2, 3);
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
})
}
#[bench]
fn bench_deserializer_u8_100(b: &mut Bencher) {
b.iter(|| {
let v: Vec<u8> = (0 .. 100).collect();
run_deserializer(deserializer::Deserializer::new(v.clone()), v)
})
}
+3 -9
View File
@@ -5,13 +5,7 @@ use std::path::Path;
fn main() {
let out_dir = env::var_os("OUT_DIR").unwrap();
for &(src, dst) in &[
("tests/test.rs.in", "test.rs"),
("benches/bench.rs.in", "bench.rs"),
] {
let src = Path::new(src);
let dst = Path::new(&out_dir).join(dst);
serde_codegen::expand(&src, &dst).unwrap();
}
let src = Path::new("tests/test.rs.in");
let dst = Path::new(&out_dir).join("test.rs");
serde_codegen::expand(&src, &dst).unwrap();
}
+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;
+6 -6
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)) {
@@ -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!()
@@ -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)
+44 -451
View File
@@ -1,460 +1,53 @@
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::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::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,
]);
}
+115 -16
View File
@@ -3,7 +3,7 @@ use std::net;
use std::path::PathBuf;
use std::time::Duration;
use serde::Deserialize;
use serde::de::{Deserialize, Type};
extern crate fnv;
use self::fnv::FnvHasher;
@@ -32,12 +32,43 @@ 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 }
Map { a: i32, b: i32, c: i32 },
}
#[derive(PartialEq, Debug, Deserialize)]
enum EnumSkipAll {
#[allow(dead_code)]
#[serde(skip_deserializing)]
Skipped,
}
//////////////////////////////////////////////////////////////////////////
@@ -215,6 +246,9 @@ declare_tests! {
Token::SeqEnd,
],
}
test_unit_string {
String::new() => &[Token::Unit],
}
test_tuple_struct {
TupleStruct(1, 2, 3) => &[
Token::SeqStart(Some(3)),
@@ -675,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"),
@@ -717,20 +774,6 @@ declare_tests! {
Token::EnumMapEnd,
],
}
test_enum_unit_usize {
Enum::Unit => &[
Token::EnumStart("Enum"),
Token::Usize(0),
Token::Unit,
],
}
test_enum_unit_bytes {
Enum::Unit => &[
Token::EnumStart("Enum"),
Token::Bytes(b"Unit"),
Token::Unit,
],
}
test_box {
Box::new(0i32) => &[Token::I32(0)],
}
@@ -796,12 +839,52 @@ 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::UnknownField("d".to_owned()),
}
test_skipped_field_is_unknown<StructDenyUnknown> {
&[
Token::StructStart("StructDenyUnknown", 2),
Token::StructSep,
Token::Str("b"),
],
Error::UnknownField("b".to_owned()),
}
test_skip_all_deny_unknown<StructSkipAllDenyUnknown> {
&[
Token::StructStart("StructSkipAllDenyUnknown", 1),
Token::StructSep,
Token::Str("a"),
],
Error::UnknownField("a".to_owned()),
}
test_unknown_variant<Enum> {
&[
Token::EnumUnit("Enum", "Foo"),
],
Error::UnknownVariant("Foo".to_owned()),
}
test_enum_skipped_variant<Enum> {
&[
Token::EnumUnit("Enum", "Skipped"),
],
Error::UnknownVariant("Skipped".to_owned()),
}
test_enum_skip_all<EnumSkipAll> {
&[
Token::EnumUnit("EnumSkipAll", "Skipped"),
],
Error::UnknownVariant("Skipped".to_owned()),
}
test_struct_seq_too_long<Struct> {
&[
Token::SeqStart(Some(4)),
@@ -835,4 +918,20 @@ declare_error_tests! {
],
Error::DuplicateField("a"),
}
test_enum_unit_usize<Enum> {
&[
Token::EnumStart("Enum"),
Token::Usize(0),
Token::Unit,
],
Error::InvalidType(Type::U64),
}
test_enum_unit_bytes<Enum> {
&[
Token::EnumStart("Enum"),
Token::Bytes(b"Unit"),
Token::Unit,
],
Error::InvalidType(Type::Bytes),
}
}
+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!()
}
}
+25
View File
@@ -600,3 +600,28 @@ fn test_default_ty_param() {
]
);
}
#[test]
fn test_enum_state_field() {
#[derive(Debug, PartialEq, Serialize, Deserialize)]
enum SomeEnum {
Key { key: char, state: bool },
}
assert_tokens(
&SomeEnum::Key { key: 'a', state: true },
&[
Token::EnumMapStart("SomeEnum", "Key", 2),
Token::EnumMapSep,
Token::Str("key"),
Token::Char('a'),
Token::EnumMapSep,
Token::Str("state"),
Token::Bool(true),
Token::EnumMapEnd,
]
);
}
+75 -1
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() {
@@ -388,3 +442,23 @@ fn test_cannot_serialize_paths() {
&[],
Error::InvalidValue("Path contains invalid UTF-8 characters".to_owned()));
}
#[test]
fn test_enum_skipped() {
assert_ser_tokens_error(
&Enum::SkippedUnit,
&[],
Error::InvalidValue("The enum variant Enum::SkippedUnit cannot be serialized".to_owned()));
assert_ser_tokens_error(
&Enum::SkippedOne(42),
&[],
Error::InvalidValue("The enum variant Enum::SkippedOne cannot be serialized".to_owned()));
assert_ser_tokens_error(
&Enum::SkippedSeq(1, 2),
&[],
Error::InvalidValue("The enum variant Enum::SkippedSeq cannot be serialized".to_owned()));
assert_ser_tokens_error(
&Enum::SkippedMap { _a: 1, _b: 2 },
&[],
Error::InvalidValue("The enum variant Enum::SkippedMap cannot be serialized".to_owned()));
}