├── .github
├── FUNDING.yml
├── ISSUE_TEMPLATE
│ ├── 1-problem.md
│ ├── 2-suggestion.md
│ ├── 3-documentation.md
│ └── 4-other.md
└── workflows
│ └── ci.yml
├── .gitignore
├── CONTRIBUTING.md
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── crates-io.md
├── serde
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── build.rs
├── crates-io.md
└── src
│ ├── de
│ ├── ignored_any.rs
│ ├── impls.rs
│ ├── mod.rs
│ ├── seed.rs
│ ├── size_hint.rs
│ └── value.rs
│ ├── format.rs
│ ├── integer128.rs
│ ├── lib.rs
│ ├── macros.rs
│ ├── private
│ ├── de.rs
│ ├── doc.rs
│ ├── mod.rs
│ └── ser.rs
│ ├── ser
│ ├── fmt.rs
│ ├── impls.rs
│ ├── impossible.rs
│ └── mod.rs
│ └── std_error.rs
├── serde_derive
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── build.rs
├── crates-io.md
└── src
│ ├── bound.rs
│ ├── de.rs
│ ├── dummy.rs
│ ├── fragment.rs
│ ├── internals
│ ├── ast.rs
│ ├── attr.rs
│ ├── case.rs
│ ├── check.rs
│ ├── ctxt.rs
│ ├── mod.rs
│ ├── name.rs
│ ├── receiver.rs
│ ├── respan.rs
│ └── symbol.rs
│ ├── lib.rs
│ ├── pretend.rs
│ ├── ser.rs
│ └── this.rs
├── serde_derive_internals
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── build.rs
├── lib.rs
└── src
└── test_suite
├── Cargo.toml
├── no_std
├── .gitignore
├── Cargo.toml
└── src
│ └── main.rs
└── tests
├── bytes
└── mod.rs
├── compiletest.rs
├── macros
└── mod.rs
├── regression.rs
├── regression
├── issue1904.rs
├── issue2371.rs
├── issue2409.rs
├── issue2415.rs
├── issue2565.rs
├── issue2792.rs
├── issue2844.rs
└── issue2846.rs
├── test_annotations.rs
├── test_borrow.rs
├── test_de.rs
├── test_de_error.rs
├── test_enum_adjacently_tagged.rs
├── test_enum_internally_tagged.rs
├── test_enum_untagged.rs
├── test_gen.rs
├── test_identifier.rs
├── test_ignored_any.rs
├── test_macros.rs
├── test_remote.rs
├── test_roundtrip.rs
├── test_self.rs
├── test_ser.rs
├── test_serde_path.rs
├── test_unstable.rs
├── test_value.rs
├── ui
├── borrow
│ ├── bad_lifetimes.rs
│ ├── bad_lifetimes.stderr
│ ├── duplicate_lifetime.rs
│ ├── duplicate_lifetime.stderr
│ ├── duplicate_variant.rs
│ ├── duplicate_variant.stderr
│ ├── empty_lifetimes.rs
│ ├── empty_lifetimes.stderr
│ ├── no_lifetimes.rs
│ ├── no_lifetimes.stderr
│ ├── struct_variant.rs
│ ├── struct_variant.stderr
│ ├── wrong_lifetime.rs
│ └── wrong_lifetime.stderr
├── conflict
│ ├── adjacent-tag.rs
│ ├── adjacent-tag.stderr
│ ├── alias-enum.rs
│ ├── alias-enum.stderr
│ ├── alias.rs
│ ├── alias.stderr
│ ├── flatten-newtype-struct.rs
│ ├── flatten-newtype-struct.stderr
│ ├── flatten-tuple-struct.rs
│ ├── flatten-tuple-struct.stderr
│ ├── from-try-from.rs
│ ├── from-try-from.stderr
│ ├── internal-tag-alias.rs
│ ├── internal-tag-alias.stderr
│ ├── internal-tag.rs
│ └── internal-tag.stderr
├── default-attribute
│ ├── enum.rs
│ ├── enum.stderr
│ ├── enum_path.rs
│ ├── enum_path.stderr
│ ├── incorrect_type_enum_adjacently_tagged.rs
│ ├── incorrect_type_enum_adjacently_tagged.stderr
│ ├── incorrect_type_enum_externally_tagged.rs
│ ├── incorrect_type_enum_externally_tagged.stderr
│ ├── incorrect_type_enum_internally_tagged.rs
│ ├── incorrect_type_enum_internally_tagged.stderr
│ ├── incorrect_type_enum_untagged.rs
│ ├── incorrect_type_enum_untagged.stderr
│ ├── incorrect_type_newtype.rs
│ ├── incorrect_type_newtype.stderr
│ ├── incorrect_type_struct.rs
│ ├── incorrect_type_struct.stderr
│ ├── incorrect_type_tuple.rs
│ ├── incorrect_type_tuple.stderr
│ ├── tuple_struct.rs
│ ├── tuple_struct.stderr
│ ├── tuple_struct_path.rs
│ ├── tuple_struct_path.stderr
│ ├── union.rs
│ ├── union.stderr
│ ├── union_path.rs
│ ├── union_path.stderr
│ ├── unit.rs
│ ├── unit.stderr
│ ├── unit_path.rs
│ └── unit_path.stderr
├── duplicate-attribute
│ ├── rename-and-ser.rs
│ ├── rename-and-ser.stderr
│ ├── rename-ser-rename-ser.rs
│ ├── rename-ser-rename-ser.stderr
│ ├── rename-ser-rename.rs
│ ├── rename-ser-rename.stderr
│ ├── rename-ser-ser.rs
│ ├── rename-ser-ser.stderr
│ ├── two-rename-ser.rs
│ ├── two-rename-ser.stderr
│ ├── with-and-serialize-with.rs
│ └── with-and-serialize-with.stderr
├── enum-representation
│ ├── content-no-tag.rs
│ ├── content-no-tag.stderr
│ ├── internal-tuple-variant.rs
│ ├── internal-tuple-variant.stderr
│ ├── partially_tagged_wrong_order.rs
│ ├── partially_tagged_wrong_order.stderr
│ ├── untagged-and-adjacent.rs
│ ├── untagged-and-adjacent.stderr
│ ├── untagged-and-content.rs
│ ├── untagged-and-content.stderr
│ ├── untagged-and-internal.rs
│ ├── untagged-and-internal.stderr
│ ├── untagged-struct.rs
│ └── untagged-struct.stderr
├── expected-string
│ ├── boolean.rs
│ ├── boolean.stderr
│ ├── byte_character.rs
│ ├── byte_character.stderr
│ ├── byte_string.rs
│ ├── byte_string.stderr
│ ├── character.rs
│ ├── character.stderr
│ ├── float.rs
│ ├── float.stderr
│ ├── integer.rs
│ └── integer.stderr
├── identifier
│ ├── both.rs
│ ├── both.stderr
│ ├── field_struct.rs
│ ├── field_struct.stderr
│ ├── field_tuple.rs
│ ├── field_tuple.stderr
│ ├── newtype_not_last.rs
│ ├── newtype_not_last.stderr
│ ├── not_unit.rs
│ ├── not_unit.stderr
│ ├── other_not_last.rs
│ ├── other_not_last.stderr
│ ├── other_untagged.rs
│ ├── other_untagged.stderr
│ ├── other_variant.rs
│ ├── other_variant.stderr
│ ├── variant_struct.rs
│ ├── variant_struct.stderr
│ ├── variant_tuple.rs
│ └── variant_tuple.stderr
├── malformed
│ ├── bound.rs
│ ├── bound.stderr
│ ├── cut_off.rs
│ ├── cut_off.stderr
│ ├── not_list.rs
│ ├── not_list.stderr
│ ├── rename.rs
│ ├── rename.stderr
│ ├── str_suffix.rs
│ ├── str_suffix.stderr
│ ├── trailing_expr.rs
│ └── trailing_expr.stderr
├── on_unimplemented.rs
├── on_unimplemented.stderr
├── precondition
│ ├── deserialize_de_lifetime.rs
│ ├── deserialize_de_lifetime.stderr
│ ├── deserialize_dst.rs
│ ├── deserialize_dst.stderr
│ ├── serialize_field_identifier.rs
│ ├── serialize_field_identifier.stderr
│ ├── serialize_variant_identifier.rs
│ └── serialize_variant_identifier.stderr
├── remote
│ ├── bad_getter.rs
│ ├── bad_getter.stderr
│ ├── bad_remote.rs
│ ├── bad_remote.stderr
│ ├── double_generic.rs
│ ├── double_generic.stderr
│ ├── enum_getter.rs
│ ├── enum_getter.stderr
│ ├── missing_field.rs
│ ├── missing_field.stderr
│ ├── nonremote_getter.rs
│ ├── nonremote_getter.stderr
│ ├── unknown_field.rs
│ ├── unknown_field.stderr
│ ├── wrong_de.rs
│ ├── wrong_de.stderr
│ ├── wrong_getter.rs
│ ├── wrong_getter.stderr
│ ├── wrong_ser.rs
│ └── wrong_ser.stderr
├── rename
│ ├── container_unknown_rename_rule.rs
│ ├── container_unknown_rename_rule.stderr
│ ├── variant_unknown_rename_rule.rs
│ └── variant_unknown_rename_rule.stderr
├── struct-representation
│ ├── internally-tagged-tuple.rs
│ ├── internally-tagged-tuple.stderr
│ ├── internally-tagged-unit.rs
│ └── internally-tagged-unit.stderr
├── transparent
│ ├── at_most_one.rs
│ ├── at_most_one.stderr
│ ├── de_at_least_one.rs
│ ├── de_at_least_one.stderr
│ ├── enum.rs
│ ├── enum.stderr
│ ├── ser_at_least_one.rs
│ ├── ser_at_least_one.stderr
│ ├── unit_struct.rs
│ ├── unit_struct.stderr
│ ├── with_from.rs
│ ├── with_from.stderr
│ ├── with_into.rs
│ ├── with_into.stderr
│ ├── with_try_from.rs
│ └── with_try_from.stderr
├── type-attribute
│ ├── from.rs
│ ├── from.stderr
│ ├── into.rs
│ ├── into.stderr
│ ├── try_from.rs
│ └── try_from.stderr
├── unexpected-literal
│ ├── container.rs
│ ├── container.stderr
│ ├── field.rs
│ ├── field.stderr
│ ├── variant.rs
│ └── variant.stderr
├── unknown-attribute
│ ├── container.rs
│ ├── container.stderr
│ ├── field.rs
│ ├── field.stderr
│ ├── variant.rs
│ └── variant.stderr
├── unsupported
│ ├── union_de.rs
│ ├── union_de.stderr
│ ├── union_ser.rs
│ └── union_ser.stderr
├── with-variant
│ ├── skip_de_newtype_field.rs
│ ├── skip_de_newtype_field.stderr
│ ├── skip_de_struct_field.rs
│ ├── skip_de_struct_field.stderr
│ ├── skip_de_tuple_field.rs
│ ├── skip_de_tuple_field.stderr
│ ├── skip_de_whole_variant.rs
│ ├── skip_de_whole_variant.stderr
│ ├── skip_ser_newtype_field.rs
│ ├── skip_ser_newtype_field.stderr
│ ├── skip_ser_newtype_field_if.rs
│ ├── skip_ser_newtype_field_if.stderr
│ ├── skip_ser_struct_field.rs
│ ├── skip_ser_struct_field.stderr
│ ├── skip_ser_struct_field_if.rs
│ ├── skip_ser_struct_field_if.stderr
│ ├── skip_ser_tuple_field.rs
│ ├── skip_ser_tuple_field.stderr
│ ├── skip_ser_tuple_field_if.rs
│ ├── skip_ser_tuple_field_if.stderr
│ ├── skip_ser_whole_variant.rs
│ └── skip_ser_whole_variant.stderr
└── with
│ ├── incorrect_type.rs
│ └── incorrect_type.stderr
└── unstable
└── mod.rs
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: dtolnay
2 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/1-problem.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Problem
3 | about: Something does not seem right
4 |
5 | ---
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/2-suggestion.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Suggestion
3 | about: Share how Serde could support your use case better
4 |
5 | ---
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/3-documentation.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Documentation
3 | about: Certainly there is room for improvement
4 |
5 | ---
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/4-other.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Anything else!
3 | about: Whatever is on your mind
4 |
5 | ---
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | /Cargo.lock
3 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to Serde
2 |
3 | Serde welcomes contribution from everyone in the form of suggestions, bug
4 | reports, pull requests, and feedback. This document gives some guidance if you
5 | are thinking of helping us.
6 |
7 | ## Submitting bug reports and feature requests
8 |
9 | Serde development is spread across lots of repositories, but this serde-rs/serde
10 | repository is always a safe choice for opening any issues related to Serde.
11 |
12 | When reporting a bug or asking for help, please include enough details so that
13 | the people helping you can reproduce the behavior you are seeing. For some tips
14 | on how to approach this, read about how to produce a [Minimal, Complete, and
15 | Verifiable example].
16 |
17 | [Minimal, Complete, and Verifiable example]: https://stackoverflow.com/help/mcve
18 |
19 | When making a feature request, please make it clear what problem you intend to
20 | solve with the feature, any ideas for how Serde could support solving that
21 | problem, any possible alternatives, and any disadvantages.
22 |
23 | ## Running the test suite
24 |
25 | We encourage you to check that the test suite passes locally before submitting a
26 | pull request with your changes. If anything does not pass, typically it will be
27 | easier to iterate and fix it locally than waiting for the CI servers to run
28 | tests for you.
29 |
30 | ##### In the [`serde`] directory
31 |
32 | ```sh
33 | # Test all the example code in Serde documentation
34 | cargo test --features derive
35 | ```
36 |
37 | ##### In the [`test_suite`] directory
38 |
39 | ```sh
40 | # Run the full test suite, including tests of unstable functionality
41 | cargo +nightly test --features unstable
42 | ```
43 |
44 | Note that this test suite currently only supports running on a nightly compiler.
45 |
46 | [`serde`]: https://github.com/serde-rs/serde/tree/master/serde
47 | [`test_suite`]: https://github.com/serde-rs/serde/tree/master/test_suite
48 |
49 | ## Conduct
50 |
51 | In all Serde-related forums, we follow the [Rust Code of Conduct]. For
52 | escalation or moderation issues please contact Erick (erick.tryzelaar@gmail.com)
53 | instead of the Rust moderation team.
54 |
55 | [Rust Code of Conduct]: https://www.rust-lang.org/policies/code-of-conduct
56 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [workspace]
2 | members = [
3 | "serde",
4 | "serde_derive",
5 | "serde_derive_internals",
6 | "test_suite",
7 | ]
8 | resolver = "2"
9 |
10 | [patch.crates-io]
11 | serde = { path = "serde" }
12 |
13 | [workspace.dependencies]
14 | proc-macro2 = { version = "1.0.74", default-features = false }
15 | quote = { version = "1.0.35", default-features = false }
16 | syn = { version = "2.0.81", default-features = false }
17 |
--------------------------------------------------------------------------------
/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | Permission is hereby granted, free of charge, to any
2 | person obtaining a copy of this software and associated
3 | documentation files (the "Software"), to deal in the
4 | Software without restriction, including without
5 | limitation the rights to use, copy, modify, merge,
6 | publish, distribute, sublicense, and/or sell copies of
7 | the Software, and to permit persons to whom the Software
8 | is furnished to do so, subject to the following
9 | conditions:
10 |
11 | The above copyright notice and this permission notice
12 | shall be included in all copies or substantial portions
13 | of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23 | DEALINGS IN THE SOFTWARE.
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Serde [![Build Status]][actions] [![Latest Version]][crates.io] [![serde msrv]][Rust 1.56] [![serde_derive msrv]][Rust 1.61]
2 |
3 | [Build Status]: https://img.shields.io/github/actions/workflow/status/serde-rs/serde/ci.yml?branch=master
4 | [actions]: https://github.com/serde-rs/serde/actions?query=branch%3Amaster
5 | [Latest Version]: https://img.shields.io/crates/v/serde.svg
6 | [crates.io]: https://crates.io/crates/serde
7 | [serde msrv]: https://img.shields.io/crates/msrv/serde.svg?label=serde%20msrv&color=lightgray
8 | [serde_derive msrv]: https://img.shields.io/crates/msrv/serde_derive.svg?label=serde_derive%20msrv&color=lightgray
9 | [Rust 1.56]: https://blog.rust-lang.org/2021/10/21/Rust-1.56.0.html
10 | [Rust 1.61]: https://blog.rust-lang.org/2022/05/19/Rust-1.61.0.html
11 |
12 | **Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.**
13 |
14 | ---
15 |
16 | You may be looking for:
17 |
18 | - [An overview of Serde](https://serde.rs/)
19 | - [Data formats supported by Serde](https://serde.rs/#data-formats)
20 | - [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html)
21 | - [Examples](https://serde.rs/examples.html)
22 | - [API documentation](https://docs.rs/serde)
23 | - [Release notes](https://github.com/serde-rs/serde/releases)
24 |
25 | ## Serde in action
26 |
27 |
28 |
29 | Click to show Cargo.toml.
30 | Run this code in the playground.
31 |
32 |
33 | ```toml
34 | [dependencies]
35 |
36 | # The core APIs, including the Serialize and Deserialize traits. Always
37 | # required when using Serde. The "derive" feature is only required when
38 | # using #[derive(Serialize, Deserialize)] to make Serde work with structs
39 | # and enums defined in your crate.
40 | serde = { version = "1.0", features = ["derive"] }
41 |
42 | # Each data format lives in its own crate; the sample code below uses JSON
43 | # but you may be using a different one.
44 | serde_json = "1.0"
45 | ```
46 |
47 |
48 |
49 |
50 | ```rust
51 | use serde::{Deserialize, Serialize};
52 |
53 | #[derive(Serialize, Deserialize, Debug)]
54 | struct Point {
55 | x: i32,
56 | y: i32,
57 | }
58 |
59 | fn main() {
60 | let point = Point { x: 1, y: 2 };
61 |
62 | // Convert the Point to a JSON string.
63 | let serialized = serde_json::to_string(&point).unwrap();
64 |
65 | // Prints serialized = {"x":1,"y":2}
66 | println!("serialized = {}", serialized);
67 |
68 | // Convert the JSON string back to a Point.
69 | let deserialized: Point = serde_json::from_str(&serialized).unwrap();
70 |
71 | // Prints deserialized = Point { x: 1, y: 2 }
72 | println!("deserialized = {:?}", deserialized);
73 | }
74 | ```
75 |
76 | ## Getting help
77 |
78 | Serde is one of the most widely used Rust libraries so any place that Rustaceans
79 | congregate will be able to help you out. For chat, consider trying the
80 | [#rust-questions] or [#rust-beginners] channels of the unofficial community
81 | Discord (invite: ), the [#rust-usage] or
82 | [#beginners] channels of the official Rust Project Discord (invite:
83 | ), or the [#general][zulip] stream in Zulip. For
84 | asynchronous, consider the [\[rust\] tag on StackOverflow][stackoverflow], the
85 | [/r/rust] subreddit which has a pinned weekly easy questions post, or the Rust
86 | [Discourse forum][discourse]. It's acceptable to file a support issue in this
87 | repo but they tend not to get as many eyes as any of the above and may get
88 | closed without a response after some time.
89 |
90 | [#rust-questions]: https://discord.com/channels/273534239310479360/274215136414400513
91 | [#rust-beginners]: https://discord.com/channels/273534239310479360/273541522815713281
92 | [#rust-usage]: https://discord.com/channels/442252698964721669/443150878111694848
93 | [#beginners]: https://discord.com/channels/442252698964721669/448238009733742612
94 | [zulip]: https://rust-lang.zulipchat.com/#narrow/stream/122651-general
95 | [stackoverflow]: https://stackoverflow.com/questions/tagged/rust
96 | [/r/rust]: https://www.reddit.com/r/rust
97 | [discourse]: https://users.rust-lang.org
98 |
99 |
100 |
101 | #### License
102 |
103 |
104 | Licensed under either of Apache License, Version
105 | 2.0 or MIT license at your option.
106 |
107 |
108 |
109 |
110 |
111 | Unless you explicitly state otherwise, any contribution intentionally submitted
112 | for inclusion in Serde by you, as defined in the Apache-2.0 license, shall be
113 | dual licensed as above, without any additional terms or conditions.
114 |
115 |
--------------------------------------------------------------------------------
/crates-io.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | **Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.**
4 |
5 | ---
6 |
7 | You may be looking for:
8 |
9 | - [An overview of Serde](https://serde.rs/)
10 | - [Data formats supported by Serde](https://serde.rs/#data-formats)
11 | - [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html)
12 | - [Examples](https://serde.rs/examples.html)
13 | - [API documentation](https://docs.rs/serde)
14 | - [Release notes](https://github.com/serde-rs/serde/releases)
15 |
16 | ## Serde in action
17 |
18 | ```rust
19 | use serde::{Deserialize, Serialize};
20 |
21 | #[derive(Serialize, Deserialize, Debug)]
22 | struct Point {
23 | x: i32,
24 | y: i32,
25 | }
26 |
27 | fn main() {
28 | let point = Point { x: 1, y: 2 };
29 |
30 | // Convert the Point to a JSON string.
31 | let serialized = serde_json::to_string(&point).unwrap();
32 |
33 | // Prints serialized = {"x":1,"y":2}
34 | println!("serialized = {}", serialized);
35 |
36 | // Convert the JSON string back to a Point.
37 | let deserialized: Point = serde_json::from_str(&serialized).unwrap();
38 |
39 | // Prints deserialized = Point { x: 1, y: 2 }
40 | println!("deserialized = {:?}", deserialized);
41 | }
42 | ```
43 |
44 | ## Getting help
45 |
46 | Serde is one of the most widely used Rust libraries so any place that Rustaceans
47 | congregate will be able to help you out. For chat, consider trying the
48 | [#rust-questions] or [#rust-beginners] channels of the unofficial community
49 | Discord (invite: ), the [#rust-usage]
50 | or [#beginners] channels of the official Rust Project Discord (invite:
51 | ), or the [#general][zulip] stream in Zulip. For
52 | asynchronous, consider the [\[rust\] tag on StackOverflow][stackoverflow], the
53 | [/r/rust] subreddit which has a pinned weekly easy questions post, or the Rust
54 | [Discourse forum][discourse]. It's acceptable to file a support issue in this
55 | repo but they tend not to get as many eyes as any of the above and may get
56 | closed without a response after some time.
57 |
58 | [#rust-questions]: https://discord.com/channels/273534239310479360/274215136414400513
59 | [#rust-beginners]: https://discord.com/channels/273534239310479360/273541522815713281
60 | [#rust-usage]: https://discord.com/channels/442252698964721669/443150878111694848
61 | [#beginners]: https://discord.com/channels/442252698964721669/448238009733742612
62 | [zulip]: https://rust-lang.zulipchat.com/#narrow/stream/122651-general
63 | [stackoverflow]: https://stackoverflow.com/questions/tagged/rust
64 | [/r/rust]: https://www.reddit.com/r/rust
65 | [discourse]: https://users.rust-lang.org
66 |
--------------------------------------------------------------------------------
/serde/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "serde"
3 | version = "1.0.219"
4 | authors = ["Erick Tryzelaar ", "David Tolnay "]
5 | build = "build.rs"
6 | categories = ["encoding", "no-std", "no-std::no-alloc"]
7 | description = "A generic serialization/deserialization framework"
8 | documentation = "https://docs.rs/serde"
9 | edition = "2021"
10 | homepage = "https://serde.rs"
11 | keywords = ["serde", "serialization", "no_std"]
12 | license = "MIT OR Apache-2.0"
13 | readme = "crates-io.md"
14 | repository = "https://github.com/serde-rs/serde"
15 | rust-version = "1.56"
16 |
17 | [dependencies]
18 | serde_derive = { version = "1", optional = true, path = "../serde_derive" }
19 |
20 | [dev-dependencies]
21 | serde_derive = { version = "1", path = "../serde_derive" }
22 |
23 | [package.metadata.playground]
24 | features = ["derive", "rc"]
25 |
26 | [package.metadata.docs.rs]
27 | features = ["derive", "rc", "unstable"]
28 | targets = ["x86_64-unknown-linux-gnu"]
29 | rustdoc-args = [
30 | "--generate-link-to-definition",
31 | "--extern-html-root-url=core=https://doc.rust-lang.org",
32 | "--extern-html-root-url=alloc=https://doc.rust-lang.org",
33 | "--extern-html-root-url=std=https://doc.rust-lang.org",
34 | ]
35 |
36 | # This cfg cannot be enabled, but it still forces Cargo to keep serde_derive's
37 | # version in lockstep with serde's, even if someone depends on the two crates
38 | # separately with serde's "derive" feature disabled. Every serde_derive release
39 | # is compatible with exactly one serde release because the generated code
40 | # involves nonpublic APIs which are not bound by semver.
41 | [target.'cfg(any())'.dependencies]
42 | serde_derive = { version = "=1.0.219", path = "../serde_derive" }
43 |
44 |
45 | ### FEATURES #################################################################
46 |
47 | [features]
48 | default = ["std"]
49 |
50 | # Provide derive(Serialize, Deserialize) macros.
51 | derive = ["serde_derive"]
52 |
53 | # Provide impls for common standard library types like Vec and HashMap.
54 | # Requires a dependency on the Rust standard library.
55 | std = []
56 |
57 | # Provide impls for types that require unstable functionality. For tracking and
58 | # discussion of unstable functionality please refer to this issue:
59 | #
60 | # https://github.com/serde-rs/serde/issues/812
61 | unstable = []
62 |
63 | # Provide impls for types in the Rust core allocation and collections library
64 | # including String, Box, Vec, and Cow. This is a subset of std but may
65 | # be enabled without depending on all of std.
66 | alloc = []
67 |
68 | # Opt into impls for Rc and Arc. Serializing and deserializing these types
69 | # does not preserve identity and may result in multiple copies of the same data.
70 | # Be sure that this is what you want before enabling this feature.
71 | rc = []
72 |
--------------------------------------------------------------------------------
/serde/LICENSE-APACHE:
--------------------------------------------------------------------------------
1 | ../LICENSE-APACHE
--------------------------------------------------------------------------------
/serde/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | ../LICENSE-MIT
--------------------------------------------------------------------------------
/serde/README.md:
--------------------------------------------------------------------------------
1 | ../README.md
--------------------------------------------------------------------------------
/serde/build.rs:
--------------------------------------------------------------------------------
1 | use std::env;
2 | use std::process::Command;
3 | use std::str;
4 |
5 | // The rustc-cfg strings below are *not* public API. Please let us know by
6 | // opening a GitHub issue if your build environment requires some way to enable
7 | // these cfgs other than by executing our build script.
8 | fn main() {
9 | println!("cargo:rerun-if-changed=build.rs");
10 |
11 | let minor = match rustc_minor_version() {
12 | Some(minor) => minor,
13 | None => return,
14 | };
15 |
16 | if minor >= 77 {
17 | println!("cargo:rustc-check-cfg=cfg(no_core_cstr)");
18 | println!("cargo:rustc-check-cfg=cfg(no_core_error)");
19 | println!("cargo:rustc-check-cfg=cfg(no_core_net)");
20 | println!("cargo:rustc-check-cfg=cfg(no_core_num_saturating)");
21 | println!("cargo:rustc-check-cfg=cfg(no_diagnostic_namespace)");
22 | println!("cargo:rustc-check-cfg=cfg(no_serde_derive)");
23 | println!("cargo:rustc-check-cfg=cfg(no_std_atomic)");
24 | println!("cargo:rustc-check-cfg=cfg(no_std_atomic64)");
25 | println!("cargo:rustc-check-cfg=cfg(no_target_has_atomic)");
26 | }
27 |
28 | let target = env::var("TARGET").unwrap();
29 | let emscripten = target == "asmjs-unknown-emscripten" || target == "wasm32-unknown-emscripten";
30 |
31 | // Support for #[cfg(target_has_atomic = "...")] stabilized in Rust 1.60.
32 | if minor < 60 {
33 | println!("cargo:rustc-cfg=no_target_has_atomic");
34 | // Allowlist of archs that support std::sync::atomic module. This is
35 | // based on rustc's compiler/rustc_target/src/spec/*.rs.
36 | let has_atomic64 = target.starts_with("x86_64")
37 | || target.starts_with("i686")
38 | || target.starts_with("aarch64")
39 | || target.starts_with("powerpc64")
40 | || target.starts_with("sparc64")
41 | || target.starts_with("mips64el")
42 | || target.starts_with("riscv64");
43 | let has_atomic32 = has_atomic64 || emscripten;
44 | if minor < 34 || !has_atomic64 {
45 | println!("cargo:rustc-cfg=no_std_atomic64");
46 | }
47 | if minor < 34 || !has_atomic32 {
48 | println!("cargo:rustc-cfg=no_std_atomic");
49 | }
50 | }
51 |
52 | // Current minimum supported version of serde_derive crate is Rust 1.61.
53 | if minor < 61 {
54 | println!("cargo:rustc-cfg=no_serde_derive");
55 | }
56 |
57 | // Support for core::ffi::CStr and alloc::ffi::CString stabilized in Rust 1.64.
58 | // https://blog.rust-lang.org/2022/09/22/Rust-1.64.0.html#c-compatible-ffi-types-in-core-and-alloc
59 | if minor < 64 {
60 | println!("cargo:rustc-cfg=no_core_cstr");
61 | }
62 |
63 | // Support for core::num::Saturating and std::num::Saturating stabilized in Rust 1.74
64 | // https://blog.rust-lang.org/2023/11/16/Rust-1.74.0.html#stabilized-apis
65 | if minor < 74 {
66 | println!("cargo:rustc-cfg=no_core_num_saturating");
67 | }
68 |
69 | // Support for core::net stabilized in Rust 1.77.
70 | // https://blog.rust-lang.org/2024/03/21/Rust-1.77.0.html
71 | if minor < 77 {
72 | println!("cargo:rustc-cfg=no_core_net");
73 | }
74 |
75 | // Support for the `#[diagnostic]` tool attribute namespace
76 | // https://blog.rust-lang.org/2024/05/02/Rust-1.78.0.html#diagnostic-attributes
77 | if minor < 78 {
78 | println!("cargo:rustc-cfg=no_diagnostic_namespace");
79 | }
80 |
81 | // The Error trait became available in core in 1.81.
82 | // https://blog.rust-lang.org/2024/09/05/Rust-1.81.0.html#coreerrorerror
83 | if minor < 81 {
84 | println!("cargo:rustc-cfg=no_core_error");
85 | }
86 | }
87 |
88 | fn rustc_minor_version() -> Option {
89 | let rustc = env::var_os("RUSTC")?;
90 | let output = Command::new(rustc).arg("--version").output().ok()?;
91 | let version = str::from_utf8(&output.stdout).ok()?;
92 | let mut pieces = version.split('.');
93 | if pieces.next() != Some("rustc 1") {
94 | return None;
95 | }
96 | pieces.next()?.parse().ok()
97 | }
98 |
--------------------------------------------------------------------------------
/serde/crates-io.md:
--------------------------------------------------------------------------------
1 | ../crates-io.md
--------------------------------------------------------------------------------
/serde/src/de/seed.rs:
--------------------------------------------------------------------------------
1 | use crate::de::{Deserialize, DeserializeSeed, Deserializer};
2 |
3 | /// A DeserializeSeed helper for implementing deserialize_in_place Visitors.
4 | ///
5 | /// Wraps a mutable reference and calls deserialize_in_place on it.
6 | pub struct InPlaceSeed<'a, T: 'a>(pub &'a mut T);
7 |
8 | impl<'a, 'de, T> DeserializeSeed<'de> for InPlaceSeed<'a, T>
9 | where
10 | T: Deserialize<'de>,
11 | {
12 | type Value = ();
13 | fn deserialize(self, deserializer: D) -> Result
14 | where
15 | D: Deserializer<'de>,
16 | {
17 | T::deserialize_in_place(deserializer, self.0)
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/serde/src/de/size_hint.rs:
--------------------------------------------------------------------------------
1 | #[cfg(any(feature = "std", feature = "alloc"))]
2 | use crate::lib::*;
3 |
4 | pub fn from_bounds(iter: &I) -> Option
5 | where
6 | I: Iterator,
7 | {
8 | helper(iter.size_hint())
9 | }
10 |
11 | #[cfg(any(feature = "std", feature = "alloc"))]
12 | pub fn cautious(hint: Option) -> usize {
13 | const MAX_PREALLOC_BYTES: usize = 1024 * 1024;
14 |
15 | if mem::size_of::() == 0 {
16 | 0
17 | } else {
18 | cmp::min(
19 | hint.unwrap_or(0),
20 | MAX_PREALLOC_BYTES / mem::size_of::(),
21 | )
22 | }
23 | }
24 |
25 | fn helper(bounds: (usize, Option)) -> Option {
26 | match bounds {
27 | (lower, Some(upper)) if lower == upper => Some(upper),
28 | _ => None,
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/serde/src/format.rs:
--------------------------------------------------------------------------------
1 | use crate::lib::fmt::{self, Write};
2 | use crate::lib::str;
3 |
4 | pub(super) struct Buf<'a> {
5 | bytes: &'a mut [u8],
6 | offset: usize,
7 | }
8 |
9 | impl<'a> Buf<'a> {
10 | pub fn new(bytes: &'a mut [u8]) -> Self {
11 | Buf { bytes, offset: 0 }
12 | }
13 |
14 | pub fn as_str(&self) -> &str {
15 | let slice = &self.bytes[..self.offset];
16 | unsafe { str::from_utf8_unchecked(slice) }
17 | }
18 | }
19 |
20 | impl<'a> Write for Buf<'a> {
21 | fn write_str(&mut self, s: &str) -> fmt::Result {
22 | if self.offset + s.len() > self.bytes.len() {
23 | Err(fmt::Error)
24 | } else {
25 | self.bytes[self.offset..self.offset + s.len()].copy_from_slice(s.as_bytes());
26 | self.offset += s.len();
27 | Ok(())
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/serde/src/integer128.rs:
--------------------------------------------------------------------------------
1 | // No longer used. Old versions of serde used this macro for supporting targets
2 | // that did not yet have 128-bit integer support.
3 | #[macro_export]
4 | #[doc(hidden)]
5 | macro_rules! serde_if_integer128 {
6 | ($($tt:tt)*) => {
7 | $($tt)*
8 | };
9 | }
10 |
--------------------------------------------------------------------------------
/serde/src/private/doc.rs:
--------------------------------------------------------------------------------
1 | // Used only by Serde doc tests. Not public API.
2 |
3 | use crate::lib::*;
4 |
5 | use crate::ser;
6 |
7 | #[doc(hidden)]
8 | #[derive(Debug)]
9 | pub struct Error;
10 |
11 | impl ser::Error for Error {
12 | fn custom(_: T) -> Self
13 | where
14 | T: Display,
15 | {
16 | unimplemented!()
17 | }
18 | }
19 |
20 | #[cfg(feature = "std")]
21 | impl error::Error for Error {
22 | fn description(&self) -> &str {
23 | unimplemented!()
24 | }
25 | }
26 |
27 | impl Display for Error {
28 | fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
29 | unimplemented!()
30 | }
31 | }
32 |
33 | #[doc(hidden)]
34 | #[macro_export]
35 | macro_rules! __private_serialize {
36 | () => {
37 | trait Serialize {
38 | fn serialize(&self, serializer: S) -> Result
39 | where
40 | S: $crate::Serializer;
41 | }
42 | };
43 | }
44 |
45 | #[doc(hidden)]
46 | #[macro_export(local_inner_macros)]
47 | macro_rules! __serialize_unimplemented {
48 | ($($func:ident)*) => {
49 | $(
50 | __serialize_unimplemented_helper!($func);
51 | )*
52 | };
53 | }
54 |
55 | #[doc(hidden)]
56 | #[macro_export]
57 | macro_rules! __serialize_unimplemented_method {
58 | ($func:ident $(<$t:ident>)* ($($arg:ty),*) -> $ret:ident) => {
59 | fn $func $(<$t>)* (self $(, _: $arg)*) -> $crate::__private::Result
60 | where
61 | $($t: ?Sized + $crate::Serialize,)*
62 | {
63 | unimplemented!()
64 | }
65 | };
66 | }
67 |
68 | #[doc(hidden)]
69 | #[macro_export(local_inner_macros)]
70 | macro_rules! __serialize_unimplemented_helper {
71 | (bool) => {
72 | __serialize_unimplemented_method!(serialize_bool(bool) -> Ok);
73 | };
74 | (i8) => {
75 | __serialize_unimplemented_method!(serialize_i8(i8) -> Ok);
76 | };
77 | (i16) => {
78 | __serialize_unimplemented_method!(serialize_i16(i16) -> Ok);
79 | };
80 | (i32) => {
81 | __serialize_unimplemented_method!(serialize_i32(i32) -> Ok);
82 | };
83 | (i64) => {
84 | __serialize_unimplemented_method!(serialize_i64(i64) -> Ok);
85 | };
86 | (u8) => {
87 | __serialize_unimplemented_method!(serialize_u8(u8) -> Ok);
88 | };
89 | (u16) => {
90 | __serialize_unimplemented_method!(serialize_u16(u16) -> Ok);
91 | };
92 | (u32) => {
93 | __serialize_unimplemented_method!(serialize_u32(u32) -> Ok);
94 | };
95 | (u64) => {
96 | __serialize_unimplemented_method!(serialize_u64(u64) -> Ok);
97 | };
98 | (f32) => {
99 | __serialize_unimplemented_method!(serialize_f32(f32) -> Ok);
100 | };
101 | (f64) => {
102 | __serialize_unimplemented_method!(serialize_f64(f64) -> Ok);
103 | };
104 | (char) => {
105 | __serialize_unimplemented_method!(serialize_char(char) -> Ok);
106 | };
107 | (str) => {
108 | __serialize_unimplemented_method!(serialize_str(&str) -> Ok);
109 | };
110 | (bytes) => {
111 | __serialize_unimplemented_method!(serialize_bytes(&[u8]) -> Ok);
112 | };
113 | (none) => {
114 | __serialize_unimplemented_method!(serialize_none() -> Ok);
115 | };
116 | (some) => {
117 | __serialize_unimplemented_method!(serialize_some(&T) -> Ok);
118 | };
119 | (unit) => {
120 | __serialize_unimplemented_method!(serialize_unit() -> Ok);
121 | };
122 | (unit_struct) => {
123 | __serialize_unimplemented_method!(serialize_unit_struct(&str) -> Ok);
124 | };
125 | (unit_variant) => {
126 | __serialize_unimplemented_method!(serialize_unit_variant(&str, u32, &str) -> Ok);
127 | };
128 | (newtype_struct) => {
129 | __serialize_unimplemented_method!(serialize_newtype_struct(&str, &T) -> Ok);
130 | };
131 | (newtype_variant) => {
132 | __serialize_unimplemented_method!(serialize_newtype_variant(&str, u32, &str, &T) -> Ok);
133 | };
134 | (seq) => {
135 | type SerializeSeq = $crate::ser::Impossible;
136 | __serialize_unimplemented_method!(serialize_seq(Option) -> SerializeSeq);
137 | };
138 | (tuple) => {
139 | type SerializeTuple = $crate::ser::Impossible;
140 | __serialize_unimplemented_method!(serialize_tuple(usize) -> SerializeTuple);
141 | };
142 | (tuple_struct) => {
143 | type SerializeTupleStruct = $crate::ser::Impossible;
144 | __serialize_unimplemented_method!(serialize_tuple_struct(&str, usize) -> SerializeTupleStruct);
145 | };
146 | (tuple_variant) => {
147 | type SerializeTupleVariant = $crate::ser::Impossible;
148 | __serialize_unimplemented_method!(serialize_tuple_variant(&str, u32, &str, usize) -> SerializeTupleVariant);
149 | };
150 | (map) => {
151 | type SerializeMap = $crate::ser::Impossible;
152 | __serialize_unimplemented_method!(serialize_map(Option) -> SerializeMap);
153 | };
154 | (struct) => {
155 | type SerializeStruct = $crate::ser::Impossible;
156 | __serialize_unimplemented_method!(serialize_struct(&str, usize) -> SerializeStruct);
157 | };
158 | (struct_variant) => {
159 | type SerializeStructVariant = $crate::ser::Impossible;
160 | __serialize_unimplemented_method!(serialize_struct_variant(&str, u32, &str, usize) -> SerializeStructVariant);
161 | };
162 | }
163 |
--------------------------------------------------------------------------------
/serde/src/private/mod.rs:
--------------------------------------------------------------------------------
1 | #[cfg(not(no_serde_derive))]
2 | pub mod de;
3 | #[cfg(not(no_serde_derive))]
4 | pub mod ser;
5 |
6 | // FIXME: #[cfg(doctest)] once https://github.com/rust-lang/rust/issues/67295 is fixed.
7 | pub mod doc;
8 |
9 | pub use crate::lib::clone::Clone;
10 | pub use crate::lib::convert::{From, Into, TryFrom};
11 | pub use crate::lib::default::Default;
12 | pub use crate::lib::fmt::{self, Formatter};
13 | pub use crate::lib::marker::PhantomData;
14 | pub use crate::lib::option::Option::{self, None, Some};
15 | pub use crate::lib::ptr;
16 | pub use crate::lib::result::Result::{self, Err, Ok};
17 |
18 | pub use self::string::from_utf8_lossy;
19 |
20 | #[cfg(any(feature = "alloc", feature = "std"))]
21 | pub use crate::lib::{ToString, Vec};
22 |
23 | mod string {
24 | use crate::lib::*;
25 |
26 | #[cfg(any(feature = "std", feature = "alloc"))]
27 | pub fn from_utf8_lossy(bytes: &[u8]) -> Cow {
28 | String::from_utf8_lossy(bytes)
29 | }
30 |
31 | // The generated code calls this like:
32 | //
33 | // let value = &_serde::__private::from_utf8_lossy(bytes);
34 | // Err(_serde::de::Error::unknown_variant(value, VARIANTS))
35 | //
36 | // so it is okay for the return type to be different from the std case as long
37 | // as the above works.
38 | #[cfg(not(any(feature = "std", feature = "alloc")))]
39 | pub fn from_utf8_lossy(bytes: &[u8]) -> &str {
40 | // Three unicode replacement characters if it fails. They look like a
41 | // white-on-black question mark. The user will recognize it as invalid
42 | // UTF-8.
43 | str::from_utf8(bytes).unwrap_or("\u{fffd}\u{fffd}\u{fffd}")
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/serde/src/ser/fmt.rs:
--------------------------------------------------------------------------------
1 | use crate::lib::*;
2 | use crate::ser::{Error, Impossible, Serialize, Serializer};
3 |
4 | impl Error for fmt::Error {
5 | fn custom(_msg: T) -> Self {
6 | fmt::Error
7 | }
8 | }
9 |
10 | macro_rules! fmt_primitives {
11 | ($($f:ident: $t:ty,)*) => {
12 | $(
13 | fn $f(self, v: $t) -> fmt::Result {
14 | Display::fmt(&v, self)
15 | }
16 | )*
17 | };
18 | }
19 |
20 | /// ```edition2021
21 | /// use serde::ser::Serialize;
22 | /// use serde_derive::Serialize;
23 | /// use std::fmt::{self, Display};
24 | ///
25 | /// #[derive(Serialize)]
26 | /// #[serde(rename_all = "kebab-case")]
27 | /// pub enum MessageType {
28 | /// StartRequest,
29 | /// EndRequest,
30 | /// }
31 | ///
32 | /// impl Display for MessageType {
33 | /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34 | /// self.serialize(f)
35 | /// }
36 | /// }
37 | /// ```
38 | impl<'a> Serializer for &mut fmt::Formatter<'a> {
39 | type Ok = ();
40 | type Error = fmt::Error;
41 | type SerializeSeq = Impossible<(), fmt::Error>;
42 | type SerializeTuple = Impossible<(), fmt::Error>;
43 | type SerializeTupleStruct = Impossible<(), fmt::Error>;
44 | type SerializeTupleVariant = Impossible<(), fmt::Error>;
45 | type SerializeMap = Impossible<(), fmt::Error>;
46 | type SerializeStruct = Impossible<(), fmt::Error>;
47 | type SerializeStructVariant = Impossible<(), fmt::Error>;
48 |
49 | fmt_primitives! {
50 | serialize_bool: bool,
51 | serialize_i8: i8,
52 | serialize_i16: i16,
53 | serialize_i32: i32,
54 | serialize_i64: i64,
55 | serialize_i128: i128,
56 | serialize_u8: u8,
57 | serialize_u16: u16,
58 | serialize_u32: u32,
59 | serialize_u64: u64,
60 | serialize_u128: u128,
61 | serialize_f32: f32,
62 | serialize_f64: f64,
63 | serialize_char: char,
64 | serialize_str: &str,
65 | serialize_unit_struct: &'static str,
66 | }
67 |
68 | fn serialize_unit_variant(
69 | self,
70 | _name: &'static str,
71 | _variant_index: u32,
72 | variant: &'static str,
73 | ) -> fmt::Result {
74 | Display::fmt(variant, self)
75 | }
76 |
77 | fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> fmt::Result
78 | where
79 | T: ?Sized + Serialize,
80 | {
81 | Serialize::serialize(value, self)
82 | }
83 |
84 | fn serialize_bytes(self, _v: &[u8]) -> fmt::Result {
85 | Err(fmt::Error)
86 | }
87 |
88 | fn serialize_none(self) -> fmt::Result {
89 | Err(fmt::Error)
90 | }
91 |
92 | fn serialize_some(self, _value: &T) -> fmt::Result
93 | where
94 | T: ?Sized + Serialize,
95 | {
96 | Err(fmt::Error)
97 | }
98 |
99 | fn serialize_unit(self) -> fmt::Result {
100 | Err(fmt::Error)
101 | }
102 |
103 | fn serialize_newtype_variant(
104 | self,
105 | _name: &'static str,
106 | _variant_index: u32,
107 | _variant: &'static str,
108 | _value: &T,
109 | ) -> fmt::Result
110 | where
111 | T: ?Sized + Serialize,
112 | {
113 | Err(fmt::Error)
114 | }
115 |
116 | fn serialize_seq(self, _len: Option) -> Result {
117 | Err(fmt::Error)
118 | }
119 |
120 | fn serialize_tuple(self, _len: usize) -> Result {
121 | Err(fmt::Error)
122 | }
123 |
124 | fn serialize_tuple_struct(
125 | self,
126 | _name: &'static str,
127 | _len: usize,
128 | ) -> Result {
129 | Err(fmt::Error)
130 | }
131 |
132 | fn serialize_tuple_variant(
133 | self,
134 | _name: &'static str,
135 | _variant_index: u32,
136 | _variant: &'static str,
137 | _len: usize,
138 | ) -> Result {
139 | Err(fmt::Error)
140 | }
141 |
142 | fn serialize_map(self, _len: Option) -> Result {
143 | Err(fmt::Error)
144 | }
145 |
146 | fn serialize_struct(
147 | self,
148 | _name: &'static str,
149 | _len: usize,
150 | ) -> Result {
151 | Err(fmt::Error)
152 | }
153 |
154 | fn serialize_struct_variant(
155 | self,
156 | _name: &'static str,
157 | _variant_index: u32,
158 | _variant: &'static str,
159 | _len: usize,
160 | ) -> Result {
161 | Err(fmt::Error)
162 | }
163 |
164 | fn collect_str(self, value: &T) -> fmt::Result
165 | where
166 | T: ?Sized + Display,
167 | {
168 | Display::fmt(value, self)
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/serde/src/ser/impossible.rs:
--------------------------------------------------------------------------------
1 | //! This module contains `Impossible` serializer and its implementations.
2 |
3 | use crate::lib::*;
4 |
5 | use crate::ser::{
6 | self, Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant,
7 | SerializeTuple, SerializeTupleStruct, SerializeTupleVariant,
8 | };
9 |
10 | /// Helper type for implementing a `Serializer` that does not support
11 | /// serializing one of the compound types.
12 | ///
13 | /// This type cannot be instantiated, but implements every one of the traits
14 | /// corresponding to the [`Serializer`] compound types: [`SerializeSeq`],
15 | /// [`SerializeTuple`], [`SerializeTupleStruct`], [`SerializeTupleVariant`],
16 | /// [`SerializeMap`], [`SerializeStruct`], and [`SerializeStructVariant`].
17 | ///
18 | /// ```edition2021
19 | /// # use serde::ser::{Serializer, Impossible};
20 | /// # use serde::__private::doc::Error;
21 | /// #
22 | /// # struct MySerializer;
23 | /// #
24 | /// impl Serializer for MySerializer {
25 | /// type Ok = ();
26 | /// type Error = Error;
27 | ///
28 | /// type SerializeSeq = Impossible<(), Error>;
29 | /// /* other associated types */
30 | ///
31 | /// /// This data format does not support serializing sequences.
32 | /// fn serialize_seq(self,
33 | /// len: Option)
34 | /// -> Result {
35 | /// // Given Impossible cannot be instantiated, the only
36 | /// // thing we can do here is to return an error.
37 | /// # stringify! {
38 | /// Err(...)
39 | /// # };
40 | /// # unimplemented!()
41 | /// }
42 | ///
43 | /// /* other Serializer methods */
44 | /// # serde::__serialize_unimplemented! {
45 | /// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str bytes none some
46 | /// # unit unit_struct unit_variant newtype_struct newtype_variant
47 | /// # tuple tuple_struct tuple_variant map struct struct_variant
48 | /// # }
49 | /// }
50 | /// ```
51 | ///
52 | /// [`Serializer`]: crate::Serializer
53 | /// [`SerializeSeq`]: crate::ser::SerializeSeq
54 | /// [`SerializeTuple`]: crate::ser::SerializeTuple
55 | /// [`SerializeTupleStruct`]: crate::ser::SerializeTupleStruct
56 | /// [`SerializeTupleVariant`]: crate::ser::SerializeTupleVariant
57 | /// [`SerializeMap`]: crate::ser::SerializeMap
58 | /// [`SerializeStruct`]: crate::ser::SerializeStruct
59 | /// [`SerializeStructVariant`]: crate::ser::SerializeStructVariant
60 | pub struct Impossible {
61 | void: Void,
62 | ok: PhantomData,
63 | error: PhantomData,
64 | }
65 |
66 | enum Void {}
67 |
68 | impl SerializeSeq for Impossible
69 | where
70 | Error: ser::Error,
71 | {
72 | type Ok = Ok;
73 | type Error = Error;
74 |
75 | fn serialize_element(&mut self, value: &T) -> Result<(), Error>
76 | where
77 | T: ?Sized + Serialize,
78 | {
79 | let _ = value;
80 | match self.void {}
81 | }
82 |
83 | fn end(self) -> Result {
84 | match self.void {}
85 | }
86 | }
87 |
88 | impl SerializeTuple for Impossible
89 | where
90 | Error: ser::Error,
91 | {
92 | type Ok = Ok;
93 | type Error = Error;
94 |
95 | fn serialize_element(&mut self, value: &T) -> Result<(), Error>
96 | where
97 | T: ?Sized + Serialize,
98 | {
99 | let _ = value;
100 | match self.void {}
101 | }
102 |
103 | fn end(self) -> Result {
104 | match self.void {}
105 | }
106 | }
107 |
108 | impl SerializeTupleStruct for Impossible
109 | where
110 | Error: ser::Error,
111 | {
112 | type Ok = Ok;
113 | type Error = Error;
114 |
115 | fn serialize_field(&mut self, value: &T) -> Result<(), Error>
116 | where
117 | T: ?Sized + Serialize,
118 | {
119 | let _ = value;
120 | match self.void {}
121 | }
122 |
123 | fn end(self) -> Result {
124 | match self.void {}
125 | }
126 | }
127 |
128 | impl SerializeTupleVariant for Impossible
129 | where
130 | Error: ser::Error,
131 | {
132 | type Ok = Ok;
133 | type Error = Error;
134 |
135 | fn serialize_field(&mut self, value: &T) -> Result<(), Error>
136 | where
137 | T: ?Sized + Serialize,
138 | {
139 | let _ = value;
140 | match self.void {}
141 | }
142 |
143 | fn end(self) -> Result {
144 | match self.void {}
145 | }
146 | }
147 |
148 | impl SerializeMap for Impossible
149 | where
150 | Error: ser::Error,
151 | {
152 | type Ok = Ok;
153 | type Error = Error;
154 |
155 | fn serialize_key(&mut self, key: &T) -> Result<(), Error>
156 | where
157 | T: ?Sized + Serialize,
158 | {
159 | let _ = key;
160 | match self.void {}
161 | }
162 |
163 | fn serialize_value(&mut self, value: &T) -> Result<(), Error>
164 | where
165 | T: ?Sized + Serialize,
166 | {
167 | let _ = value;
168 | match self.void {}
169 | }
170 |
171 | fn end(self) -> Result {
172 | match self.void {}
173 | }
174 | }
175 |
176 | impl SerializeStruct for Impossible
177 | where
178 | Error: ser::Error,
179 | {
180 | type Ok = Ok;
181 | type Error = Error;
182 |
183 | fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Error>
184 | where
185 | T: ?Sized + Serialize,
186 | {
187 | let _ = key;
188 | let _ = value;
189 | match self.void {}
190 | }
191 |
192 | fn end(self) -> Result {
193 | match self.void {}
194 | }
195 | }
196 |
197 | impl SerializeStructVariant for Impossible
198 | where
199 | Error: ser::Error,
200 | {
201 | type Ok = Ok;
202 | type Error = Error;
203 |
204 | fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Error>
205 | where
206 | T: ?Sized + Serialize,
207 | {
208 | let _ = key;
209 | let _ = value;
210 | match self.void {}
211 | }
212 |
213 | fn end(self) -> Result {
214 | match self.void {}
215 | }
216 | }
217 |
--------------------------------------------------------------------------------
/serde/src/std_error.rs:
--------------------------------------------------------------------------------
1 | use crate::lib::{Debug, Display};
2 |
3 | /// Either a re-export of std::error::Error or a new identical trait, depending
4 | /// on whether Serde's "std" feature is enabled.
5 | ///
6 | /// Serde's error traits [`serde::ser::Error`] and [`serde::de::Error`] require
7 | /// [`std::error::Error`] as a supertrait, but only when Serde is built with
8 | /// "std" enabled. Data formats that don't care about no\_std support should
9 | /// generally provide their error types with a `std::error::Error` impl
10 | /// directly:
11 | ///
12 | /// ```edition2021
13 | /// #[derive(Debug)]
14 | /// struct MySerError {...}
15 | ///
16 | /// impl serde::ser::Error for MySerError {...}
17 | ///
18 | /// impl std::fmt::Display for MySerError {...}
19 | ///
20 | /// // We don't support no_std!
21 | /// impl std::error::Error for MySerError {}
22 | /// ```
23 | ///
24 | /// Data formats that *do* support no\_std may either have a "std" feature of
25 | /// their own:
26 | ///
27 | /// ```toml
28 | /// [features]
29 | /// std = ["serde/std"]
30 | /// ```
31 | ///
32 | /// ```edition2021
33 | /// #[cfg(feature = "std")]
34 | /// impl std::error::Error for MySerError {}
35 | /// ```
36 | ///
37 | /// ... or else provide the std Error impl unconditionally via Serde's
38 | /// re-export:
39 | ///
40 | /// ```edition2021
41 | /// impl serde::ser::StdError for MySerError {}
42 | /// ```
43 | pub trait Error: Debug + Display {
44 | /// The underlying cause of this error, if any.
45 | fn source(&self) -> Option<&(dyn Error + 'static)> {
46 | None
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/serde_derive/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "serde_derive"
3 | version = "1.0.219"
4 | authors = ["Erick Tryzelaar ", "David Tolnay "]
5 | categories = ["no-std", "no-std::no-alloc"]
6 | description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]"
7 | documentation = "https://serde.rs/derive.html"
8 | edition = "2021"
9 | exclude = ["build.rs"]
10 | homepage = "https://serde.rs"
11 | keywords = ["serde", "serialization", "no_std", "derive"]
12 | license = "MIT OR Apache-2.0"
13 | readme = "crates-io.md"
14 | repository = "https://github.com/serde-rs/serde"
15 | rust-version = "1.61"
16 |
17 | [features]
18 | default = []
19 | deserialize_in_place = []
20 |
21 | [lib]
22 | name = "serde_derive"
23 | proc-macro = true
24 |
25 | [dependencies]
26 | proc-macro2 = { workspace = true, features = ["proc-macro"] }
27 | quote = { workspace = true, features = ["proc-macro"] }
28 | syn = { workspace = true, features = ["clone-impls", "derive", "parsing", "printing", "proc-macro"] }
29 |
30 | [dev-dependencies]
31 | serde = { version = "1", path = "../serde" }
32 |
33 | [package.metadata.docs.rs]
34 | targets = ["x86_64-unknown-linux-gnu"]
35 | rustdoc-args = [
36 | "--generate-link-to-definition",
37 | "--extern-html-root-url=core=https://doc.rust-lang.org",
38 | "--extern-html-root-url=alloc=https://doc.rust-lang.org",
39 | "--extern-html-root-url=std=https://doc.rust-lang.org",
40 | "--extern-html-root-url=proc_macro=https://doc.rust-lang.org",
41 | ]
42 |
--------------------------------------------------------------------------------
/serde_derive/LICENSE-APACHE:
--------------------------------------------------------------------------------
1 | ../LICENSE-APACHE
--------------------------------------------------------------------------------
/serde_derive/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | ../LICENSE-MIT
--------------------------------------------------------------------------------
/serde_derive/README.md:
--------------------------------------------------------------------------------
1 | ../README.md
--------------------------------------------------------------------------------
/serde_derive/build.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | // Warning: build.rs is not published to crates.io.
3 |
4 | println!("cargo:rerun-if-changed=build.rs");
5 | println!("cargo:rustc-cfg=check_cfg");
6 | println!("cargo:rustc-check-cfg=cfg(check_cfg)");
7 | println!("cargo:rustc-check-cfg=cfg(exhaustive)");
8 | }
9 |
--------------------------------------------------------------------------------
/serde_derive/crates-io.md:
--------------------------------------------------------------------------------
1 | ../crates-io.md
--------------------------------------------------------------------------------
/serde_derive/src/dummy.rs:
--------------------------------------------------------------------------------
1 | use proc_macro2::TokenStream;
2 | use quote::quote;
3 |
4 | pub fn wrap_in_const(serde_path: Option<&syn::Path>, code: TokenStream) -> TokenStream {
5 | let use_serde = match serde_path {
6 | Some(path) => quote! {
7 | use #path as _serde;
8 | },
9 | None => quote! {
10 | #[allow(unused_extern_crates, clippy::useless_attribute)]
11 | extern crate serde as _serde;
12 | },
13 | };
14 |
15 | quote! {
16 | #[doc(hidden)]
17 | #[allow(
18 | non_upper_case_globals,
19 | unused_attributes,
20 | unused_qualifications,
21 | clippy::absolute_paths,
22 | )]
23 | const _: () = {
24 | #use_serde
25 | #code
26 | };
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/serde_derive/src/fragment.rs:
--------------------------------------------------------------------------------
1 | use proc_macro2::TokenStream;
2 | use quote::ToTokens;
3 | use syn::{token, Token};
4 |
5 | pub enum Fragment {
6 | /// Tokens that can be used as an expression.
7 | Expr(TokenStream),
8 | /// Tokens that can be used inside a block. The surrounding curly braces are
9 | /// not part of these tokens.
10 | Block(TokenStream),
11 | }
12 |
13 | macro_rules! quote_expr {
14 | ($($tt:tt)*) => {
15 | $crate::fragment::Fragment::Expr(quote!($($tt)*))
16 | }
17 | }
18 |
19 | macro_rules! quote_block {
20 | ($($tt:tt)*) => {
21 | $crate::fragment::Fragment::Block(quote!($($tt)*))
22 | }
23 | }
24 |
25 | /// Interpolate a fragment in place of an expression. This involves surrounding
26 | /// Block fragments in curly braces.
27 | pub struct Expr(pub Fragment);
28 | impl ToTokens for Expr {
29 | fn to_tokens(&self, out: &mut TokenStream) {
30 | match &self.0 {
31 | Fragment::Expr(expr) => expr.to_tokens(out),
32 | Fragment::Block(block) => {
33 | token::Brace::default().surround(out, |out| block.to_tokens(out));
34 | }
35 | }
36 | }
37 | }
38 |
39 | /// Interpolate a fragment as the statements of a block.
40 | pub struct Stmts(pub Fragment);
41 | impl ToTokens for Stmts {
42 | fn to_tokens(&self, out: &mut TokenStream) {
43 | match &self.0 {
44 | Fragment::Expr(expr) => expr.to_tokens(out),
45 | Fragment::Block(block) => block.to_tokens(out),
46 | }
47 | }
48 | }
49 |
50 | /// Interpolate a fragment as the value part of a `match` expression. This
51 | /// involves putting a comma after expressions and curly braces around blocks.
52 | pub struct Match(pub Fragment);
53 | impl ToTokens for Match {
54 | fn to_tokens(&self, out: &mut TokenStream) {
55 | match &self.0 {
56 | Fragment::Expr(expr) => {
57 | expr.to_tokens(out);
58 | ::default().to_tokens(out);
59 | }
60 | Fragment::Block(block) => {
61 | token::Brace::default().surround(out, |out| block.to_tokens(out));
62 | }
63 | }
64 | }
65 | }
66 |
67 | impl AsRef for Fragment {
68 | fn as_ref(&self) -> &TokenStream {
69 | match self {
70 | Fragment::Expr(expr) => expr,
71 | Fragment::Block(block) => block,
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/serde_derive/src/internals/ctxt.rs:
--------------------------------------------------------------------------------
1 | use quote::ToTokens;
2 | use std::cell::RefCell;
3 | use std::fmt::Display;
4 | use std::thread;
5 |
6 | /// A type to collect errors together and format them.
7 | ///
8 | /// Dropping this object will cause a panic. It must be consumed using `check`.
9 | ///
10 | /// References can be shared since this type uses run-time exclusive mut checking.
11 | #[derive(Default)]
12 | pub struct Ctxt {
13 | // The contents will be set to `None` during checking. This is so that checking can be
14 | // enforced.
15 | errors: RefCell