Repository: serde-rs/serde
Branch: master
Commit: fa7da4a93567
Files: 347
Total size: 1.3 MB
Directory structure:
gitextract_h3ikti25/
├── .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
│ ├── build.rs
│ └── src/
│ ├── integer128.rs
│ ├── lib.rs
│ └── private/
│ ├── de.rs
│ ├── mod.rs
│ └── ser.rs
├── serde_core/
│ ├── Cargo.toml
│ ├── README.md
│ ├── build.rs
│ └── src/
│ ├── crate_root.rs
│ ├── de/
│ │ ├── ignored_any.rs
│ │ ├── impls.rs
│ │ ├── mod.rs
│ │ └── value.rs
│ ├── format.rs
│ ├── lib.rs
│ ├── macros.rs
│ ├── private/
│ │ ├── content.rs
│ │ ├── doc.rs
│ │ ├── mod.rs
│ │ ├── seed.rs
│ │ ├── size_hint.rs
│ │ └── string.rs
│ ├── ser/
│ │ ├── fmt.rs
│ │ ├── impls.rs
│ │ ├── impossible.rs
│ │ └── mod.rs
│ └── std_error.rs
├── serde_derive/
│ ├── Cargo.toml
│ ├── build.rs
│ └── src/
│ ├── bound.rs
│ ├── de/
│ │ ├── enum_.rs
│ │ ├── enum_adjacently.rs
│ │ ├── enum_externally.rs
│ │ ├── enum_internally.rs
│ │ ├── enum_untagged.rs
│ │ ├── identifier.rs
│ │ ├── struct_.rs
│ │ ├── tuple.rs
│ │ └── unit.rs
│ ├── de.rs
│ ├── deprecated.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
│ ├── build.rs
│ └── lib.rs
└── test_suite/
├── Cargo.toml
├── no_std/
│ ├── .gitignore
│ ├── Cargo.toml
│ └── src/
│ └── main.rs
└── tests/
├── bytes/
│ └── mod.rs
├── compiletest.rs
├── macros/
│ └── mod.rs
├── regression/
│ ├── issue1904.rs
│ ├── issue2371.rs
│ ├── issue2409.rs
│ ├── issue2415.rs
│ ├── issue2565.rs
│ ├── issue2792.rs
│ ├── issue2844.rs
│ └── issue2846.rs
├── regression.rs
├── test_annotations.rs
├── test_borrow.rs
├── test_de.rs
├── test_de_error.rs
├── test_deprecated.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
│ ├── deprecated/
│ │ ├── deprecated_de_with.rs
│ │ ├── deprecated_de_with.stderr
│ │ ├── deprecated_ser_with.rs
│ │ └── deprecated_ser_with.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
│ ├── 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
│ ├── unimplemented/
│ │ ├── required_by_dependency.rs
│ │ ├── required_by_dependency.stderr
│ │ ├── required_locally.rs
│ │ └── required_locally.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/
│ │ ├── incorrect_type.rs
│ │ └── incorrect_type.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
└── unstable/
└── mod.rs
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/FUNDING.yml
================================================
github: dtolnay
================================================
FILE: .github/ISSUE_TEMPLATE/1-problem.md
================================================
---
name: Problem
about: Something does not seem right
---
================================================
FILE: .github/ISSUE_TEMPLATE/2-suggestion.md
================================================
---
name: Suggestion
about: Share how Serde could support your use case better
---
================================================
FILE: .github/ISSUE_TEMPLATE/3-documentation.md
================================================
---
name: Documentation
about: Certainly there is room for improvement
---
================================================
FILE: .github/ISSUE_TEMPLATE/4-other.md
================================================
---
name: Anything else!
about: Whatever is on your mind
---
================================================
FILE: .github/workflows/ci.yml
================================================
name: CI
on:
push:
pull_request:
workflow_dispatch:
schedule: [cron: "40 1 * * *"]
permissions:
contents: read
env:
RUSTFLAGS: -Dwarnings
jobs:
test:
name: Test suite
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@nightly
- run: cd test_suite && cargo test --features unstable
- uses: actions/upload-artifact@v6
if: always()
with:
name: Cargo.lock
path: Cargo.lock
continue-on-error: true
windows:
name: Test suite (windows)
runs-on: windows-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@nightly
- run: cd test_suite && cargo test --features unstable -- --skip ui --exact
stable:
name: Rust ${{matrix.rust}}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
rust: [stable, beta]
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{matrix.rust}}
- run: cd serde && cargo build --features rc
- run: cd serde && cargo build --no-default-features
- run: cd test_suite/no_std && cargo build
nightly:
name: Rust nightly${{matrix.os == 'windows' && ' (windows)' || ''}}
runs-on: ${{matrix.os}}-latest
strategy:
fail-fast: false
matrix:
os: [ubuntu, windows]
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@nightly
- run: cd serde && cargo build
- run: cd serde && cargo build --no-default-features
- run: cd serde && cargo build --no-default-features --features alloc
- run: cd serde && cargo build --no-default-features --features rc,alloc
- run: cd serde && cargo build --no-default-features --features unstable
- run: cd serde_core && cargo test --features rc,unstable
- run: cd test_suite/no_std && cargo build
if: matrix.os != 'windows'
- run: cd serde_derive && cargo check --tests
env:
RUSTFLAGS: --cfg exhaustive ${{env.RUSTFLAGS}}
if: matrix.os != 'windows'
build:
name: Rust ${{matrix.rust}}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
rust: [1.56.0, 1.60.0]
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{matrix.rust}}
- run: sed -i '/"test_suite"/d' Cargo.toml
- run: cd serde && cargo build --features rc
- run: cd serde && cargo build --no-default-features
- run: cd serde && cargo build --no-default-features --features alloc
- run: cd serde && cargo build
derive:
name: Rust 1.71.0
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@1.71.0
- run: |
sed -i 's/proc-macro2 = { workspace = true/proc-macro2 = { version = "1"/' serde_derive*/Cargo.toml
sed -i 's/quote = { workspace = true/quote = { version = "1"/' serde_derive*/Cargo.toml
sed -i 's/syn = { workspace = true/syn = { version = "2"/' serde_derive*/Cargo.toml
- run: cd serde && cargo check --no-default-features
- run: cd serde && cargo check
- run: cd serde_derive && cargo check
minimal:
name: Minimal versions
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@nightly
- run: cargo generate-lockfile -Z minimal-versions
- run: cargo check --locked --workspace
doc:
name: Documentation
runs-on: ubuntu-latest
timeout-minutes: 45
env:
RUSTDOCFLAGS: -Dwarnings
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@nightly
- uses: dtolnay/install@cargo-docs-rs
- run: cargo docs-rs -p serde
- run: cargo docs-rs -p serde_core
- run: cargo docs-rs -p serde_derive
- run: cargo docs-rs -p serde_derive_internals
clippy:
name: Clippy
runs-on: ubuntu-latest
if: github.event_name != 'pull_request'
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@clippy
- run: cd serde && cargo clippy --features rc,unstable -- -Dclippy::all -Dclippy::pedantic
- run: cd serde_core && cargo clippy --features rc,unstable -- -Dclippy::all -Dclippy::pedantic
- run: cd serde_derive && cargo clippy -- -Dclippy::all -Dclippy::pedantic
- run: cd serde_derive_internals && cargo clippy -- -Dclippy::all -Dclippy::pedantic
- run: cd test_suite && cargo clippy --tests --features unstable -- -Dclippy::all -Dclippy::pedantic
- run: cd test_suite/no_std && cargo clippy -- -Dclippy::all -Dclippy::pedantic
miri:
name: Miri
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@miri
- run: cargo miri setup
- run: cd serde_core && cargo miri test --features rc,unstable
env:
MIRIFLAGS: -Zmiri-strict-provenance
- run: cd test_suite && cargo miri test --features unstable
env:
MIRIFLAGS: -Zmiri-strict-provenance
outdated:
name: Outdated
runs-on: ubuntu-latest
if: github.event_name != 'pull_request'
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/install@cargo-outdated
- run: cargo outdated --workspace --exit-code 1
================================================
FILE: .gitignore
================================================
/target/
/Cargo.lock
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to Serde
Serde welcomes contribution from everyone in the form of suggestions, bug
reports, pull requests, and feedback. This document gives some guidance if you
are thinking of helping us.
## Submitting bug reports and feature requests
Serde development is spread across lots of repositories, but this serde-rs/serde
repository is always a safe choice for opening any issues related to Serde.
When reporting a bug or asking for help, please include enough details so that
the people helping you can reproduce the behavior you are seeing. For some tips
on how to approach this, read about how to produce a [Minimal, Complete, and
Verifiable example].
[Minimal, Complete, and Verifiable example]: https://stackoverflow.com/help/mcve
When making a feature request, please make it clear what problem you intend to
solve with the feature, any ideas for how Serde could support solving that
problem, any possible alternatives, and any disadvantages.
## Running the test suite
We encourage you to check that the test suite passes locally before submitting a
pull request with your changes. If anything does not pass, typically it will be
easier to iterate and fix it locally than waiting for the CI servers to run
tests for you.
##### In the [`serde_core`] directory
```sh
# Test all the example code in Serde documentation
cargo test
```
##### In the [`test_suite`] directory
```sh
# Run the full test suite, including tests of unstable functionality
cargo +nightly test --features unstable
```
Note that this test suite currently only supports running on a nightly compiler.
[`serde_core`]: https://github.com/serde-rs/serde/tree/master/serde_core
[`test_suite`]: https://github.com/serde-rs/serde/tree/master/test_suite
## Conduct
In all Serde-related forums, we follow the [Rust Code of Conduct]. For
escalation or moderation issues please contact Erick (erick.tryzelaar@gmail.com)
instead of the Rust moderation team.
[Rust Code of Conduct]: https://www.rust-lang.org/policies/code-of-conduct
================================================
FILE: Cargo.toml
================================================
[workspace]
members = [
"serde",
"serde_core",
"serde_derive",
"serde_derive_internals",
"test_suite",
]
resolver = "2"
[patch.crates-io]
serde = { path = "serde" }
serde_core = { path = "serde_core" }
serde_derive = { path = "serde_derive" }
[workspace.dependencies]
proc-macro2 = { version = "1.0.74", default-features = false }
quote = { version = "1.0.35", default-features = false }
syn = { version = "2.0.81", default-features = false }
================================================
FILE: LICENSE-APACHE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
================================================
FILE: LICENSE-MIT
================================================
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
================================================
FILE: README.md
================================================
# Serde [![Build Status]][actions] [![Latest Version]][crates.io] [![serde msrv]][Rust 1.56] [![serde_derive msrv]][Rust 1.71]
[Build Status]: https://img.shields.io/github/actions/workflow/status/serde-rs/serde/ci.yml?branch=master
[actions]: https://github.com/serde-rs/serde/actions?query=branch%3Amaster
[Latest Version]: https://img.shields.io/crates/v/serde.svg
[crates.io]: https://crates.io/crates/serde
[serde msrv]: https://img.shields.io/crates/msrv/serde.svg?label=serde%20msrv&color=lightgray
[serde_derive msrv]: https://img.shields.io/crates/msrv/serde_derive.svg?label=serde_derive%20msrv&color=lightgray
[Rust 1.56]: https://blog.rust-lang.org/2021/10/21/Rust-1.56.0/
[Rust 1.71]: https://blog.rust-lang.org/2023/07/13/Rust-1.71.0/
**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.**
---
You may be looking for:
- [An overview of Serde](https://serde.rs)
- [Data formats supported by Serde](https://serde.rs/#data-formats)
- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html)
- [Examples](https://serde.rs/examples.html)
- [API documentation](https://docs.rs/serde)
- [Release notes](https://github.com/serde-rs/serde/releases)
## Serde in action
Click to show Cargo.toml.
Run this code in the playground.
```toml
[dependencies]
# The core APIs, including the Serialize and Deserialize traits. Always
# required when using Serde. The "derive" feature is only required when
# using #[derive(Serialize, Deserialize)] to make Serde work with structs
# and enums defined in your crate.
serde = { version = "1.0", features = ["derive"] }
# Each data format lives in its own crate; the sample code below uses JSON
# but you may be using a different one.
serde_json = "1.0"
```
```rust
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let point = Point { x: 1, y: 2 };
// Convert the Point to a JSON string.
let serialized = serde_json::to_string(&point).unwrap();
// Prints serialized = {"x":1,"y":2}
println!("serialized = {}", serialized);
// Convert the JSON string back to a Point.
let deserialized: Point = serde_json::from_str(&serialized).unwrap();
// Prints deserialized = Point { x: 1, y: 2 }
println!("deserialized = {:?}", deserialized);
}
```
## Getting help
Serde is one of the most widely used Rust libraries so any place that Rustaceans
congregate will be able to help you out. For chat, consider trying the
[#rust-questions] or [#rust-beginners] channels of the unofficial community
Discord (invite: ), the [#rust-usage] or
[#beginners] channels of the official Rust Project Discord (invite:
), or the [#general][zulip] stream in Zulip. For
asynchronous, consider the [\[rust\] tag on StackOverflow][stackoverflow], the
[/r/rust] subreddit which has a pinned weekly easy questions post, or the Rust
[Discourse forum][discourse]. It's acceptable to file a support issue in this
repo but they tend not to get as many eyes as any of the above and may get
closed without a response after some time.
[#rust-questions]: https://discord.com/channels/273534239310479360/274215136414400513
[#rust-beginners]: https://discord.com/channels/273534239310479360/273541522815713281
[#rust-usage]: https://discord.com/channels/442252698964721669/443150878111694848
[#beginners]: https://discord.com/channels/442252698964721669/448238009733742612
[zulip]: https://rust-lang.zulipchat.com/#narrow/stream/122651-general
[stackoverflow]: https://stackoverflow.com/questions/tagged/rust
[/r/rust]: https://www.reddit.com/r/rust
[discourse]: https://users.rust-lang.org
#### License
Licensed under either of Apache License, Version
2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in Serde by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.
================================================
FILE: crates-io.md
================================================
**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.**
---
You may be looking for:
- [An overview of Serde](https://serde.rs)
- [Data formats supported by Serde](https://serde.rs/#data-formats)
- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html)
- [Examples](https://serde.rs/examples.html)
- [API documentation](https://docs.rs/serde)
- [Release notes](https://github.com/serde-rs/serde/releases)
## Serde in action
```rust
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let point = Point { x: 1, y: 2 };
// Convert the Point to a JSON string.
let serialized = serde_json::to_string(&point).unwrap();
// Prints serialized = {"x":1,"y":2}
println!("serialized = {}", serialized);
// Convert the JSON string back to a Point.
let deserialized: Point = serde_json::from_str(&serialized).unwrap();
// Prints deserialized = Point { x: 1, y: 2 }
println!("deserialized = {:?}", deserialized);
}
```
## Getting help
Serde is one of the most widely used Rust libraries so any place that Rustaceans
congregate will be able to help you out. For chat, consider trying the
[#rust-questions] or [#rust-beginners] channels of the unofficial community
Discord (invite: ), the [#rust-usage]
or [#beginners] channels of the official Rust Project Discord (invite:
), or the [#general][zulip] stream in Zulip. For
asynchronous, consider the [\[rust\] tag on StackOverflow][stackoverflow], the
[/r/rust] subreddit which has a pinned weekly easy questions post, or the Rust
[Discourse forum][discourse]. It's acceptable to file a support issue in this
repo but they tend not to get as many eyes as any of the above and may get
closed without a response after some time.
[#rust-questions]: https://discord.com/channels/273534239310479360/274215136414400513
[#rust-beginners]: https://discord.com/channels/273534239310479360/273541522815713281
[#rust-usage]: https://discord.com/channels/442252698964721669/443150878111694848
[#beginners]: https://discord.com/channels/442252698964721669/448238009733742612
[zulip]: https://rust-lang.zulipchat.com/#narrow/stream/122651-general
[stackoverflow]: https://stackoverflow.com/questions/tagged/rust
[/r/rust]: https://www.reddit.com/r/rust
[discourse]: https://users.rust-lang.org
================================================
FILE: serde/Cargo.toml
================================================
[package]
name = "serde"
version = "1.0.228"
authors = ["Erick Tryzelaar ", "David Tolnay "]
build = "build.rs"
categories = ["encoding", "no-std", "no-std::no-alloc"]
description = "A generic serialization/deserialization framework"
documentation = "https://docs.rs/serde"
edition = "2021"
homepage = "https://serde.rs"
keywords = ["serde", "serialization", "no_std"]
license = "MIT OR Apache-2.0"
readme = "crates-io.md"
repository = "https://github.com/serde-rs/serde"
rust-version = "1.56"
[dependencies]
serde_core = { version = "=1.0.228", path = "../serde_core", default-features = false, features = ["result"] }
serde_derive = { version = "1", optional = true, path = "../serde_derive" }
[package.metadata.playground]
features = ["derive", "rc"]
[package.metadata.docs.rs]
features = ["derive", "rc", "unstable"]
targets = ["x86_64-unknown-linux-gnu"]
rustdoc-args = [
"--generate-link-to-definition",
"--generate-macro-expansion",
"--extern-html-root-url=core=https://doc.rust-lang.org",
"--extern-html-root-url=alloc=https://doc.rust-lang.org",
"--extern-html-root-url=std=https://doc.rust-lang.org",
]
### FEATURES #################################################################
[features]
default = ["std"]
# Provide derive(Serialize, Deserialize) macros.
derive = ["serde_derive"]
# Provide impls for common standard library types like Vec and HashMap.
# Requires a dependency on the Rust standard library.
std = ["serde_core/std"]
# Provide impls for types that require unstable functionality. For tracking and
# discussion of unstable functionality please refer to this issue:
#
# https://github.com/serde-rs/serde/issues/812
unstable = ["serde_core/unstable"]
# Provide impls for types in the Rust core allocation and collections library
# including String, Box, Vec, and Cow. This is a subset of std but may
# be enabled without depending on all of std.
alloc = ["serde_core/alloc"]
# Opt into impls for Rc and Arc. Serializing and deserializing these types
# does not preserve identity and may result in multiple copies of the same data.
# Be sure that this is what you want before enabling this feature.
rc = ["serde_core/rc"]
================================================
FILE: serde/build.rs
================================================
use std::env;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use std::str;
const PRIVATE: &str = "\
#[doc(hidden)]
pub mod __private$$ {
#[doc(hidden)]
pub use crate::private::*;
}
use serde_core::__private$$ as serde_core_private;
";
// The rustc-cfg strings below are *not* public API. Please let us know by
// opening a GitHub issue if your build environment requires some way to enable
// these cfgs other than by executing our build script.
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rustc-cfg=if_docsrs_then_no_serde_core");
let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let patch_version = env::var("CARGO_PKG_VERSION_PATCH").unwrap();
let module = PRIVATE.replace("$$", &patch_version);
fs::write(out_dir.join("private.rs"), module).unwrap();
let minor = match rustc_minor_version() {
Some(minor) => minor,
None => return,
};
if minor >= 77 {
println!("cargo:rustc-check-cfg=cfg(feature, values(\"result\"))");
println!("cargo:rustc-check-cfg=cfg(if_docsrs_then_no_serde_core)");
println!("cargo:rustc-check-cfg=cfg(no_core_cstr)");
println!("cargo:rustc-check-cfg=cfg(no_core_error)");
println!("cargo:rustc-check-cfg=cfg(no_core_net)");
println!("cargo:rustc-check-cfg=cfg(no_core_num_saturating)");
println!("cargo:rustc-check-cfg=cfg(no_diagnostic_namespace)");
println!("cargo:rustc-check-cfg=cfg(no_serde_derive)");
println!("cargo:rustc-check-cfg=cfg(no_std_atomic)");
println!("cargo:rustc-check-cfg=cfg(no_std_atomic64)");
println!("cargo:rustc-check-cfg=cfg(no_target_has_atomic)");
}
// Current minimum supported version of serde_derive crate is Rust 1.71.
if minor < 71 {
println!("cargo:rustc-cfg=no_serde_derive");
}
// Support for the `#[diagnostic]` tool attribute namespace
// https://blog.rust-lang.org/2024/05/02/Rust-1.78.0.html#diagnostic-attributes
if minor < 78 {
println!("cargo:rustc-cfg=no_diagnostic_namespace");
}
}
fn rustc_minor_version() -> Option {
let rustc = env::var_os("RUSTC")?;
let output = Command::new(rustc).arg("--version").output().ok()?;
let version = str::from_utf8(&output.stdout).ok()?;
let mut pieces = version.split('.');
if pieces.next() != Some("rustc 1") {
return None;
}
pieces.next()?.parse().ok()
}
================================================
FILE: serde/src/integer128.rs
================================================
#[macro_export]
#[deprecated = "
This macro has no effect on any version of Serde released in the past 2 years.
It was used long ago in crates that needed to support Rustc older than 1.26.0,
or Emscripten targets older than 1.40.0, which did not yet have 128-bit integer
support. These days Serde requires a Rust compiler newer than that so 128-bit
integers are always supported.
"]
#[doc(hidden)]
macro_rules! serde_if_integer128 {
($($tt:tt)*) => {
$($tt)*
};
}
================================================
FILE: serde/src/lib.rs
================================================
//! # Serde
//!
//! Serde is a framework for ***ser***ializing and ***de***serializing Rust data
//! structures efficiently and generically.
//!
//! The Serde ecosystem consists of data structures that know how to serialize
//! and deserialize themselves along with data formats that know how to
//! serialize and deserialize other things. Serde provides the layer by which
//! these two groups interact with each other, allowing any supported data
//! structure to be serialized and deserialized using any supported data format.
//!
//! See the Serde website for additional documentation and
//! usage examples.
//!
//! ## Design
//!
//! Where many other languages rely on runtime reflection for serializing data,
//! Serde is instead built on Rust's powerful trait system. A data structure
//! that knows how to serialize and deserialize itself is one that implements
//! Serde's `Serialize` and `Deserialize` traits (or uses Serde's derive
//! attribute to automatically generate implementations at compile time). This
//! avoids any overhead of reflection or runtime type information. In fact in
//! many situations the interaction between data structure and data format can
//! be completely optimized away by the Rust compiler, leaving Serde
//! serialization to perform the same speed as a handwritten serializer for the
//! specific selection of data structure and data format.
//!
//! ## Data formats
//!
//! The following is a partial list of data formats that have been implemented
//! for Serde by the community.
//!
//! - [JSON], the ubiquitous JavaScript Object Notation used by many HTTP APIs.
//! - [Postcard], a no\_std and embedded-systems friendly compact binary format.
//! - [CBOR], a Concise Binary Object Representation designed for small message
//! size without the need for version negotiation.
//! - [YAML], a self-proclaimed human-friendly configuration language that ain't
//! markup language.
//! - [MessagePack], an efficient binary format that resembles a compact JSON.
//! - [TOML], a minimal configuration format used by [Cargo].
//! - [Pickle], a format common in the Python world.
//! - [RON], a Rusty Object Notation.
//! - [BSON], the data storage and network transfer format used by MongoDB.
//! - [Avro], a binary format used within Apache Hadoop, with support for schema
//! definition.
//! - [JSON5], a superset of JSON including some productions from ES5.
//! - [URL] query strings, in the x-www-form-urlencoded format.
//! - [Starlark], the format used for describing build targets by the Bazel and
//! Buck build systems. *(serialization only)*
//! - [Envy], a way to deserialize environment variables into Rust structs.
//! *(deserialization only)*
//! - [Envy Store], a way to deserialize [AWS Parameter Store] parameters into
//! Rust structs. *(deserialization only)*
//! - [S-expressions], the textual representation of code and data used by the
//! Lisp language family.
//! - [D-Bus]'s binary wire format.
//! - [FlexBuffers], the schemaless cousin of Google's FlatBuffers zero-copy
//! serialization format.
//! - [Bencode], a simple binary format used in the BitTorrent protocol.
//! - [Token streams], for processing Rust procedural macro input.
//! *(deserialization only)*
//! - [DynamoDB Items], the format used by [rusoto_dynamodb] to transfer data to
//! and from DynamoDB.
//! - [Hjson], a syntax extension to JSON designed around human reading and
//! editing. *(deserialization only)*
//! - [CSV], Comma-separated values is a tabular text file format.
//!
//! [JSON]: https://github.com/serde-rs/json
//! [Postcard]: https://github.com/jamesmunns/postcard
//! [CBOR]: https://github.com/enarx/ciborium
//! [YAML]: https://github.com/dtolnay/serde-yaml
//! [MessagePack]: https://github.com/3Hren/msgpack-rust
//! [TOML]: https://docs.rs/toml
//! [Pickle]: https://github.com/birkenfeld/serde-pickle
//! [RON]: https://github.com/ron-rs/ron
//! [BSON]: https://github.com/mongodb/bson-rust
//! [Avro]: https://docs.rs/apache-avro
//! [JSON5]: https://github.com/callum-oakley/json5-rs
//! [URL]: https://docs.rs/serde_qs
//! [Starlark]: https://github.com/dtolnay/serde-starlark
//! [Envy]: https://github.com/softprops/envy
//! [Envy Store]: https://github.com/softprops/envy-store
//! [Cargo]: https://doc.rust-lang.org/cargo/reference/manifest.html
//! [AWS Parameter Store]: https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html
//! [S-expressions]: https://github.com/rotty/lexpr-rs
//! [D-Bus]: https://docs.rs/zvariant
//! [FlexBuffers]: https://github.com/google/flatbuffers/tree/master/rust/flexbuffers
//! [Bencode]: https://github.com/P3KI/bendy
//! [Token streams]: https://github.com/oxidecomputer/serde_tokenstream
//! [DynamoDB Items]: https://docs.rs/serde_dynamo
//! [rusoto_dynamodb]: https://docs.rs/rusoto_dynamodb
//! [Hjson]: https://github.com/Canop/deser-hjson
//! [CSV]: https://docs.rs/csv
////////////////////////////////////////////////////////////////////////////////
// Serde types in rustdoc of other crates get linked to here.
#![doc(html_root_url = "https://docs.rs/serde/1.0.228")]
// Support using Serde without the standard library!
#![cfg_attr(not(feature = "std"), no_std)]
// Show which crate feature enables conditionally compiled APIs in documentation.
#![cfg_attr(docsrs, feature(doc_cfg, rustdoc_internals))]
#![cfg_attr(docsrs, allow(internal_features))]
// Unstable functionality only if the user asks for it. For tracking and
// discussion of these features please refer to this issue:
//
// https://github.com/serde-rs/serde/issues/812
#![cfg_attr(all(feature = "unstable", docsrs), feature(never_type))]
#![allow(
unknown_lints,
bare_trait_objects,
deprecated,
mismatched_lifetime_syntaxes
)]
// Ignored clippy and clippy_pedantic lints
#![allow(
// clippy bug: https://github.com/rust-lang/rust-clippy/issues/5704
clippy::unnested_or_patterns,
// clippy bug: https://github.com/rust-lang/rust-clippy/issues/7768
clippy::semicolon_if_nothing_returned,
// not available in our oldest supported compiler
clippy::empty_enums,
clippy::type_repetition_in_bounds, // https://github.com/rust-lang/rust-clippy/issues/8772
// integer and float ser/de requires these sorts of casts
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_precision_loss,
clippy::cast_sign_loss,
// things are often more readable this way
clippy::cast_lossless,
clippy::module_name_repetitions,
clippy::single_match_else,
clippy::type_complexity,
clippy::use_self,
clippy::zero_prefixed_literal,
// correctly used
clippy::derive_partial_eq_without_eq,
clippy::enum_glob_use,
clippy::explicit_auto_deref,
clippy::incompatible_msrv,
clippy::let_underscore_untyped,
clippy::map_err_ignore,
clippy::new_without_default,
clippy::result_unit_err,
clippy::wildcard_imports,
// not practical
clippy::needless_pass_by_value,
clippy::similar_names,
clippy::too_many_lines,
// preference
clippy::doc_markdown,
clippy::elidable_lifetime_names,
clippy::needless_lifetimes,
clippy::unseparated_literal_suffix,
// false positive
clippy::needless_doctest_main,
// noisy
clippy::missing_errors_doc,
clippy::must_use_candidate,
)]
// Restrictions
#![deny(clippy::question_mark_used)]
// Rustc lints.
#![deny(missing_docs, unused_imports)]
////////////////////////////////////////////////////////////////////////////////
#[cfg(feature = "alloc")]
extern crate alloc;
// Rustdoc has a lot of shortcomings related to cross-crate re-exports that make
// the rendered documentation of serde_core traits in serde more challenging to
// understand than the equivalent documentation of the same items in serde_core.
// https://github.com/rust-lang/rust/labels/A-cross-crate-reexports
// So, just for the purpose of docs.rs documentation, we inline the contents of
// serde_core into serde. This sidesteps all the cross-crate rustdoc bugs.
#[cfg(docsrs)]
#[macro_use]
#[path = "core/crate_root.rs"]
mod crate_root;
#[cfg(docsrs)]
#[macro_use]
#[path = "core/macros.rs"]
mod macros;
#[cfg(not(docsrs))]
macro_rules! crate_root {
() => {
/// A facade around all the types we need from the `std`, `core`, and `alloc`
/// crates. This avoids elaborate import wrangling having to happen in every
/// module.
mod lib {
mod core {
#[cfg(not(feature = "std"))]
pub use core::*;
#[cfg(feature = "std")]
pub use std::*;
}
pub use self::core::{f32, f64};
pub use self::core::{ptr, str};
#[cfg(any(feature = "std", feature = "alloc"))]
pub use self::core::slice;
pub use self::core::clone;
pub use self::core::convert;
pub use self::core::default;
pub use self::core::fmt::{self, Debug, Display, Write as FmtWrite};
pub use self::core::marker::{self, PhantomData};
pub use self::core::option;
pub use self::core::result;
#[cfg(all(feature = "alloc", not(feature = "std")))]
pub use alloc::borrow::{Cow, ToOwned};
#[cfg(feature = "std")]
pub use std::borrow::{Cow, ToOwned};
#[cfg(all(feature = "alloc", not(feature = "std")))]
pub use alloc::string::{String, ToString};
#[cfg(feature = "std")]
pub use std::string::{String, ToString};
#[cfg(all(feature = "alloc", not(feature = "std")))]
pub use alloc::vec::Vec;
#[cfg(feature = "std")]
pub use std::vec::Vec;
#[cfg(all(feature = "alloc", not(feature = "std")))]
pub use alloc::boxed::Box;
#[cfg(feature = "std")]
pub use std::boxed::Box;
}
// None of this crate's error handling needs the `From::from` error conversion
// performed implicitly by the `?` operator or the standard library's `try!`
// macro. This simplified macro gives a 5.5% improvement in compile time
// compared to standard `try!`, and 9% improvement compared to `?`.
#[cfg(not(no_serde_derive))]
macro_rules! tri {
($expr:expr) => {
match $expr {
Ok(val) => val,
Err(err) => return Err(err),
}
};
}
////////////////////////////////////////////////////////////////////////////////
pub use serde_core::{
de, forward_to_deserialize_any, ser, Deserialize, Deserializer, Serialize, Serializer,
};
// Used by generated code and doc tests. Not public API.
#[doc(hidden)]
mod private;
include!(concat!(env!("OUT_DIR"), "/private.rs"));
};
}
crate_root!();
mod integer128;
// Re-export #[derive(Serialize, Deserialize)].
//
// The reason re-exporting is not enabled by default is that disabling it would
// be annoying for crates that provide handwritten impls or data formats. They
// would need to disable default features and then explicitly re-enable std.
#[cfg(feature = "serde_derive")]
extern crate serde_derive;
/// Derive macro available if serde is built with `features = ["derive"]`.
#[cfg(feature = "serde_derive")]
#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
pub use serde_derive::{Deserialize, Serialize};
#[macro_export]
#[doc(hidden)]
macro_rules! __require_serde_not_serde_core {
() => {};
}
================================================
FILE: serde/src/private/de.rs
================================================
use crate::lib::*;
use crate::de::value::{BorrowedBytesDeserializer, BytesDeserializer};
use crate::de::{
Deserialize, DeserializeSeed, Deserializer, EnumAccess, Error, IntoDeserializer, VariantAccess,
Visitor,
};
#[cfg(any(feature = "std", feature = "alloc"))]
use crate::de::{MapAccess, Unexpected};
#[cfg(any(feature = "std", feature = "alloc"))]
pub use self::content::{
content_as_str, Content, ContentDeserializer, ContentRefDeserializer, ContentVisitor,
EnumDeserializer, InternallyTaggedUnitVisitor, TagContentOtherField,
TagContentOtherFieldVisitor, TagOrContentField, TagOrContentFieldVisitor, TaggedContentVisitor,
UntaggedUnitVisitor,
};
pub use crate::serde_core_private::InPlaceSeed;
/// If the missing field is of type `Option` then treat is as `None`,
/// otherwise it is an error.
pub fn missing_field<'de, V, E>(field: &'static str) -> Result
where
V: Deserialize<'de>,
E: Error,
{
struct MissingFieldDeserializer(&'static str, PhantomData);
#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)]
impl<'de, E> Deserializer<'de> for MissingFieldDeserializer
where
E: Error,
{
type Error = E;
fn deserialize_any(self, _visitor: V) -> Result
where
V: Visitor<'de>,
{
Err(Error::missing_field(self.0))
}
fn deserialize_option(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
visitor.visit_none()
}
serde_core::forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
let deserializer = MissingFieldDeserializer(field, PhantomData);
Deserialize::deserialize(deserializer)
}
#[cfg(any(feature = "std", feature = "alloc"))]
pub fn borrow_cow_str<'de: 'a, 'a, D, R>(deserializer: D) -> Result
where
D: Deserializer<'de>,
R: From>,
{
struct CowStrVisitor;
#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)]
impl<'a> Visitor<'a> for CowStrVisitor {
type Value = Cow<'a, str>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string")
}
fn visit_str(self, v: &str) -> Result
where
E: Error,
{
Ok(Cow::Owned(v.to_owned()))
}
fn visit_borrowed_str(self, v: &'a str) -> Result
where
E: Error,
{
Ok(Cow::Borrowed(v))
}
fn visit_string(self, v: String) -> Result
where
E: Error,
{
Ok(Cow::Owned(v))
}
fn visit_bytes(self, v: &[u8]) -> Result
where
E: Error,
{
match str::from_utf8(v) {
Ok(s) => Ok(Cow::Owned(s.to_owned())),
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
}
}
fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result
where
E: Error,
{
match str::from_utf8(v) {
Ok(s) => Ok(Cow::Borrowed(s)),
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
}
}
fn visit_byte_buf(self, v: Vec) -> Result
where
E: Error,
{
match String::from_utf8(v) {
Ok(s) => Ok(Cow::Owned(s)),
Err(e) => Err(Error::invalid_value(
Unexpected::Bytes(&e.into_bytes()),
&self,
)),
}
}
}
deserializer.deserialize_str(CowStrVisitor).map(From::from)
}
#[cfg(any(feature = "std", feature = "alloc"))]
pub fn borrow_cow_bytes<'de: 'a, 'a, D, R>(deserializer: D) -> Result
where
D: Deserializer<'de>,
R: From>,
{
struct CowBytesVisitor;
#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)]
impl<'a> Visitor<'a> for CowBytesVisitor {
type Value = Cow<'a, [u8]>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a byte array")
}
fn visit_str(self, v: &str) -> Result
where
E: Error,
{
Ok(Cow::Owned(v.as_bytes().to_vec()))
}
fn visit_borrowed_str(self, v: &'a str) -> Result
where
E: Error,
{
Ok(Cow::Borrowed(v.as_bytes()))
}
fn visit_string(self, v: String) -> Result
where
E: Error,
{
Ok(Cow::Owned(v.into_bytes()))
}
fn visit_bytes(self, v: &[u8]) -> Result
where
E: Error,
{
Ok(Cow::Owned(v.to_vec()))
}
fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result
where
E: Error,
{
Ok(Cow::Borrowed(v))
}
fn visit_byte_buf(self, v: Vec) -> Result
where
E: Error,
{
Ok(Cow::Owned(v))
}
}
deserializer
.deserialize_bytes(CowBytesVisitor)
.map(From::from)
}
#[cfg(any(feature = "std", feature = "alloc"))]
mod content {
// This module is private and nothing here should be used outside of
// generated code.
//
// We will iterate on the implementation for a few releases and only have to
// worry about backward compatibility for the `untagged` and `tag` attributes
// rather than for this entire mechanism.
//
// This issue is tracking making some of this stuff public:
// https://github.com/serde-rs/serde/issues/741
use crate::lib::*;
use crate::de::{
self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, Expected, IgnoredAny,
MapAccess, SeqAccess, Unexpected, Visitor,
};
use crate::serde_core_private::size_hint;
pub use crate::serde_core_private::Content;
pub fn content_as_str<'a, 'de>(content: &'a Content<'de>) -> Option<&'a str> {
match *content {
Content::Str(x) => Some(x),
Content::String(ref x) => Some(x),
Content::Bytes(x) => str::from_utf8(x).ok(),
Content::ByteBuf(ref x) => str::from_utf8(x).ok(),
_ => None,
}
}
fn content_clone<'de>(content: &Content<'de>) -> Content<'de> {
match content {
Content::Bool(b) => Content::Bool(*b),
Content::U8(n) => Content::U8(*n),
Content::U16(n) => Content::U16(*n),
Content::U32(n) => Content::U32(*n),
Content::U64(n) => Content::U64(*n),
Content::I8(n) => Content::I8(*n),
Content::I16(n) => Content::I16(*n),
Content::I32(n) => Content::I32(*n),
Content::I64(n) => Content::I64(*n),
Content::F32(f) => Content::F32(*f),
Content::F64(f) => Content::F64(*f),
Content::Char(c) => Content::Char(*c),
Content::String(s) => Content::String(s.clone()),
Content::Str(s) => Content::Str(*s),
Content::ByteBuf(b) => Content::ByteBuf(b.clone()),
Content::Bytes(b) => Content::Bytes(b),
Content::None => Content::None,
Content::Some(content) => Content::Some(Box::new(content_clone(content))),
Content::Unit => Content::Unit,
Content::Newtype(content) => Content::Newtype(Box::new(content_clone(content))),
Content::Seq(seq) => Content::Seq(seq.iter().map(content_clone).collect()),
Content::Map(map) => Content::Map(
map.iter()
.map(|(k, v)| (content_clone(k), content_clone(v)))
.collect(),
),
}
}
#[cold]
fn content_unexpected<'a, 'de>(content: &'a Content<'de>) -> Unexpected<'a> {
match *content {
Content::Bool(b) => Unexpected::Bool(b),
Content::U8(n) => Unexpected::Unsigned(n as u64),
Content::U16(n) => Unexpected::Unsigned(n as u64),
Content::U32(n) => Unexpected::Unsigned(n as u64),
Content::U64(n) => Unexpected::Unsigned(n),
Content::I8(n) => Unexpected::Signed(n as i64),
Content::I16(n) => Unexpected::Signed(n as i64),
Content::I32(n) => Unexpected::Signed(n as i64),
Content::I64(n) => Unexpected::Signed(n),
Content::F32(f) => Unexpected::Float(f as f64),
Content::F64(f) => Unexpected::Float(f),
Content::Char(c) => Unexpected::Char(c),
Content::String(ref s) => Unexpected::Str(s),
Content::Str(s) => Unexpected::Str(s),
Content::ByteBuf(ref b) => Unexpected::Bytes(b),
Content::Bytes(b) => Unexpected::Bytes(b),
Content::None | Content::Some(_) => Unexpected::Option,
Content::Unit => Unexpected::Unit,
Content::Newtype(_) => Unexpected::NewtypeStruct,
Content::Seq(_) => Unexpected::Seq,
Content::Map(_) => Unexpected::Map,
}
}
pub struct ContentVisitor<'de> {
value: PhantomData>,
}
impl<'de> ContentVisitor<'de> {
pub fn new() -> Self {
ContentVisitor { value: PhantomData }
}
}
#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)]
impl<'de> DeserializeSeed<'de> for ContentVisitor<'de> {
type Value = Content<'de>;
fn deserialize(self, deserializer: D) -> Result
where
D: Deserializer<'de>,
{
deserializer.__deserialize_content_v1(self)
}
}
#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)]
impl<'de> Visitor<'de> for ContentVisitor<'de> {
type Value = Content<'de>;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("any value")
}
fn visit_bool(self, value: bool) -> Result
where
F: de::Error,
{
Ok(Content::Bool(value))
}
fn visit_i8(self, value: i8) -> Result
where
F: de::Error,
{
Ok(Content::I8(value))
}
fn visit_i16(self, value: i16) -> Result
where
F: de::Error,
{
Ok(Content::I16(value))
}
fn visit_i32(self, value: i32) -> Result
where
F: de::Error,
{
Ok(Content::I32(value))
}
fn visit_i64(self, value: i64) -> Result
where
F: de::Error,
{
Ok(Content::I64(value))
}
fn visit_u8(self, value: u8) -> Result
where
F: de::Error,
{
Ok(Content::U8(value))
}
fn visit_u16(self, value: u16) -> Result
where
F: de::Error,
{
Ok(Content::U16(value))
}
fn visit_u32(self, value: u32) -> Result
where
F: de::Error,
{
Ok(Content::U32(value))
}
fn visit_u64(self, value: u64) -> Result
where
F: de::Error,
{
Ok(Content::U64(value))
}
fn visit_f32(self, value: f32) -> Result
where
F: de::Error,
{
Ok(Content::F32(value))
}
fn visit_f64(self, value: f64) -> Result
where
F: de::Error,
{
Ok(Content::F64(value))
}
fn visit_char(self, value: char) -> Result
where
F: de::Error,
{
Ok(Content::Char(value))
}
fn visit_str(self, value: &str) -> Result
where
F: de::Error,
{
Ok(Content::String(value.into()))
}
fn visit_borrowed_str(self, value: &'de str) -> Result
where
F: de::Error,
{
Ok(Content::Str(value))
}
fn visit_string(self, value: String) -> Result
where
F: de::Error,
{
Ok(Content::String(value))
}
fn visit_bytes(self, value: &[u8]) -> Result
where
F: de::Error,
{
Ok(Content::ByteBuf(value.into()))
}
fn visit_borrowed_bytes(self, value: &'de [u8]) -> Result
where
F: de::Error,
{
Ok(Content::Bytes(value))
}
fn visit_byte_buf(self, value: Vec) -> Result
where
F: de::Error,
{
Ok(Content::ByteBuf(value))
}
fn visit_unit(self) -> Result
where
F: de::Error,
{
Ok(Content::Unit)
}
fn visit_none(self) -> Result
where
F: de::Error,
{
Ok(Content::None)
}
fn visit_some(self, deserializer: D) -> Result
where
D: Deserializer<'de>,
{
let v = tri!(ContentVisitor::new().deserialize(deserializer));
Ok(Content::Some(Box::new(v)))
}
fn visit_newtype_struct(self, deserializer: D) -> Result
where
D: Deserializer<'de>,
{
let v = tri!(ContentVisitor::new().deserialize(deserializer));
Ok(Content::Newtype(Box::new(v)))
}
fn visit_seq(self, mut visitor: V) -> Result
where
V: SeqAccess<'de>,
{
let mut vec =
Vec::::with_capacity(size_hint::cautious::(visitor.size_hint()));
while let Some(e) = tri!(visitor.next_element_seed(ContentVisitor::new())) {
vec.push(e);
}
Ok(Content::Seq(vec))
}
fn visit_map(self, mut visitor: V) -> Result
where
V: MapAccess<'de>,
{
let mut vec =
Vec::<(Content, Content)>::with_capacity(
size_hint::cautious::<(Content, Content)>(visitor.size_hint()),
);
while let Some(kv) =
tri!(visitor.next_entry_seed(ContentVisitor::new(), ContentVisitor::new()))
{
vec.push(kv);
}
Ok(Content::Map(vec))
}
fn visit_enum(self, _visitor: V) -> Result
where
V: EnumAccess<'de>,
{
Err(de::Error::custom(
"untagged and internally tagged enums do not support enum input",
))
}
}
/// This is the type of the map keys in an internally tagged enum.
///
/// Not public API.
pub enum TagOrContent<'de> {
Tag,
Content(Content<'de>),
}
/// Serves as a seed for deserializing a key of internally tagged enum.
/// Cannot capture externally tagged enums, `i128` and `u128`.
struct TagOrContentVisitor<'de> {
name: &'static str,
value: PhantomData>,
}
impl<'de> TagOrContentVisitor<'de> {
fn new(name: &'static str) -> Self {
TagOrContentVisitor {
name,
value: PhantomData,
}
}
}
#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)]
impl<'de> DeserializeSeed<'de> for TagOrContentVisitor<'de> {
type Value = TagOrContent<'de>;
fn deserialize(self, deserializer: D) -> Result
where
D: Deserializer<'de>,
{
// Internally tagged enums are only supported in self-describing
// formats.
deserializer.deserialize_any(self)
}
}
#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)]
impl<'de> Visitor<'de> for TagOrContentVisitor<'de> {
type Value = TagOrContent<'de>;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "a type tag `{}` or any other value", self.name)
}
fn visit_bool(self, value: bool) -> Result
where
F: de::Error,
{
ContentVisitor::new()
.visit_bool(value)
.map(TagOrContent::Content)
}
fn visit_i8(self, value: i8) -> Result
where
F: de::Error,
{
ContentVisitor::new()
.visit_i8(value)
.map(TagOrContent::Content)
}
fn visit_i16(self, value: i16) -> Result
where
F: de::Error,
{
ContentVisitor::new()
.visit_i16(value)
.map(TagOrContent::Content)
}
fn visit_i32(self, value: i32) -> Result
where
F: de::Error,
{
ContentVisitor::new()
.visit_i32(value)
.map(TagOrContent::Content)
}
fn visit_i64(self, value: i64) -> Result
where
F: de::Error,
{
ContentVisitor::new()
.visit_i64(value)
.map(TagOrContent::Content)
}
fn visit_u8(self, value: u8) -> Result
where
F: de::Error,
{
ContentVisitor::new()
.visit_u8(value)
.map(TagOrContent::Content)
}
fn visit_u16(self, value: u16) -> Result
where
F: de::Error,
{
ContentVisitor::new()
.visit_u16(value)
.map(TagOrContent::Content)
}
fn visit_u32(self, value: u32) -> Result
where
F: de::Error,
{
ContentVisitor::new()
.visit_u32(value)
.map(TagOrContent::Content)
}
fn visit_u64(self, value: u64) -> Result
where
F: de::Error,
{
ContentVisitor::new()
.visit_u64(value)
.map(TagOrContent::Content)
}
fn visit_f32(self, value: f32) -> Result
where
F: de::Error,
{
ContentVisitor::new()
.visit_f32(value)
.map(TagOrContent::Content)
}
fn visit_f64(self, value: f64) -> Result
where
F: de::Error,
{
ContentVisitor::new()
.visit_f64(value)
.map(TagOrContent::Content)
}
fn visit_char(self, value: char) -> Result
where
F: de::Error,
{
ContentVisitor::new()
.visit_char(value)
.map(TagOrContent::Content)
}
fn visit_str(self, value: &str) -> Result
where
F: de::Error,
{
if value == self.name {
Ok(TagOrContent::Tag)
} else {
ContentVisitor::new()
.visit_str(value)
.map(TagOrContent::Content)
}
}
fn visit_borrowed_str(self, value: &'de str) -> Result
where
F: de::Error,
{
if value == self.name {
Ok(TagOrContent::Tag)
} else {
ContentVisitor::new()
.visit_borrowed_str(value)
.map(TagOrContent::Content)
}
}
fn visit_string(self, value: String) -> Result
where
F: de::Error,
{
if value == self.name {
Ok(TagOrContent::Tag)
} else {
ContentVisitor::new()
.visit_string(value)
.map(TagOrContent::Content)
}
}
fn visit_bytes(self, value: &[u8]) -> Result
where
F: de::Error,
{
if value == self.name.as_bytes() {
Ok(TagOrContent::Tag)
} else {
ContentVisitor::new()
.visit_bytes(value)
.map(TagOrContent::Content)
}
}
fn visit_borrowed_bytes(self, value: &'de [u8]) -> Result
where
F: de::Error,
{
if value == self.name.as_bytes() {
Ok(TagOrContent::Tag)
} else {
ContentVisitor::new()
.visit_borrowed_bytes(value)
.map(TagOrContent::Content)
}
}
fn visit_byte_buf(self, value: Vec) -> Result
where
F: de::Error,
{
if value == self.name.as_bytes() {
Ok(TagOrContent::Tag)
} else {
ContentVisitor::new()
.visit_byte_buf(value)
.map(TagOrContent::Content)
}
}
fn visit_unit(self) -> Result
where
F: de::Error,
{
ContentVisitor::new()
.visit_unit()
.map(TagOrContent::Content)
}
fn visit_none(self) -> Result
where
F: de::Error,
{
ContentVisitor::new()
.visit_none()
.map(TagOrContent::Content)
}
fn visit_some(self, deserializer: D) -> Result
where
D: Deserializer<'de>,
{
ContentVisitor::new()
.visit_some(deserializer)
.map(TagOrContent::Content)
}
fn visit_newtype_struct(self, deserializer: D) -> Result
where
D: Deserializer<'de>,
{
ContentVisitor::new()
.visit_newtype_struct(deserializer)
.map(TagOrContent::Content)
}
fn visit_seq(self, visitor: V) -> Result
where
V: SeqAccess<'de>,
{
ContentVisitor::new()
.visit_seq(visitor)
.map(TagOrContent::Content)
}
fn visit_map(self, visitor: V) -> Result
where
V: MapAccess<'de>,
{
ContentVisitor::new()
.visit_map(visitor)
.map(TagOrContent::Content)
}
fn visit_enum(self, visitor: V) -> Result
where
V: EnumAccess<'de>,
{
ContentVisitor::new()
.visit_enum(visitor)
.map(TagOrContent::Content)
}
}
/// Used by generated code to deserialize an internally tagged enum.
///
/// Captures map or sequence from the original deserializer and searches
/// a tag in it (in case of sequence, tag is the first element of sequence).
///
/// Not public API.
pub struct TaggedContentVisitor {
tag_name: &'static str,
expecting: &'static str,
value: PhantomData,
}
impl TaggedContentVisitor {
/// Visitor for the content of an internally tagged enum with the given
/// tag name.
pub fn new(name: &'static str, expecting: &'static str) -> Self {
TaggedContentVisitor {
tag_name: name,
expecting,
value: PhantomData,
}
}
}
#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)]
impl<'de, T> Visitor<'de> for TaggedContentVisitor
where
T: Deserialize<'de>,
{
type Value = (T, Content<'de>);
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(self.expecting)
}
fn visit_seq(self, mut seq: S) -> Result
where
S: SeqAccess<'de>,
{
let tag = match tri!(seq.next_element()) {
Some(tag) => tag,
None => {
return Err(de::Error::missing_field(self.tag_name));
}
};
let rest = de::value::SeqAccessDeserializer::new(seq);
Ok((tag, tri!(ContentVisitor::new().deserialize(rest))))
}
fn visit_map(self, mut map: M) -> Result
where
M: MapAccess<'de>,
{
let mut tag = None;
let mut vec = Vec::<(Content, Content)>::with_capacity(size_hint::cautious::<(
Content,
Content,
)>(map.size_hint()));
while let Some(k) = tri!(map.next_key_seed(TagOrContentVisitor::new(self.tag_name))) {
match k {
TagOrContent::Tag => {
if tag.is_some() {
return Err(de::Error::duplicate_field(self.tag_name));
}
tag = Some(tri!(map.next_value()));
}
TagOrContent::Content(k) => {
let v = tri!(map.next_value_seed(ContentVisitor::new()));
vec.push((k, v));
}
}
}
match tag {
None => Err(de::Error::missing_field(self.tag_name)),
Some(tag) => Ok((tag, Content::Map(vec))),
}
}
}
/// Used by generated code to deserialize an adjacently tagged enum.
///
/// Not public API.
pub enum TagOrContentField {
Tag,
Content,
}
/// Not public API.
pub struct TagOrContentFieldVisitor {
/// Name of the tag field of the adjacently tagged enum
pub tag: &'static str,
/// Name of the content field of the adjacently tagged enum
pub content: &'static str,
}
#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)]
impl<'de> DeserializeSeed<'de> for TagOrContentFieldVisitor {
type Value = TagOrContentField;
fn deserialize(self, deserializer: D) -> Result
where
D: Deserializer<'de>,
{
deserializer.deserialize_identifier(self)
}
}
#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)]
impl<'de> Visitor<'de> for TagOrContentFieldVisitor {
type Value = TagOrContentField;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "{:?} or {:?}", self.tag, self.content)
}
fn visit_u64(self, field_index: u64) -> Result
where
E: de::Error,
{
match field_index {
0 => Ok(TagOrContentField::Tag),
1 => Ok(TagOrContentField::Content),
_ => Err(de::Error::invalid_value(
Unexpected::Unsigned(field_index),
&self,
)),
}
}
fn visit_str(self, field: &str) -> Result
where
E: de::Error,
{
if field == self.tag {
Ok(TagOrContentField::Tag)
} else if field == self.content {
Ok(TagOrContentField::Content)
} else {
Err(de::Error::invalid_value(Unexpected::Str(field), &self))
}
}
fn visit_bytes(self, field: &[u8]) -> Result
where
E: de::Error,
{
if field == self.tag.as_bytes() {
Ok(TagOrContentField::Tag)
} else if field == self.content.as_bytes() {
Ok(TagOrContentField::Content)
} else {
Err(de::Error::invalid_value(Unexpected::Bytes(field), &self))
}
}
}
/// Used by generated code to deserialize an adjacently tagged enum when
/// ignoring unrelated fields is allowed.
///
/// Not public API.
pub enum TagContentOtherField {
Tag,
Content,
Other,
}
/// Not public API.
pub struct TagContentOtherFieldVisitor {
/// Name of the tag field of the adjacently tagged enum
pub tag: &'static str,
/// Name of the content field of the adjacently tagged enum
pub content: &'static str,
}
#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)]
impl<'de> DeserializeSeed<'de> for TagContentOtherFieldVisitor {
type Value = TagContentOtherField;
fn deserialize(self, deserializer: D) -> Result
where
D: Deserializer<'de>,
{
deserializer.deserialize_identifier(self)
}
}
#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)]
impl<'de> Visitor<'de> for TagContentOtherFieldVisitor {
type Value = TagContentOtherField;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(
formatter,
"{:?}, {:?}, or other ignored fields",
self.tag, self.content
)
}
fn visit_u64(self, field_index: u64) -> Result
where
E: de::Error,
{
match field_index {
0 => Ok(TagContentOtherField::Tag),
1 => Ok(TagContentOtherField::Content),
_ => Ok(TagContentOtherField::Other),
}
}
fn visit_str(self, field: &str) -> Result
where
E: de::Error,
{
self.visit_bytes(field.as_bytes())
}
fn visit_bytes(self, field: &[u8]) -> Result
where
E: de::Error,
{
if field == self.tag.as_bytes() {
Ok(TagContentOtherField::Tag)
} else if field == self.content.as_bytes() {
Ok(TagContentOtherField::Content)
} else {
Ok(TagContentOtherField::Other)
}
}
}
/// Not public API
pub struct ContentDeserializer<'de, E> {
content: Content<'de>,
err: PhantomData,
}
impl<'de, E> ContentDeserializer<'de, E>
where
E: de::Error,
{
#[cold]
fn invalid_type(self, exp: &dyn Expected) -> E {
de::Error::invalid_type(content_unexpected(&self.content), exp)
}
fn deserialize_integer(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
match self.content {
Content::U8(v) => visitor.visit_u8(v),
Content::U16(v) => visitor.visit_u16(v),
Content::U32(v) => visitor.visit_u32(v),
Content::U64(v) => visitor.visit_u64(v),
Content::I8(v) => visitor.visit_i8(v),
Content::I16(v) => visitor.visit_i16(v),
Content::I32(v) => visitor.visit_i32(v),
Content::I64(v) => visitor.visit_i64(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_float(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
match self.content {
Content::F32(v) => visitor.visit_f32(v),
Content::F64(v) => visitor.visit_f64(v),
Content::U8(v) => visitor.visit_u8(v),
Content::U16(v) => visitor.visit_u16(v),
Content::U32(v) => visitor.visit_u32(v),
Content::U64(v) => visitor.visit_u64(v),
Content::I8(v) => visitor.visit_i8(v),
Content::I16(v) => visitor.visit_i16(v),
Content::I32(v) => visitor.visit_i32(v),
Content::I64(v) => visitor.visit_i64(v),
_ => Err(self.invalid_type(&visitor)),
}
}
}
fn visit_content_seq<'de, V, E>(content: Vec>, visitor: V) -> Result
where
V: Visitor<'de>,
E: de::Error,
{
let mut seq_visitor = SeqDeserializer::new(content);
let value = tri!(visitor.visit_seq(&mut seq_visitor));
tri!(seq_visitor.end());
Ok(value)
}
fn visit_content_map<'de, V, E>(
content: Vec<(Content<'de>, Content<'de>)>,
visitor: V,
) -> Result
where
V: Visitor<'de>,
E: de::Error,
{
let mut map_visitor = MapDeserializer::new(content);
let value = tri!(visitor.visit_map(&mut map_visitor));
tri!(map_visitor.end());
Ok(value)
}
/// Used when deserializing an internally tagged enum because the content
/// will be used exactly once.
#[cfg_attr(not(no_diagnostic_namespace), diagnostic::do_not_recommend)]
impl<'de, E> Deserializer<'de> for ContentDeserializer<'de, E>
where
E: de::Error,
{
type Error = E;
fn deserialize_any(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
match self.content {
Content::Bool(v) => visitor.visit_bool(v),
Content::U8(v) => visitor.visit_u8(v),
Content::U16(v) => visitor.visit_u16(v),
Content::U32(v) => visitor.visit_u32(v),
Content::U64(v) => visitor.visit_u64(v),
Content::I8(v) => visitor.visit_i8(v),
Content::I16(v) => visitor.visit_i16(v),
Content::I32(v) => visitor.visit_i32(v),
Content::I64(v) => visitor.visit_i64(v),
Content::F32(v) => visitor.visit_f32(v),
Content::F64(v) => visitor.visit_f64(v),
Content::Char(v) => visitor.visit_char(v),
Content::String(v) => visitor.visit_string(v),
Content::Str(v) => visitor.visit_borrowed_str(v),
Content::ByteBuf(v) => visitor.visit_byte_buf(v),
Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
Content::Unit => visitor.visit_unit(),
Content::None => visitor.visit_none(),
Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)),
Content::Seq(v) => visit_content_seq(v, visitor),
Content::Map(v) => visit_content_map(v, visitor),
}
}
fn deserialize_bool(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
match self.content {
Content::Bool(v) => visitor.visit_bool(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_i8(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_i16(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_i32(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_i64(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_u8(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_u16(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_u32(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_u64(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
self.deserialize_integer(visitor)
}
fn deserialize_f32(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
self.deserialize_float(visitor)
}
fn deserialize_f64(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
self.deserialize_float(visitor)
}
fn deserialize_char(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
match self.content {
Content::Char(v) => visitor.visit_char(v),
Content::String(v) => visitor.visit_string(v),
Content::Str(v) => visitor.visit_borrowed_str(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_str(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
self.deserialize_string(visitor)
}
fn deserialize_string(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
match self.content {
Content::String(v) => visitor.visit_string(v),
Content::Str(v) => visitor.visit_borrowed_str(v),
Content::ByteBuf(v) => visitor.visit_byte_buf(v),
Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_bytes(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
self.deserialize_byte_buf(visitor)
}
fn deserialize_byte_buf(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
match self.content {
Content::String(v) => visitor.visit_string(v),
Content::Str(v) => visitor.visit_borrowed_str(v),
Content::ByteBuf(v) => visitor.visit_byte_buf(v),
Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
Content::Seq(v) => visit_content_seq(v, visitor),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_option(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
match self.content {
Content::None => visitor.visit_none(),
Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
Content::Unit => visitor.visit_unit(),
_ => visitor.visit_some(self),
}
}
fn deserialize_unit(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
match self.content {
Content::Unit => visitor.visit_unit(),
// Allow deserializing newtype variant containing unit.
//
// #[derive(Deserialize)]
// #[serde(tag = "result")]
// enum Response {
// Success(T),
// }
//
// We want {"result":"Success"} to deserialize into Response<()>.
Content::Map(ref v) if v.is_empty() => visitor.visit_unit(),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_unit_struct(
self,
_name: &'static str,
visitor: V,
) -> Result
where
V: Visitor<'de>,
{
match self.content {
// As a special case, allow deserializing untagged newtype
// variant containing unit struct.
//
// #[derive(Deserialize)]
// struct Info;
//
// #[derive(Deserialize)]
// #[serde(tag = "topic")]
// enum Message {
// Info(Info),
// }
//
// We want {"topic":"Info"} to deserialize even though
// ordinarily unit structs do not deserialize from empty map/seq.
Content::Map(ref v) if v.is_empty() => visitor.visit_unit(),
Content::Seq(ref v) if v.is_empty() => visitor.visit_unit(),
_ => self.deserialize_any(visitor),
}
}
fn deserialize_newtype_struct(
self,
_name: &str,
visitor: V,
) -> Result
where
V: Visitor<'de>,
{
match self.content {
Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)),
_ => visitor.visit_newtype_struct(self),
}
}
fn deserialize_seq(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
match self.content {
Content::Seq(v) => visit_content_seq(v, visitor),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_tuple(self, _len: usize, visitor: V) -> Result
where
V: Visitor<'de>,
{
self.deserialize_seq(visitor)
}
fn deserialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
visitor: V,
) -> Result
where
V: Visitor<'de>,
{
self.deserialize_seq(visitor)
}
fn deserialize_map(self, visitor: V) -> Result
where
V: Visitor<'de>,
{
match self.content {
Content::Map(v) => visit_content_map(v, visitor),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_struct(
self,
_name: &'static str,
_fields: &'static [&'static str],
visitor: V,
) -> Result
where
V: Visitor<'de>,
{
match self.content {
Content::Seq(v) => visit_content_seq(v, visitor),
Content::Map(v) => visit_content_map(v, visitor),
_ => Err(self.invalid_type(&visitor)),
}
}
fn deserialize_enum(
self,
_name: &str,
_variants: &'static [&'static str],
visitor: V,
) -> Result
where
V: Visitor<'de>,
{
let (variant, value) = match self.content {
Content::Map(value) => {
let mut iter = value.into_iter();
let (variant, value) = match iter.next() {
Some(v) => v,
None => {
return Err(de::Error::invalid_value(
de::Unexpected::Map,
&"map with a single key",
));
}
};
// enums are encoded in json as maps with a single key:value pair
if iter.next().is_some() {
return Err(de::Error::invalid_value(
de::Unexpected::Map,
&"map with a single key",
));
}
(variant, Some(value))
}
s @ Content::String(_) | s @ Content::Str(_) => (s, None),
other => {
return Err(de::Error::invalid_type(
content_unexpected(&other),
&"string or map",
));
}
};
visitor.visit_enum(EnumDeserializer::new(variant, value))
}
fn deserialize_identifier(self, visitor: V) -> Result