mirror of
https://github.com/pezkuwichain/serde.git
synced 2026-04-22 21:48:02 +00:00
Compare commits
445 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 18dcae0a77 | |||
| 58c307f9cc | |||
| 8cc4809414 | |||
| 1179158def | |||
| 91aa40e749 | |||
| 595019e979 | |||
| b0d7917f88 | |||
| 8e6637a1e4 | |||
| 694fe05953 | |||
| f3dfd2a237 | |||
| 9e6158e9e6 | |||
| d577c4a2ce | |||
| fee0b82a40 | |||
| 7aafa26314 | |||
| d5bc546ca5 | |||
| 45ae217728 | |||
| b7b97dda73 | |||
| 5d3c563d46 | |||
| 376185458b | |||
| a8f14840ab | |||
| 9e32a40b1c | |||
| 87f635e54d | |||
| d4b2dfbde2 | |||
| f6ab0bc56f | |||
| 48cc2a6327 | |||
| 3202a6858a | |||
| b4f1bc16ff | |||
| 029ab46f71 | |||
| 220ca0ca9d | |||
| 20306f493a | |||
| cc865ac523 | |||
| 2d973c1805 | |||
| 6ca499b2dd | |||
| 1477028717 | |||
| 789740be0d | |||
| 8fe7539bb2 | |||
| f6623a3654 | |||
| c4fb923335 | |||
| 65b7eea775 | |||
| 01cd696fd1 | |||
| c13b3f7e68 | |||
| a6571ee0da | |||
| 6e38afff49 | |||
| 3d1b19ed90 | |||
| 5b24f88e73 | |||
| 74d06708dd | |||
| 3bfab6ef7f | |||
| 364cd8d8f7 | |||
| 9f8c579bf5 | |||
| eae7c2d684 | |||
| 3f43fca90d | |||
| 76449488ca | |||
| 00c4b0cef8 | |||
| 89139e2c11 | |||
| c9cab490f7 | |||
| 5fa711d75d | |||
| f5d8ae423a | |||
| 1d54973b92 | |||
| b8fafefd85 | |||
| c42ebb8839 | |||
| 9e680620b5 | |||
| 846f865de2 | |||
| ede9762a58 | |||
| d438c2d67b | |||
| bef110b92a | |||
| b971ef11d1 | |||
| 29d9f69399 | |||
| aecb4083bd | |||
| 1c675ab3a3 | |||
| dd619630a3 | |||
| 111803ab07 | |||
| 0024f74f34 | |||
| 03eec42c33 | |||
| 196f311ae2 | |||
| 38d9e0b209 | |||
| 6502b31316 | |||
| 6f1a8c3115 | |||
| d883c94cc9 | |||
| 961fa59a74 | |||
| 8bc71def55 | |||
| 7c65a9dc0e | |||
| d2d977a6c6 | |||
| a9a6ee9d7f | |||
| 28c5d215c1 | |||
| 3d6a789562 | |||
| a0e68698e3 | |||
| 44613c7d01 | |||
| c706281df3 | |||
| 65d75b8fe3 | |||
| 332b0cba40 | |||
| 8c4af41296 | |||
| 24a78f071b | |||
| c91c33436d | |||
| 2083f43a28 | |||
| 4676abdc9e | |||
| 35700eb23e | |||
| 59892e7b58 | |||
| 97dd07a7d1 | |||
| c8bc97c81b | |||
| 9dacfbbd69 | |||
| 05c2509d07 | |||
| 64f949b37b | |||
| 3f339de36a | |||
| 215c2b71ef | |||
| ce8fef7e0b | |||
| 0726b2c479 | |||
| 589549d7e6 | |||
| edb1a586d8 | |||
| 11c2917040 | |||
| 6ba9c12ff6 | |||
| d2fcc346b9 | |||
| a091a07aa2 | |||
| bb4135cae8 | |||
| 8de84b7ca3 | |||
| 9cdf332029 | |||
| e94fc65f01 | |||
| b908487476 | |||
| 2a7c7faeb4 | |||
| e302e15eea | |||
| 1cbea892cf | |||
| 37a32857a2 | |||
| 8c4aad3a59 | |||
| 1774794b19 | |||
| 1af23f1f2d | |||
| 94fbc3d388 | |||
| 8da2058e2a | |||
| 09993a904a | |||
| 5d1403461c | |||
| ddc1ee564b | |||
| 00a54b848a | |||
| dad15b9fd0 | |||
| d89c19f903 | |||
| 146dc0fad5 | |||
| d26852deef | |||
| e1c27243b2 | |||
| dbbfe7abe2 | |||
| dc24d12ce0 | |||
| 4e7533e872 | |||
| 5d036515ed | |||
| a741293886 | |||
| f8d0b26d2f | |||
| 7007c1bea5 | |||
| 0d8ebac7e1 | |||
| 212c42c74f | |||
| 919f6be887 | |||
| c0f70428ba | |||
| e797c90ebd | |||
| fc04d1219a | |||
| df4ad5884d | |||
| 3c7dd6fc1e | |||
| 8b196ea1c8 | |||
| 1f8c8ad5a3 | |||
| 870925d503 | |||
| d593215ef7 | |||
| 110af31b48 | |||
| 360606b9a6 | |||
| 151b45ae36 | |||
| 2ea7e1300f | |||
| 4617c957b9 | |||
| 2547ed83ca | |||
| bfcd44704f | |||
| 7b548db91e | |||
| d39dea85ad | |||
| 5e56c9fba8 | |||
| 8d3a03288b | |||
| cb490ec16d | |||
| 45271c3676 | |||
| 6a097eca93 | |||
| 84d1c5385d | |||
| 05a5b7e3c6 | |||
| 3bff326fb3 | |||
| aaadd93878 | |||
| 9c864f0b02 | |||
| 070cce0d9c | |||
| b58e8bac12 | |||
| ada50b077e | |||
| 5e313a7330 | |||
| 2a36d11238 | |||
| b6685cf9dd | |||
| fc273c6763 | |||
| bd7b0e257e | |||
| 73931692b2 | |||
| 4d93e9f44c | |||
| da55ed7e8d | |||
| e3617e1f28 | |||
| 431636af0d | |||
| 891ced598a | |||
| 57dc0ee769 | |||
| 5e102c4da1 | |||
| 5c33931422 | |||
| 4aa54222f4 | |||
| ef4f860384 | |||
| 9bd52ec5c1 | |||
| 5cdd82d41e | |||
| 110bf10481 | |||
| 43035f6f37 | |||
| 83b1a3d5dc | |||
| 878110a4bc | |||
| 59ec8b7db2 | |||
| cae1b43829 | |||
| 99fde4ee3e | |||
| afe3872810 | |||
| 3a3e6bf103 | |||
| 935f0bd70f | |||
| 5c18bfeda6 | |||
| 957ef206d1 | |||
| 0c367838cc | |||
| 2023cf345f | |||
| 033d05f70b | |||
| fe4e3fd3b0 | |||
| 8a8a8a70ee | |||
| 339dca828d | |||
| 0d7349fa4e | |||
| 830528d5b1 | |||
| ab90fbc7c9 | |||
| 3eec111e8f | |||
| 9388433642 | |||
| ba12070665 | |||
| a57a324d72 | |||
| 92e91b3557 | |||
| 4dcf791706 | |||
| e77900fb94 | |||
| 1b14cadf20 | |||
| 4f59cd217a | |||
| 27c8b2d66a | |||
| 89976c2712 | |||
| c91737fef1 | |||
| a100719bc6 | |||
| 9a0e149225 | |||
| 9350927903 | |||
| 677c13a4ec | |||
| ee8e1ee7ff | |||
| f969080b9f | |||
| c2b16bfbb0 | |||
| e7df53701c | |||
| 02c34e490b | |||
| 427c839b3d | |||
| 48aa054f53 | |||
| 3616860203 | |||
| 861b0dfea2 | |||
| 8b3d71ae2d | |||
| ff5442cd9e | |||
| 92d686f9a5 | |||
| 7b09cccd77 | |||
| 6f1f38d046 | |||
| db8f06467b | |||
| 91ec1c290f | |||
| 0676673ca5 | |||
| 7a4335d664 | |||
| 31a0e73489 | |||
| 74fe70855f | |||
| e74925bc43 | |||
| 56be1c203e | |||
| 2f9bf4d3eb | |||
| ad94aed753 | |||
| 30db83fc44 | |||
| b0f7b00e1f | |||
| 7255e192d8 | |||
| 2102e1aa42 | |||
| 85d5c1fd38 | |||
| b789286bc3 | |||
| a6a8a334f7 | |||
| 78a11a27b6 | |||
| d2d7bad04a | |||
| b978854258 | |||
| 0fb672a1ef | |||
| dd9913675d | |||
| 11677ad926 | |||
| 25a53f10db | |||
| 26e2ef001c | |||
| 30f79b3b2e | |||
| 89f84c2915 | |||
| 6882285be0 | |||
| 3260bc5896 | |||
| 6140b6f527 | |||
| 4cabc9f293 | |||
| aa7c6345a4 | |||
| f709fc05b0 | |||
| 089aae1292 | |||
| 855acaf112 | |||
| 7ca7720262 | |||
| 78fea3aa4a | |||
| 1efb8b6a53 | |||
| bc1960b106 | |||
| 967023b755 | |||
| bb51e68f16 | |||
| 27414c90a8 | |||
| 50e2f4b213 | |||
| 22be673beb | |||
| 166c89fabf | |||
| 6e0b13eedb | |||
| 7e8f978ca9 | |||
| 6c0e838a7c | |||
| d3da41927a | |||
| 425a4b7a74 | |||
| 63c65ef742 | |||
| e838b0bd81 | |||
| 041e99c78a | |||
| 07dcc4f7fe | |||
| b88052d875 | |||
| a28292764c | |||
| 2027088741 | |||
| e2d8589976 | |||
| c8a9f99d14 | |||
| 645d04012d | |||
| 100ddada2f | |||
| 2ef1cd4b35 | |||
| be9c3fd69d | |||
| ef522e1d16 | |||
| 1ddb6c2fdb | |||
| eb3f2329af | |||
| 9e8f14816b | |||
| 4e5e55bf1c | |||
| 4513a9e6a7 | |||
| 4f922e4e5b | |||
| 993966600e | |||
| 5b96cf1bde | |||
| f3d50e5209 | |||
| ab21d4d017 | |||
| f7c5d93e6a | |||
| 52a7d40e6e | |||
| 348bc6b257 | |||
| 03da66c805 | |||
| f75426f47e | |||
| 662fc3861c | |||
| 28c10020b9 | |||
| 89c8d85de9 | |||
| 6502838f27 | |||
| c93a0f335a | |||
| 8264e002a7 | |||
| 117ef22142 | |||
| 3fb5e71c33 | |||
| 296db177e2 | |||
| e4a4389177 | |||
| 7aa0453c3b | |||
| 09b78b24e9 | |||
| a622b8a74a | |||
| 399ef081ec | |||
| 3686277e14 | |||
| 807bd20a64 | |||
| ed9a140348 | |||
| 2de7c2bea2 | |||
| e6a4a3772e | |||
| 0fca04e1a6 | |||
| 92bfc8d3af | |||
| fa0312ac45 | |||
| 1920b694aa | |||
| 3bfd41d624 | |||
| 290449f19b | |||
| 3a1f387e69 | |||
| 541603ac94 | |||
| 0666fbfa20 | |||
| ea071ae1d4 | |||
| 992a01bad2 | |||
| d640b5624f | |||
| 48479e4bae | |||
| dfaf48bc09 | |||
| dcbc3e0162 | |||
| 0289d31724 | |||
| 015e39776f | |||
| 6a9a21f178 | |||
| 81ac54b20d | |||
| 6b4e75520a | |||
| b053b4f492 | |||
| 4cf1fec575 | |||
| ee7d77defa | |||
| d0dfc4577e | |||
| bbbd1d24c9 | |||
| fb3a9e0d7c | |||
| 5ffebeb6ef | |||
| 75db73066b | |||
| 2796833c82 | |||
| 95730dc7f7 | |||
| 795261919f | |||
| 3783a30ae7 | |||
| b61ec84886 | |||
| 780a461d92 | |||
| c0ba323166 | |||
| 20a48c9580 | |||
| 09938803af | |||
| 6d0b43a220 | |||
| c604bdbfe4 | |||
| 9fef892f6d | |||
| b1c7db47b8 | |||
| e76e87a430 | |||
| 8a4dfa7231 | |||
| 107018c628 | |||
| a398237930 | |||
| b63c65d7f5 | |||
| f60324e883 | |||
| 361c23a09a | |||
| 43b23c7ea0 | |||
| 6081497506 | |||
| 48e5753e76 | |||
| bbba632ab3 | |||
| e77db40b8d | |||
| 2c1f62d4b4 | |||
| 1aebdc2760 | |||
| 705e58be8c | |||
| 7c2c12aa43 | |||
| a0f850f15b | |||
| fccb9499bc | |||
| a139ab2572 | |||
| 1d910a484c | |||
| ee9166ec97 | |||
| b5a9eff32e | |||
| 9441a29663 | |||
| ab6588ef74 | |||
| 1d11f03449 | |||
| e11d01fe1d | |||
| a901f50850 | |||
| c399e9c368 | |||
| 25381be0c9 | |||
| ef2a7c753f | |||
| 99f165b45a | |||
| 2fb5560746 | |||
| bd653ab30c | |||
| b5d68aedaa | |||
| 624879c4c6 | |||
| bd9e9abf35 | |||
| 3e4a23cbd0 | |||
| 6326ceec3f | |||
| 8f4d37c7ec | |||
| 1b8290b318 | |||
| 48193fbccd | |||
| 51799dd654 | |||
| 732ac49321 | |||
| ac8ea72d88 | |||
| f583401284 | |||
| 2d88228b7d | |||
| 0c6a2bbf79 | |||
| a80d830f27 | |||
| 5f3fd9994e | |||
| d6de911855 | |||
| 04af32230e | |||
| 4cb8d079f8 | |||
| 6ab55a1e52 | |||
| acfd19cb46 | |||
| e3058105f0 | |||
| dc200a6450 | |||
| 2c0999a0b9 | |||
| dd460f82a1 | |||
| c3d637f397 | |||
| a803ec1c1f | |||
| 983347484e |
@@ -1 +0,0 @@
|
||||
test_suite/tests/expand/*.expanded.rs linguist-generated
|
||||
+42
-33
@@ -3,6 +3,7 @@ name: CI
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
schedule: [cron: "40 1 * * *"]
|
||||
|
||||
permissions:
|
||||
@@ -17,7 +18,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@nightly
|
||||
- run: cd test_suite && cargo test --features unstable
|
||||
|
||||
@@ -26,7 +27,7 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@nightly
|
||||
- run: cd test_suite && cargo test --features unstable -- --skip ui --exact
|
||||
|
||||
@@ -39,14 +40,12 @@ jobs:
|
||||
rust: [stable, beta]
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- 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 serde_test && cargo build
|
||||
- run: cd serde_test && cargo test --features serde/derive,serde/rc
|
||||
|
||||
nightly:
|
||||
name: Rust nightly ${{matrix.os == 'windows' && '(windows)' || ''}}
|
||||
@@ -57,12 +56,13 @@ jobs:
|
||||
os: [ubuntu, windows]
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- 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 && cargo test --features derive,rc,unstable
|
||||
- run: cd test_suite/no_std && cargo build
|
||||
if: matrix.os != 'windows'
|
||||
@@ -77,43 +77,26 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
rust: [1.19.0, 1.20.0, 1.21.0, 1.25.0, 1.26.0, 1.34.0]
|
||||
rust: [1.31.0, 1.34.0]
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- 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
|
||||
- run: cd serde_test && cargo build
|
||||
|
||||
more:
|
||||
name: Rust ${{matrix.rust}}
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
rust: [1.27.0, 1.28.0]
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: ${{matrix.rust}}
|
||||
# Work around failing to parse manifest because editions are unstable.
|
||||
- run: sed -i /test_suite/d Cargo.toml
|
||||
- run: cd serde && cargo build --no-default-features
|
||||
- run: cd serde && cargo build
|
||||
|
||||
derive:
|
||||
name: Rust 1.56.0
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@1.56.0
|
||||
- run: sed -i '/"test_suite"/d' Cargo.toml
|
||||
- run: cd serde && cargo check --no-default-features
|
||||
- run: cd serde && cargo check
|
||||
- run: cd serde_derive && cargo check
|
||||
@@ -123,22 +106,46 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@1.36.0
|
||||
- run: sed -i '/"test_suite"/d' Cargo.toml
|
||||
- run: cd serde && cargo build --no-default-features --features alloc
|
||||
|
||||
minimal:
|
||||
name: Minimal versions
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- 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@v4
|
||||
- uses: dtolnay/rust-toolchain@nightly
|
||||
- uses: dtolnay/install@cargo-docs-rs
|
||||
- run: cargo docs-rs -p serde
|
||||
- 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@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@clippy
|
||||
- run: cd serde && 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 serde_test && 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
|
||||
|
||||
@@ -147,8 +154,9 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@miri
|
||||
- run: cargo miri setup
|
||||
- run: cd serde && cargo miri test --features derive,rc,unstable
|
||||
env:
|
||||
MIRIFLAGS: -Zmiri-strict-provenance
|
||||
@@ -162,6 +170,7 @@ jobs:
|
||||
if: github.event_name != 'pull_request'
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: dtolnay/install@cargo-outdated
|
||||
- run: cargo outdated --workspace --exit-code 1
|
||||
|
||||
+8
-1
@@ -3,6 +3,13 @@ members = [
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_derive_internals",
|
||||
"serde_test",
|
||||
"test_suite",
|
||||
]
|
||||
|
||||
[patch.crates-io]
|
||||
serde = { path = "serde" }
|
||||
|
||||
[workspace.dependencies]
|
||||
proc-macro2 = { version = "1.0.74", default-features = false }
|
||||
quote = { version = "1.0.35", default-features = false }
|
||||
syn = { version = "2.0.46", default-features = false }
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# Serde   [![Build Status]][actions] [![Latest Version]][crates.io] [![serde: rustc 1.19+]][Rust 1.19] [![serde_derive: rustc 1.56+]][Rust 1.56]
|
||||
# Serde   [![Build Status]][actions] [![Latest Version]][crates.io] [![serde msrv]][Rust 1.31] [![serde_derive msrv]][Rust 1.56]
|
||||
|
||||
[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: rustc 1.19+]: https://img.shields.io/badge/serde-rustc_1.19+-lightgray.svg
|
||||
[serde_derive: rustc 1.56+]: https://img.shields.io/badge/serde_derive-rustc_1.56+-lightgray.svg
|
||||
[Rust 1.19]: https://blog.rust-lang.org/2017/07/20/Rust-1.19.html
|
||||
[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.31]: https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html
|
||||
[Rust 1.56]: https://blog.rust-lang.org/2021/10/21/Rust-1.56.0.html
|
||||
|
||||
**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.**
|
||||
@@ -48,7 +48,7 @@ serde_json = "1.0"
|
||||
<p></p>
|
||||
|
||||
```rust
|
||||
use serde::{Serialize, Deserialize};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
struct Point {
|
||||
|
||||
+3
-3
@@ -16,7 +16,7 @@ You may be looking for:
|
||||
## Serde in action
|
||||
|
||||
```rust
|
||||
use serde::{Serialize, Deserialize};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
struct Point {
|
||||
@@ -46,8 +46,8 @@ fn main() {
|
||||
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: <https://discord.gg/rust-lang-community>, the [#rust-usage] or
|
||||
[#beginners] channels of the official Rust Project Discord (invite:
|
||||
Discord (invite: <https://discord.gg/rust-lang-community>), the [#rust-usage]
|
||||
or [#beginners] channels of the official Rust Project Discord (invite:
|
||||
<https://discord.gg/rust-lang>), 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
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
msrv = "1.13.0"
|
||||
+16
-7
@@ -1,24 +1,24 @@
|
||||
[package]
|
||||
name = "serde"
|
||||
version = "1.0.157" # remember to update html_root_url and serde_derive dependency
|
||||
version = "1.0.204"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"]
|
||||
build = "build.rs"
|
||||
categories = ["encoding", "no-std"]
|
||||
categories = ["encoding", "no-std", "no-std::no-alloc"]
|
||||
description = "A generic serialization/deserialization framework"
|
||||
documentation = "https://docs.rs/serde"
|
||||
edition = "2018"
|
||||
homepage = "https://serde.rs"
|
||||
include = ["build.rs", "src/**/*.rs", "crates-io.md", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
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.19"
|
||||
rust-version = "1.31"
|
||||
|
||||
[dependencies]
|
||||
serde_derive = { version = "=1.0.157", optional = true, path = "../serde_derive" }
|
||||
serde_derive = { version = "1", optional = true, path = "../serde_derive" }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_derive = { version = "1.0", path = "../serde_derive" }
|
||||
serde_derive = { version = "1", path = "../serde_derive" }
|
||||
|
||||
[lib]
|
||||
doc-scrape-examples = false
|
||||
@@ -27,8 +27,17 @@ doc-scrape-examples = false
|
||||
features = ["derive", "rc"]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["derive"]
|
||||
features = ["derive", "rc", "unstable"]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
rustdoc-args = ["--generate-link-to-definition"]
|
||||
|
||||
# This cfg cannot be enabled, but it still forces Cargo to keep serde_derive's
|
||||
# version in lockstep with serde's, even if someone depends on the two crates
|
||||
# separately with serde's "derive" feature disabled. Every serde_derive release
|
||||
# is compatible with exactly one serde release because the generated code
|
||||
# involves nonpublic APIs which are not bound by semver.
|
||||
[target.'cfg(any())'.dependencies]
|
||||
serde_derive = { version = "=1.0.204", path = "../serde_derive" }
|
||||
|
||||
|
||||
### FEATURES #################################################################
|
||||
|
||||
+33
-62
@@ -13,71 +13,24 @@ fn main() {
|
||||
None => return,
|
||||
};
|
||||
|
||||
if minor >= 77 {
|
||||
println!("cargo:rustc-check-cfg=cfg(no_core_cstr)");
|
||||
println!("cargo:rustc-check-cfg=cfg(no_core_num_saturating)");
|
||||
println!("cargo:rustc-check-cfg=cfg(no_core_try_from)");
|
||||
println!("cargo:rustc-check-cfg=cfg(no_diagnostic_namespace)");
|
||||
println!("cargo:rustc-check-cfg=cfg(no_float_copysign)");
|
||||
println!("cargo:rustc-check-cfg=cfg(no_num_nonzero_signed)");
|
||||
println!("cargo:rustc-check-cfg=cfg(no_relaxed_trait_bounds)");
|
||||
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_systemtime_checked_add)");
|
||||
println!("cargo:rustc-check-cfg=cfg(no_target_has_atomic)");
|
||||
}
|
||||
|
||||
let target = env::var("TARGET").unwrap();
|
||||
let emscripten = target == "asmjs-unknown-emscripten" || target == "wasm32-unknown-emscripten";
|
||||
|
||||
// std::collections::Bound was stabilized in Rust 1.17
|
||||
// but it was moved to core::ops later in Rust 1.26:
|
||||
// https://doc.rust-lang.org/core/ops/enum.Bound.html
|
||||
if minor < 26 {
|
||||
println!("cargo:rustc-cfg=no_ops_bound");
|
||||
if minor < 17 {
|
||||
println!("cargo:rustc-cfg=no_collections_bound");
|
||||
}
|
||||
}
|
||||
|
||||
// core::cmp::Reverse stabilized in Rust 1.19:
|
||||
// https://doc.rust-lang.org/stable/core/cmp/struct.Reverse.html
|
||||
if minor < 19 {
|
||||
println!("cargo:rustc-cfg=no_core_reverse");
|
||||
}
|
||||
|
||||
// CString::into_boxed_c_str and PathBuf::into_boxed_path stabilized in Rust 1.20:
|
||||
// https://doc.rust-lang.org/std/ffi/struct.CString.html#method.into_boxed_c_str
|
||||
// https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.into_boxed_path
|
||||
if minor < 20 {
|
||||
println!("cargo:rustc-cfg=no_de_boxed_c_str");
|
||||
println!("cargo:rustc-cfg=no_de_boxed_path");
|
||||
}
|
||||
|
||||
// From<Box<T>> for Rc<T> / Arc<T> stabilized in Rust 1.21:
|
||||
// https://doc.rust-lang.org/std/rc/struct.Rc.html#impl-From<Box<T>>
|
||||
// https://doc.rust-lang.org/std/sync/struct.Arc.html#impl-From<Box<T>>
|
||||
if minor < 21 {
|
||||
println!("cargo:rustc-cfg=no_de_rc_dst");
|
||||
}
|
||||
|
||||
// Duration available in core since Rust 1.25:
|
||||
// https://blog.rust-lang.org/2018/03/29/Rust-1.25.html#library-stabilizations
|
||||
if minor < 25 {
|
||||
println!("cargo:rustc-cfg=no_core_duration");
|
||||
}
|
||||
|
||||
// 128-bit integers stabilized in Rust 1.26:
|
||||
// https://blog.rust-lang.org/2018/05/10/Rust-1.26.html
|
||||
//
|
||||
// Disabled on Emscripten targets before Rust 1.40 since
|
||||
// Emscripten did not support 128-bit integers until Rust 1.40
|
||||
// (https://github.com/rust-lang/rust/pull/65251)
|
||||
if minor < 26 || emscripten && minor < 40 {
|
||||
println!("cargo:rustc-cfg=no_integer128");
|
||||
}
|
||||
|
||||
// Inclusive ranges methods stabilized in Rust 1.27:
|
||||
// https://github.com/rust-lang/rust/pull/50758
|
||||
// Also Iterator::try_for_each:
|
||||
// https://blog.rust-lang.org/2018/06/21/Rust-1.27.html#library-stabilizations
|
||||
if minor < 27 {
|
||||
println!("cargo:rustc-cfg=no_range_inclusive");
|
||||
println!("cargo:rustc-cfg=no_iterator_try_fold");
|
||||
}
|
||||
|
||||
// Non-zero integers stabilized in Rust 1.28:
|
||||
// https://blog.rust-lang.org/2018/08/02/Rust-1.28.html#library-stabilizations
|
||||
if minor < 28 {
|
||||
println!("cargo:rustc-cfg=no_num_nonzero");
|
||||
}
|
||||
|
||||
// TryFrom, Atomic types, non-zero signed integers, and SystemTime::checked_add
|
||||
// stabilized in Rust 1.34:
|
||||
// https://blog.rust-lang.org/2019/04/11/Rust-1.34.0.html#tryfrom-and-tryinto
|
||||
@@ -89,6 +42,12 @@ fn main() {
|
||||
println!("cargo:rustc-cfg=no_relaxed_trait_bounds");
|
||||
}
|
||||
|
||||
// f32::copysign and f64::copysign stabilized in Rust 1.35.
|
||||
// https://blog.rust-lang.org/2019/05/23/Rust-1.35.0.html#copy-the-sign-of-a-floating-point-number-onto-another
|
||||
if minor < 35 {
|
||||
println!("cargo:rustc-cfg=no_float_copysign");
|
||||
}
|
||||
|
||||
// Current minimum supported version of serde_derive crate is Rust 1.56.
|
||||
if minor < 56 {
|
||||
println!("cargo:rustc-cfg=no_serde_derive");
|
||||
@@ -120,6 +79,18 @@ fn main() {
|
||||
if minor < 64 {
|
||||
println!("cargo:rustc-cfg=no_core_cstr");
|
||||
}
|
||||
|
||||
// Support for core::num::Saturating and std::num::Saturating stabilized in Rust 1.74
|
||||
// https://blog.rust-lang.org/2023/11/16/Rust-1.74.0.html#stabilized-apis
|
||||
if minor < 74 {
|
||||
println!("cargo:rustc-cfg=no_core_num_saturating");
|
||||
}
|
||||
|
||||
// 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<u32> {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use lib::fmt::{self, Write};
|
||||
use lib::str;
|
||||
use crate::lib::fmt::{self, Write};
|
||||
use crate::lib::str;
|
||||
|
||||
pub(super) struct Buf<'a> {
|
||||
bytes: &'a mut [u8],
|
||||
|
||||
+17
-22
@@ -1,6 +1,6 @@
|
||||
use lib::*;
|
||||
use crate::lib::*;
|
||||
|
||||
use de::{
|
||||
use crate::de::{
|
||||
Deserialize, Deserializer, EnumAccess, Error, MapAccess, SeqAccess, VariantAccess, Visitor,
|
||||
};
|
||||
|
||||
@@ -10,13 +10,12 @@ use de::{
|
||||
/// any type, except that it does not store any information about the data that
|
||||
/// gets deserialized.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// use std::fmt;
|
||||
/// use std::marker::PhantomData;
|
||||
///
|
||||
/// ```edition2021
|
||||
/// use serde::de::{
|
||||
/// self, Deserialize, DeserializeSeed, Deserializer, IgnoredAny, SeqAccess, Visitor,
|
||||
/// };
|
||||
/// use std::fmt;
|
||||
/// use std::marker::PhantomData;
|
||||
///
|
||||
/// /// A seed that can be used to deserialize only the `n`th element of a sequence
|
||||
/// /// while efficiently discarding elements of any type before or after index `n`.
|
||||
@@ -108,7 +107,7 @@ use de::{
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
#[derive(Copy, Clone, Debug, Default)]
|
||||
#[derive(Copy, Clone, Debug, Default, PartialEq)]
|
||||
pub struct IgnoredAny;
|
||||
|
||||
impl<'de> Visitor<'de> for IgnoredAny {
|
||||
@@ -130,12 +129,10 @@ impl<'de> Visitor<'de> for IgnoredAny {
|
||||
Ok(IgnoredAny)
|
||||
}
|
||||
|
||||
serde_if_integer128! {
|
||||
#[inline]
|
||||
fn visit_i128<E>(self, x: i128) -> Result<Self::Value, E> {
|
||||
let _ = x;
|
||||
Ok(IgnoredAny)
|
||||
}
|
||||
#[inline]
|
||||
fn visit_i128<E>(self, x: i128) -> Result<Self::Value, E> {
|
||||
let _ = x;
|
||||
Ok(IgnoredAny)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -144,12 +141,10 @@ impl<'de> Visitor<'de> for IgnoredAny {
|
||||
Ok(IgnoredAny)
|
||||
}
|
||||
|
||||
serde_if_integer128! {
|
||||
#[inline]
|
||||
fn visit_u128<E>(self, x: u128) -> Result<Self::Value, E> {
|
||||
let _ = x;
|
||||
Ok(IgnoredAny)
|
||||
}
|
||||
#[inline]
|
||||
fn visit_u128<E>(self, x: u128) -> Result<Self::Value, E> {
|
||||
let _ = x;
|
||||
Ok(IgnoredAny)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -198,7 +193,7 @@ impl<'de> Visitor<'de> for IgnoredAny {
|
||||
where
|
||||
A: SeqAccess<'de>,
|
||||
{
|
||||
while let Some(IgnoredAny) = try!(seq.next_element()) {
|
||||
while let Some(IgnoredAny) = tri!(seq.next_element()) {
|
||||
// Gobble
|
||||
}
|
||||
Ok(IgnoredAny)
|
||||
@@ -209,7 +204,7 @@ impl<'de> Visitor<'de> for IgnoredAny {
|
||||
where
|
||||
A: MapAccess<'de>,
|
||||
{
|
||||
while let Some((IgnoredAny, IgnoredAny)) = try!(map.next_entry()) {
|
||||
while let Some((IgnoredAny, IgnoredAny)) = tri!(map.next_entry()) {
|
||||
// Gobble
|
||||
}
|
||||
Ok(IgnoredAny)
|
||||
@@ -228,7 +223,7 @@ impl<'de> Visitor<'de> for IgnoredAny {
|
||||
where
|
||||
A: EnumAccess<'de>,
|
||||
{
|
||||
try!(data.variant::<IgnoredAny>()).1.newtype_variant()
|
||||
tri!(data.variant::<IgnoredAny>()).1.newtype_variant()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+754
-293
File diff suppressed because it is too large
Load Diff
+155
-118
@@ -64,8 +64,8 @@
|
||||
//! - RefCell\<T\>
|
||||
//! - Mutex\<T\>
|
||||
//! - RwLock\<T\>
|
||||
//! - Rc\<T\> *(if* features = ["rc"] *is enabled)*
|
||||
//! - Arc\<T\> *(if* features = ["rc"] *is enabled)*
|
||||
//! - Rc\<T\> *(if* features = \["rc"\] *is enabled)*
|
||||
//! - Arc\<T\> *(if* features = \["rc"\] *is enabled)*
|
||||
//! - **Collection types**:
|
||||
//! - BTreeMap\<K, V\>
|
||||
//! - BTreeSet\<T\>
|
||||
@@ -112,26 +112,28 @@
|
||||
//! [derive section of the manual]: https://serde.rs/derive.html
|
||||
//! [data formats]: https://serde.rs/#data-formats
|
||||
|
||||
use lib::*;
|
||||
use crate::lib::*;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub mod value;
|
||||
|
||||
#[cfg(not(no_integer128))]
|
||||
mod format;
|
||||
mod ignored_any;
|
||||
mod impls;
|
||||
mod utf8;
|
||||
pub(crate) mod size_hint;
|
||||
|
||||
pub use self::ignored_any::IgnoredAny;
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "unstable")))]
|
||||
#[doc(no_inline)]
|
||||
pub use crate::std_error::Error as StdError;
|
||||
#[cfg(all(feature = "unstable", not(feature = "std")))]
|
||||
#[doc(no_inline)]
|
||||
pub use core::error::Error as StdError;
|
||||
#[cfg(feature = "std")]
|
||||
#[doc(no_inline)]
|
||||
pub use std::error::Error as StdError;
|
||||
#[cfg(not(feature = "std"))]
|
||||
#[doc(no_inline)]
|
||||
pub use std_error::Error as StdError;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -162,7 +164,7 @@ macro_rules! declare_error_trait {
|
||||
///
|
||||
/// The message should not be capitalized and should not end with a period.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use std::str::FromStr;
|
||||
/// #
|
||||
/// # struct IpAddr;
|
||||
@@ -307,7 +309,7 @@ declare_error_trait!(Error: Sized + Debug + Display);
|
||||
/// This is used as an argument to the `invalid_type`, `invalid_value`, and
|
||||
/// `invalid_length` methods of the `Error` trait to build error messages.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use std::fmt;
|
||||
/// #
|
||||
/// # use serde::de::{self, Unexpected, Visitor};
|
||||
@@ -400,20 +402,20 @@ impl<'a> fmt::Display for Unexpected<'a> {
|
||||
Bool(b) => write!(formatter, "boolean `{}`", b),
|
||||
Unsigned(i) => write!(formatter, "integer `{}`", i),
|
||||
Signed(i) => write!(formatter, "integer `{}`", i),
|
||||
Float(f) => write!(formatter, "floating point `{}`", f),
|
||||
Float(f) => write!(formatter, "floating point `{}`", WithDecimalPoint(f)),
|
||||
Char(c) => write!(formatter, "character `{}`", c),
|
||||
Str(s) => write!(formatter, "string {:?}", s),
|
||||
Bytes(_) => write!(formatter, "byte array"),
|
||||
Unit => write!(formatter, "unit value"),
|
||||
Option => write!(formatter, "Option value"),
|
||||
NewtypeStruct => write!(formatter, "newtype struct"),
|
||||
Seq => write!(formatter, "sequence"),
|
||||
Map => write!(formatter, "map"),
|
||||
Enum => write!(formatter, "enum"),
|
||||
UnitVariant => write!(formatter, "unit variant"),
|
||||
NewtypeVariant => write!(formatter, "newtype variant"),
|
||||
TupleVariant => write!(formatter, "tuple variant"),
|
||||
StructVariant => write!(formatter, "struct variant"),
|
||||
Bytes(_) => formatter.write_str("byte array"),
|
||||
Unit => formatter.write_str("unit value"),
|
||||
Option => formatter.write_str("Option value"),
|
||||
NewtypeStruct => formatter.write_str("newtype struct"),
|
||||
Seq => formatter.write_str("sequence"),
|
||||
Map => formatter.write_str("map"),
|
||||
Enum => formatter.write_str("enum"),
|
||||
UnitVariant => formatter.write_str("unit variant"),
|
||||
NewtypeVariant => formatter.write_str("newtype variant"),
|
||||
TupleVariant => formatter.write_str("tuple variant"),
|
||||
StructVariant => formatter.write_str("struct variant"),
|
||||
Other(other) => formatter.write_str(other),
|
||||
}
|
||||
}
|
||||
@@ -432,10 +434,9 @@ impl<'a> fmt::Display for Unexpected<'a> {
|
||||
/// Within the context of a `Visitor` implementation, the `Visitor` itself
|
||||
/// (`&self`) is an implementation of this trait.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use std::fmt;
|
||||
/// #
|
||||
/// ```edition2021
|
||||
/// # use serde::de::{self, Unexpected, Visitor};
|
||||
/// # use std::fmt;
|
||||
/// #
|
||||
/// # struct Example;
|
||||
/// #
|
||||
@@ -457,7 +458,7 @@ impl<'a> fmt::Display for Unexpected<'a> {
|
||||
///
|
||||
/// Outside of a `Visitor`, `&"..."` can be used.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::de::{self, Unexpected};
|
||||
/// #
|
||||
/// # fn example<E>() -> Result<(), E>
|
||||
@@ -465,7 +466,10 @@ impl<'a> fmt::Display for Unexpected<'a> {
|
||||
/// # E: de::Error,
|
||||
/// # {
|
||||
/// # let v = true;
|
||||
/// return Err(de::Error::invalid_type(Unexpected::Bool(v), &"a negative integer"));
|
||||
/// return Err(de::Error::invalid_type(
|
||||
/// Unexpected::Bool(v),
|
||||
/// &"a negative integer",
|
||||
/// ));
|
||||
/// # }
|
||||
/// ```
|
||||
pub trait Expected {
|
||||
@@ -528,6 +532,13 @@ impl<'a> Display for Expected + 'a {
|
||||
/// deserializer lifetimes] for a more detailed explanation of these lifetimes.
|
||||
///
|
||||
/// [Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html
|
||||
#[cfg_attr(
|
||||
not(no_diagnostic_namespace),
|
||||
diagnostic::on_unimplemented(
|
||||
note = "for local types consider adding `#[derive(serde::Deserialize)]` to your `{Self}` type",
|
||||
note = "for types from other crates check whether the crate offers a `serde` feature flag",
|
||||
)
|
||||
)]
|
||||
pub trait Deserialize<'de>: Sized {
|
||||
/// Deserialize this value from the given Serde deserializer.
|
||||
///
|
||||
@@ -564,7 +575,7 @@ pub trait Deserialize<'de>: Sized {
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
// Default implementation just delegates to `deserialize` impl.
|
||||
*place = try!(Deserialize::deserialize(deserializer));
|
||||
*place = tri!(Deserialize::deserialize(deserializer));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -577,7 +588,7 @@ pub trait Deserialize<'de>: Sized {
|
||||
/// from the input string, but a `from_reader` function may only deserialize
|
||||
/// owned data.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::de::{Deserialize, DeserializeOwned};
|
||||
/// # use std::io::{Read, Result};
|
||||
/// #
|
||||
@@ -616,7 +627,7 @@ impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
|
||||
///
|
||||
/// The canonical API for stateless deserialization looks like this:
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Deserialize;
|
||||
/// #
|
||||
/// # enum Error {}
|
||||
@@ -630,7 +641,7 @@ impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
|
||||
/// Adjusting an API like this to support stateful deserialization is a matter
|
||||
/// of accepting a seed as input:
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::de::DeserializeSeed;
|
||||
/// #
|
||||
/// # enum Error {}
|
||||
@@ -663,12 +674,11 @@ impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
|
||||
/// into it. This requires stateful deserialization using the `DeserializeSeed`
|
||||
/// trait.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::de::{Deserialize, DeserializeSeed, Deserializer, SeqAccess, Visitor};
|
||||
/// use std::fmt;
|
||||
/// use std::marker::PhantomData;
|
||||
///
|
||||
/// use serde::de::{Deserialize, DeserializeSeed, Deserializer, SeqAccess, Visitor};
|
||||
///
|
||||
/// // A DeserializeSeed implementation that uses stateful deserialization to
|
||||
/// // append array elements onto the end of an existing vector. The preexisting
|
||||
/// // state ("seed") in this case is the Vec<T>. The `deserialize` method of
|
||||
@@ -709,7 +719,7 @@ impl<T> DeserializeOwned for T where T: for<'de> Deserialize<'de> {}
|
||||
/// {
|
||||
/// // Decrease the number of reallocations if there are many elements
|
||||
/// if let Some(size_hint) = seq.size_hint() {
|
||||
/// self.0.reserve(size_hint);
|
||||
/// self.0.reserve(size_hint);
|
||||
/// }
|
||||
///
|
||||
/// // Visit each element in the inner array and push it onto
|
||||
@@ -945,18 +955,15 @@ pub trait Deserializer<'de>: Sized {
|
||||
where
|
||||
V: Visitor<'de>;
|
||||
|
||||
serde_if_integer128! {
|
||||
/// Hint that the `Deserialize` type is expecting an `i128` value.
|
||||
///
|
||||
/// This method is available only on Rust compiler versions >=1.26. The
|
||||
/// default behavior unconditionally returns an error.
|
||||
fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>
|
||||
{
|
||||
let _ = visitor;
|
||||
Err(Error::custom("i128 is not supported"))
|
||||
}
|
||||
/// Hint that the `Deserialize` type is expecting an `i128` value.
|
||||
///
|
||||
/// The default behavior unconditionally returns an error.
|
||||
fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
let _ = visitor;
|
||||
Err(Error::custom("i128 is not supported"))
|
||||
}
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a `u8` value.
|
||||
@@ -979,18 +986,15 @@ pub trait Deserializer<'de>: Sized {
|
||||
where
|
||||
V: Visitor<'de>;
|
||||
|
||||
serde_if_integer128! {
|
||||
/// Hint that the `Deserialize` type is expecting an `u128` value.
|
||||
///
|
||||
/// This method is available only on Rust compiler versions >=1.26. The
|
||||
/// default behavior unconditionally returns an error.
|
||||
fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>
|
||||
{
|
||||
let _ = visitor;
|
||||
Err(Error::custom("u128 is not supported"))
|
||||
}
|
||||
/// Hint that the `Deserialize` type is expecting an `u128` value.
|
||||
///
|
||||
/// The default behavior unconditionally returns an error.
|
||||
fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
let _ = visitor;
|
||||
Err(Error::custom("u128 is not supported"))
|
||||
}
|
||||
|
||||
/// Hint that the `Deserialize` type is expecting a `f32` value.
|
||||
@@ -1158,7 +1162,7 @@ pub trait Deserializer<'de>: Sized {
|
||||
/// human-readable one and binary formats like Postcard will prefer the
|
||||
/// compact one.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use std::ops::Add;
|
||||
/// # use std::str::FromStr;
|
||||
/// #
|
||||
@@ -1225,11 +1229,11 @@ pub trait Deserializer<'de>: Sized {
|
||||
#[doc(hidden)]
|
||||
fn __deserialize_content<V>(
|
||||
self,
|
||||
_: ::actually_private::T,
|
||||
_: crate::actually_private::T,
|
||||
visitor: V,
|
||||
) -> Result<::private::de::Content<'de>, Self::Error>
|
||||
) -> Result<crate::__private::de::Content<'de>, Self::Error>
|
||||
where
|
||||
V: Visitor<'de, Value = ::private::de::Content<'de>>,
|
||||
V: Visitor<'de, Value = crate::__private::de::Content<'de>>,
|
||||
{
|
||||
self.deserialize_any(visitor)
|
||||
}
|
||||
@@ -1249,10 +1253,9 @@ pub trait Deserializer<'de>: Sized {
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use std::fmt;
|
||||
/// #
|
||||
/// ```edition2021
|
||||
/// # use serde::de::{self, Unexpected, Visitor};
|
||||
/// # use std::fmt;
|
||||
/// #
|
||||
/// /// A visitor that deserializes a long string - a string containing at least
|
||||
/// /// some minimum number of bytes.
|
||||
@@ -1290,7 +1293,7 @@ pub trait Visitor<'de>: Sized {
|
||||
/// "an integer between 0 and 64". The message should not be capitalized and
|
||||
/// should not end with a period.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use std::fmt;
|
||||
/// #
|
||||
/// # struct S {
|
||||
@@ -1363,20 +1366,20 @@ pub trait Visitor<'de>: Sized {
|
||||
Err(Error::invalid_type(Unexpected::Signed(v), &self))
|
||||
}
|
||||
|
||||
serde_if_integer128! {
|
||||
/// The input contains a `i128`.
|
||||
///
|
||||
/// This method is available only on Rust compiler versions >=1.26. The
|
||||
/// default implementation fails with a type error.
|
||||
fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
let mut buf = [0u8; 58];
|
||||
let mut writer = format::Buf::new(&mut buf);
|
||||
fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as i128", v)).unwrap();
|
||||
Err(Error::invalid_type(Unexpected::Other(writer.as_str()), &self))
|
||||
}
|
||||
/// The input contains a `i128`.
|
||||
///
|
||||
/// The default implementation fails with a type error.
|
||||
fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
let mut buf = [0u8; 58];
|
||||
let mut writer = format::Buf::new(&mut buf);
|
||||
fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as i128", v)).unwrap();
|
||||
Err(Error::invalid_type(
|
||||
Unexpected::Other(writer.as_str()),
|
||||
&self,
|
||||
))
|
||||
}
|
||||
|
||||
/// The input contains a `u8`.
|
||||
@@ -1425,20 +1428,20 @@ pub trait Visitor<'de>: Sized {
|
||||
Err(Error::invalid_type(Unexpected::Unsigned(v), &self))
|
||||
}
|
||||
|
||||
serde_if_integer128! {
|
||||
/// The input contains a `u128`.
|
||||
///
|
||||
/// This method is available only on Rust compiler versions >=1.26. The
|
||||
/// default implementation fails with a type error.
|
||||
fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
let mut buf = [0u8; 57];
|
||||
let mut writer = format::Buf::new(&mut buf);
|
||||
fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as u128", v)).unwrap();
|
||||
Err(Error::invalid_type(Unexpected::Other(writer.as_str()), &self))
|
||||
}
|
||||
/// The input contains a `u128`.
|
||||
///
|
||||
/// The default implementation fails with a type error.
|
||||
fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
let mut buf = [0u8; 57];
|
||||
let mut writer = format::Buf::new(&mut buf);
|
||||
fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as u128", v)).unwrap();
|
||||
Err(Error::invalid_type(
|
||||
Unexpected::Other(writer.as_str()),
|
||||
&self,
|
||||
))
|
||||
}
|
||||
|
||||
/// The input contains an `f32`.
|
||||
@@ -1474,7 +1477,7 @@ pub trait Visitor<'de>: Sized {
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.visit_str(utf8::encode(v).as_str())
|
||||
self.visit_str(v.encode_utf8(&mut [0u8; 4]))
|
||||
}
|
||||
|
||||
/// The input contains a string. The lifetime of the string is ephemeral and
|
||||
@@ -1529,6 +1532,7 @@ pub trait Visitor<'de>: Sized {
|
||||
/// `String`.
|
||||
#[inline]
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
@@ -1551,7 +1555,6 @@ pub trait Visitor<'de>: Sized {
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
let _ = v;
|
||||
Err(Error::invalid_type(Unexpected::Bytes(v), &self))
|
||||
}
|
||||
|
||||
@@ -1588,6 +1591,7 @@ pub trait Visitor<'de>: Sized {
|
||||
/// The default implementation forwards to `visit_bytes` and then drops the
|
||||
/// `Vec<u8>`.
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
@@ -1738,9 +1742,9 @@ pub trait SeqAccess<'de> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, 'a, A: ?Sized> SeqAccess<'de> for &'a mut A
|
||||
impl<'de, 'a, A> SeqAccess<'de> for &'a mut A
|
||||
where
|
||||
A: SeqAccess<'de>,
|
||||
A: ?Sized + SeqAccess<'de>,
|
||||
{
|
||||
type Error = A::Error;
|
||||
|
||||
@@ -1831,9 +1835,9 @@ pub trait MapAccess<'de> {
|
||||
K: DeserializeSeed<'de>,
|
||||
V: DeserializeSeed<'de>,
|
||||
{
|
||||
match try!(self.next_key_seed(kseed)) {
|
||||
match tri!(self.next_key_seed(kseed)) {
|
||||
Some(key) => {
|
||||
let value = try!(self.next_value_seed(vseed));
|
||||
let value = tri!(self.next_value_seed(vseed));
|
||||
Ok(Some((key, value)))
|
||||
}
|
||||
None => Ok(None),
|
||||
@@ -1891,9 +1895,9 @@ pub trait MapAccess<'de> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, 'a, A: ?Sized> MapAccess<'de> for &'a mut A
|
||||
impl<'de, 'a, A> MapAccess<'de> for &'a mut A
|
||||
where
|
||||
A: MapAccess<'de>,
|
||||
A: ?Sized + MapAccess<'de>,
|
||||
{
|
||||
type Error = A::Error;
|
||||
|
||||
@@ -2035,7 +2039,7 @@ pub trait VariantAccess<'de>: Sized {
|
||||
/// If the data contains a different type of variant, the following
|
||||
/// `invalid_type` error should be constructed:
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
|
||||
/// #
|
||||
/// # struct X;
|
||||
@@ -2075,7 +2079,7 @@ pub trait VariantAccess<'de>: Sized {
|
||||
/// If the data contains a different type of variant, the following
|
||||
/// `invalid_type` error should be constructed:
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
|
||||
/// #
|
||||
/// # struct X;
|
||||
@@ -2131,7 +2135,7 @@ pub trait VariantAccess<'de>: Sized {
|
||||
/// If the data contains a different type of variant, the following
|
||||
/// `invalid_type` error should be constructed:
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
|
||||
/// #
|
||||
/// # struct X;
|
||||
@@ -2148,11 +2152,7 @@ pub trait VariantAccess<'de>: Sized {
|
||||
/// # T: DeserializeSeed<'de>,
|
||||
/// # { unimplemented!() }
|
||||
/// #
|
||||
/// fn tuple_variant<V>(
|
||||
/// self,
|
||||
/// _len: usize,
|
||||
/// _visitor: V,
|
||||
/// ) -> Result<V::Value, Self::Error>
|
||||
/// fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
|
||||
/// where
|
||||
/// V: Visitor<'de>,
|
||||
/// {
|
||||
@@ -2178,7 +2178,7 @@ pub trait VariantAccess<'de>: Sized {
|
||||
/// If the data contains a different type of variant, the following
|
||||
/// `invalid_type` error should be constructed:
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
|
||||
/// #
|
||||
/// # struct X;
|
||||
@@ -2238,10 +2238,10 @@ pub trait VariantAccess<'de>: Sized {
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::de::{value, Deserialize, IntoDeserializer};
|
||||
/// use serde_derive::Deserialize;
|
||||
/// use std::str::FromStr;
|
||||
/// use serde::Deserialize;
|
||||
/// use serde::de::{value, IntoDeserializer};
|
||||
///
|
||||
/// #[derive(Deserialize)]
|
||||
/// enum Setting {
|
||||
@@ -2285,15 +2285,52 @@ impl Display for OneOf {
|
||||
1 => write!(formatter, "`{}`", self.names[0]),
|
||||
2 => write!(formatter, "`{}` or `{}`", self.names[0], self.names[1]),
|
||||
_ => {
|
||||
try!(write!(formatter, "one of "));
|
||||
tri!(formatter.write_str("one of "));
|
||||
for (i, alt) in self.names.iter().enumerate() {
|
||||
if i > 0 {
|
||||
try!(write!(formatter, ", "));
|
||||
tri!(formatter.write_str(", "));
|
||||
}
|
||||
try!(write!(formatter, "`{}`", alt));
|
||||
tri!(write!(formatter, "`{}`", alt));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct WithDecimalPoint(f64);
|
||||
|
||||
impl Display for WithDecimalPoint {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
struct LookForDecimalPoint<'f, 'a> {
|
||||
formatter: &'f mut fmt::Formatter<'a>,
|
||||
has_decimal_point: bool,
|
||||
}
|
||||
|
||||
impl<'f, 'a> fmt::Write for LookForDecimalPoint<'f, 'a> {
|
||||
fn write_str(&mut self, fragment: &str) -> fmt::Result {
|
||||
self.has_decimal_point |= fragment.contains('.');
|
||||
self.formatter.write_str(fragment)
|
||||
}
|
||||
|
||||
fn write_char(&mut self, ch: char) -> fmt::Result {
|
||||
self.has_decimal_point |= ch == '.';
|
||||
self.formatter.write_char(ch)
|
||||
}
|
||||
}
|
||||
|
||||
if self.0.is_finite() {
|
||||
let mut writer = LookForDecimalPoint {
|
||||
formatter,
|
||||
has_decimal_point: false,
|
||||
};
|
||||
tri!(write!(writer, "{}", self.0));
|
||||
if !writer.has_decimal_point {
|
||||
tri!(formatter.write_str(".0"));
|
||||
}
|
||||
} else {
|
||||
tri!(write!(formatter, "{}", self.0));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use de::{Deserialize, DeserializeSeed, Deserializer};
|
||||
use crate::de::{Deserialize, DeserializeSeed, Deserializer};
|
||||
|
||||
/// A DeserializeSeed helper for implementing deserialize_in_place Visitors.
|
||||
///
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use lib::*;
|
||||
use crate::lib::*;
|
||||
|
||||
pub fn from_bounds<I>(iter: &I) -> Option<usize>
|
||||
where
|
||||
@@ -8,9 +8,17 @@ where
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[inline]
|
||||
pub fn cautious(hint: Option<usize>) -> usize {
|
||||
cmp::min(hint.unwrap_or(0), 4096)
|
||||
pub fn cautious<Element>(hint: Option<usize>) -> usize {
|
||||
const MAX_PREALLOC_BYTES: usize = 1024 * 1024;
|
||||
|
||||
if mem::size_of::<Element>() == 0 {
|
||||
0
|
||||
} else {
|
||||
cmp::min(
|
||||
hint.unwrap_or(0),
|
||||
MAX_PREALLOC_BYTES / mem::size_of::<Element>(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn helper(bounds: (usize, Option<usize>)) -> Option<usize> {
|
||||
@@ -1,46 +0,0 @@
|
||||
use lib::*;
|
||||
|
||||
const TAG_CONT: u8 = 0b1000_0000;
|
||||
const TAG_TWO_B: u8 = 0b1100_0000;
|
||||
const TAG_THREE_B: u8 = 0b1110_0000;
|
||||
const TAG_FOUR_B: u8 = 0b1111_0000;
|
||||
const MAX_ONE_B: u32 = 0x80;
|
||||
const MAX_TWO_B: u32 = 0x800;
|
||||
const MAX_THREE_B: u32 = 0x10000;
|
||||
|
||||
#[inline]
|
||||
pub fn encode(c: char) -> Encode {
|
||||
let code = c as u32;
|
||||
let mut buf = [0; 4];
|
||||
let pos = if code < MAX_ONE_B {
|
||||
buf[3] = code as u8;
|
||||
3
|
||||
} else if code < MAX_TWO_B {
|
||||
buf[2] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
|
||||
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
2
|
||||
} else if code < MAX_THREE_B {
|
||||
buf[1] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
1
|
||||
} else {
|
||||
buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
|
||||
buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
|
||||
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
|
||||
0
|
||||
};
|
||||
Encode { buf: buf, pos: pos }
|
||||
}
|
||||
|
||||
pub struct Encode {
|
||||
buf: [u8; 4],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl Encode {
|
||||
pub fn as_str(&self) -> &str {
|
||||
str::from_utf8(&self.buf[self.pos..]).unwrap()
|
||||
}
|
||||
}
|
||||
+50
-44
@@ -1,10 +1,10 @@
|
||||
//! Building blocks for deserializing basic values using the `IntoDeserializer`
|
||||
//! trait.
|
||||
//!
|
||||
//! ```edition2018
|
||||
//! ```edition2021
|
||||
//! use serde::de::{value, Deserialize, IntoDeserializer};
|
||||
//! use serde_derive::Deserialize;
|
||||
//! use std::str::FromStr;
|
||||
//! use serde::Deserialize;
|
||||
//! use serde::de::{value, IntoDeserializer};
|
||||
//!
|
||||
//! #[derive(Deserialize)]
|
||||
//! enum Setting {
|
||||
@@ -21,12 +21,11 @@
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
use lib::*;
|
||||
use crate::lib::*;
|
||||
|
||||
use self::private::{First, Second};
|
||||
use __private::size_hint;
|
||||
use de::{self, Deserializer, Expected, IntoDeserializer, SeqAccess, Visitor};
|
||||
use ser;
|
||||
use crate::de::{self, size_hint, Deserializer, Expected, IntoDeserializer, SeqAccess, Visitor};
|
||||
use crate::ser;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -113,6 +112,7 @@ impl Debug for Error {
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl error::Error for Error {
|
||||
fn description(&self) -> &str {
|
||||
&self.err
|
||||
@@ -185,12 +185,14 @@ impl<E> Debug for UnitDeserializer<E> {
|
||||
|
||||
/// A deserializer that cannot be instantiated.
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
|
||||
pub struct NeverDeserializer<E> {
|
||||
never: !,
|
||||
marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
|
||||
impl<'de, E> IntoDeserializer<'de, E> for !
|
||||
where
|
||||
E: de::Error,
|
||||
@@ -251,7 +253,7 @@ macro_rules! primitive_deserializer {
|
||||
#[allow(missing_docs)]
|
||||
pub fn new(value: $ty) -> Self {
|
||||
$name {
|
||||
value: value,
|
||||
value,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -293,20 +295,17 @@ primitive_deserializer!(i8, "an `i8`.", I8Deserializer, visit_i8);
|
||||
primitive_deserializer!(i16, "an `i16`.", I16Deserializer, visit_i16);
|
||||
primitive_deserializer!(i32, "an `i32`.", I32Deserializer, visit_i32);
|
||||
primitive_deserializer!(i64, "an `i64`.", I64Deserializer, visit_i64);
|
||||
primitive_deserializer!(i128, "an `i128`.", I128Deserializer, visit_i128);
|
||||
primitive_deserializer!(isize, "an `isize`.", IsizeDeserializer, visit_i64 as i64);
|
||||
primitive_deserializer!(u8, "a `u8`.", U8Deserializer, visit_u8);
|
||||
primitive_deserializer!(u16, "a `u16`.", U16Deserializer, visit_u16);
|
||||
primitive_deserializer!(u64, "a `u64`.", U64Deserializer, visit_u64);
|
||||
primitive_deserializer!(u128, "a `u128`.", U128Deserializer, visit_u128);
|
||||
primitive_deserializer!(usize, "a `usize`.", UsizeDeserializer, visit_u64 as u64);
|
||||
primitive_deserializer!(f32, "an `f32`.", F32Deserializer, visit_f32);
|
||||
primitive_deserializer!(f64, "an `f64`.", F64Deserializer, visit_f64);
|
||||
primitive_deserializer!(char, "a `char`.", CharDeserializer, visit_char);
|
||||
|
||||
serde_if_integer128! {
|
||||
primitive_deserializer!(i128, "an `i128`.", I128Deserializer, visit_i128);
|
||||
primitive_deserializer!(u128, "a `u128`.", U128Deserializer, visit_u128);
|
||||
}
|
||||
|
||||
/// A deserializer holding a `u32`.
|
||||
pub struct U32Deserializer<E> {
|
||||
value: u32,
|
||||
@@ -330,7 +329,7 @@ impl<E> U32Deserializer<E> {
|
||||
#[allow(missing_docs)]
|
||||
pub fn new(value: u32) -> Self {
|
||||
U32Deserializer {
|
||||
value: value,
|
||||
value,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -419,7 +418,7 @@ impl<'a, E> StrDeserializer<'a, E> {
|
||||
#[allow(missing_docs)]
|
||||
pub fn new(value: &'a str) -> Self {
|
||||
StrDeserializer {
|
||||
value: value,
|
||||
value,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -498,7 +497,7 @@ impl<'de, E> BorrowedStrDeserializer<'de, E> {
|
||||
/// Create a new borrowed deserializer from the given string.
|
||||
pub fn new(value: &'de str) -> BorrowedStrDeserializer<'de, E> {
|
||||
BorrowedStrDeserializer {
|
||||
value: value,
|
||||
value,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -566,6 +565,7 @@ impl<'de, E> Debug for BorrowedStrDeserializer<'de, E> {
|
||||
|
||||
/// A deserializer holding a `String`.
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
pub struct StringDeserializer<E> {
|
||||
value: String,
|
||||
marker: PhantomData<E>,
|
||||
@@ -582,6 +582,7 @@ impl<E> Clone for StringDeserializer<E> {
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
impl<'de, E> IntoDeserializer<'de, E> for String
|
||||
where
|
||||
E: de::Error,
|
||||
@@ -598,7 +599,7 @@ impl<E> StringDeserializer<E> {
|
||||
#[allow(missing_docs)]
|
||||
pub fn new(value: String) -> Self {
|
||||
StringDeserializer {
|
||||
value: value,
|
||||
value,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -669,6 +670,7 @@ impl<E> Debug for StringDeserializer<E> {
|
||||
|
||||
/// A deserializer holding a `Cow<str>`.
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
pub struct CowStrDeserializer<'a, E> {
|
||||
value: Cow<'a, str>,
|
||||
marker: PhantomData<E>,
|
||||
@@ -685,6 +687,7 @@ impl<'a, E> Clone for CowStrDeserializer<'a, E> {
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
impl<'de, 'a, E> IntoDeserializer<'de, E> for Cow<'a, str>
|
||||
where
|
||||
E: de::Error,
|
||||
@@ -701,7 +704,7 @@ impl<'a, E> CowStrDeserializer<'a, E> {
|
||||
#[allow(missing_docs)]
|
||||
pub fn new(value: Cow<'a, str>) -> Self {
|
||||
CowStrDeserializer {
|
||||
value: value,
|
||||
value,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -783,7 +786,7 @@ impl<'a, E> BytesDeserializer<'a, E> {
|
||||
/// Create a new deserializer from the given bytes.
|
||||
pub fn new(value: &'a [u8]) -> Self {
|
||||
BytesDeserializer {
|
||||
value: value,
|
||||
value,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -842,7 +845,7 @@ impl<'de, E> BorrowedBytesDeserializer<'de, E> {
|
||||
/// Create a new borrowed deserializer from the given borrowed bytes.
|
||||
pub fn new(value: &'de [u8]) -> Self {
|
||||
BorrowedBytesDeserializer {
|
||||
value: value,
|
||||
value,
|
||||
marker: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -937,8 +940,8 @@ where
|
||||
where
|
||||
V: de::Visitor<'de>,
|
||||
{
|
||||
let v = try!(visitor.visit_seq(&mut self));
|
||||
try!(self.end());
|
||||
let v = tri!(visitor.visit_seq(&mut self));
|
||||
tri!(self.end());
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
@@ -980,7 +983,7 @@ struct ExpectedInSeq(usize);
|
||||
impl Expected for ExpectedInSeq {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
if self.0 == 1 {
|
||||
write!(formatter, "1 element in sequence")
|
||||
formatter.write_str("1 element in sequence")
|
||||
} else {
|
||||
write!(formatter, "{} elements in sequence", self.0)
|
||||
}
|
||||
@@ -1003,6 +1006,7 @@ where
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
impl<'de, T, E> IntoDeserializer<'de, E> for Vec<T>
|
||||
where
|
||||
T: IntoDeserializer<'de, E>,
|
||||
@@ -1016,6 +1020,7 @@ where
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
impl<'de, T, E> IntoDeserializer<'de, E> for BTreeSet<T>
|
||||
where
|
||||
T: IntoDeserializer<'de, E> + Eq + Ord,
|
||||
@@ -1029,6 +1034,7 @@ where
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl<'de, T, S, E> IntoDeserializer<'de, E> for HashSet<T, S>
|
||||
where
|
||||
T: IntoDeserializer<'de, E> + Eq + Hash,
|
||||
@@ -1053,7 +1059,7 @@ pub struct SeqAccessDeserializer<A> {
|
||||
impl<A> SeqAccessDeserializer<A> {
|
||||
/// Construct a new `SeqAccessDeserializer<A>`.
|
||||
pub fn new(seq: A) -> Self {
|
||||
SeqAccessDeserializer { seq: seq }
|
||||
SeqAccessDeserializer { seq }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1162,8 +1168,8 @@ where
|
||||
where
|
||||
V: de::Visitor<'de>,
|
||||
{
|
||||
let value = try!(visitor.visit_map(&mut self));
|
||||
try!(self.end());
|
||||
let value = tri!(visitor.visit_map(&mut self));
|
||||
tri!(self.end());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
@@ -1171,8 +1177,8 @@ where
|
||||
where
|
||||
V: de::Visitor<'de>,
|
||||
{
|
||||
let value = try!(visitor.visit_seq(&mut self));
|
||||
try!(self.end());
|
||||
let value = tri!(visitor.visit_seq(&mut self));
|
||||
tri!(self.end());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
@@ -1236,8 +1242,8 @@ where
|
||||
{
|
||||
match self.next_pair() {
|
||||
Some((key, value)) => {
|
||||
let key = try!(kseed.deserialize(key.into_deserializer()));
|
||||
let value = try!(vseed.deserialize(value.into_deserializer()));
|
||||
let key = tri!(kseed.deserialize(key.into_deserializer()));
|
||||
let value = tri!(vseed.deserialize(value.into_deserializer()));
|
||||
Ok(Some((key, value)))
|
||||
}
|
||||
None => Ok(None),
|
||||
@@ -1341,7 +1347,7 @@ where
|
||||
V: de::Visitor<'de>,
|
||||
{
|
||||
let mut pair_visitor = PairVisitor(Some(self.0), Some(self.1), PhantomData);
|
||||
let pair = try!(visitor.visit_seq(&mut pair_visitor));
|
||||
let pair = tri!(visitor.visit_seq(&mut pair_visitor));
|
||||
if pair_visitor.1.is_none() {
|
||||
Ok(pair)
|
||||
} else {
|
||||
@@ -1405,7 +1411,7 @@ struct ExpectedInMap(usize);
|
||||
impl Expected for ExpectedInMap {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
if self.0 == 1 {
|
||||
write!(formatter, "1 element in map")
|
||||
formatter.write_str("1 element in map")
|
||||
} else {
|
||||
write!(formatter, "{} elements in map", self.0)
|
||||
}
|
||||
@@ -1415,6 +1421,7 @@ impl Expected for ExpectedInMap {
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
impl<'de, K, V, E> IntoDeserializer<'de, E> for BTreeMap<K, V>
|
||||
where
|
||||
K: IntoDeserializer<'de, E> + Eq + Ord,
|
||||
@@ -1429,6 +1436,7 @@ where
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl<'de, K, V, S, E> IntoDeserializer<'de, E> for HashMap<K, V, S>
|
||||
where
|
||||
K: IntoDeserializer<'de, E> + Eq + Hash,
|
||||
@@ -1454,7 +1462,7 @@ pub struct MapAccessDeserializer<A> {
|
||||
impl<A> MapAccessDeserializer<A> {
|
||||
/// Construct a new `MapAccessDeserializer<A>`.
|
||||
pub fn new(map: A) -> Self {
|
||||
MapAccessDeserializer { map: map }
|
||||
MapAccessDeserializer { map }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1501,7 +1509,7 @@ where
|
||||
where
|
||||
T: de::DeserializeSeed<'de>,
|
||||
{
|
||||
match try!(self.map.next_key_seed(seed)) {
|
||||
match tri!(self.map.next_key_seed(seed)) {
|
||||
Some(key) => Ok((key, private::map_as_enum(self.map))),
|
||||
None => Err(de::Error::invalid_type(de::Unexpected::Map, &"enum")),
|
||||
}
|
||||
@@ -1519,7 +1527,7 @@ pub struct EnumAccessDeserializer<A> {
|
||||
impl<A> EnumAccessDeserializer<A> {
|
||||
/// Construct a new `EnumAccessDeserializer<A>`.
|
||||
pub fn new(access: A) -> Self {
|
||||
EnumAccessDeserializer { access: access }
|
||||
EnumAccessDeserializer { access }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1546,9 +1554,11 @@ where
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
mod private {
|
||||
use lib::*;
|
||||
use crate::lib::*;
|
||||
|
||||
use de::{self, DeserializeSeed, Deserializer, MapAccess, Unexpected, VariantAccess, Visitor};
|
||||
use crate::de::{
|
||||
self, DeserializeSeed, Deserializer, MapAccess, Unexpected, VariantAccess, Visitor,
|
||||
};
|
||||
|
||||
pub struct UnitOnly<E> {
|
||||
marker: PhantomData<E>,
|
||||
@@ -1613,7 +1623,7 @@ mod private {
|
||||
}
|
||||
|
||||
pub fn map_as_enum<A>(map: A) -> MapAsEnum<A> {
|
||||
MapAsEnum { map: map }
|
||||
MapAsEnum { map }
|
||||
}
|
||||
|
||||
impl<'de, A> VariantAccess<'de> for MapAsEnum<A>
|
||||
@@ -1637,10 +1647,7 @@ mod private {
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
self.map.next_value_seed(SeedTupleVariant {
|
||||
len: len,
|
||||
visitor: visitor,
|
||||
})
|
||||
self.map.next_value_seed(SeedTupleVariant { len, visitor })
|
||||
}
|
||||
|
||||
fn struct_variant<V>(
|
||||
@@ -1651,8 +1658,7 @@ mod private {
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
self.map
|
||||
.next_value_seed(SeedStructVariant { visitor: visitor })
|
||||
self.map.next_value_seed(SeedStructVariant { visitor })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-76
@@ -1,82 +1,9 @@
|
||||
/// Conditional compilation depending on whether Serde is built with support for
|
||||
/// 128-bit integers.
|
||||
///
|
||||
/// Data formats that wish to support Rust compiler versions older than 1.26
|
||||
/// (or targets that lack 128-bit integers) may place the i128 / u128 methods
|
||||
/// of their Serializer and Deserializer behind this macro.
|
||||
///
|
||||
/// Data formats that require a minimum Rust compiler version of at least 1.26,
|
||||
/// or do not target platforms that lack 128-bit integers, do not need to
|
||||
/// bother with this macro and may assume support for 128-bit integers.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::__private::doc::Error;
|
||||
/// #
|
||||
/// # struct MySerializer;
|
||||
/// #
|
||||
/// use serde::{serde_if_integer128, Serializer};
|
||||
///
|
||||
/// impl Serializer for MySerializer {
|
||||
/// type Ok = ();
|
||||
/// type Error = Error;
|
||||
///
|
||||
/// fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
|
||||
/// /* ... */
|
||||
/// # unimplemented!()
|
||||
/// }
|
||||
///
|
||||
/// /* ... */
|
||||
///
|
||||
/// serde_if_integer128! {
|
||||
/// fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
|
||||
/// /* ... */
|
||||
/// # unimplemented!()
|
||||
/// }
|
||||
///
|
||||
/// fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
|
||||
/// /* ... */
|
||||
/// # unimplemented!()
|
||||
/// }
|
||||
/// }
|
||||
/// #
|
||||
/// # serde::__serialize_unimplemented! {
|
||||
/// # bool i8 i16 i32 u8 u16 u32 u64 f32 f64 char str bytes none some
|
||||
/// # unit unit_struct unit_variant newtype_struct newtype_variant seq
|
||||
/// # tuple tuple_struct tuple_variant map struct struct_variant
|
||||
/// # }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When Serde is built with support for 128-bit integers, this macro expands
|
||||
/// transparently into just the input tokens.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// macro_rules! serde_if_integer128 {
|
||||
/// ($($tt:tt)*) => {
|
||||
/// $($tt)*
|
||||
/// };
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When built without support for 128-bit integers, this macro expands to
|
||||
/// nothing.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// macro_rules! serde_if_integer128 {
|
||||
/// ($($tt:tt)*) => {};
|
||||
/// }
|
||||
/// ```
|
||||
#[cfg(not(no_integer128))]
|
||||
// No longer used. Old versions of serde used this macro for supporting targets
|
||||
// that did not yet have 128-bit integer support.
|
||||
#[macro_export]
|
||||
#[doc(hidden)]
|
||||
macro_rules! serde_if_integer128 {
|
||||
($($tt:tt)*) => {
|
||||
$($tt)*
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(no_integer128)]
|
||||
#[macro_export]
|
||||
#[doc(hidden)]
|
||||
macro_rules! serde_if_integer128 {
|
||||
($($tt:tt)*) => {};
|
||||
}
|
||||
|
||||
+71
-80
@@ -63,6 +63,7 @@
|
||||
//! 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
|
||||
@@ -89,66 +90,69 @@
|
||||
//! [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.157")]
|
||||
#![doc(html_root_url = "https://docs.rs/serde/1.0.204")]
|
||||
// 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(feature = "unstable", feature(error_in_core, never_type))]
|
||||
#![cfg_attr(feature = "unstable", feature(never_type))]
|
||||
#![allow(unknown_lints, bare_trait_objects, deprecated)]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))]
|
||||
// Ignored clippy and clippy_pedantic lints
|
||||
#![cfg_attr(
|
||||
feature = "cargo-clippy",
|
||||
allow(
|
||||
// clippy bug: https://github.com/rust-lang/rust-clippy/issues/5704
|
||||
unnested_or_patterns,
|
||||
// clippy bug: https://github.com/rust-lang/rust-clippy/issues/7768
|
||||
semicolon_if_nothing_returned,
|
||||
// not available in our oldest supported compiler
|
||||
empty_enum,
|
||||
type_repetition_in_bounds, // https://github.com/rust-lang/rust-clippy/issues/8772
|
||||
// integer and float ser/de requires these sorts of casts
|
||||
cast_possible_truncation,
|
||||
cast_possible_wrap,
|
||||
cast_sign_loss,
|
||||
// things are often more readable this way
|
||||
cast_lossless,
|
||||
module_name_repetitions,
|
||||
option_if_let_else,
|
||||
single_match_else,
|
||||
type_complexity,
|
||||
use_self,
|
||||
zero_prefixed_literal,
|
||||
// correctly used
|
||||
derive_partial_eq_without_eq,
|
||||
enum_glob_use,
|
||||
explicit_auto_deref,
|
||||
let_underscore_untyped,
|
||||
map_err_ignore,
|
||||
new_without_default,
|
||||
result_unit_err,
|
||||
wildcard_imports,
|
||||
// not practical
|
||||
needless_pass_by_value,
|
||||
similar_names,
|
||||
too_many_lines,
|
||||
// preference
|
||||
doc_markdown,
|
||||
unseparated_literal_suffix,
|
||||
// false positive
|
||||
needless_doctest_main,
|
||||
// noisy
|
||||
missing_errors_doc,
|
||||
must_use_candidate,
|
||||
)
|
||||
#![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_enum,
|
||||
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::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)]
|
||||
|
||||
@@ -168,21 +172,26 @@ mod lib {
|
||||
pub use std::*;
|
||||
}
|
||||
|
||||
pub use self::core::{cmp, iter, mem, num, ptr, slice, str};
|
||||
pub use self::core::{f32, f64};
|
||||
pub use self::core::{i16, i32, i64, i8, isize};
|
||||
pub use self::core::{iter, num, ptr, str};
|
||||
pub use self::core::{u16, u32, u64, u8, usize};
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub use self::core::{cmp, mem, slice};
|
||||
|
||||
pub use self::core::cell::{Cell, RefCell};
|
||||
pub use self::core::clone::{self, Clone};
|
||||
pub use self::core::convert::{self, From, Into};
|
||||
pub use self::core::default::{self, Default};
|
||||
pub use self::core::fmt::{self, Debug, Display};
|
||||
pub use self::core::clone;
|
||||
pub use self::core::cmp::Reverse;
|
||||
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::num::Wrapping;
|
||||
pub use self::core::ops::Range;
|
||||
pub use self::core::option::{self, Option};
|
||||
pub use self::core::result::{self, Result};
|
||||
pub use self::core::ops::{Bound, Range, RangeFrom, RangeInclusive, RangeTo};
|
||||
pub use self::core::option;
|
||||
pub use self::core::result;
|
||||
pub use self::core::time::Duration;
|
||||
|
||||
#[cfg(all(feature = "alloc", not(feature = "std")))]
|
||||
pub use alloc::borrow::{Cow, ToOwned};
|
||||
@@ -220,7 +229,7 @@ mod lib {
|
||||
pub use std::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque};
|
||||
|
||||
#[cfg(all(not(no_core_cstr), not(feature = "std")))]
|
||||
pub use core::ffi::CStr;
|
||||
pub use self::core::ffi::CStr;
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::ffi::CStr;
|
||||
|
||||
@@ -247,18 +256,6 @@ mod lib {
|
||||
#[cfg(feature = "std")]
|
||||
pub use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[cfg(all(feature = "std", not(no_collections_bound), no_ops_bound))]
|
||||
pub use std::collections::Bound;
|
||||
|
||||
#[cfg(not(no_core_reverse))]
|
||||
pub use self::core::cmp::Reverse;
|
||||
|
||||
#[cfg(not(no_ops_bound))]
|
||||
pub use self::core::ops::Bound;
|
||||
|
||||
#[cfg(not(no_range_inclusive))]
|
||||
pub use self::core::ops::RangeInclusive;
|
||||
|
||||
#[cfg(all(feature = "std", no_target_has_atomic, not(no_std_atomic)))]
|
||||
pub use std::sync::atomic::{
|
||||
AtomicBool, AtomicI16, AtomicI32, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, AtomicU8,
|
||||
@@ -280,15 +277,15 @@ mod lib {
|
||||
#[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "ptr"))]
|
||||
pub use std::sync::atomic::{AtomicIsize, AtomicUsize};
|
||||
|
||||
#[cfg(any(feature = "std", not(no_core_duration)))]
|
||||
pub use self::core::time::Duration;
|
||||
#[cfg(not(no_core_num_saturating))]
|
||||
pub use self::core::num::Saturating;
|
||||
}
|
||||
|
||||
// None of this crate's error handling needs the `From::from` error conversion
|
||||
// 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 `?`.
|
||||
macro_rules! try {
|
||||
macro_rules! tri {
|
||||
($expr:expr) => {
|
||||
match $expr {
|
||||
Ok(val) => val,
|
||||
@@ -309,20 +306,15 @@ pub mod de;
|
||||
pub mod ser;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use de::{Deserialize, Deserializer};
|
||||
pub use crate::de::{Deserialize, Deserializer};
|
||||
#[doc(inline)]
|
||||
pub use ser::{Serialize, Serializer};
|
||||
pub use crate::ser::{Serialize, Serializer};
|
||||
|
||||
// Used by generated code and doc tests. Not public API.
|
||||
#[doc(hidden)]
|
||||
#[path = "private/mod.rs"]
|
||||
pub mod __private;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use self::__private as export;
|
||||
#[allow(unused_imports)]
|
||||
use self::__private as private;
|
||||
|
||||
#[path = "de/seed.rs"]
|
||||
mod seed;
|
||||
|
||||
@@ -335,12 +327,11 @@ mod std_error;
|
||||
// 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")]
|
||||
#[allow(unused_imports)]
|
||||
#[macro_use]
|
||||
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};
|
||||
|
||||
#[cfg(all(not(no_serde_derive), any(feature = "std", feature = "alloc")))]
|
||||
|
||||
+7
-12
@@ -11,7 +11,7 @@
|
||||
/// input. This requires repetitive implementations of all the [`Deserializer`]
|
||||
/// trait methods.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::forward_to_deserialize_any;
|
||||
/// # use serde::de::{value, Deserializer, Visitor};
|
||||
/// #
|
||||
@@ -47,7 +47,7 @@
|
||||
/// methods so that they forward directly to [`Deserializer::deserialize_any`].
|
||||
/// You can choose which methods to forward.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::forward_to_deserialize_any;
|
||||
/// # use serde::de::{value, Deserializer, Visitor};
|
||||
/// #
|
||||
@@ -78,11 +78,10 @@
|
||||
/// called `V`. A different type parameter and a different lifetime can be
|
||||
/// specified explicitly if necessary.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use std::marker::PhantomData;
|
||||
/// #
|
||||
/// ```edition2021
|
||||
/// # use serde::forward_to_deserialize_any;
|
||||
/// # use serde::de::{value, Deserializer, Visitor};
|
||||
/// # use std::marker::PhantomData;
|
||||
/// #
|
||||
/// # struct MyDeserializer<V>(PhantomData<V>);
|
||||
/// #
|
||||
@@ -124,7 +123,7 @@ macro_rules! forward_to_deserialize_any {
|
||||
macro_rules! forward_to_deserialize_any_method {
|
||||
($func:ident<$l:tt, $v:ident>($($arg:ident : $ty:ty),*)) => {
|
||||
#[inline]
|
||||
fn $func<$v>(self, $($arg: $ty,)* visitor: $v) -> $crate::__private::Result<$v::Value, Self::Error>
|
||||
fn $func<$v>(self, $($arg: $ty,)* visitor: $v) -> $crate::__private::Result<$v::Value, <Self as $crate::de::Deserializer<$l>>::Error>
|
||||
where
|
||||
$v: $crate::de::Visitor<$l>,
|
||||
{
|
||||
@@ -155,9 +154,7 @@ macro_rules! forward_to_deserialize_any_helper {
|
||||
forward_to_deserialize_any_method!{deserialize_i64<$l, $v>()}
|
||||
};
|
||||
(i128<$l:tt, $v:ident>) => {
|
||||
serde_if_integer128! {
|
||||
forward_to_deserialize_any_method!{deserialize_i128<$l, $v>()}
|
||||
}
|
||||
forward_to_deserialize_any_method!{deserialize_i128<$l, $v>()}
|
||||
};
|
||||
(u8<$l:tt, $v:ident>) => {
|
||||
forward_to_deserialize_any_method!{deserialize_u8<$l, $v>()}
|
||||
@@ -172,9 +169,7 @@ macro_rules! forward_to_deserialize_any_helper {
|
||||
forward_to_deserialize_any_method!{deserialize_u64<$l, $v>()}
|
||||
};
|
||||
(u128<$l:tt, $v:ident>) => {
|
||||
serde_if_integer128! {
|
||||
forward_to_deserialize_any_method!{deserialize_u128<$l, $v>()}
|
||||
}
|
||||
forward_to_deserialize_any_method!{deserialize_u128<$l, $v>()}
|
||||
};
|
||||
(f32<$l:tt, $v:ident>) => {
|
||||
forward_to_deserialize_any_method!{deserialize_f32<$l, $v>()}
|
||||
|
||||
+231
-327
@@ -1,10 +1,13 @@
|
||||
use lib::*;
|
||||
use crate::lib::*;
|
||||
|
||||
use de::value::{BorrowedBytesDeserializer, BytesDeserializer};
|
||||
use de::{Deserialize, Deserializer, Error, IntoDeserializer, Visitor};
|
||||
use crate::de::value::{BorrowedBytesDeserializer, BytesDeserializer};
|
||||
use crate::de::{
|
||||
Deserialize, DeserializeSeed, Deserializer, EnumAccess, Error, IntoDeserializer, VariantAccess,
|
||||
Visitor,
|
||||
};
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
use de::{DeserializeSeed, MapAccess, Unexpected};
|
||||
use crate::de::{MapAccess, Unexpected};
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub use self::content::{
|
||||
@@ -13,7 +16,7 @@ pub use self::content::{
|
||||
TagOrContentField, TagOrContentFieldVisitor, TaggedContentVisitor, UntaggedUnitVisitor,
|
||||
};
|
||||
|
||||
pub use seed::InPlaceSeed;
|
||||
pub use crate::seed::InPlaceSeed;
|
||||
|
||||
/// If the missing field is of type `Option<T>` then treat is as `None`,
|
||||
/// otherwise it is an error.
|
||||
@@ -203,13 +206,13 @@ mod content {
|
||||
// This issue is tracking making some of this stuff public:
|
||||
// https://github.com/serde-rs/serde/issues/741
|
||||
|
||||
use lib::*;
|
||||
use crate::lib::*;
|
||||
|
||||
use __private::size_hint;
|
||||
use actually_private;
|
||||
use de::{
|
||||
self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, Expected, IgnoredAny,
|
||||
MapAccess, SeqAccess, Unexpected, Visitor,
|
||||
use crate::actually_private;
|
||||
use crate::de::value::{MapDeserializer, SeqDeserializer};
|
||||
use crate::de::{
|
||||
self, size_hint, Deserialize, DeserializeSeed, Deserializer, EnumAccess, Expected,
|
||||
IgnoredAny, MapAccess, SeqAccess, Unexpected, Visitor,
|
||||
};
|
||||
|
||||
/// Used from generated code to buffer the contents of the Deserializer when
|
||||
@@ -299,6 +302,19 @@ mod content {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, E> de::IntoDeserializer<'de, E> for Content<'de>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
type Deserializer = ContentDeserializer<'de, E>;
|
||||
|
||||
fn into_deserializer(self) -> Self::Deserializer {
|
||||
ContentDeserializer::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Used to capture data in [`Content`] from other deserializers.
|
||||
/// Cannot capture externally tagged enums, `i128` and `u128`.
|
||||
struct ContentVisitor<'de> {
|
||||
value: PhantomData<Content<'de>>,
|
||||
}
|
||||
@@ -474,8 +490,9 @@ mod content {
|
||||
where
|
||||
V: SeqAccess<'de>,
|
||||
{
|
||||
let mut vec = Vec::with_capacity(size_hint::cautious(visitor.size_hint()));
|
||||
while let Some(e) = try!(visitor.next_element()) {
|
||||
let mut vec =
|
||||
Vec::<Content>::with_capacity(size_hint::cautious::<Content>(visitor.size_hint()));
|
||||
while let Some(e) = tri!(visitor.next_element()) {
|
||||
vec.push(e);
|
||||
}
|
||||
Ok(Content::Seq(vec))
|
||||
@@ -485,8 +502,11 @@ mod content {
|
||||
where
|
||||
V: MapAccess<'de>,
|
||||
{
|
||||
let mut vec = Vec::with_capacity(size_hint::cautious(visitor.size_hint()));
|
||||
while let Some(kv) = try!(visitor.next_entry()) {
|
||||
let mut vec =
|
||||
Vec::<(Content, Content)>::with_capacity(
|
||||
size_hint::cautious::<(Content, Content)>(visitor.size_hint()),
|
||||
);
|
||||
while let Some(kv) = tri!(visitor.next_entry()) {
|
||||
vec.push(kv);
|
||||
}
|
||||
Ok(Content::Map(vec))
|
||||
@@ -510,6 +530,8 @@ mod content {
|
||||
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<TagOrContent<'de>>,
|
||||
@@ -518,7 +540,7 @@ mod content {
|
||||
impl<'de> TagOrContentVisitor<'de> {
|
||||
fn new(name: &'static str) -> Self {
|
||||
TagOrContentVisitor {
|
||||
name: name,
|
||||
name,
|
||||
value: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -796,52 +818,33 @@ mod 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 TaggedContent<'de, T> {
|
||||
pub tag: T,
|
||||
pub content: Content<'de>,
|
||||
}
|
||||
|
||||
/// Not public API.
|
||||
pub struct TaggedContentVisitor<'de, T> {
|
||||
pub struct TaggedContentVisitor<T> {
|
||||
tag_name: &'static str,
|
||||
expecting: &'static str,
|
||||
value: PhantomData<TaggedContent<'de, T>>,
|
||||
value: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<'de, T> TaggedContentVisitor<'de, T> {
|
||||
impl<T> TaggedContentVisitor<T> {
|
||||
/// 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: expecting,
|
||||
expecting,
|
||||
value: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, T> DeserializeSeed<'de> for TaggedContentVisitor<'de, T>
|
||||
impl<'de, T> Visitor<'de> for TaggedContentVisitor<T>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
type Value = TaggedContent<'de, T>;
|
||||
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
// Internally tagged enums are only supported in self-describing
|
||||
// formats.
|
||||
deserializer.deserialize_any(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, T> Visitor<'de> for TaggedContentVisitor<'de, T>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
type Value = TaggedContent<'de, T>;
|
||||
type Value = (T, Content<'de>);
|
||||
|
||||
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
fmt.write_str(self.expecting)
|
||||
@@ -851,17 +854,14 @@ mod content {
|
||||
where
|
||||
S: SeqAccess<'de>,
|
||||
{
|
||||
let tag = match try!(seq.next_element()) {
|
||||
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(TaggedContent {
|
||||
tag: tag,
|
||||
content: try!(Content::deserialize(rest)),
|
||||
})
|
||||
Ok((tag, tri!(Content::deserialize(rest))))
|
||||
}
|
||||
|
||||
fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
|
||||
@@ -869,27 +869,27 @@ mod content {
|
||||
M: MapAccess<'de>,
|
||||
{
|
||||
let mut tag = None;
|
||||
let mut vec = Vec::with_capacity(size_hint::cautious(map.size_hint()));
|
||||
while let Some(k) = try!(map.next_key_seed(TagOrContentVisitor::new(self.tag_name))) {
|
||||
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(try!(map.next_value()));
|
||||
tag = Some(tri!(map.next_value()));
|
||||
}
|
||||
TagOrContent::Content(k) => {
|
||||
let v = try!(map.next_value());
|
||||
let v = tri!(map.next_value());
|
||||
vec.push((k, v));
|
||||
}
|
||||
}
|
||||
}
|
||||
match tag {
|
||||
None => Err(de::Error::missing_field(self.tag_name)),
|
||||
Some(tag) => Ok(TaggedContent {
|
||||
tag: tag,
|
||||
content: Content::Map(vec),
|
||||
}),
|
||||
Some(tag) => Ok((tag, Content::Map(vec))),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -915,7 +915,7 @@ mod content {
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_str(self)
|
||||
deserializer.deserialize_identifier(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -926,6 +926,20 @@ mod content {
|
||||
write!(formatter, "{:?} or {:?}", self.tag, self.content)
|
||||
}
|
||||
|
||||
fn visit_u64<E>(self, field_index: u64) -> Result<Self::Value, E>
|
||||
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<E>(self, field: &str) -> Result<Self::Value, E>
|
||||
where
|
||||
E: de::Error,
|
||||
@@ -938,6 +952,19 @@ mod content {
|
||||
Err(de::Error::invalid_value(Unexpected::Str(field), &self))
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_bytes<E>(self, field: &[u8]) -> Result<Self::Value, E>
|
||||
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
|
||||
@@ -963,7 +990,7 @@ mod content {
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_str(self)
|
||||
deserializer.deserialize_identifier(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -978,13 +1005,31 @@ mod content {
|
||||
)
|
||||
}
|
||||
|
||||
fn visit_u64<E>(self, field_index: u64) -> Result<Self::Value, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
match field_index {
|
||||
0 => Ok(TagContentOtherField::Tag),
|
||||
1 => Ok(TagContentOtherField::Content),
|
||||
_ => Ok(TagContentOtherField::Other),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, field: &str) -> Result<Self::Value, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
if field == self.tag {
|
||||
self.visit_bytes(field.as_bytes())
|
||||
}
|
||||
|
||||
fn visit_bytes<E>(self, field: &[u8]) -> Result<Self::Value, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
if field == self.tag.as_bytes() {
|
||||
Ok(TagContentOtherField::Tag)
|
||||
} else if field == self.content {
|
||||
} else if field == self.content.as_bytes() {
|
||||
Ok(TagContentOtherField::Content)
|
||||
} else {
|
||||
Ok(TagContentOtherField::Other)
|
||||
@@ -1050,9 +1095,9 @@ mod content {
|
||||
E: de::Error,
|
||||
{
|
||||
let seq = content.into_iter().map(ContentDeserializer::new);
|
||||
let mut seq_visitor = de::value::SeqDeserializer::new(seq);
|
||||
let value = try!(visitor.visit_seq(&mut seq_visitor));
|
||||
try!(seq_visitor.end());
|
||||
let mut seq_visitor = SeqDeserializer::new(seq);
|
||||
let value = tri!(visitor.visit_seq(&mut seq_visitor));
|
||||
tri!(seq_visitor.end());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
@@ -1067,9 +1112,9 @@ mod content {
|
||||
let map = content
|
||||
.into_iter()
|
||||
.map(|(k, v)| (ContentDeserializer::new(k), ContentDeserializer::new(v)));
|
||||
let mut map_visitor = de::value::MapDeserializer::new(map);
|
||||
let value = try!(visitor.visit_map(&mut map_visitor));
|
||||
try!(map_visitor.end());
|
||||
let mut map_visitor = MapDeserializer::new(map);
|
||||
let value = tri!(visitor.visit_map(&mut map_visitor));
|
||||
tri!(map_visitor.end());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
@@ -1457,7 +1502,7 @@ mod content {
|
||||
/// private API, don't use
|
||||
pub fn new(content: Content<'de>) -> Self {
|
||||
ContentDeserializer {
|
||||
content: content,
|
||||
content,
|
||||
err: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -1478,8 +1523,8 @@ mod content {
|
||||
{
|
||||
pub fn new(variant: Content<'de>, value: Option<Content<'de>>) -> EnumDeserializer<'de, E> {
|
||||
EnumDeserializer {
|
||||
variant: variant,
|
||||
value: value,
|
||||
variant,
|
||||
value,
|
||||
err: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -1545,7 +1590,7 @@ mod content {
|
||||
{
|
||||
match self.value {
|
||||
Some(Content::Seq(v)) => {
|
||||
de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor)
|
||||
de::Deserializer::deserialize_any(SeqDeserializer::new(v.into_iter()), visitor)
|
||||
}
|
||||
Some(other) => Err(de::Error::invalid_type(
|
||||
other.unexpected(),
|
||||
@@ -1568,10 +1613,10 @@ mod content {
|
||||
{
|
||||
match self.value {
|
||||
Some(Content::Map(v)) => {
|
||||
de::Deserializer::deserialize_any(MapDeserializer::new(v), visitor)
|
||||
de::Deserializer::deserialize_any(MapDeserializer::new(v.into_iter()), visitor)
|
||||
}
|
||||
Some(Content::Seq(v)) => {
|
||||
de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor)
|
||||
de::Deserializer::deserialize_any(SeqDeserializer::new(v.into_iter()), visitor)
|
||||
}
|
||||
Some(other) => Err(de::Error::invalid_type(
|
||||
other.unexpected(),
|
||||
@@ -1585,156 +1630,6 @@ mod content {
|
||||
}
|
||||
}
|
||||
|
||||
struct SeqDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
iter: <Vec<Content<'de>> as IntoIterator>::IntoIter,
|
||||
err: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<'de, E> SeqDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
fn new(vec: Vec<Content<'de>>) -> Self {
|
||||
SeqDeserializer {
|
||||
iter: vec.into_iter(),
|
||||
err: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, E> de::Deserializer<'de> for SeqDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
#[inline]
|
||||
fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: de::Visitor<'de>,
|
||||
{
|
||||
let len = self.iter.len();
|
||||
if len == 0 {
|
||||
visitor.visit_unit()
|
||||
} else {
|
||||
let ret = try!(visitor.visit_seq(&mut self));
|
||||
let remaining = self.iter.len();
|
||||
if remaining == 0 {
|
||||
Ok(ret)
|
||||
} else {
|
||||
Err(de::Error::invalid_length(len, &"fewer elements in array"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
|
||||
bytes byte_buf option unit unit_struct newtype_struct seq tuple
|
||||
tuple_struct map struct enum identifier ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, E> de::SeqAccess<'de> for SeqDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
|
||||
where
|
||||
T: de::DeserializeSeed<'de>,
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some(value) => seed.deserialize(ContentDeserializer::new(value)).map(Some),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> Option<usize> {
|
||||
size_hint::from_bounds(&self.iter)
|
||||
}
|
||||
}
|
||||
|
||||
struct MapDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
iter: <Vec<(Content<'de>, Content<'de>)> as IntoIterator>::IntoIter,
|
||||
value: Option<Content<'de>>,
|
||||
err: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<'de, E> MapDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
fn new(map: Vec<(Content<'de>, Content<'de>)>) -> Self {
|
||||
MapDeserializer {
|
||||
iter: map.into_iter(),
|
||||
value: None,
|
||||
err: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, E> de::MapAccess<'de> for MapDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
|
||||
where
|
||||
T: de::DeserializeSeed<'de>,
|
||||
{
|
||||
match self.iter.next() {
|
||||
Some((key, value)) => {
|
||||
self.value = Some(value);
|
||||
seed.deserialize(ContentDeserializer::new(key)).map(Some)
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
|
||||
where
|
||||
T: de::DeserializeSeed<'de>,
|
||||
{
|
||||
match self.value.take() {
|
||||
Some(value) => seed.deserialize(ContentDeserializer::new(value)),
|
||||
None => Err(de::Error::custom("value is missing")),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> Option<usize> {
|
||||
size_hint::from_bounds(&self.iter)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, E> de::Deserializer<'de> for MapDeserializer<'de, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
type Error = E;
|
||||
|
||||
#[inline]
|
||||
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_map(self)
|
||||
}
|
||||
|
||||
forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
|
||||
bytes byte_buf option unit unit_struct newtype_struct seq tuple
|
||||
tuple_struct map struct enum identifier ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
/// Not public API.
|
||||
pub struct ContentRefDeserializer<'a, 'de: 'a, E> {
|
||||
content: &'a Content<'de>,
|
||||
@@ -1796,9 +1691,9 @@ mod content {
|
||||
E: de::Error,
|
||||
{
|
||||
let seq = content.iter().map(ContentRefDeserializer::new);
|
||||
let mut seq_visitor = de::value::SeqDeserializer::new(seq);
|
||||
let value = try!(visitor.visit_seq(&mut seq_visitor));
|
||||
try!(seq_visitor.end());
|
||||
let mut seq_visitor = SeqDeserializer::new(seq);
|
||||
let value = tri!(visitor.visit_seq(&mut seq_visitor));
|
||||
tri!(seq_visitor.end());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
@@ -1816,9 +1711,9 @@ mod content {
|
||||
ContentRefDeserializer::new(v),
|
||||
)
|
||||
});
|
||||
let mut map_visitor = de::value::MapDeserializer::new(map);
|
||||
let value = try!(visitor.visit_map(&mut map_visitor));
|
||||
try!(map_visitor.end());
|
||||
let mut map_visitor = MapDeserializer::new(map);
|
||||
let value = tri!(visitor.visit_map(&mut map_visitor));
|
||||
tri!(map_visitor.end());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
@@ -2135,8 +2030,8 @@ mod content {
|
||||
};
|
||||
|
||||
visitor.visit_enum(EnumRefDeserializer {
|
||||
variant: variant,
|
||||
value: value,
|
||||
variant,
|
||||
value,
|
||||
err: PhantomData,
|
||||
})
|
||||
}
|
||||
@@ -2180,12 +2075,20 @@ mod content {
|
||||
/// private API, don't use
|
||||
pub fn new(content: &'a Content<'de>) -> Self {
|
||||
ContentRefDeserializer {
|
||||
content: content,
|
||||
content,
|
||||
err: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'de: 'a, E> Copy for ContentRefDeserializer<'a, 'de, E> {}
|
||||
|
||||
impl<'a, 'de: 'a, E> Clone for ContentRefDeserializer<'a, 'de, E> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
struct EnumRefDeserializer<'a, 'de: 'a, E>
|
||||
where
|
||||
E: de::Error,
|
||||
@@ -2330,7 +2233,7 @@ mod content {
|
||||
if len == 0 {
|
||||
visitor.visit_unit()
|
||||
} else {
|
||||
let ret = try!(visitor.visit_seq(&mut self));
|
||||
let ret = tri!(visitor.visit_seq(&mut self));
|
||||
let remaining = self.iter.len();
|
||||
if remaining == 0 {
|
||||
Ok(ret)
|
||||
@@ -2481,8 +2384,8 @@ mod content {
|
||||
/// Not public API.
|
||||
pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
|
||||
InternallyTaggedUnitVisitor {
|
||||
type_name: type_name,
|
||||
variant_name: variant_name,
|
||||
type_name,
|
||||
variant_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2509,7 +2412,7 @@ mod content {
|
||||
where
|
||||
M: MapAccess<'de>,
|
||||
{
|
||||
while try!(access.next_entry::<IgnoredAny, IgnoredAny>()).is_some() {}
|
||||
while tri!(access.next_entry::<IgnoredAny, IgnoredAny>()).is_some() {}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -2526,8 +2429,8 @@ mod content {
|
||||
/// Not public API.
|
||||
pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
|
||||
UntaggedUnitVisitor {
|
||||
type_name: type_name,
|
||||
variant_name: variant_name,
|
||||
type_name,
|
||||
variant_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2731,11 +2634,7 @@ where
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_map(FlatInternallyTaggedAccess {
|
||||
iter: self.0.iter_mut(),
|
||||
pending: None,
|
||||
_marker: PhantomData,
|
||||
})
|
||||
self.deserialize_map(visitor)
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(
|
||||
@@ -2747,17 +2646,8 @@ where
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
for item in self.0.iter_mut() {
|
||||
// items in the vector are nulled out when used. So we can only use
|
||||
// an item if it's still filled in and if the field is one we care
|
||||
// about.
|
||||
let use_item = match *item {
|
||||
None => false,
|
||||
Some((ref c, _)) => c.as_str().map_or(false, |x| variants.contains(&x)),
|
||||
};
|
||||
|
||||
if use_item {
|
||||
let (key, value) = item.take().unwrap();
|
||||
for entry in self.0 {
|
||||
if let Some((key, value)) = flat_map_take_entry(entry, variants) {
|
||||
return visitor.visit_enum(EnumDeserializer::new(key, Some(value)));
|
||||
}
|
||||
}
|
||||
@@ -2772,7 +2662,11 @@ where
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_map(FlatMapAccess::new(self.0.iter()))
|
||||
visitor.visit_map(FlatMapAccess {
|
||||
iter: self.0.iter(),
|
||||
pending_content: None,
|
||||
_marker: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
fn deserialize_struct<V>(
|
||||
@@ -2784,7 +2678,12 @@ where
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_map(FlatStructAccess::new(self.0.iter_mut(), fields))
|
||||
visitor.visit_map(FlatStructAccess {
|
||||
iter: self.0.iter_mut(),
|
||||
pending_content: None,
|
||||
fields,
|
||||
_marker: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
|
||||
@@ -2811,6 +2710,13 @@ where
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
||||
fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
||||
forward_to_deserialize_other! {
|
||||
deserialize_bool()
|
||||
deserialize_i8()
|
||||
@@ -2833,30 +2739,16 @@ where
|
||||
deserialize_tuple(usize)
|
||||
deserialize_tuple_struct(&'static str, usize)
|
||||
deserialize_identifier()
|
||||
deserialize_ignored_any()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub struct FlatMapAccess<'a, 'de: 'a, E> {
|
||||
struct FlatMapAccess<'a, 'de: 'a, E> {
|
||||
iter: slice::Iter<'a, Option<(Content<'de>, Content<'de>)>>,
|
||||
pending_content: Option<&'a Content<'de>>,
|
||||
_marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, 'de, E> FlatMapAccess<'a, 'de, E> {
|
||||
fn new(
|
||||
iter: slice::Iter<'a, Option<(Content<'de>, Content<'de>)>>,
|
||||
) -> FlatMapAccess<'a, 'de, E> {
|
||||
FlatMapAccess {
|
||||
iter: iter,
|
||||
pending_content: None,
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, 'de, E> MapAccess<'de> for FlatMapAccess<'a, 'de, E>
|
||||
where
|
||||
@@ -2871,6 +2763,10 @@ where
|
||||
for item in &mut self.iter {
|
||||
// Items in the vector are nulled out when used by a struct.
|
||||
if let Some((ref key, ref content)) = *item {
|
||||
// Do not take(), instead borrow this entry. The internally tagged
|
||||
// enum does its own buffering so we can't tell whether this entry
|
||||
// is going to be consumed. Borrowing here leaves the entry
|
||||
// available for later flattened fields.
|
||||
self.pending_content = Some(content);
|
||||
return seed.deserialize(ContentRefDeserializer::new(key)).map(Some);
|
||||
}
|
||||
@@ -2890,28 +2786,13 @@ where
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub struct FlatStructAccess<'a, 'de: 'a, E> {
|
||||
struct FlatStructAccess<'a, 'de: 'a, E> {
|
||||
iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>,
|
||||
pending_content: Option<Content<'de>>,
|
||||
fields: &'static [&'static str],
|
||||
_marker: PhantomData<E>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, 'de, E> FlatStructAccess<'a, 'de, E> {
|
||||
fn new(
|
||||
iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>,
|
||||
fields: &'static [&'static str],
|
||||
) -> FlatStructAccess<'a, 'de, E> {
|
||||
FlatStructAccess {
|
||||
iter: iter,
|
||||
pending_content: None,
|
||||
fields: fields,
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, 'de, E> MapAccess<'de> for FlatStructAccess<'a, 'de, E>
|
||||
where
|
||||
@@ -2923,17 +2804,8 @@ where
|
||||
where
|
||||
T: DeserializeSeed<'de>,
|
||||
{
|
||||
while let Some(item) = self.iter.next() {
|
||||
// items in the vector are nulled out when used. So we can only use
|
||||
// an item if it's still filled in and if the field is one we care
|
||||
// about. In case we do not know which fields we want, we take them all.
|
||||
let use_item = match *item {
|
||||
None => false,
|
||||
Some((ref c, _)) => c.as_str().map_or(false, |key| self.fields.contains(&key)),
|
||||
};
|
||||
|
||||
if use_item {
|
||||
let (key, content) = item.take().unwrap();
|
||||
for entry in self.iter.by_ref() {
|
||||
if let Some((key, content)) = flat_map_take_entry(entry, self.fields) {
|
||||
self.pending_content = Some(content);
|
||||
return seed.deserialize(ContentDeserializer::new(key)).map(Some);
|
||||
}
|
||||
@@ -2952,44 +2824,76 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Claims one key-value pair from a FlatMapDeserializer's field buffer if the
|
||||
/// field name matches any of the recognized ones.
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub struct FlatInternallyTaggedAccess<'a, 'de: 'a, E> {
|
||||
iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>,
|
||||
pending: Option<&'a Content<'de>>,
|
||||
_marker: PhantomData<E>,
|
||||
fn flat_map_take_entry<'de>(
|
||||
entry: &mut Option<(Content<'de>, Content<'de>)>,
|
||||
recognized: &[&str],
|
||||
) -> Option<(Content<'de>, Content<'de>)> {
|
||||
// Entries in the FlatMapDeserializer buffer are nulled out as they get
|
||||
// claimed for deserialization. We only use an entry if it is still present
|
||||
// and if the field is one recognized by the current data structure.
|
||||
let is_recognized = match entry {
|
||||
None => false,
|
||||
Some((k, _v)) => k.as_str().map_or(false, |name| recognized.contains(&name)),
|
||||
};
|
||||
|
||||
if is_recognized {
|
||||
entry.take()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, 'de, E> MapAccess<'de> for FlatInternallyTaggedAccess<'a, 'de, E>
|
||||
pub struct AdjacentlyTaggedEnumVariantSeed<F> {
|
||||
pub enum_name: &'static str,
|
||||
pub variants: &'static [&'static str],
|
||||
pub fields_enum: PhantomData<F>,
|
||||
}
|
||||
|
||||
pub struct AdjacentlyTaggedEnumVariantVisitor<F> {
|
||||
enum_name: &'static str,
|
||||
fields_enum: PhantomData<F>,
|
||||
}
|
||||
|
||||
impl<'de, F> Visitor<'de> for AdjacentlyTaggedEnumVariantVisitor<F>
|
||||
where
|
||||
E: Error,
|
||||
F: Deserialize<'de>,
|
||||
{
|
||||
type Error = E;
|
||||
type Value = F;
|
||||
|
||||
fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
|
||||
where
|
||||
T: DeserializeSeed<'de>,
|
||||
{
|
||||
for item in &mut self.iter {
|
||||
if let Some((ref key, ref content)) = *item {
|
||||
// Do not take(), instead borrow this entry. The internally tagged
|
||||
// enum does its own buffering so we can't tell whether this entry
|
||||
// is going to be consumed. Borrowing here leaves the entry
|
||||
// available for later flattened fields.
|
||||
self.pending = Some(content);
|
||||
return seed.deserialize(ContentRefDeserializer::new(key)).map(Some);
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "variant of enum {}", self.enum_name)
|
||||
}
|
||||
|
||||
fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
|
||||
fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
|
||||
where
|
||||
T: DeserializeSeed<'de>,
|
||||
A: EnumAccess<'de>,
|
||||
{
|
||||
match self.pending.take() {
|
||||
Some(value) => seed.deserialize(ContentRefDeserializer::new(value)),
|
||||
None => panic!("value is missing"),
|
||||
}
|
||||
let (variant, variant_access) = tri!(data.variant());
|
||||
tri!(variant_access.unit_variant());
|
||||
Ok(variant)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, F> DeserializeSeed<'de> for AdjacentlyTaggedEnumVariantSeed<F>
|
||||
where
|
||||
F: Deserialize<'de>,
|
||||
{
|
||||
type Value = F;
|
||||
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_enum(
|
||||
self.enum_name,
|
||||
self.variants,
|
||||
AdjacentlyTaggedEnumVariantVisitor {
|
||||
enum_name: self.enum_name,
|
||||
fields_enum: PhantomData,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Used only by Serde doc tests. Not public API.
|
||||
|
||||
use lib::*;
|
||||
use crate::lib::*;
|
||||
|
||||
use ser;
|
||||
use crate::ser;
|
||||
|
||||
#[doc(hidden)]
|
||||
#[derive(Debug)]
|
||||
@@ -56,7 +56,10 @@ macro_rules! __serialize_unimplemented {
|
||||
#[macro_export]
|
||||
macro_rules! __serialize_unimplemented_method {
|
||||
($func:ident $(<$t:ident>)* ($($arg:ty),*) -> $ret:ident) => {
|
||||
fn $func $(<$t: ?Sized + $crate::Serialize>)* (self $(, _: $arg)*) -> $crate::__private::Result<Self::$ret, Self::Error> {
|
||||
fn $func $(<$t>)* (self $(, _: $arg)*) -> $crate::__private::Result<Self::$ret, Self::Error>
|
||||
where
|
||||
$($t: ?Sized + $crate::Serialize,)*
|
||||
{
|
||||
unimplemented!()
|
||||
}
|
||||
};
|
||||
|
||||
+11
-13
@@ -3,30 +3,28 @@ pub mod de;
|
||||
#[cfg(not(no_serde_derive))]
|
||||
pub mod ser;
|
||||
|
||||
pub mod size_hint;
|
||||
|
||||
// FIXME: #[cfg(doctest)] once https://github.com/rust-lang/rust/issues/67295 is fixed.
|
||||
pub mod doc;
|
||||
|
||||
pub use lib::clone::Clone;
|
||||
pub use lib::convert::{From, Into};
|
||||
pub use lib::default::Default;
|
||||
pub use lib::fmt::{self, Formatter};
|
||||
pub use lib::marker::PhantomData;
|
||||
pub use lib::option::Option::{self, None, Some};
|
||||
pub use lib::ptr;
|
||||
pub use lib::result::Result::{self, Err, Ok};
|
||||
pub use crate::lib::clone::Clone;
|
||||
pub use crate::lib::convert::{From, Into};
|
||||
pub use crate::lib::default::Default;
|
||||
pub use crate::lib::fmt::{self, Formatter};
|
||||
pub use crate::lib::marker::PhantomData;
|
||||
pub use crate::lib::option::Option::{self, None, Some};
|
||||
pub use crate::lib::ptr;
|
||||
pub use crate::lib::result::Result::{self, Err, Ok};
|
||||
|
||||
pub use self::string::from_utf8_lossy;
|
||||
|
||||
#[cfg(any(feature = "alloc", feature = "std"))]
|
||||
pub use lib::{ToString, Vec};
|
||||
pub use crate::lib::{ToString, Vec};
|
||||
|
||||
#[cfg(not(no_core_try_from))]
|
||||
pub use lib::convert::TryFrom;
|
||||
pub use crate::lib::convert::TryFrom;
|
||||
|
||||
mod string {
|
||||
use lib::*;
|
||||
use crate::lib::*;
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub fn from_utf8_lossy(bytes: &[u8]) -> Cow<str> {
|
||||
|
||||
+213
-158
@@ -1,6 +1,6 @@
|
||||
use lib::*;
|
||||
use crate::lib::*;
|
||||
|
||||
use ser::{self, Impossible, Serialize, SerializeMap, SerializeStruct, Serializer};
|
||||
use crate::ser::{self, Impossible, Serialize, SerializeMap, SerializeStruct, Serializer};
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
use self::content::{
|
||||
@@ -27,10 +27,10 @@ where
|
||||
T: Serialize,
|
||||
{
|
||||
value.serialize(TaggedSerializer {
|
||||
type_ident: type_ident,
|
||||
variant_ident: variant_ident,
|
||||
tag: tag,
|
||||
variant_name: variant_name,
|
||||
type_ident,
|
||||
variant_ident,
|
||||
tag,
|
||||
variant_name,
|
||||
delegate: serializer,
|
||||
})
|
||||
}
|
||||
@@ -174,22 +174,22 @@ where
|
||||
Err(self.bad_type(Unsupported::Optional))
|
||||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error>
|
||||
fn serialize_some<T>(self, _: &T) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
Err(self.bad_type(Unsupported::Optional))
|
||||
}
|
||||
|
||||
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
|
||||
let mut map = try!(self.delegate.serialize_map(Some(1)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
let mut map = tri!(self.delegate.serialize_map(Some(1)));
|
||||
tri!(map.serialize_entry(self.tag, self.variant_name));
|
||||
map.end()
|
||||
}
|
||||
|
||||
fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
|
||||
let mut map = try!(self.delegate.serialize_map(Some(1)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
let mut map = tri!(self.delegate.serialize_map(Some(1)));
|
||||
tri!(map.serialize_entry(self.tag, self.variant_name));
|
||||
map.end()
|
||||
}
|
||||
|
||||
@@ -199,24 +199,24 @@ where
|
||||
_: u32,
|
||||
inner_variant: &'static str,
|
||||
) -> Result<Self::Ok, Self::Error> {
|
||||
let mut map = try!(self.delegate.serialize_map(Some(2)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
try!(map.serialize_entry(inner_variant, &()));
|
||||
let mut map = tri!(self.delegate.serialize_map(Some(2)));
|
||||
tri!(map.serialize_entry(self.tag, self.variant_name));
|
||||
tri!(map.serialize_entry(inner_variant, &()));
|
||||
map.end()
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized>(
|
||||
fn serialize_newtype_struct<T>(
|
||||
self,
|
||||
_: &'static str,
|
||||
value: &T,
|
||||
) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: ?Sized>(
|
||||
fn serialize_newtype_variant<T>(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: u32,
|
||||
@@ -224,11 +224,11 @@ where
|
||||
inner_value: &T,
|
||||
) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let mut map = try!(self.delegate.serialize_map(Some(2)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
try!(map.serialize_entry(inner_variant, inner_value));
|
||||
let mut map = tri!(self.delegate.serialize_map(Some(2)));
|
||||
tri!(map.serialize_entry(self.tag, self.variant_name));
|
||||
tri!(map.serialize_entry(inner_variant, inner_value));
|
||||
map.end()
|
||||
}
|
||||
|
||||
@@ -269,9 +269,9 @@ where
|
||||
inner_variant: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTupleVariant, Self::Error> {
|
||||
let mut map = try!(self.delegate.serialize_map(Some(2)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
try!(map.serialize_key(inner_variant));
|
||||
let mut map = tri!(self.delegate.serialize_map(Some(2)));
|
||||
tri!(map.serialize_entry(self.tag, self.variant_name));
|
||||
tri!(map.serialize_key(inner_variant));
|
||||
Ok(SerializeTupleVariantAsMapValue::new(
|
||||
map,
|
||||
inner_variant,
|
||||
@@ -280,8 +280,8 @@ where
|
||||
}
|
||||
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
|
||||
let mut map = try!(self.delegate.serialize_map(len.map(|len| len + 1)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
let mut map = tri!(self.delegate.serialize_map(len.map(|len| len + 1)));
|
||||
tri!(map.serialize_entry(self.tag, self.variant_name));
|
||||
Ok(map)
|
||||
}
|
||||
|
||||
@@ -290,8 +290,8 @@ where
|
||||
name: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStruct, Self::Error> {
|
||||
let mut state = try!(self.delegate.serialize_struct(name, len + 1));
|
||||
try!(state.serialize_field(self.tag, self.variant_name));
|
||||
let mut state = tri!(self.delegate.serialize_struct(name, len + 1));
|
||||
tri!(state.serialize_field(self.tag, self.variant_name));
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
@@ -316,9 +316,9 @@ where
|
||||
inner_variant: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStructVariant, Self::Error> {
|
||||
let mut map = try!(self.delegate.serialize_map(Some(2)));
|
||||
try!(map.serialize_entry(self.tag, self.variant_name));
|
||||
try!(map.serialize_key(inner_variant));
|
||||
let mut map = tri!(self.delegate.serialize_map(Some(2)));
|
||||
tri!(map.serialize_entry(self.tag, self.variant_name));
|
||||
tri!(map.serialize_key(inner_variant));
|
||||
Ok(SerializeStructVariantAsMapValue::new(
|
||||
map,
|
||||
inner_variant,
|
||||
@@ -327,9 +327,9 @@ where
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
fn collect_str<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error>
|
||||
fn collect_str<T>(self, _: &T) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Display,
|
||||
T: ?Sized + Display,
|
||||
{
|
||||
Err(self.bad_type(Unsupported::String))
|
||||
}
|
||||
@@ -337,9 +337,9 @@ where
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
mod content {
|
||||
use lib::*;
|
||||
use crate::lib::*;
|
||||
|
||||
use ser::{self, Serialize, Serializer};
|
||||
use crate::ser::{self, Serialize, Serializer};
|
||||
|
||||
pub struct SerializeTupleVariantAsMapValue<M> {
|
||||
map: M,
|
||||
@@ -350,8 +350,8 @@ mod content {
|
||||
impl<M> SerializeTupleVariantAsMapValue<M> {
|
||||
pub fn new(map: M, name: &'static str, len: usize) -> Self {
|
||||
SerializeTupleVariantAsMapValue {
|
||||
map: map,
|
||||
name: name,
|
||||
map,
|
||||
name,
|
||||
fields: Vec::with_capacity(len),
|
||||
}
|
||||
}
|
||||
@@ -364,17 +364,17 @@ mod content {
|
||||
type Ok = M::Ok;
|
||||
type Error = M::Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), M::Error>
|
||||
fn serialize_field<T>(&mut self, value: &T) -> Result<(), M::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let value = try!(value.serialize(ContentSerializer::<M::Error>::new()));
|
||||
let value = tri!(value.serialize(ContentSerializer::<M::Error>::new()));
|
||||
self.fields.push(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(mut self) -> Result<M::Ok, M::Error> {
|
||||
try!(self
|
||||
tri!(self
|
||||
.map
|
||||
.serialize_value(&Content::TupleStruct(self.name, self.fields)));
|
||||
self.map.end()
|
||||
@@ -390,8 +390,8 @@ mod content {
|
||||
impl<M> SerializeStructVariantAsMapValue<M> {
|
||||
pub fn new(map: M, name: &'static str, len: usize) -> Self {
|
||||
SerializeStructVariantAsMapValue {
|
||||
map: map,
|
||||
name: name,
|
||||
map,
|
||||
name,
|
||||
fields: Vec::with_capacity(len),
|
||||
}
|
||||
}
|
||||
@@ -404,21 +404,17 @@ mod content {
|
||||
type Ok = M::Ok;
|
||||
type Error = M::Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(
|
||||
&mut self,
|
||||
key: &'static str,
|
||||
value: &T,
|
||||
) -> Result<(), M::Error>
|
||||
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), M::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let value = try!(value.serialize(ContentSerializer::<M::Error>::new()));
|
||||
let value = tri!(value.serialize(ContentSerializer::<M::Error>::new()));
|
||||
self.fields.push((key, value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(mut self) -> Result<M::Ok, M::Error> {
|
||||
try!(self
|
||||
tri!(self
|
||||
.map
|
||||
.serialize_value(&Content::Struct(self.name, self.fields)));
|
||||
self.map.end()
|
||||
@@ -499,50 +495,50 @@ mod content {
|
||||
}
|
||||
Content::Seq(ref elements) => elements.serialize(serializer),
|
||||
Content::Tuple(ref elements) => {
|
||||
use ser::SerializeTuple;
|
||||
let mut tuple = try!(serializer.serialize_tuple(elements.len()));
|
||||
use crate::ser::SerializeTuple;
|
||||
let mut tuple = tri!(serializer.serialize_tuple(elements.len()));
|
||||
for e in elements {
|
||||
try!(tuple.serialize_element(e));
|
||||
tri!(tuple.serialize_element(e));
|
||||
}
|
||||
tuple.end()
|
||||
}
|
||||
Content::TupleStruct(n, ref fields) => {
|
||||
use ser::SerializeTupleStruct;
|
||||
let mut ts = try!(serializer.serialize_tuple_struct(n, fields.len()));
|
||||
use crate::ser::SerializeTupleStruct;
|
||||
let mut ts = tri!(serializer.serialize_tuple_struct(n, fields.len()));
|
||||
for f in fields {
|
||||
try!(ts.serialize_field(f));
|
||||
tri!(ts.serialize_field(f));
|
||||
}
|
||||
ts.end()
|
||||
}
|
||||
Content::TupleVariant(n, i, v, ref fields) => {
|
||||
use ser::SerializeTupleVariant;
|
||||
let mut tv = try!(serializer.serialize_tuple_variant(n, i, v, fields.len()));
|
||||
use crate::ser::SerializeTupleVariant;
|
||||
let mut tv = tri!(serializer.serialize_tuple_variant(n, i, v, fields.len()));
|
||||
for f in fields {
|
||||
try!(tv.serialize_field(f));
|
||||
tri!(tv.serialize_field(f));
|
||||
}
|
||||
tv.end()
|
||||
}
|
||||
Content::Map(ref entries) => {
|
||||
use ser::SerializeMap;
|
||||
let mut map = try!(serializer.serialize_map(Some(entries.len())));
|
||||
use crate::ser::SerializeMap;
|
||||
let mut map = tri!(serializer.serialize_map(Some(entries.len())));
|
||||
for (k, v) in entries {
|
||||
try!(map.serialize_entry(k, v));
|
||||
tri!(map.serialize_entry(k, v));
|
||||
}
|
||||
map.end()
|
||||
}
|
||||
Content::Struct(n, ref fields) => {
|
||||
use ser::SerializeStruct;
|
||||
let mut s = try!(serializer.serialize_struct(n, fields.len()));
|
||||
use crate::ser::SerializeStruct;
|
||||
let mut s = tri!(serializer.serialize_struct(n, fields.len()));
|
||||
for &(k, ref v) in fields {
|
||||
try!(s.serialize_field(k, v));
|
||||
tri!(s.serialize_field(k, v));
|
||||
}
|
||||
s.end()
|
||||
}
|
||||
Content::StructVariant(n, i, v, ref fields) => {
|
||||
use ser::SerializeStructVariant;
|
||||
let mut sv = try!(serializer.serialize_struct_variant(n, i, v, fields.len()));
|
||||
use crate::ser::SerializeStructVariant;
|
||||
let mut sv = tri!(serializer.serialize_struct_variant(n, i, v, fields.len()));
|
||||
for &(k, ref v) in fields {
|
||||
try!(sv.serialize_field(k, v));
|
||||
tri!(sv.serialize_field(k, v));
|
||||
}
|
||||
sv.end()
|
||||
}
|
||||
@@ -635,11 +631,11 @@ mod content {
|
||||
Ok(Content::None)
|
||||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Content, E>
|
||||
fn serialize_some<T>(self, value: &T) -> Result<Content, E>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
Ok(Content::Some(Box::new(try!(value.serialize(self)))))
|
||||
Ok(Content::Some(Box::new(tri!(value.serialize(self)))))
|
||||
}
|
||||
|
||||
fn serialize_unit(self) -> Result<Content, E> {
|
||||
@@ -659,21 +655,17 @@ mod content {
|
||||
Ok(Content::UnitVariant(name, variant_index, variant))
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized>(
|
||||
self,
|
||||
name: &'static str,
|
||||
value: &T,
|
||||
) -> Result<Content, E>
|
||||
fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<Content, E>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
Ok(Content::NewtypeStruct(
|
||||
name,
|
||||
Box::new(try!(value.serialize(self))),
|
||||
Box::new(tri!(value.serialize(self))),
|
||||
))
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: ?Sized>(
|
||||
fn serialize_newtype_variant<T>(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: u32,
|
||||
@@ -681,13 +673,13 @@ mod content {
|
||||
value: &T,
|
||||
) -> Result<Content, E>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
Ok(Content::NewtypeVariant(
|
||||
name,
|
||||
variant_index,
|
||||
variant,
|
||||
Box::new(try!(value.serialize(self))),
|
||||
Box::new(tri!(value.serialize(self))),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -711,7 +703,7 @@ mod content {
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTupleStruct, E> {
|
||||
Ok(SerializeTupleStruct {
|
||||
name: name,
|
||||
name,
|
||||
fields: Vec::with_capacity(len),
|
||||
error: PhantomData,
|
||||
})
|
||||
@@ -725,9 +717,9 @@ mod content {
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTupleVariant, E> {
|
||||
Ok(SerializeTupleVariant {
|
||||
name: name,
|
||||
variant_index: variant_index,
|
||||
variant: variant,
|
||||
name,
|
||||
variant_index,
|
||||
variant,
|
||||
fields: Vec::with_capacity(len),
|
||||
error: PhantomData,
|
||||
})
|
||||
@@ -747,7 +739,7 @@ mod content {
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStruct, E> {
|
||||
Ok(SerializeStruct {
|
||||
name: name,
|
||||
name,
|
||||
fields: Vec::with_capacity(len),
|
||||
error: PhantomData,
|
||||
})
|
||||
@@ -761,9 +753,9 @@ mod content {
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStructVariant, E> {
|
||||
Ok(SerializeStructVariant {
|
||||
name: name,
|
||||
variant_index: variant_index,
|
||||
variant: variant,
|
||||
name,
|
||||
variant_index,
|
||||
variant,
|
||||
fields: Vec::with_capacity(len),
|
||||
error: PhantomData,
|
||||
})
|
||||
@@ -782,11 +774,11 @@ mod content {
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
|
||||
fn serialize_element<T>(&mut self, value: &T) -> Result<(), E>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
let value = tri!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.elements.push(value);
|
||||
Ok(())
|
||||
}
|
||||
@@ -808,11 +800,11 @@ mod content {
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
|
||||
fn serialize_element<T>(&mut self, value: &T) -> Result<(), E>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
let value = tri!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.elements.push(value);
|
||||
Ok(())
|
||||
}
|
||||
@@ -835,11 +827,11 @@ mod content {
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
|
||||
fn serialize_field<T>(&mut self, value: &T) -> Result<(), E>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
let value = tri!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.fields.push(value);
|
||||
Ok(())
|
||||
}
|
||||
@@ -864,11 +856,11 @@ mod content {
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
|
||||
fn serialize_field<T>(&mut self, value: &T) -> Result<(), E>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
let value = tri!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.fields.push(value);
|
||||
Ok(())
|
||||
}
|
||||
@@ -896,24 +888,24 @@ mod content {
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), E>
|
||||
fn serialize_key<T>(&mut self, key: &T) -> Result<(), E>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let key = try!(key.serialize(ContentSerializer::<E>::new()));
|
||||
let key = tri!(key.serialize(ContentSerializer::<E>::new()));
|
||||
self.key = Some(key);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
|
||||
fn serialize_value<T>(&mut self, value: &T) -> Result<(), E>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let key = self
|
||||
.key
|
||||
.take()
|
||||
.expect("serialize_value called before serialize_key");
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
let value = tri!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.entries.push((key, value));
|
||||
Ok(())
|
||||
}
|
||||
@@ -922,13 +914,13 @@ mod content {
|
||||
Ok(Content::Map(self.entries))
|
||||
}
|
||||
|
||||
fn serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<(), E>
|
||||
fn serialize_entry<K, V>(&mut self, key: &K, value: &V) -> Result<(), E>
|
||||
where
|
||||
K: Serialize,
|
||||
V: Serialize,
|
||||
K: ?Sized + Serialize,
|
||||
V: ?Sized + Serialize,
|
||||
{
|
||||
let key = try!(key.serialize(ContentSerializer::<E>::new()));
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
let key = tri!(key.serialize(ContentSerializer::<E>::new()));
|
||||
let value = tri!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.entries.push((key, value));
|
||||
Ok(())
|
||||
}
|
||||
@@ -947,11 +939,11 @@ mod content {
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E>
|
||||
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), E>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
let value = tri!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.fields.push((key, value));
|
||||
Ok(())
|
||||
}
|
||||
@@ -976,11 +968,11 @@ mod content {
|
||||
type Ok = Content;
|
||||
type Error = E;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E>
|
||||
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), E>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let value = try!(value.serialize(ContentSerializer::<E>::new()));
|
||||
let value = tri!(value.serialize(ContentSerializer::<E>::new()));
|
||||
self.fields.push((key, value));
|
||||
Ok(())
|
||||
}
|
||||
@@ -1025,7 +1017,7 @@ where
|
||||
type SerializeTupleStruct = Impossible<Self::Ok, M::Error>;
|
||||
type SerializeMap = FlatMapSerializeMap<'a, M>;
|
||||
type SerializeStruct = FlatMapSerializeStruct<'a, M>;
|
||||
type SerializeTupleVariant = Impossible<Self::Ok, M::Error>;
|
||||
type SerializeTupleVariant = FlatMapSerializeTupleVariantAsMapValue<'a, M>;
|
||||
type SerializeStructVariant = FlatMapSerializeStructVariantAsMapValue<'a, M>;
|
||||
|
||||
fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
|
||||
@@ -1088,9 +1080,9 @@ where
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
|
||||
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
value.serialize(self)
|
||||
}
|
||||
@@ -1112,18 +1104,18 @@ where
|
||||
Err(Self::bad_type(Unsupported::Enum))
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized>(
|
||||
fn serialize_newtype_struct<T>(
|
||||
self,
|
||||
_: &'static str,
|
||||
value: &T,
|
||||
) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: ?Sized>(
|
||||
fn serialize_newtype_variant<T>(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: u32,
|
||||
@@ -1131,9 +1123,9 @@ where
|
||||
value: &T,
|
||||
) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
try!(self.0.serialize_key(variant));
|
||||
tri!(self.0.serialize_key(variant));
|
||||
self.0.serialize_value(value)
|
||||
}
|
||||
|
||||
@@ -1157,10 +1149,11 @@ where
|
||||
self,
|
||||
_: &'static str,
|
||||
_: u32,
|
||||
_: &'static str,
|
||||
variant: &'static str,
|
||||
_: usize,
|
||||
) -> Result<Self::SerializeTupleVariant, Self::Error> {
|
||||
Err(Self::bad_type(Unsupported::Enum))
|
||||
tri!(self.0.serialize_key(variant));
|
||||
Ok(FlatMapSerializeTupleVariantAsMapValue::new(self.0))
|
||||
}
|
||||
|
||||
fn serialize_map(self, _: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
|
||||
@@ -1182,7 +1175,7 @@ where
|
||||
inner_variant: &'static str,
|
||||
_: usize,
|
||||
) -> Result<Self::SerializeStructVariant, Self::Error> {
|
||||
try!(self.0.serialize_key(inner_variant));
|
||||
tri!(self.0.serialize_key(inner_variant));
|
||||
Ok(FlatMapSerializeStructVariantAsMapValue::new(
|
||||
self.0,
|
||||
inner_variant,
|
||||
@@ -1201,28 +1194,24 @@ where
|
||||
type Ok = ();
|
||||
type Error = M::Error;
|
||||
|
||||
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
|
||||
fn serialize_key<T>(&mut self, key: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
self.0.serialize_key(key)
|
||||
}
|
||||
|
||||
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
self.0.serialize_value(value)
|
||||
}
|
||||
|
||||
fn serialize_entry<K: ?Sized, V: ?Sized>(
|
||||
&mut self,
|
||||
key: &K,
|
||||
value: &V,
|
||||
) -> Result<(), Self::Error>
|
||||
fn serialize_entry<K, V>(&mut self, key: &K, value: &V) -> Result<(), Self::Error>
|
||||
where
|
||||
K: Serialize,
|
||||
V: Serialize,
|
||||
K: ?Sized + Serialize,
|
||||
V: ?Sized + Serialize,
|
||||
{
|
||||
self.0.serialize_entry(key, value)
|
||||
}
|
||||
@@ -1243,13 +1232,9 @@ where
|
||||
type Ok = ();
|
||||
type Error = M::Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(
|
||||
&mut self,
|
||||
key: &'static str,
|
||||
value: &T,
|
||||
) -> Result<(), Self::Error>
|
||||
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
self.0.serialize_entry(key, value)
|
||||
}
|
||||
@@ -1259,6 +1244,52 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub struct FlatMapSerializeTupleVariantAsMapValue<'a, M: 'a> {
|
||||
map: &'a mut M,
|
||||
fields: Vec<Content>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, M> FlatMapSerializeTupleVariantAsMapValue<'a, M>
|
||||
where
|
||||
M: SerializeMap + 'a,
|
||||
{
|
||||
fn new(map: &'a mut M) -> Self {
|
||||
FlatMapSerializeTupleVariantAsMapValue {
|
||||
map,
|
||||
fields: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
impl<'a, M> ser::SerializeTupleVariant for FlatMapSerializeTupleVariantAsMapValue<'a, M>
|
||||
where
|
||||
M: SerializeMap + 'a,
|
||||
{
|
||||
type Ok = ();
|
||||
type Error = M::Error;
|
||||
|
||||
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let value = tri!(value.serialize(ContentSerializer::<M::Error>::new()));
|
||||
self.fields.push(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Self::Error> {
|
||||
tri!(self.map.serialize_value(&Content::Seq(self.fields)));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
pub struct FlatMapSerializeStructVariantAsMapValue<'a, M: 'a> {
|
||||
map: &'a mut M,
|
||||
@@ -1273,8 +1304,8 @@ where
|
||||
{
|
||||
fn new(map: &'a mut M, name: &'static str) -> FlatMapSerializeStructVariantAsMapValue<'a, M> {
|
||||
FlatMapSerializeStructVariantAsMapValue {
|
||||
map: map,
|
||||
name: name,
|
||||
map,
|
||||
name,
|
||||
fields: Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -1288,23 +1319,47 @@ where
|
||||
type Ok = ();
|
||||
type Error = M::Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(
|
||||
&mut self,
|
||||
key: &'static str,
|
||||
value: &T,
|
||||
) -> Result<(), Self::Error>
|
||||
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let value = try!(value.serialize(ContentSerializer::<M::Error>::new()));
|
||||
let value = tri!(value.serialize(ContentSerializer::<M::Error>::new()));
|
||||
self.fields.push((key, value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Self::Error> {
|
||||
try!(self
|
||||
tri!(self
|
||||
.map
|
||||
.serialize_value(&Content::Struct(self.name, self.fields)));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AdjacentlyTaggedEnumVariant {
|
||||
pub enum_name: &'static str,
|
||||
pub variant_index: u32,
|
||||
pub variant_name: &'static str,
|
||||
}
|
||||
|
||||
impl Serialize for AdjacentlyTaggedEnumVariant {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_unit_variant(self.enum_name, self.variant_index, self.variant_name)
|
||||
}
|
||||
}
|
||||
|
||||
// Error when Serialize for a non_exhaustive remote enum encounters a variant
|
||||
// that is not recognized.
|
||||
pub struct CannotSerializeVariant<T>(pub T);
|
||||
|
||||
impl<T> Display for CannotSerializeVariant<T>
|
||||
where
|
||||
T: Debug,
|
||||
{
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "enum variant cannot be serialized: {:?}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
+15
-19
@@ -1,5 +1,5 @@
|
||||
use lib::*;
|
||||
use ser::{Error, Impossible, Serialize, Serializer};
|
||||
use crate::lib::*;
|
||||
use crate::ser::{Error, Impossible, Serialize, Serializer};
|
||||
|
||||
impl Error for fmt::Error {
|
||||
fn custom<T: Display>(_msg: T) -> Self {
|
||||
@@ -17,8 +17,9 @@ macro_rules! fmt_primitives {
|
||||
};
|
||||
}
|
||||
|
||||
/// ```edition2018
|
||||
/// use serde::Serialize;
|
||||
/// ```edition2021
|
||||
/// use serde::ser::Serialize;
|
||||
/// use serde_derive::Serialize;
|
||||
/// use std::fmt::{self, Display};
|
||||
///
|
||||
/// #[derive(Serialize)]
|
||||
@@ -51,10 +52,12 @@ impl<'a, 'b> Serializer for &'a mut fmt::Formatter<'b> {
|
||||
serialize_i16: i16,
|
||||
serialize_i32: i32,
|
||||
serialize_i64: i64,
|
||||
serialize_i128: i128,
|
||||
serialize_u8: u8,
|
||||
serialize_u16: u16,
|
||||
serialize_u32: u32,
|
||||
serialize_u64: u64,
|
||||
serialize_u128: u128,
|
||||
serialize_f32: f32,
|
||||
serialize_f64: f64,
|
||||
serialize_char: char,
|
||||
@@ -62,13 +65,6 @@ impl<'a, 'b> Serializer for &'a mut fmt::Formatter<'b> {
|
||||
serialize_unit_struct: &'static str,
|
||||
}
|
||||
|
||||
serde_if_integer128! {
|
||||
fmt_primitives! {
|
||||
serialize_i128: i128,
|
||||
serialize_u128: u128,
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(
|
||||
self,
|
||||
_name: &'static str,
|
||||
@@ -78,9 +74,9 @@ impl<'a, 'b> Serializer for &'a mut fmt::Formatter<'b> {
|
||||
Display::fmt(variant, self)
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> fmt::Result
|
||||
fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> fmt::Result
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
Serialize::serialize(value, self)
|
||||
}
|
||||
@@ -93,9 +89,9 @@ impl<'a, 'b> Serializer for &'a mut fmt::Formatter<'b> {
|
||||
Err(fmt::Error)
|
||||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, _value: &T) -> fmt::Result
|
||||
fn serialize_some<T>(self, _value: &T) -> fmt::Result
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
Err(fmt::Error)
|
||||
}
|
||||
@@ -104,7 +100,7 @@ impl<'a, 'b> Serializer for &'a mut fmt::Formatter<'b> {
|
||||
Err(fmt::Error)
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: ?Sized>(
|
||||
fn serialize_newtype_variant<T>(
|
||||
self,
|
||||
_name: &'static str,
|
||||
_variant_index: u32,
|
||||
@@ -112,7 +108,7 @@ impl<'a, 'b> Serializer for &'a mut fmt::Formatter<'b> {
|
||||
_value: &T,
|
||||
) -> fmt::Result
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
Err(fmt::Error)
|
||||
}
|
||||
@@ -165,9 +161,9 @@ impl<'a, 'b> Serializer for &'a mut fmt::Formatter<'b> {
|
||||
Err(fmt::Error)
|
||||
}
|
||||
|
||||
fn collect_str<T: ?Sized>(self, value: &T) -> fmt::Result
|
||||
fn collect_str<T>(self, value: &T) -> fmt::Result
|
||||
where
|
||||
T: Display,
|
||||
T: ?Sized + Display,
|
||||
{
|
||||
Display::fmt(value, self)
|
||||
}
|
||||
|
||||
+230
-101
@@ -1,6 +1,6 @@
|
||||
use lib::*;
|
||||
use crate::lib::*;
|
||||
|
||||
use ser::{Error, Serialize, SerializeTuple, Serializer};
|
||||
use crate::ser::{Error, Serialize, SerializeTuple, Serializer};
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -24,20 +24,17 @@ primitive_impl!(i8, serialize_i8);
|
||||
primitive_impl!(i16, serialize_i16);
|
||||
primitive_impl!(i32, serialize_i32);
|
||||
primitive_impl!(i64, serialize_i64);
|
||||
primitive_impl!(i128, serialize_i128);
|
||||
primitive_impl!(usize, serialize_u64 as u64);
|
||||
primitive_impl!(u8, serialize_u8);
|
||||
primitive_impl!(u16, serialize_u16);
|
||||
primitive_impl!(u32, serialize_u32);
|
||||
primitive_impl!(u64, serialize_u64);
|
||||
primitive_impl!(u128, serialize_u128);
|
||||
primitive_impl!(f32, serialize_f32);
|
||||
primitive_impl!(f64, serialize_f64);
|
||||
primitive_impl!(char, serialize_char);
|
||||
|
||||
serde_if_integer128! {
|
||||
primitive_impl!(i128, serialize_i128);
|
||||
primitive_impl!(u128, serialize_u128);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl Serialize for str {
|
||||
@@ -51,6 +48,7 @@ impl Serialize for str {
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
impl Serialize for String {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
@@ -73,6 +71,7 @@ impl<'a> Serialize for fmt::Arguments<'a> {
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", not(no_core_cstr)))]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl Serialize for CStr {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
@@ -84,6 +83,7 @@ impl Serialize for CStr {
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
impl Serialize for CString {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
@@ -114,7 +114,10 @@ where
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<T: ?Sized> Serialize for PhantomData<T> {
|
||||
impl<T> Serialize for PhantomData<T>
|
||||
where
|
||||
T: ?Sized,
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -133,7 +136,7 @@ impl<T> Serialize for [T; 0] {
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
try!(serializer.serialize_tuple(0)).end()
|
||||
tri!(serializer.serialize_tuple(0)).end()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,9 +152,9 @@ macro_rules! array_impls {
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let mut seq = try!(serializer.serialize_tuple($len));
|
||||
let mut seq = tri!(serializer.serialize_tuple($len));
|
||||
for e in self {
|
||||
try!(seq.serialize_element(e));
|
||||
tri!(seq.serialize_element(e));
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
@@ -182,9 +185,13 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(any(feature = "std", feature = "alloc"), not(no_relaxed_trait_bounds)))]
|
||||
#[cfg(not(no_relaxed_trait_bounds))]
|
||||
macro_rules! seq_impl {
|
||||
($ty:ident <T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound:ident)*>) => {
|
||||
(
|
||||
$(#[$attr:meta])*
|
||||
$ty:ident <T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound:ident)*>
|
||||
) => {
|
||||
$(#[$attr])*
|
||||
impl<T $(, $typaram)*> Serialize for $ty<T $(, $typaram)*>
|
||||
where
|
||||
T: Serialize,
|
||||
@@ -200,9 +207,13 @@ macro_rules! seq_impl {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(any(feature = "std", feature = "alloc"), no_relaxed_trait_bounds))]
|
||||
#[cfg(no_relaxed_trait_bounds)]
|
||||
macro_rules! seq_impl {
|
||||
($ty:ident <T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound:ident)*>) => {
|
||||
(
|
||||
$(#[$attr:meta])*
|
||||
$ty:ident <T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound:ident)*>
|
||||
) => {
|
||||
$(#[$attr])*
|
||||
impl<T $(, $typaram)*> Serialize for $ty<T $(, $typaram)*>
|
||||
where
|
||||
T: Serialize $(+ $tbound1 $(+ $tbound2)*)*,
|
||||
@@ -219,23 +230,41 @@ macro_rules! seq_impl {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(BinaryHeap<T: Ord>);
|
||||
seq_impl! {
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
BinaryHeap<T: Ord>
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(BTreeSet<T: Ord>);
|
||||
seq_impl! {
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
BTreeSet<T: Ord>
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
seq_impl!(HashSet<T: Eq + Hash, H: BuildHasher>);
|
||||
seq_impl! {
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
HashSet<T: Eq + Hash, H: BuildHasher>
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(LinkedList<T>);
|
||||
seq_impl! {
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
LinkedList<T>
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(Vec<T>);
|
||||
seq_impl! {
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
Vec<T>
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
seq_impl!(VecDeque<T>);
|
||||
seq_impl! {
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
VecDeque<T>
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -248,16 +277,32 @@ where
|
||||
S: Serializer,
|
||||
{
|
||||
use super::SerializeStruct;
|
||||
let mut state = try!(serializer.serialize_struct("Range", 2));
|
||||
try!(state.serialize_field("start", &self.start));
|
||||
try!(state.serialize_field("end", &self.end));
|
||||
let mut state = tri!(serializer.serialize_struct("Range", 2));
|
||||
tri!(state.serialize_field("start", &self.start));
|
||||
tri!(state.serialize_field("end", &self.end));
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<Idx> Serialize for RangeFrom<Idx>
|
||||
where
|
||||
Idx: Serialize,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
use super::SerializeStruct;
|
||||
let mut state = tri!(serializer.serialize_struct("RangeFrom", 1));
|
||||
tri!(state.serialize_field("start", &self.start));
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(not(no_range_inclusive))]
|
||||
impl<Idx> Serialize for RangeInclusive<Idx>
|
||||
where
|
||||
Idx: Serialize,
|
||||
@@ -267,16 +312,32 @@ where
|
||||
S: Serializer,
|
||||
{
|
||||
use super::SerializeStruct;
|
||||
let mut state = try!(serializer.serialize_struct("RangeInclusive", 2));
|
||||
try!(state.serialize_field("start", &self.start()));
|
||||
try!(state.serialize_field("end", &self.end()));
|
||||
let mut state = tri!(serializer.serialize_struct("RangeInclusive", 2));
|
||||
tri!(state.serialize_field("start", &self.start()));
|
||||
tri!(state.serialize_field("end", &self.end()));
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<Idx> Serialize for RangeTo<Idx>
|
||||
where
|
||||
Idx: Serialize,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
use super::SerializeStruct;
|
||||
let mut state = tri!(serializer.serialize_struct("RangeTo", 1));
|
||||
tri!(state.serialize_field("end", &self.end));
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(not(no_ops_bound), all(feature = "std", not(no_collections_bound))))]
|
||||
impl<T> Serialize for Bound<T>
|
||||
where
|
||||
T: Serialize,
|
||||
@@ -310,6 +371,7 @@ impl Serialize for () {
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
|
||||
impl Serialize for ! {
|
||||
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -324,28 +386,46 @@ impl Serialize for ! {
|
||||
macro_rules! tuple_impls {
|
||||
($($len:expr => ($($n:tt $name:ident)+))+) => {
|
||||
$(
|
||||
#[cfg_attr(docsrs, doc(hidden))]
|
||||
impl<$($name),+> Serialize for ($($name,)+)
|
||||
where
|
||||
$($name: Serialize,)+
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let mut tuple = try!(serializer.serialize_tuple($len));
|
||||
$(
|
||||
try!(tuple.serialize_element(&self.$n));
|
||||
)+
|
||||
tuple.end()
|
||||
}
|
||||
tuple_impl_body!($len => ($($n)+));
|
||||
}
|
||||
)+
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! tuple_impl_body {
|
||||
($len:expr => ($($n:tt)+)) => {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let mut tuple = tri!(serializer.serialize_tuple($len));
|
||||
$(
|
||||
tri!(tuple.serialize_element(&self.$n));
|
||||
)+
|
||||
tuple.end()
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg_attr(docsrs, doc(fake_variadic))]
|
||||
#[cfg_attr(
|
||||
docsrs,
|
||||
doc = "This trait is implemented for tuples up to 16 items long."
|
||||
)]
|
||||
impl<T> Serialize for (T,)
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
tuple_impl_body!(1 => (0));
|
||||
}
|
||||
|
||||
tuple_impls! {
|
||||
1 => (0 T0)
|
||||
2 => (0 T0 1 T1)
|
||||
3 => (0 T0 1 T1 2 T2)
|
||||
4 => (0 T0 1 T1 2 T2 3 T3)
|
||||
@@ -365,9 +445,13 @@ tuple_impls! {
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(all(any(feature = "std", feature = "alloc"), not(no_relaxed_trait_bounds)))]
|
||||
#[cfg(not(no_relaxed_trait_bounds))]
|
||||
macro_rules! map_impl {
|
||||
($ty:ident <K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound:ident)*>) => {
|
||||
(
|
||||
$(#[$attr:meta])*
|
||||
$ty:ident <K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound:ident)*>
|
||||
) => {
|
||||
$(#[$attr])*
|
||||
impl<K, V $(, $typaram)*> Serialize for $ty<K, V $(, $typaram)*>
|
||||
where
|
||||
K: Serialize,
|
||||
@@ -384,9 +468,13 @@ macro_rules! map_impl {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(any(feature = "std", feature = "alloc"), no_relaxed_trait_bounds))]
|
||||
#[cfg(no_relaxed_trait_bounds)]
|
||||
macro_rules! map_impl {
|
||||
($ty:ident <K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound:ident)*>) => {
|
||||
(
|
||||
$(#[$attr:meta])*
|
||||
$ty:ident <K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound:ident)*>
|
||||
) => {
|
||||
$(#[$attr])*
|
||||
impl<K, V $(, $typaram)*> Serialize for $ty<K, V $(, $typaram)*>
|
||||
where
|
||||
K: Serialize $(+ $kbound1 $(+ $kbound2)*)*,
|
||||
@@ -404,20 +492,26 @@ macro_rules! map_impl {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
map_impl!(BTreeMap<K: Ord, V>);
|
||||
map_impl! {
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
BTreeMap<K: Ord, V>
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
map_impl!(HashMap<K: Eq + Hash, V, H: BuildHasher>);
|
||||
map_impl! {
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
HashMap<K: Eq + Hash, V, H: BuildHasher>
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
macro_rules! deref_impl {
|
||||
(
|
||||
$(#[doc = $doc:tt])*
|
||||
$(#[$attr:meta])*
|
||||
<$($desc:tt)+
|
||||
) => {
|
||||
$(#[doc = $doc])*
|
||||
$(#[$attr])*
|
||||
impl <$($desc)+ {
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
@@ -430,13 +524,20 @@ macro_rules! deref_impl {
|
||||
};
|
||||
}
|
||||
|
||||
deref_impl!(<'a, T: ?Sized> Serialize for &'a T where T: Serialize);
|
||||
deref_impl!(<'a, T: ?Sized> Serialize for &'a mut T where T: Serialize);
|
||||
deref_impl! {
|
||||
<'a, T> Serialize for &'a T where T: ?Sized + Serialize
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
deref_impl!(<T: ?Sized> Serialize for Box<T> where T: Serialize);
|
||||
deref_impl! {
|
||||
<'a, T> Serialize for &'a mut T where T: ?Sized + Serialize
|
||||
}
|
||||
|
||||
deref_impl! {
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
<T> Serialize for Box<T> where T: ?Sized + Serialize
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
deref_impl! {
|
||||
/// This impl requires the [`"rc"`] Cargo feature of Serde.
|
||||
///
|
||||
@@ -446,10 +547,11 @@ deref_impl! {
|
||||
/// repeated data.
|
||||
///
|
||||
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
|
||||
<T: ?Sized> Serialize for Rc<T> where T: Serialize
|
||||
#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))]
|
||||
<T> Serialize for Rc<T> where T: ?Sized + Serialize
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
deref_impl! {
|
||||
/// This impl requires the [`"rc"`] Cargo feature of Serde.
|
||||
///
|
||||
@@ -459,11 +561,16 @@ deref_impl! {
|
||||
/// repeated data.
|
||||
///
|
||||
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
|
||||
<T: ?Sized> Serialize for Arc<T> where T: Serialize
|
||||
#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))]
|
||||
<T> Serialize for Arc<T> where T: ?Sized + Serialize
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
deref_impl!(<'a, T: ?Sized> Serialize for Cow<'a, T> where T: Serialize + ToOwned);
|
||||
deref_impl! {
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
|
||||
<'a, T> Serialize for Cow<'a, T> where T: ?Sized + Serialize + ToOwned
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -471,9 +578,13 @@ deref_impl!(<'a, T: ?Sized> Serialize for Cow<'a, T> where T: Serialize + ToOwne
|
||||
///
|
||||
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
|
||||
#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
impl<T: ?Sized> Serialize for RcWeak<T>
|
||||
#[cfg_attr(
|
||||
docsrs,
|
||||
doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc"))))
|
||||
)]
|
||||
impl<T> Serialize for RcWeak<T>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -487,9 +598,13 @@ where
|
||||
///
|
||||
/// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
|
||||
#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
|
||||
impl<T: ?Sized> Serialize for ArcWeak<T>
|
||||
#[cfg_attr(
|
||||
docsrs,
|
||||
doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc"))))
|
||||
)]
|
||||
impl<T> Serialize for ArcWeak<T>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -504,7 +619,6 @@ where
|
||||
macro_rules! nonzero_integers {
|
||||
($($T:ident,)+) => {
|
||||
$(
|
||||
#[cfg(not(no_num_nonzero))]
|
||||
impl Serialize for num::$T {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -522,6 +636,7 @@ nonzero_integers! {
|
||||
NonZeroU16,
|
||||
NonZeroU32,
|
||||
NonZeroU64,
|
||||
NonZeroU128,
|
||||
NonZeroUsize,
|
||||
}
|
||||
|
||||
@@ -531,22 +646,10 @@ nonzero_integers! {
|
||||
NonZeroI16,
|
||||
NonZeroI32,
|
||||
NonZeroI64,
|
||||
NonZeroI128,
|
||||
NonZeroIsize,
|
||||
}
|
||||
|
||||
// Currently 128-bit integers do not work on Emscripten targets so we need an
|
||||
// additional `#[cfg]`
|
||||
serde_if_integer128! {
|
||||
nonzero_integers! {
|
||||
NonZeroU128,
|
||||
}
|
||||
|
||||
#[cfg(not(no_num_nonzero_signed))]
|
||||
nonzero_integers! {
|
||||
NonZeroI128,
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Serialize for Cell<T>
|
||||
where
|
||||
T: Serialize + Copy,
|
||||
@@ -559,9 +662,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ?Sized> Serialize for RefCell<T>
|
||||
impl<T> Serialize for RefCell<T>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -575,9 +678,10 @@ where
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T: ?Sized> Serialize for Mutex<T>
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl<T> Serialize for Mutex<T>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -591,9 +695,10 @@ where
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T: ?Sized> Serialize for RwLock<T>
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl<T> Serialize for RwLock<T>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -628,16 +733,15 @@ where
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(any(feature = "std", not(no_core_duration)))]
|
||||
impl Serialize for Duration {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
use super::SerializeStruct;
|
||||
let mut state = try!(serializer.serialize_struct("Duration", 2));
|
||||
try!(state.serialize_field("secs", &self.as_secs()));
|
||||
try!(state.serialize_field("nanos", &self.subsec_nanos()));
|
||||
let mut state = tri!(serializer.serialize_struct("Duration", 2));
|
||||
tri!(state.serialize_field("secs", &self.as_secs()));
|
||||
tri!(state.serialize_field("nanos", &self.subsec_nanos()));
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
@@ -645,6 +749,7 @@ impl Serialize for Duration {
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl Serialize for SystemTime {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -655,9 +760,9 @@ impl Serialize for SystemTime {
|
||||
Ok(duration_since_epoch) => duration_since_epoch,
|
||||
Err(_) => return Err(S::Error::custom("SystemTime must be later than UNIX_EPOCH")),
|
||||
};
|
||||
let mut state = try!(serializer.serialize_struct("SystemTime", 2));
|
||||
try!(state.serialize_field("secs_since_epoch", &duration_since_epoch.as_secs()));
|
||||
try!(state.serialize_field("nanos_since_epoch", &duration_since_epoch.subsec_nanos()));
|
||||
let mut state = tri!(serializer.serialize_struct("SystemTime", 2));
|
||||
tri!(state.serialize_field("secs_since_epoch", &duration_since_epoch.as_secs()));
|
||||
tri!(state.serialize_field("nanos_since_epoch", &duration_since_epoch.subsec_nanos()));
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
@@ -689,6 +794,7 @@ macro_rules! serialize_display_bounded_length {
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl Serialize for net::IpAddr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -713,7 +819,7 @@ impl Serialize for net::IpAddr {
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
const DEC_DIGITS_LUT: &'static [u8] = b"\
|
||||
const DEC_DIGITS_LUT: &[u8] = b"\
|
||||
0001020304050607080910111213141516171819\
|
||||
2021222324252627282930313233343536373839\
|
||||
4041424344454647484950515253545556575859\
|
||||
@@ -759,6 +865,7 @@ fn test_format_u8() {
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl Serialize for net::Ipv4Addr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -783,6 +890,7 @@ impl Serialize for net::Ipv4Addr {
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl Serialize for net::Ipv6Addr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -799,6 +907,7 @@ impl Serialize for net::Ipv6Addr {
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl Serialize for net::SocketAddr {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -823,6 +932,7 @@ impl Serialize for net::SocketAddr {
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl Serialize for net::SocketAddrV4 {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -839,6 +949,7 @@ impl Serialize for net::SocketAddrV4 {
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl Serialize for net::SocketAddrV6 {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -860,6 +971,7 @@ impl Serialize for net::SocketAddrV6 {
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl Serialize for Path {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -873,6 +985,7 @@ impl Serialize for Path {
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
||||
impl Serialize for PathBuf {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -883,6 +996,7 @@ impl Serialize for PathBuf {
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "std", any(unix, windows)))]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))]
|
||||
impl Serialize for OsStr {
|
||||
#[cfg(unix)]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
@@ -905,6 +1019,7 @@ impl Serialize for OsStr {
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "std", any(unix, windows)))]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", any(unix, windows)))))]
|
||||
impl Serialize for OsString {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -929,7 +1044,20 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(no_core_reverse))]
|
||||
#[cfg(not(no_core_num_saturating))]
|
||||
impl<T> Serialize for Saturating<T>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
self.0.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Serialize for Reverse<T>
|
||||
where
|
||||
T: Serialize,
|
||||
@@ -950,6 +1078,7 @@ macro_rules! atomic_impl {
|
||||
($($ty:ident $size:expr)*) => {
|
||||
$(
|
||||
#[cfg(any(no_target_has_atomic, target_has_atomic = $size))]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", target_has_atomic = $size))))]
|
||||
impl Serialize for $ty {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
|
||||
+19
-19
@@ -1,8 +1,8 @@
|
||||
//! This module contains `Impossible` serializer and its implementations.
|
||||
|
||||
use lib::*;
|
||||
use crate::lib::*;
|
||||
|
||||
use ser::{
|
||||
use crate::ser::{
|
||||
self, Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant,
|
||||
SerializeTuple, SerializeTupleStruct, SerializeTupleVariant,
|
||||
};
|
||||
@@ -15,7 +15,7 @@ use ser::{
|
||||
/// [`SerializeTuple`], [`SerializeTupleStruct`], [`SerializeTupleVariant`],
|
||||
/// [`SerializeMap`], [`SerializeStruct`], and [`SerializeStructVariant`].
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::ser::{Serializer, Impossible};
|
||||
/// # use serde::__private::doc::Error;
|
||||
/// #
|
||||
@@ -72,9 +72,9 @@ where
|
||||
type Ok = Ok;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let _ = value;
|
||||
match self.void {}
|
||||
@@ -92,9 +92,9 @@ where
|
||||
type Ok = Ok;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let _ = value;
|
||||
match self.void {}
|
||||
@@ -112,9 +112,9 @@ where
|
||||
type Ok = Ok;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let _ = value;
|
||||
match self.void {}
|
||||
@@ -132,9 +132,9 @@ where
|
||||
type Ok = Ok;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let _ = value;
|
||||
match self.void {}
|
||||
@@ -152,17 +152,17 @@ where
|
||||
type Ok = Ok;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Error>
|
||||
fn serialize_key<T>(&mut self, key: &T) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let _ = key;
|
||||
match self.void {}
|
||||
}
|
||||
|
||||
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||
fn serialize_value<T>(&mut self, value: &T) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let _ = value;
|
||||
match self.void {}
|
||||
@@ -180,9 +180,9 @@ where
|
||||
type Ok = Ok;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
|
||||
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let _ = key;
|
||||
let _ = value;
|
||||
@@ -201,9 +201,9 @@ where
|
||||
type Ok = Ok;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
|
||||
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
T: ?Sized + Serialize,
|
||||
{
|
||||
let _ = key;
|
||||
let _ = value;
|
||||
|
||||
+158
-192
@@ -61,8 +61,8 @@
|
||||
//! - RefCell\<T\>
|
||||
//! - Mutex\<T\>
|
||||
//! - RwLock\<T\>
|
||||
//! - Rc\<T\> *(if* features = ["rc"] *is enabled)*
|
||||
//! - Arc\<T\> *(if* features = ["rc"] *is enabled)*
|
||||
//! - Rc\<T\> *(if* features = \["rc"\] *is enabled)*
|
||||
//! - Arc\<T\> *(if* features = \["rc"\] *is enabled)*
|
||||
//! - **Collection types**:
|
||||
//! - BTreeMap\<K, V\>
|
||||
//! - BTreeSet\<T\>
|
||||
@@ -107,7 +107,7 @@
|
||||
//! [derive section of the manual]: https://serde.rs/derive.html
|
||||
//! [data formats]: https://serde.rs/#data-formats
|
||||
|
||||
use lib::*;
|
||||
use crate::lib::*;
|
||||
|
||||
mod fmt;
|
||||
mod impls;
|
||||
@@ -115,15 +115,15 @@ mod impossible;
|
||||
|
||||
pub use self::impossible::Impossible;
|
||||
|
||||
#[cfg(not(any(feature = "std", feature = "unstable")))]
|
||||
#[doc(no_inline)]
|
||||
pub use crate::std_error::Error as StdError;
|
||||
#[cfg(all(feature = "unstable", not(feature = "std")))]
|
||||
#[doc(inline)]
|
||||
#[doc(no_inline)]
|
||||
pub use core::error::Error as StdError;
|
||||
#[cfg(feature = "std")]
|
||||
#[doc(no_inline)]
|
||||
pub use std::error::Error as StdError;
|
||||
#[cfg(not(any(feature = "std", feature = "unstable")))]
|
||||
#[doc(no_inline)]
|
||||
pub use std_error::Error as StdError;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -149,7 +149,7 @@ macro_rules! declare_error_trait {
|
||||
/// For example, a filesystem [`Path`] may refuse to serialize
|
||||
/// itself if it contains invalid UTF-8 data.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # struct Path;
|
||||
/// #
|
||||
/// # impl Path {
|
||||
@@ -215,13 +215,20 @@ declare_error_trait!(Error: Sized + Debug + Display);
|
||||
/// [`linked-hash-map`]: https://crates.io/crates/linked-hash-map
|
||||
/// [`serde_derive`]: https://crates.io/crates/serde_derive
|
||||
/// [derive section of the manual]: https://serde.rs/derive.html
|
||||
#[cfg_attr(
|
||||
not(no_diagnostic_namespace),
|
||||
diagnostic::on_unimplemented(
|
||||
note = "for local types consider adding `#[derive(serde::Serialize)]` to your `{Self}` type",
|
||||
note = "for types from other crates check whether the crate offers a `serde` feature flag",
|
||||
)
|
||||
)]
|
||||
pub trait Serialize {
|
||||
/// Serialize this value into the given Serde serializer.
|
||||
///
|
||||
/// See the [Implementing `Serialize`] section of the manual for more
|
||||
/// information about how to implement this method.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::ser::{Serialize, SerializeStruct, Serializer};
|
||||
///
|
||||
/// struct Person {
|
||||
@@ -388,7 +395,7 @@ pub trait Serializer: Sized {
|
||||
|
||||
/// Serialize a `bool` value.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
@@ -410,7 +417,7 @@ pub trait Serializer: Sized {
|
||||
/// reasonable implementation would be to cast the value to `i64` and
|
||||
/// forward to `serialize_i64`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
@@ -432,7 +439,7 @@ pub trait Serializer: Sized {
|
||||
/// reasonable implementation would be to cast the value to `i64` and
|
||||
/// forward to `serialize_i64`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
@@ -454,7 +461,7 @@ pub trait Serializer: Sized {
|
||||
/// reasonable implementation would be to cast the value to `i64` and
|
||||
/// forward to `serialize_i64`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
@@ -472,7 +479,7 @@ pub trait Serializer: Sized {
|
||||
|
||||
/// Serialize an `i64` value.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
@@ -488,30 +495,27 @@ pub trait Serializer: Sized {
|
||||
/// ```
|
||||
fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
serde_if_integer128! {
|
||||
/// Serialize an `i128` value.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
/// #
|
||||
/// impl Serialize for i128 {
|
||||
/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
/// where
|
||||
/// S: Serializer,
|
||||
/// {
|
||||
/// serializer.serialize_i128(*self)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This method is available only on Rust compiler versions >=1.26. The
|
||||
/// default behavior unconditionally returns an error.
|
||||
fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
|
||||
let _ = v;
|
||||
Err(Error::custom("i128 is not supported"))
|
||||
}
|
||||
/// Serialize an `i128` value.
|
||||
///
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
/// #
|
||||
/// impl Serialize for i128 {
|
||||
/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
/// where
|
||||
/// S: Serializer,
|
||||
/// {
|
||||
/// serializer.serialize_i128(*self)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The default behavior unconditionally returns an error.
|
||||
fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
|
||||
let _ = v;
|
||||
Err(Error::custom("i128 is not supported"))
|
||||
}
|
||||
|
||||
/// Serialize a `u8` value.
|
||||
@@ -520,7 +524,7 @@ pub trait Serializer: Sized {
|
||||
/// reasonable implementation would be to cast the value to `u64` and
|
||||
/// forward to `serialize_u64`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
@@ -542,7 +546,7 @@ pub trait Serializer: Sized {
|
||||
/// reasonable implementation would be to cast the value to `u64` and
|
||||
/// forward to `serialize_u64`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
@@ -564,7 +568,7 @@ pub trait Serializer: Sized {
|
||||
/// reasonable implementation would be to cast the value to `u64` and
|
||||
/// forward to `serialize_u64`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
@@ -582,7 +586,7 @@ pub trait Serializer: Sized {
|
||||
|
||||
/// Serialize a `u64` value.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
@@ -598,30 +602,27 @@ pub trait Serializer: Sized {
|
||||
/// ```
|
||||
fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>;
|
||||
|
||||
serde_if_integer128! {
|
||||
/// Serialize a `u128` value.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
/// #
|
||||
/// impl Serialize for u128 {
|
||||
/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
/// where
|
||||
/// S: Serializer,
|
||||
/// {
|
||||
/// serializer.serialize_u128(*self)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This method is available only on Rust compiler versions >=1.26. The
|
||||
/// default behavior unconditionally returns an error.
|
||||
fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
|
||||
let _ = v;
|
||||
Err(Error::custom("u128 is not supported"))
|
||||
}
|
||||
/// Serialize a `u128` value.
|
||||
///
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
/// #
|
||||
/// impl Serialize for u128 {
|
||||
/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
/// where
|
||||
/// S: Serializer,
|
||||
/// {
|
||||
/// serializer.serialize_u128(*self)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The default behavior unconditionally returns an error.
|
||||
fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
|
||||
let _ = v;
|
||||
Err(Error::custom("u128 is not supported"))
|
||||
}
|
||||
|
||||
/// Serialize an `f32` value.
|
||||
@@ -630,7 +631,7 @@ pub trait Serializer: Sized {
|
||||
/// reasonable implementation would be to cast the value to `f64` and
|
||||
/// forward to `serialize_f64`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
@@ -648,7 +649,7 @@ pub trait Serializer: Sized {
|
||||
|
||||
/// Serialize an `f64` value.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
@@ -669,7 +670,7 @@ pub trait Serializer: Sized {
|
||||
/// If the format does not support characters, it is reasonable to serialize
|
||||
/// it as a single element `str` or a `u32`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
@@ -687,7 +688,7 @@ pub trait Serializer: Sized {
|
||||
|
||||
/// Serialize a `&str`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
@@ -711,7 +712,7 @@ pub trait Serializer: Sized {
|
||||
/// `serialize_seq`. If forwarded, the implementation looks usually just
|
||||
/// like this:
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::ser::{Serializer, SerializeSeq};
|
||||
/// # use serde::__private::doc::Error;
|
||||
/// #
|
||||
@@ -740,7 +741,7 @@ pub trait Serializer: Sized {
|
||||
|
||||
/// Serialize a [`None`] value.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::{Serialize, Serializer};
|
||||
/// #
|
||||
/// # enum Option<T> {
|
||||
@@ -773,7 +774,7 @@ pub trait Serializer: Sized {
|
||||
|
||||
/// Serialize a [`Some(T)`] value.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::{Serialize, Serializer};
|
||||
/// #
|
||||
/// # enum Option<T> {
|
||||
@@ -802,13 +803,13 @@ pub trait Serializer: Sized {
|
||||
/// ```
|
||||
///
|
||||
/// [`Some(T)`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.Some
|
||||
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
|
||||
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Serialize;
|
||||
T: ?Sized + Serialize;
|
||||
|
||||
/// Serialize a `()` value.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use serde::Serializer;
|
||||
/// #
|
||||
/// # serde::__private_serialize!();
|
||||
@@ -828,7 +829,7 @@ pub trait Serializer: Sized {
|
||||
///
|
||||
/// A reasonable implementation would be to forward to `serialize_unit`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::{Serialize, Serializer};
|
||||
///
|
||||
/// struct Nothing;
|
||||
@@ -850,7 +851,7 @@ pub trait Serializer: Sized {
|
||||
/// this variant within the enum, and the `variant` is the name of the
|
||||
/// variant.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::{Serialize, Serializer};
|
||||
///
|
||||
/// enum E {
|
||||
@@ -883,7 +884,7 @@ pub trait Serializer: Sized {
|
||||
/// wrappers around the data they contain. A reasonable implementation would
|
||||
/// be to forward to `value.serialize(self)`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::{Serialize, Serializer};
|
||||
///
|
||||
/// struct Millimeters(u8);
|
||||
@@ -897,13 +898,13 @@ pub trait Serializer: Sized {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn serialize_newtype_struct<T: ?Sized>(
|
||||
fn serialize_newtype_struct<T>(
|
||||
self,
|
||||
name: &'static str,
|
||||
value: &T,
|
||||
) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Serialize;
|
||||
T: ?Sized + Serialize;
|
||||
|
||||
/// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`.
|
||||
///
|
||||
@@ -911,7 +912,7 @@ pub trait Serializer: Sized {
|
||||
/// this variant within the enum, and the `variant` is the name of the
|
||||
/// variant. The `value` is the data contained within this newtype variant.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::{Serialize, Serializer};
|
||||
///
|
||||
/// enum E {
|
||||
@@ -931,7 +932,7 @@ pub trait Serializer: Sized {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn serialize_newtype_variant<T: ?Sized>(
|
||||
fn serialize_newtype_variant<T>(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: u32,
|
||||
@@ -939,7 +940,7 @@ pub trait Serializer: Sized {
|
||||
value: &T,
|
||||
) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Serialize;
|
||||
T: ?Sized + Serialize;
|
||||
|
||||
/// Begin to serialize a variably sized sequence. This call must be
|
||||
/// followed by zero or more calls to `serialize_element`, then a call to
|
||||
@@ -949,7 +950,7 @@ pub trait Serializer: Sized {
|
||||
/// not be computable before the sequence is iterated. Some serializers only
|
||||
/// support sequences whose length is known up front.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use std::marker::PhantomData;
|
||||
/// #
|
||||
/// # struct Vec<T>(PhantomData<T>);
|
||||
@@ -962,14 +963,14 @@ pub trait Serializer: Sized {
|
||||
/// #
|
||||
/// # impl<'a, T> IntoIterator for &'a Vec<T> {
|
||||
/// # type Item = &'a T;
|
||||
/// # type IntoIter = Box<Iterator<Item = &'a T>>;
|
||||
/// # type IntoIter = Box<dyn Iterator<Item = &'a T>>;
|
||||
/// #
|
||||
/// # fn into_iter(self) -> Self::IntoIter {
|
||||
/// # unimplemented!()
|
||||
/// # }
|
||||
/// # }
|
||||
/// #
|
||||
/// use serde::ser::{Serialize, Serializer, SerializeSeq};
|
||||
/// use serde::ser::{Serialize, SerializeSeq, Serializer};
|
||||
///
|
||||
/// impl<T> Serialize for Vec<T>
|
||||
/// where
|
||||
@@ -994,8 +995,8 @@ pub trait Serializer: Sized {
|
||||
/// This call must be followed by zero or more calls to `serialize_element`,
|
||||
/// then a call to `end`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// use serde::ser::{Serialize, Serializer, SerializeTuple};
|
||||
/// ```edition2021
|
||||
/// use serde::ser::{Serialize, SerializeTuple, Serializer};
|
||||
///
|
||||
/// # mod fool {
|
||||
/// # trait Serialize {}
|
||||
@@ -1024,7 +1025,7 @@ pub trait Serializer: Sized {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::ser::{Serialize, SerializeTuple, Serializer};
|
||||
///
|
||||
/// const VRAM_SIZE: usize = 386;
|
||||
@@ -1052,7 +1053,7 @@ pub trait Serializer: Sized {
|
||||
/// The `name` is the name of the tuple struct and the `len` is the number
|
||||
/// of data fields that will be serialized.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::ser::{Serialize, SerializeTupleStruct, Serializer};
|
||||
///
|
||||
/// struct Rgb(u8, u8, u8);
|
||||
@@ -1084,7 +1085,7 @@ pub trait Serializer: Sized {
|
||||
/// this variant within the enum, the `variant` is the name of the variant,
|
||||
/// and the `len` is the number of data fields that will be serialized.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::ser::{Serialize, SerializeTupleVariant, Serializer};
|
||||
///
|
||||
/// enum E {
|
||||
@@ -1130,7 +1131,7 @@ pub trait Serializer: Sized {
|
||||
/// be computable before the map is iterated. Some serializers only support
|
||||
/// maps whose length is known up front.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use std::marker::PhantomData;
|
||||
/// #
|
||||
/// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>);
|
||||
@@ -1143,14 +1144,14 @@ pub trait Serializer: Sized {
|
||||
/// #
|
||||
/// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> {
|
||||
/// # type Item = (&'a K, &'a V);
|
||||
/// # type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>;
|
||||
/// # type IntoIter = Box<dyn Iterator<Item = (&'a K, &'a V)>>;
|
||||
/// #
|
||||
/// # fn into_iter(self) -> Self::IntoIter {
|
||||
/// # unimplemented!()
|
||||
/// # }
|
||||
/// # }
|
||||
/// #
|
||||
/// use serde::ser::{Serialize, Serializer, SerializeMap};
|
||||
/// use serde::ser::{Serialize, SerializeMap, Serializer};
|
||||
///
|
||||
/// impl<K, V> Serialize for HashMap<K, V>
|
||||
/// where
|
||||
@@ -1176,9 +1177,10 @@ pub trait Serializer: Sized {
|
||||
/// then a call to `end`.
|
||||
///
|
||||
/// The `name` is the name of the struct and the `len` is the number of
|
||||
/// data fields that will be serialized.
|
||||
/// data fields that will be serialized. `len` does not include fields
|
||||
/// which are skipped with [`SerializeStruct::skip_field`].
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::ser::{Serialize, SerializeStruct, Serializer};
|
||||
///
|
||||
/// struct Rgb {
|
||||
@@ -1213,8 +1215,10 @@ pub trait Serializer: Sized {
|
||||
/// The `name` is the name of the enum, the `variant_index` is the index of
|
||||
/// this variant within the enum, the `variant` is the name of the variant,
|
||||
/// and the `len` is the number of data fields that will be serialized.
|
||||
/// `len` does not include fields which are skipped with
|
||||
/// [`SerializeStructVariant::skip_field`].
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::ser::{Serialize, SerializeStructVariant, Serializer};
|
||||
///
|
||||
/// enum E {
|
||||
@@ -1256,7 +1260,7 @@ pub trait Serializer: Sized {
|
||||
/// using [`serialize_seq`]. Implementors should not need to override this
|
||||
/// method.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::{Serialize, Serializer};
|
||||
///
|
||||
/// struct SecretlyOneHigher {
|
||||
@@ -1279,22 +1283,9 @@ pub trait Serializer: Sized {
|
||||
I: IntoIterator,
|
||||
<I as IntoIterator>::Item: Serialize,
|
||||
{
|
||||
let iter = iter.into_iter();
|
||||
let mut serializer = try!(self.serialize_seq(iterator_len_hint(&iter)));
|
||||
|
||||
#[cfg(not(no_iterator_try_fold))]
|
||||
{
|
||||
let mut iter = iter;
|
||||
try!(iter.try_for_each(|item| serializer.serialize_element(&item)));
|
||||
}
|
||||
|
||||
#[cfg(no_iterator_try_fold)]
|
||||
{
|
||||
for item in iter {
|
||||
try!(serializer.serialize_element(&item));
|
||||
}
|
||||
}
|
||||
|
||||
let mut iter = iter.into_iter();
|
||||
let mut serializer = tri!(self.serialize_seq(iterator_len_hint(&iter)));
|
||||
tri!(iter.try_for_each(|item| serializer.serialize_element(&item)));
|
||||
serializer.end()
|
||||
}
|
||||
|
||||
@@ -1304,7 +1295,7 @@ pub trait Serializer: Sized {
|
||||
/// using [`serialize_map`]. Implementors should not need to override this
|
||||
/// method.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::{Serialize, Serializer};
|
||||
/// use std::collections::BTreeSet;
|
||||
///
|
||||
@@ -1330,22 +1321,9 @@ pub trait Serializer: Sized {
|
||||
V: Serialize,
|
||||
I: IntoIterator<Item = (K, V)>,
|
||||
{
|
||||
let iter = iter.into_iter();
|
||||
let mut serializer = try!(self.serialize_map(iterator_len_hint(&iter)));
|
||||
|
||||
#[cfg(not(no_iterator_try_fold))]
|
||||
{
|
||||
let mut iter = iter;
|
||||
try!(iter.try_for_each(|(key, value)| serializer.serialize_entry(&key, &value)));
|
||||
}
|
||||
|
||||
#[cfg(no_iterator_try_fold)]
|
||||
{
|
||||
for (key, value) in iter {
|
||||
try!(serializer.serialize_entry(&key, &value));
|
||||
}
|
||||
}
|
||||
|
||||
let mut iter = iter.into_iter();
|
||||
let mut serializer = tri!(self.serialize_map(iterator_len_hint(&iter)));
|
||||
tri!(iter.try_for_each(|(key, value)| serializer.serialize_entry(&key, &value)));
|
||||
serializer.end()
|
||||
}
|
||||
|
||||
@@ -1355,7 +1333,7 @@ pub trait Serializer: Sized {
|
||||
/// delegates to [`serialize_str`]. Serializers are encouraged to provide a
|
||||
/// more efficient implementation if possible.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # struct DateTime;
|
||||
/// #
|
||||
/// # impl DateTime {
|
||||
@@ -1370,9 +1348,7 @@ pub trait Serializer: Sized {
|
||||
/// where
|
||||
/// S: Serializer,
|
||||
/// {
|
||||
/// serializer.collect_str(&format_args!("{:?}{:?}",
|
||||
/// self.naive_local(),
|
||||
/// self.offset()))
|
||||
/// serializer.collect_str(&format_args!("{:?}{:?}", self.naive_local(), self.offset()))
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
@@ -1380,9 +1356,9 @@ pub trait Serializer: Sized {
|
||||
/// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
|
||||
/// [`serialize_str`]: #tymethod.serialize_str
|
||||
#[cfg(any(feature = "std", feature = "alloc"))]
|
||||
fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
|
||||
fn collect_str<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Display,
|
||||
T: ?Sized + Display,
|
||||
{
|
||||
self.serialize_str(&value.to_string())
|
||||
}
|
||||
@@ -1393,7 +1369,7 @@ pub trait Serializer: Sized {
|
||||
/// of this method. If no more sensible behavior is possible, the
|
||||
/// implementation is expected to return an error.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # struct DateTime;
|
||||
/// #
|
||||
/// # impl DateTime {
|
||||
@@ -1408,16 +1384,14 @@ pub trait Serializer: Sized {
|
||||
/// where
|
||||
/// S: Serializer,
|
||||
/// {
|
||||
/// serializer.collect_str(&format_args!("{:?}{:?}",
|
||||
/// self.naive_local(),
|
||||
/// self.offset()))
|
||||
/// serializer.collect_str(&format_args!("{:?}{:?}", self.naive_local(), self.offset()))
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[cfg(not(any(feature = "std", feature = "alloc")))]
|
||||
fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
|
||||
fn collect_str<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
|
||||
where
|
||||
T: Display;
|
||||
T: ?Sized + Display;
|
||||
|
||||
/// Determine whether `Serialize` implementations should serialize in
|
||||
/// human-readable form.
|
||||
@@ -1428,7 +1402,7 @@ pub trait Serializer: Sized {
|
||||
/// human-readable one and binary formats like Postcard will prefer the
|
||||
/// compact one.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use std::fmt::{self, Display};
|
||||
/// #
|
||||
/// # struct Timestamp;
|
||||
@@ -1477,7 +1451,7 @@ pub trait Serializer: Sized {
|
||||
///
|
||||
/// # Example use
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use std::marker::PhantomData;
|
||||
/// #
|
||||
/// # struct Vec<T>(PhantomData<T>);
|
||||
@@ -1490,13 +1464,13 @@ pub trait Serializer: Sized {
|
||||
/// #
|
||||
/// # impl<'a, T> IntoIterator for &'a Vec<T> {
|
||||
/// # type Item = &'a T;
|
||||
/// # type IntoIter = Box<Iterator<Item = &'a T>>;
|
||||
/// # type IntoIter = Box<dyn Iterator<Item = &'a T>>;
|
||||
/// # fn into_iter(self) -> Self::IntoIter {
|
||||
/// # unimplemented!()
|
||||
/// # }
|
||||
/// # }
|
||||
/// #
|
||||
/// use serde::ser::{Serialize, Serializer, SerializeSeq};
|
||||
/// use serde::ser::{Serialize, SerializeSeq, Serializer};
|
||||
///
|
||||
/// impl<T> Serialize for Vec<T>
|
||||
/// where
|
||||
@@ -1529,9 +1503,9 @@ pub trait SerializeSeq {
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a sequence element.
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize;
|
||||
T: ?Sized + Serialize;
|
||||
|
||||
/// Finish serializing a sequence.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
@@ -1541,8 +1515,8 @@ pub trait SerializeSeq {
|
||||
///
|
||||
/// # Example use
|
||||
///
|
||||
/// ```edition2018
|
||||
/// use serde::ser::{Serialize, Serializer, SerializeTuple};
|
||||
/// ```edition2021
|
||||
/// use serde::ser::{Serialize, SerializeTuple, Serializer};
|
||||
///
|
||||
/// # mod fool {
|
||||
/// # trait Serialize {}
|
||||
@@ -1571,7 +1545,7 @@ pub trait SerializeSeq {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use std::marker::PhantomData;
|
||||
/// #
|
||||
/// # struct Array<T>(PhantomData<T>);
|
||||
@@ -1584,13 +1558,13 @@ pub trait SerializeSeq {
|
||||
/// #
|
||||
/// # impl<'a, T> IntoIterator for &'a Array<T> {
|
||||
/// # type Item = &'a T;
|
||||
/// # type IntoIter = Box<Iterator<Item = &'a T>>;
|
||||
/// # type IntoIter = Box<dyn Iterator<Item = &'a T>>;
|
||||
/// # fn into_iter(self) -> Self::IntoIter {
|
||||
/// # unimplemented!()
|
||||
/// # }
|
||||
/// # }
|
||||
/// #
|
||||
/// use serde::ser::{Serialize, Serializer, SerializeTuple};
|
||||
/// use serde::ser::{Serialize, SerializeTuple, Serializer};
|
||||
///
|
||||
/// # mod fool {
|
||||
/// # trait Serialize {}
|
||||
@@ -1629,9 +1603,9 @@ pub trait SerializeTuple {
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a tuple element.
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize;
|
||||
T: ?Sized + Serialize;
|
||||
|
||||
/// Finish serializing a tuple.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
@@ -1641,7 +1615,7 @@ pub trait SerializeTuple {
|
||||
///
|
||||
/// # Example use
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::ser::{Serialize, SerializeTupleStruct, Serializer};
|
||||
///
|
||||
/// struct Rgb(u8, u8, u8);
|
||||
@@ -1674,9 +1648,9 @@ pub trait SerializeTupleStruct {
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a tuple struct field.
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize;
|
||||
T: ?Sized + Serialize;
|
||||
|
||||
/// Finish serializing a tuple struct.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
@@ -1686,7 +1660,7 @@ pub trait SerializeTupleStruct {
|
||||
///
|
||||
/// # Example use
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::ser::{Serialize, SerializeTupleVariant, Serializer};
|
||||
///
|
||||
/// enum E {
|
||||
@@ -1732,9 +1706,9 @@ pub trait SerializeTupleVariant {
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a tuple variant field.
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize;
|
||||
T: ?Sized + Serialize;
|
||||
|
||||
/// Finish serializing a tuple variant.
|
||||
fn end(self) -> Result<Self::Ok, Self::Error>;
|
||||
@@ -1744,7 +1718,7 @@ pub trait SerializeTupleVariant {
|
||||
///
|
||||
/// # Example use
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// # use std::marker::PhantomData;
|
||||
/// #
|
||||
/// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>);
|
||||
@@ -1757,14 +1731,14 @@ pub trait SerializeTupleVariant {
|
||||
/// #
|
||||
/// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> {
|
||||
/// # type Item = (&'a K, &'a V);
|
||||
/// # type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>;
|
||||
/// # type IntoIter = Box<dyn Iterator<Item = (&'a K, &'a V)>>;
|
||||
/// #
|
||||
/// # fn into_iter(self) -> Self::IntoIter {
|
||||
/// # unimplemented!()
|
||||
/// # }
|
||||
/// # }
|
||||
/// #
|
||||
/// use serde::ser::{Serialize, Serializer, SerializeMap};
|
||||
/// use serde::ser::{Serialize, SerializeMap, Serializer};
|
||||
///
|
||||
/// impl<K, V> Serialize for HashMap<K, V>
|
||||
/// where
|
||||
@@ -1803,9 +1777,9 @@ pub trait SerializeMap {
|
||||
/// `serialize_entry` instead as it may be implemented more efficiently in
|
||||
/// some formats compared to a pair of calls to `serialize_key` and
|
||||
/// `serialize_value`.
|
||||
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
|
||||
fn serialize_key<T>(&mut self, key: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize;
|
||||
T: ?Sized + Serialize;
|
||||
|
||||
/// Serialize a map value.
|
||||
///
|
||||
@@ -1813,9 +1787,9 @@ pub trait SerializeMap {
|
||||
///
|
||||
/// Calling `serialize_value` before `serialize_key` is incorrect and is
|
||||
/// allowed to panic or produce bogus results.
|
||||
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize;
|
||||
T: ?Sized + Serialize;
|
||||
|
||||
/// Serialize a map entry consisting of a key and a value.
|
||||
///
|
||||
@@ -1834,16 +1808,12 @@ pub trait SerializeMap {
|
||||
/// [`Serialize`]: ../trait.Serialize.html
|
||||
/// [`serialize_key`]: #tymethod.serialize_key
|
||||
/// [`serialize_value`]: #tymethod.serialize_value
|
||||
fn serialize_entry<K: ?Sized, V: ?Sized>(
|
||||
&mut self,
|
||||
key: &K,
|
||||
value: &V,
|
||||
) -> Result<(), Self::Error>
|
||||
fn serialize_entry<K, V>(&mut self, key: &K, value: &V) -> Result<(), Self::Error>
|
||||
where
|
||||
K: Serialize,
|
||||
V: Serialize,
|
||||
K: ?Sized + Serialize,
|
||||
V: ?Sized + Serialize,
|
||||
{
|
||||
try!(self.serialize_key(key));
|
||||
tri!(self.serialize_key(key));
|
||||
self.serialize_value(value)
|
||||
}
|
||||
|
||||
@@ -1855,7 +1825,7 @@ pub trait SerializeMap {
|
||||
///
|
||||
/// # Example use
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::ser::{Serialize, SerializeStruct, Serializer};
|
||||
///
|
||||
/// struct Rgb {
|
||||
@@ -1892,15 +1862,13 @@ pub trait SerializeStruct {
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a struct field.
|
||||
fn serialize_field<T: ?Sized>(
|
||||
&mut self,
|
||||
key: &'static str,
|
||||
value: &T,
|
||||
) -> Result<(), Self::Error>
|
||||
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize;
|
||||
T: ?Sized + Serialize;
|
||||
|
||||
/// Indicate that a struct field has been skipped.
|
||||
///
|
||||
/// The default implementation does nothing.
|
||||
#[inline]
|
||||
fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
|
||||
let _ = key;
|
||||
@@ -1915,7 +1883,7 @@ pub trait SerializeStruct {
|
||||
///
|
||||
/// # Example use
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// use serde::ser::{Serialize, SerializeStructVariant, Serializer};
|
||||
///
|
||||
/// enum E {
|
||||
@@ -1958,15 +1926,13 @@ pub trait SerializeStructVariant {
|
||||
type Error: Error;
|
||||
|
||||
/// Serialize a struct variant field.
|
||||
fn serialize_field<T: ?Sized>(
|
||||
&mut self,
|
||||
key: &'static str,
|
||||
value: &T,
|
||||
) -> Result<(), Self::Error>
|
||||
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize;
|
||||
T: ?Sized + Serialize;
|
||||
|
||||
/// Indicate that a struct variant field has been skipped.
|
||||
///
|
||||
/// The default implementation does nothing.
|
||||
#[inline]
|
||||
fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
|
||||
let _ = key;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use lib::{Debug, Display};
|
||||
use crate::lib::{Debug, Display};
|
||||
|
||||
/// Either a re-export of std::error::Error or a new identical trait, depending
|
||||
/// on whether Serde's "std" feature is enabled.
|
||||
@@ -9,7 +9,7 @@ use lib::{Debug, Display};
|
||||
/// generally provide their error types with a `std::error::Error` impl
|
||||
/// directly:
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// #[derive(Debug)]
|
||||
/// struct MySerError {...}
|
||||
///
|
||||
@@ -29,7 +29,7 @@ use lib::{Debug, Display};
|
||||
/// std = ["serde/std"]
|
||||
/// ```
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// #[cfg(feature = "std")]
|
||||
/// impl std::error::Error for MySerError {}
|
||||
/// ```
|
||||
@@ -37,7 +37,7 @@ use lib::{Debug, Display};
|
||||
/// ... or else provide the std Error impl unconditionally via Serde's
|
||||
/// re-export:
|
||||
///
|
||||
/// ```edition2018
|
||||
/// ```edition2021
|
||||
/// impl serde::ser::StdError for MySerError {}
|
||||
/// ```
|
||||
pub trait Error: Debug + Display {
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
msrv = "1.31.0"
|
||||
@@ -1,12 +1,13 @@
|
||||
[package]
|
||||
name = "serde_derive"
|
||||
version = "1.0.157" # remember to update html_root_url
|
||||
version = "1.0.204"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"]
|
||||
categories = ["no-std"]
|
||||
categories = ["no-std", "no-std::no-alloc"]
|
||||
description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]"
|
||||
documentation = "https://serde.rs/derive.html"
|
||||
edition = "2015"
|
||||
exclude = ["build.rs"]
|
||||
homepage = "https://serde.rs"
|
||||
include = ["build.rs", "src/**/*.rs", "crates-io.md", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
keywords = ["serde", "serialization", "no_std", "derive"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
readme = "crates-io.md"
|
||||
@@ -22,12 +23,13 @@ name = "serde_derive"
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
proc-macro2 = "1.0"
|
||||
quote = "1.0"
|
||||
syn = "2.0"
|
||||
proc-macro2 = { workspace = true, features = ["proc-macro"] }
|
||||
quote = { workspace = true, features = ["proc-macro"] }
|
||||
syn = { workspace = true, features = ["clone-impls", "derive", "parsing", "printing", "proc-macro"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde = { version = "1.0", path = "../serde" }
|
||||
serde = { version = "1", path = "../serde" }
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
rustdoc-args = ["--generate-link-to-definition"]
|
||||
|
||||
+5
-35
@@ -1,38 +1,8 @@
|
||||
use std::env;
|
||||
use std::process::Command;
|
||||
use std::str;
|
||||
|
||||
// The rustc-cfg strings below are *not* public API. Please let us know by
|
||||
// opening a GitHub issue if your build environment requires some way to enable
|
||||
// these cfgs other than by executing our build script.
|
||||
fn main() {
|
||||
// Warning: build.rs is not published to crates.io.
|
||||
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
|
||||
let minor = match rustc_minor_version() {
|
||||
Some(minor) => minor,
|
||||
None => return,
|
||||
};
|
||||
|
||||
// Underscore const names stabilized in Rust 1.37:
|
||||
// https://blog.rust-lang.org/2019/08/15/Rust-1.37.0.html#using-unnamed-const-items-for-macros
|
||||
if minor < 37 {
|
||||
println!("cargo:rustc-cfg=no_underscore_consts");
|
||||
}
|
||||
|
||||
// The ptr::addr_of! macro stabilized in Rust 1.51:
|
||||
// https://blog.rust-lang.org/2021/03/25/Rust-1.51.0.html#stabilized-apis
|
||||
if minor < 51 {
|
||||
println!("cargo:rustc-cfg=no_ptr_addr_of");
|
||||
}
|
||||
}
|
||||
|
||||
fn rustc_minor_version() -> Option<u32> {
|
||||
let rustc = env::var_os("RUSTC")?;
|
||||
let output = Command::new(rustc).arg("--version").output().ok()?;
|
||||
let version = str::from_utf8(&output.stdout).ok()?;
|
||||
let mut pieces = version.split('.');
|
||||
if pieces.next() != Some("rustc 1") {
|
||||
return None;
|
||||
}
|
||||
pieces.next()?.parse().ok()
|
||||
println!("cargo:rustc-cfg=check_cfg");
|
||||
println!("cargo:rustc-check-cfg=cfg(check_cfg)");
|
||||
println!("cargo:rustc-check-cfg=cfg(exhaustive)");
|
||||
}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use syn;
|
||||
use syn::punctuated::{Pair, Punctuated};
|
||||
|
||||
use internals::ast::{Container, Data};
|
||||
use internals::{attr, ungroup};
|
||||
|
||||
use crate::internals::ast::{Container, Data};
|
||||
use crate::internals::{attr, ungroup};
|
||||
use proc_macro2::Span;
|
||||
use std::collections::HashSet;
|
||||
use syn::punctuated::{Pair, Punctuated};
|
||||
use syn::Token;
|
||||
|
||||
// Remove the default from every type parameter because in the generated impls
|
||||
// they look like associated types: "error: associated type bindings are not
|
||||
@@ -147,6 +144,7 @@ pub fn with_bound(
|
||||
|
||||
fn visit_type(&mut self, ty: &'ast syn::Type) {
|
||||
match ty {
|
||||
#![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
syn::Type::Array(ty) => self.visit_type(&ty.elem),
|
||||
syn::Type::BareFn(ty) => {
|
||||
for arg in &ty.inputs {
|
||||
@@ -184,7 +182,6 @@ pub fn with_bound(
|
||||
|
||||
syn::Type::Infer(_) | syn::Type::Never(_) | syn::Type::Verbatim(_) => {}
|
||||
|
||||
#[cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -199,16 +196,13 @@ pub fn with_bound(
|
||||
syn::PathArguments::AngleBracketed(arguments) => {
|
||||
for arg in &arguments.args {
|
||||
match arg {
|
||||
#![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
syn::GenericArgument::Type(arg) => self.visit_type(arg),
|
||||
syn::GenericArgument::AssocType(arg) => self.visit_type(&arg.ty),
|
||||
syn::GenericArgument::Lifetime(_)
|
||||
| syn::GenericArgument::Const(_)
|
||||
| syn::GenericArgument::AssocConst(_)
|
||||
| syn::GenericArgument::Constraint(_) => {}
|
||||
#[cfg_attr(
|
||||
all(test, exhaustive),
|
||||
deny(non_exhaustive_omitted_patterns)
|
||||
)]
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -231,9 +225,9 @@ pub fn with_bound(
|
||||
|
||||
fn visit_type_param_bound(&mut self, bound: &'ast syn::TypeParamBound) {
|
||||
match bound {
|
||||
#![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
syn::TypeParamBound::Trait(bound) => self.visit_path(&bound.path),
|
||||
syn::TypeParamBound::Lifetime(_) | syn::TypeParamBound::Verbatim(_) => {}
|
||||
#[cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -259,7 +253,7 @@ pub fn with_bound(
|
||||
};
|
||||
match &cont.data {
|
||||
Data::Enum(variants) => {
|
||||
for variant in variants.iter() {
|
||||
for variant in variants {
|
||||
let relevant_fields = variant
|
||||
.fields
|
||||
.iter()
|
||||
|
||||
+516
-514
File diff suppressed because it is too large
Load Diff
@@ -1,23 +1,7 @@
|
||||
use proc_macro2::{Ident, TokenStream};
|
||||
use quote::format_ident;
|
||||
|
||||
use syn;
|
||||
use try;
|
||||
|
||||
pub fn wrap_in_const(
|
||||
serde_path: Option<&syn::Path>,
|
||||
trait_: &str,
|
||||
ty: &Ident,
|
||||
code: TokenStream,
|
||||
) -> TokenStream {
|
||||
let try_replacement = try::replacement();
|
||||
|
||||
let dummy_const = if cfg!(no_underscore_consts) {
|
||||
format_ident!("_IMPL_{}_FOR_{}", trait_, unraw(ty))
|
||||
} else {
|
||||
format_ident!("_")
|
||||
};
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::quote;
|
||||
|
||||
pub fn wrap_in_const(serde_path: Option<&syn::Path>, code: TokenStream) -> TokenStream {
|
||||
let use_serde = match serde_path {
|
||||
Some(path) => quote! {
|
||||
use #path as _serde;
|
||||
@@ -31,14 +15,9 @@ pub fn wrap_in_const(
|
||||
quote! {
|
||||
#[doc(hidden)]
|
||||
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
|
||||
const #dummy_const: () = {
|
||||
const _: () = {
|
||||
#use_serde
|
||||
#try_replacement
|
||||
#code
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn unraw(ident: &Ident) -> String {
|
||||
ident.to_string().trim_start_matches("r#").to_owned()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::ToTokens;
|
||||
use syn::token;
|
||||
use syn::{token, Token};
|
||||
|
||||
pub enum Fragment {
|
||||
/// Tokens that can be used as an expression.
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
//! A Serde ast, parsed from the Syn ast and ready to generate Rust code.
|
||||
|
||||
use internals::attr;
|
||||
use internals::check;
|
||||
use internals::{Ctxt, Derive};
|
||||
use syn;
|
||||
use crate::internals::{attr, check, Ctxt, Derive};
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::Token;
|
||||
|
||||
/// A source data structure annotated with `#[derive(Serialize)]` and/or `#[derive(Deserialize)]`,
|
||||
/// parsed into an internal representation.
|
||||
@@ -88,9 +86,12 @@ impl<'a> Container<'a> {
|
||||
if field.attrs.flatten() {
|
||||
has_flatten = true;
|
||||
}
|
||||
field
|
||||
.attrs
|
||||
.rename_by_rules(variant.attrs.rename_all_rules());
|
||||
field.attrs.rename_by_rules(
|
||||
variant
|
||||
.attrs
|
||||
.rename_all_rules()
|
||||
.or(attrs.rename_all_fields_rules()),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -121,7 +122,7 @@ impl<'a> Container<'a> {
|
||||
}
|
||||
|
||||
impl<'a> Data<'a> {
|
||||
pub fn all_fields(&'a self) -> Box<Iterator<Item = &'a Field<'a>> + 'a> {
|
||||
pub fn all_fields(&'a self) -> Box<dyn Iterator<Item = &'a Field<'a>> + 'a> {
|
||||
match self {
|
||||
Data::Enum(variants) => {
|
||||
Box::new(variants.iter().flat_map(|variant| variant.fields.iter()))
|
||||
@@ -140,7 +141,7 @@ fn enum_from_ast<'a>(
|
||||
variants: &'a Punctuated<syn::Variant, Token![,]>,
|
||||
container_default: &attr::Default,
|
||||
) -> Vec<Variant<'a>> {
|
||||
variants
|
||||
let variants: Vec<Variant> = variants
|
||||
.iter()
|
||||
.map(|variant| {
|
||||
let attrs = attr::Variant::from_ast(cx, variant);
|
||||
@@ -154,7 +155,20 @@ fn enum_from_ast<'a>(
|
||||
original: variant,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
.collect();
|
||||
|
||||
let index_of_last_tagged_variant = variants
|
||||
.iter()
|
||||
.rposition(|variant| !variant.attrs.untagged());
|
||||
if let Some(index_of_last_tagged_variant) = index_of_last_tagged_variant {
|
||||
for variant in &variants[..index_of_last_tagged_variant] {
|
||||
if variant.attrs.untagged() {
|
||||
cx.error_spanned_by(&variant.ident, "all variants with the #[serde(untagged)] attribute must be placed at the end of the enum");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
variants
|
||||
}
|
||||
|
||||
fn struct_from_ast<'a>(
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
use internals::symbol::*;
|
||||
use internals::{ungroup, Ctxt};
|
||||
use crate::internals::symbol::*;
|
||||
use crate::internals::{ungroup, Ctxt};
|
||||
use proc_macro2::{Spacing, Span, TokenStream, TokenTree};
|
||||
use quote::ToTokens;
|
||||
use std::borrow::Cow;
|
||||
use std::collections::BTreeSet;
|
||||
use std::iter::FromIterator;
|
||||
use syn;
|
||||
use syn::meta::ParseNestedMeta;
|
||||
use syn::parse::ParseStream;
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::{token, Ident, Lifetime};
|
||||
use syn::{parse_quote, token, Ident, Lifetime, Token};
|
||||
|
||||
// This module handles parsing of `#[serde(...)]` attributes. The entrypoints
|
||||
// are `attr::Container::from_ast`, `attr::Variant::from_ast`, and
|
||||
@@ -19,7 +18,7 @@ use syn::{token, Ident, Lifetime};
|
||||
// user will see errors simultaneously for all bad attributes in the crate
|
||||
// rather than just the first.
|
||||
|
||||
pub use internals::case::RenameRule;
|
||||
pub use crate::internals::case::RenameRule;
|
||||
|
||||
struct Attr<'c, T> {
|
||||
cx: &'c Ctxt,
|
||||
@@ -135,7 +134,7 @@ pub struct Name {
|
||||
serialize_renamed: bool,
|
||||
deserialize: String,
|
||||
deserialize_renamed: bool,
|
||||
deserialize_aliases: Vec<String>,
|
||||
deserialize_aliases: BTreeSet<String>,
|
||||
}
|
||||
|
||||
fn unraw(ident: &Ident) -> String {
|
||||
@@ -149,16 +148,12 @@ impl Name {
|
||||
de_name: Attr<String>,
|
||||
de_aliases: Option<VecAttr<String>>,
|
||||
) -> Name {
|
||||
let deserialize_aliases = match de_aliases {
|
||||
Some(de_aliases) => {
|
||||
let mut alias_list = BTreeSet::new();
|
||||
for alias_name in de_aliases.get() {
|
||||
alias_list.insert(alias_name);
|
||||
}
|
||||
alias_list.into_iter().collect()
|
||||
let mut alias_set = BTreeSet::new();
|
||||
if let Some(de_aliases) = de_aliases {
|
||||
for alias_name in de_aliases.get() {
|
||||
alias_set.insert(alias_name);
|
||||
}
|
||||
None => Vec::new(),
|
||||
};
|
||||
}
|
||||
|
||||
let ser_name = ser_name.get();
|
||||
let ser_renamed = ser_name.is_some();
|
||||
@@ -169,33 +164,40 @@ impl Name {
|
||||
serialize_renamed: ser_renamed,
|
||||
deserialize: de_name.unwrap_or(source_name),
|
||||
deserialize_renamed: de_renamed,
|
||||
deserialize_aliases,
|
||||
deserialize_aliases: alias_set,
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the container name for the container when serializing.
|
||||
pub fn serialize_name(&self) -> String {
|
||||
self.serialize.clone()
|
||||
pub fn serialize_name(&self) -> &str {
|
||||
&self.serialize
|
||||
}
|
||||
|
||||
/// Return the container name for the container when deserializing.
|
||||
pub fn deserialize_name(&self) -> String {
|
||||
self.deserialize.clone()
|
||||
pub fn deserialize_name(&self) -> &str {
|
||||
&self.deserialize
|
||||
}
|
||||
|
||||
fn deserialize_aliases(&self) -> Vec<String> {
|
||||
let mut aliases = self.deserialize_aliases.clone();
|
||||
let main_name = self.deserialize_name();
|
||||
if !aliases.contains(&main_name) {
|
||||
aliases.push(main_name);
|
||||
}
|
||||
aliases
|
||||
fn deserialize_aliases(&self) -> &BTreeSet<String> {
|
||||
&self.deserialize_aliases
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct RenameAllRules {
|
||||
serialize: RenameRule,
|
||||
deserialize: RenameRule,
|
||||
pub serialize: RenameRule,
|
||||
pub deserialize: RenameRule,
|
||||
}
|
||||
|
||||
impl RenameAllRules {
|
||||
/// Returns a new `RenameAllRules` with the individual rules of `self` and
|
||||
/// `other_rules` joined by `RenameRules::or`.
|
||||
pub fn or(self, other_rules: Self) -> Self {
|
||||
Self {
|
||||
serialize: self.serialize.or(other_rules.serialize),
|
||||
deserialize: self.deserialize.or(other_rules.deserialize),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents struct or enum attribute information.
|
||||
@@ -205,6 +207,7 @@ pub struct Container {
|
||||
deny_unknown_fields: bool,
|
||||
default: Default,
|
||||
rename_all_rules: RenameAllRules,
|
||||
rename_all_fields_rules: RenameAllRules,
|
||||
ser_bound: Option<Vec<syn::WherePredicate>>,
|
||||
de_bound: Option<Vec<syn::WherePredicate>>,
|
||||
tag: TagType,
|
||||
@@ -218,6 +221,7 @@ pub struct Container {
|
||||
is_packed: bool,
|
||||
/// Error message generated when type can't be deserialized
|
||||
expecting: Option<String>,
|
||||
non_exhaustive: bool,
|
||||
}
|
||||
|
||||
/// Styles of representing an enum.
|
||||
@@ -288,6 +292,8 @@ impl Container {
|
||||
let mut default = Attr::none(cx, DEFAULT);
|
||||
let mut rename_all_ser_rule = Attr::none(cx, RENAME_ALL);
|
||||
let mut rename_all_de_rule = Attr::none(cx, RENAME_ALL);
|
||||
let mut rename_all_fields_ser_rule = Attr::none(cx, RENAME_ALL_FIELDS);
|
||||
let mut rename_all_fields_de_rule = Attr::none(cx, RENAME_ALL_FIELDS);
|
||||
let mut ser_bound = Attr::none(cx, BOUND);
|
||||
let mut de_bound = Attr::none(cx, BOUND);
|
||||
let mut untagged = BoolAttr::none(cx, UNTAGGED);
|
||||
@@ -301,12 +307,21 @@ impl Container {
|
||||
let mut variant_identifier = BoolAttr::none(cx, VARIANT_IDENTIFIER);
|
||||
let mut serde_path = Attr::none(cx, CRATE);
|
||||
let mut expecting = Attr::none(cx, EXPECTING);
|
||||
let mut non_exhaustive = false;
|
||||
|
||||
for attr in &item.attrs {
|
||||
if attr.path() != SERDE {
|
||||
non_exhaustive |=
|
||||
matches!(&attr.meta, syn::Meta::Path(path) if path == NON_EXHAUSTIVE);
|
||||
continue;
|
||||
}
|
||||
|
||||
if let syn::Meta::List(meta) = &attr.meta {
|
||||
if meta.tokens.is_empty() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(err) = attr.parse_nested_meta(|meta| {
|
||||
if meta.path == RENAME {
|
||||
// #[serde(rename = "foo")]
|
||||
@@ -335,6 +350,44 @@ impl Container {
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if meta.path == RENAME_ALL_FIELDS {
|
||||
// #[serde(rename_all_fields = "foo")]
|
||||
// #[serde(rename_all_fields(serialize = "foo", deserialize = "bar"))]
|
||||
let one_name = meta.input.peek(Token![=]);
|
||||
let (ser, de) = get_renames(cx, RENAME_ALL_FIELDS, &meta)?;
|
||||
|
||||
match item.data {
|
||||
syn::Data::Enum(_) => {
|
||||
if let Some(ser) = ser {
|
||||
match RenameRule::from_str(&ser.value()) {
|
||||
Ok(rename_rule) => {
|
||||
rename_all_fields_ser_rule.set(&meta.path, rename_rule);
|
||||
}
|
||||
Err(err) => cx.error_spanned_by(ser, err),
|
||||
}
|
||||
}
|
||||
if let Some(de) = de {
|
||||
match RenameRule::from_str(&de.value()) {
|
||||
Ok(rename_rule) => {
|
||||
rename_all_fields_de_rule.set(&meta.path, rename_rule);
|
||||
}
|
||||
Err(err) => {
|
||||
if !one_name {
|
||||
cx.error_spanned_by(de, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
syn::Data::Struct(_) => {
|
||||
let msg = "#[serde(rename_all_fields)] can only be used on enums";
|
||||
cx.syn_error(meta.error(msg));
|
||||
}
|
||||
syn::Data::Union(_) => {
|
||||
let msg = "#[serde(rename_all_fields)] can only be used on enums";
|
||||
cx.syn_error(meta.error(msg));
|
||||
}
|
||||
}
|
||||
} else if meta.path == TRANSPARENT {
|
||||
// #[serde(transparent)]
|
||||
transparent.set_true(meta.path);
|
||||
@@ -347,21 +400,21 @@ impl Container {
|
||||
if let Some(path) = parse_lit_into_expr_path(cx, DEFAULT, &meta)? {
|
||||
match &item.data {
|
||||
syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields {
|
||||
syn::Fields::Named(_) => {
|
||||
syn::Fields::Named(_) | syn::Fields::Unnamed(_) => {
|
||||
default.set(&meta.path, Default::Path(path));
|
||||
}
|
||||
syn::Fields::Unnamed(_) | syn::Fields::Unit => {
|
||||
let msg = "#[serde(default = \"...\")] can only be used on structs with named fields";
|
||||
cx.error_spanned_by(fields, msg);
|
||||
syn::Fields::Unit => {
|
||||
let msg = "#[serde(default = \"...\")] can only be used on structs that have fields";
|
||||
cx.syn_error(meta.error(msg));
|
||||
}
|
||||
},
|
||||
syn::Data::Enum(syn::DataEnum { enum_token, .. }) => {
|
||||
let msg = "#[serde(default = \"...\")] can only be used on structs with named fields";
|
||||
cx.error_spanned_by(enum_token, msg);
|
||||
syn::Data::Enum(_) => {
|
||||
let msg = "#[serde(default = \"...\")] can only be used on structs";
|
||||
cx.syn_error(meta.error(msg));
|
||||
}
|
||||
syn::Data::Union(syn::DataUnion { union_token, .. }) => {
|
||||
let msg = "#[serde(default = \"...\")] can only be used on structs with named fields";
|
||||
cx.error_spanned_by(union_token, msg);
|
||||
syn::Data::Union(_) => {
|
||||
let msg = "#[serde(default = \"...\")] can only be used on structs";
|
||||
cx.syn_error(meta.error(msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -369,21 +422,21 @@ impl Container {
|
||||
// #[serde(default)]
|
||||
match &item.data {
|
||||
syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields {
|
||||
syn::Fields::Named(_) => {
|
||||
syn::Fields::Named(_) | syn::Fields::Unnamed(_) => {
|
||||
default.set(meta.path, Default::Default);
|
||||
}
|
||||
syn::Fields::Unnamed(_) | syn::Fields::Unit => {
|
||||
let msg = "#[serde(default)] can only be used on structs with named fields";
|
||||
syn::Fields::Unit => {
|
||||
let msg = "#[serde(default)] can only be used on structs that have fields";
|
||||
cx.error_spanned_by(fields, msg);
|
||||
}
|
||||
},
|
||||
syn::Data::Enum(syn::DataEnum { enum_token, .. }) => {
|
||||
let msg = "#[serde(default)] can only be used on structs with named fields";
|
||||
cx.error_spanned_by(enum_token, msg);
|
||||
syn::Data::Enum(_) => {
|
||||
let msg = "#[serde(default)] can only be used on structs";
|
||||
cx.syn_error(meta.error(msg));
|
||||
}
|
||||
syn::Data::Union(syn::DataUnion { union_token, .. }) => {
|
||||
let msg = "#[serde(default)] can only be used on structs with named fields";
|
||||
cx.error_spanned_by(union_token, msg);
|
||||
syn::Data::Union(_) => {
|
||||
let msg = "#[serde(default)] can only be used on structs";
|
||||
cx.syn_error(meta.error(msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -399,13 +452,13 @@ impl Container {
|
||||
syn::Data::Enum(_) => {
|
||||
untagged.set_true(&meta.path);
|
||||
}
|
||||
syn::Data::Struct(syn::DataStruct { struct_token, .. }) => {
|
||||
syn::Data::Struct(_) => {
|
||||
let msg = "#[serde(untagged)] can only be used on enums";
|
||||
cx.error_spanned_by(struct_token, msg);
|
||||
cx.syn_error(meta.error(msg));
|
||||
}
|
||||
syn::Data::Union(syn::DataUnion { union_token, .. }) => {
|
||||
syn::Data::Union(_) => {
|
||||
let msg = "#[serde(untagged)] can only be used on enums";
|
||||
cx.error_spanned_by(union_token, msg);
|
||||
cx.syn_error(meta.error(msg));
|
||||
}
|
||||
}
|
||||
} else if meta.path == TAG {
|
||||
@@ -421,12 +474,12 @@ impl Container {
|
||||
}
|
||||
syn::Fields::Unnamed(_) | syn::Fields::Unit => {
|
||||
let msg = "#[serde(tag = \"...\")] can only be used on enums and structs with named fields";
|
||||
cx.error_spanned_by(fields, msg);
|
||||
cx.syn_error(meta.error(msg));
|
||||
}
|
||||
},
|
||||
syn::Data::Union(syn::DataUnion { union_token, .. }) => {
|
||||
syn::Data::Union(_) => {
|
||||
let msg = "#[serde(tag = \"...\")] can only be used on enums and structs with named fields";
|
||||
cx.error_spanned_by(union_token, msg);
|
||||
cx.syn_error(meta.error(msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -437,13 +490,13 @@ impl Container {
|
||||
syn::Data::Enum(_) => {
|
||||
content.set(&meta.path, s.value());
|
||||
}
|
||||
syn::Data::Struct(syn::DataStruct { struct_token, .. }) => {
|
||||
syn::Data::Struct(_) => {
|
||||
let msg = "#[serde(content = \"...\")] can only be used on enums";
|
||||
cx.error_spanned_by(struct_token, msg);
|
||||
cx.syn_error(meta.error(msg));
|
||||
}
|
||||
syn::Data::Union(syn::DataUnion { union_token, .. }) => {
|
||||
syn::Data::Union(_) => {
|
||||
let msg = "#[serde(content = \"...\")] can only be used on enums";
|
||||
cx.error_spanned_by(union_token, msg);
|
||||
cx.syn_error(meta.error(msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -522,6 +575,10 @@ impl Container {
|
||||
serialize: rename_all_ser_rule.get().unwrap_or(RenameRule::None),
|
||||
deserialize: rename_all_de_rule.get().unwrap_or(RenameRule::None),
|
||||
},
|
||||
rename_all_fields_rules: RenameAllRules {
|
||||
serialize: rename_all_fields_ser_rule.get().unwrap_or(RenameRule::None),
|
||||
deserialize: rename_all_fields_de_rule.get().unwrap_or(RenameRule::None),
|
||||
},
|
||||
ser_bound: ser_bound.get(),
|
||||
de_bound: de_bound.get(),
|
||||
tag: decide_tag(cx, item, untagged, internal_tag, content),
|
||||
@@ -534,6 +591,7 @@ impl Container {
|
||||
serde_path: serde_path.get(),
|
||||
is_packed,
|
||||
expecting: expecting.get(),
|
||||
non_exhaustive,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -541,8 +599,12 @@ impl Container {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub fn rename_all_rules(&self) -> &RenameAllRules {
|
||||
&self.rename_all_rules
|
||||
pub fn rename_all_rules(&self) -> RenameAllRules {
|
||||
self.rename_all_rules
|
||||
}
|
||||
|
||||
pub fn rename_all_fields_rules(&self) -> RenameAllRules {
|
||||
self.rename_all_fields_rules
|
||||
}
|
||||
|
||||
pub fn transparent(&self) -> bool {
|
||||
@@ -615,6 +677,10 @@ impl Container {
|
||||
pub fn expecting(&self) -> Option<&str> {
|
||||
self.expecting.as_ref().map(String::as_ref)
|
||||
}
|
||||
|
||||
pub fn non_exhaustive(&self) -> bool {
|
||||
self.non_exhaustive
|
||||
}
|
||||
}
|
||||
|
||||
fn decide_tag(
|
||||
@@ -650,7 +716,7 @@ fn decide_tag(
|
||||
}
|
||||
TagType::Internal { tag }
|
||||
}
|
||||
(Some((untagged_tokens, _)), Some((tag_tokens, _)), None) => {
|
||||
(Some((untagged_tokens, ())), Some((tag_tokens, _)), None) => {
|
||||
let msg = "enum cannot be both untagged and internally tagged";
|
||||
cx.error_spanned_by(untagged_tokens, msg);
|
||||
cx.error_spanned_by(tag_tokens, msg);
|
||||
@@ -661,14 +727,14 @@ fn decide_tag(
|
||||
cx.error_spanned_by(content_tokens, msg);
|
||||
TagType::External
|
||||
}
|
||||
(Some((untagged_tokens, _)), None, Some((content_tokens, _))) => {
|
||||
(Some((untagged_tokens, ())), None, Some((content_tokens, _))) => {
|
||||
let msg = "untagged enum cannot have #[serde(content = \"...\")]";
|
||||
cx.error_spanned_by(untagged_tokens, msg);
|
||||
cx.error_spanned_by(content_tokens, msg);
|
||||
TagType::External
|
||||
}
|
||||
(None, Some((_, tag)), Some((_, content))) => TagType::Adjacent { tag, content },
|
||||
(Some((untagged_tokens, _)), Some((tag_tokens, _)), Some((content_tokens, _))) => {
|
||||
(Some((untagged_tokens, ())), Some((tag_tokens, _)), Some((content_tokens, _))) => {
|
||||
let msg = "untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]";
|
||||
cx.error_spanned_by(untagged_tokens, msg);
|
||||
cx.error_spanned_by(tag_tokens, msg);
|
||||
@@ -690,7 +756,7 @@ fn decide_identifier(
|
||||
variant_identifier.0.get_with_tokens(),
|
||||
) {
|
||||
(_, None, None) => Identifier::No,
|
||||
(_, Some((field_identifier_tokens, _)), Some((variant_identifier_tokens, _))) => {
|
||||
(_, Some((field_identifier_tokens, ())), Some((variant_identifier_tokens, ()))) => {
|
||||
let msg =
|
||||
"#[serde(field_identifier)] and #[serde(variant_identifier)] cannot both be set";
|
||||
cx.error_spanned_by(field_identifier_tokens, msg);
|
||||
@@ -734,6 +800,7 @@ pub struct Variant {
|
||||
serialize_with: Option<syn::ExprPath>,
|
||||
deserialize_with: Option<syn::ExprPath>,
|
||||
borrow: Option<BorrowAttribute>,
|
||||
untagged: bool,
|
||||
}
|
||||
|
||||
struct BorrowAttribute {
|
||||
@@ -756,12 +823,19 @@ impl Variant {
|
||||
let mut serialize_with = Attr::none(cx, SERIALIZE_WITH);
|
||||
let mut deserialize_with = Attr::none(cx, DESERIALIZE_WITH);
|
||||
let mut borrow = Attr::none(cx, BORROW);
|
||||
let mut untagged = BoolAttr::none(cx, UNTAGGED);
|
||||
|
||||
for attr in &variant.attrs {
|
||||
if attr.path() != SERDE {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let syn::Meta::List(meta) = &attr.meta {
|
||||
if meta.tokens.is_empty() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(err) = attr.parse_nested_meta(|meta| {
|
||||
if meta.path == RENAME {
|
||||
// #[serde(rename = "foo")]
|
||||
@@ -867,6 +941,8 @@ impl Variant {
|
||||
cx.error_spanned_by(variant, msg);
|
||||
}
|
||||
}
|
||||
} else if meta.path == UNTAGGED {
|
||||
untagged.set_true(&meta.path);
|
||||
} else {
|
||||
let path = meta.path.to_token_stream().to_string().replace(' ', "");
|
||||
return Err(
|
||||
@@ -893,6 +969,7 @@ impl Variant {
|
||||
serialize_with: serialize_with.get(),
|
||||
deserialize_with: deserialize_with.get(),
|
||||
borrow: borrow.get(),
|
||||
untagged: untagged.get(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -900,21 +977,24 @@ impl Variant {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub fn aliases(&self) -> Vec<String> {
|
||||
pub fn aliases(&self) -> &BTreeSet<String> {
|
||||
self.name.deserialize_aliases()
|
||||
}
|
||||
|
||||
pub fn rename_by_rules(&mut self, rules: &RenameAllRules) {
|
||||
pub fn rename_by_rules(&mut self, rules: RenameAllRules) {
|
||||
if !self.name.serialize_renamed {
|
||||
self.name.serialize = rules.serialize.apply_to_variant(&self.name.serialize);
|
||||
}
|
||||
if !self.name.deserialize_renamed {
|
||||
self.name.deserialize = rules.deserialize.apply_to_variant(&self.name.deserialize);
|
||||
}
|
||||
self.name
|
||||
.deserialize_aliases
|
||||
.insert(self.name.deserialize.clone());
|
||||
}
|
||||
|
||||
pub fn rename_all_rules(&self) -> &RenameAllRules {
|
||||
&self.rename_all_rules
|
||||
pub fn rename_all_rules(&self) -> RenameAllRules {
|
||||
self.rename_all_rules
|
||||
}
|
||||
|
||||
pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> {
|
||||
@@ -944,6 +1024,10 @@ impl Variant {
|
||||
pub fn deserialize_with(&self) -> Option<&syn::ExprPath> {
|
||||
self.deserialize_with.as_ref()
|
||||
}
|
||||
|
||||
pub fn untagged(&self) -> bool {
|
||||
self.untagged
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents field attribute information
|
||||
@@ -1033,6 +1117,12 @@ impl Field {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let syn::Meta::List(meta) = &attr.meta {
|
||||
if meta.tokens.is_empty() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(err) = attr.parse_nested_meta(|meta| {
|
||||
if meta.path == RENAME {
|
||||
// #[serde(rename = "foo")]
|
||||
@@ -1229,17 +1319,20 @@ impl Field {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub fn aliases(&self) -> Vec<String> {
|
||||
pub fn aliases(&self) -> &BTreeSet<String> {
|
||||
self.name.deserialize_aliases()
|
||||
}
|
||||
|
||||
pub fn rename_by_rules(&mut self, rules: &RenameAllRules) {
|
||||
pub fn rename_by_rules(&mut self, rules: RenameAllRules) {
|
||||
if !self.name.serialize_renamed {
|
||||
self.name.serialize = rules.serialize.apply_to_field(&self.name.serialize);
|
||||
}
|
||||
if !self.name.deserialize_renamed {
|
||||
self.name.deserialize = rules.deserialize.apply_to_field(&self.name.deserialize);
|
||||
}
|
||||
self.name
|
||||
.deserialize_aliases
|
||||
.insert(self.name.deserialize.clone());
|
||||
}
|
||||
|
||||
pub fn skip_serializing(&self) -> bool {
|
||||
@@ -1381,21 +1474,33 @@ fn get_lit_str2(
|
||||
meta_item_name: Symbol,
|
||||
meta: &ParseNestedMeta,
|
||||
) -> syn::Result<Option<syn::LitStr>> {
|
||||
match meta.value()?.parse()? {
|
||||
syn::Expr::Lit(syn::ExprLit {
|
||||
lit: syn::Lit::Str(lit),
|
||||
..
|
||||
}) => Ok(Some(lit)),
|
||||
expr => {
|
||||
let expr: syn::Expr = meta.value()?.parse()?;
|
||||
let mut value = &expr;
|
||||
while let syn::Expr::Group(e) = value {
|
||||
value = &e.expr;
|
||||
}
|
||||
if let syn::Expr::Lit(syn::ExprLit {
|
||||
lit: syn::Lit::Str(lit),
|
||||
..
|
||||
}) = value
|
||||
{
|
||||
let suffix = lit.suffix();
|
||||
if !suffix.is_empty() {
|
||||
cx.error_spanned_by(
|
||||
expr,
|
||||
format!(
|
||||
"expected serde {} attribute to be a string: `{} = \"...\"`",
|
||||
attr_name, meta_item_name
|
||||
),
|
||||
lit,
|
||||
format!("unexpected suffix `{}` on string literal", suffix),
|
||||
);
|
||||
Ok(None)
|
||||
}
|
||||
Ok(Some(lit.clone()))
|
||||
} else {
|
||||
cx.error_spanned_by(
|
||||
expr,
|
||||
format!(
|
||||
"expected serde {} attribute to be a string: `{} = \"...\"`",
|
||||
attr_name, meta_item_name
|
||||
),
|
||||
);
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1689,6 +1794,7 @@ fn borrowable_lifetimes(
|
||||
|
||||
fn collect_lifetimes(ty: &syn::Type, out: &mut BTreeSet<syn::Lifetime>) {
|
||||
match ty {
|
||||
#![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
syn::Type::Slice(ty) => {
|
||||
collect_lifetimes(&ty.elem, out);
|
||||
}
|
||||
@@ -1724,7 +1830,10 @@ fn collect_lifetimes(ty: &syn::Type, out: &mut BTreeSet<syn::Lifetime>) {
|
||||
syn::GenericArgument::AssocType(binding) => {
|
||||
collect_lifetimes(&binding.ty, out);
|
||||
}
|
||||
_ => {}
|
||||
syn::GenericArgument::Const(_)
|
||||
| syn::GenericArgument::AssocConst(_)
|
||||
| syn::GenericArgument::Constraint(_)
|
||||
| _ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1746,7 +1855,6 @@ fn collect_lifetimes(ty: &syn::Type, out: &mut BTreeSet<syn::Lifetime>) {
|
||||
| syn::Type::Infer(_)
|
||||
| syn::Type::Verbatim(_) => {}
|
||||
|
||||
#[cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
//! Code to convert the Rust-styled field/variant (e.g. `my_field`, `MyType`) to the
|
||||
//! case of the source (e.g. `my-field`, `MY_FIELD`).
|
||||
|
||||
// See https://users.rust-lang.org/t/psa-dealing-with-warning-unused-import-std-ascii-asciiext-in-today-s-nightly/13726
|
||||
#[allow(deprecated, unused_imports)]
|
||||
use std::ascii::AsciiExt;
|
||||
|
||||
use std::fmt::{self, Debug, Display};
|
||||
|
||||
use self::RenameRule::*;
|
||||
use std::fmt::{self, Debug, Display};
|
||||
|
||||
/// The different possible ways to change case of fields in a struct, or variants in an enum.
|
||||
#[derive(Copy, Clone, PartialEq)]
|
||||
@@ -59,8 +54,8 @@ impl RenameRule {
|
||||
}
|
||||
|
||||
/// Apply a renaming rule to an enum variant, returning the version expected in the source.
|
||||
pub fn apply_to_variant(&self, variant: &str) -> String {
|
||||
match *self {
|
||||
pub fn apply_to_variant(self, variant: &str) -> String {
|
||||
match self {
|
||||
None | PascalCase => variant.to_owned(),
|
||||
LowerCase => variant.to_ascii_lowercase(),
|
||||
UpperCase => variant.to_ascii_uppercase(),
|
||||
@@ -84,8 +79,8 @@ impl RenameRule {
|
||||
}
|
||||
|
||||
/// Apply a renaming rule to a struct field, returning the version expected in the source.
|
||||
pub fn apply_to_field(&self, field: &str) -> String {
|
||||
match *self {
|
||||
pub fn apply_to_field(self, field: &str) -> String {
|
||||
match self {
|
||||
None | LowerCase | SnakeCase => field.to_owned(),
|
||||
UpperCase => field.to_ascii_uppercase(),
|
||||
PascalCase => {
|
||||
@@ -112,6 +107,14 @@ impl RenameRule {
|
||||
ScreamingKebabCase => ScreamingSnakeCase.apply_to_field(field).replace('_', "-"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the `RenameRule` if it is not `None`, `rule_b` otherwise.
|
||||
pub fn or(self, rule_b: Self) -> Self {
|
||||
match self {
|
||||
None => rule_b,
|
||||
_ => self,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ParseError<'a> {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use internals::ast::{Container, Data, Field, Style};
|
||||
use internals::attr::{Identifier, TagType};
|
||||
use internals::{ungroup, Ctxt, Derive};
|
||||
use crate::internals::ast::{Container, Data, Field, Style};
|
||||
use crate::internals::attr::{Default, Identifier, TagType};
|
||||
use crate::internals::{ungroup, Ctxt, Derive};
|
||||
use syn::{Member, Type};
|
||||
|
||||
/// Cross-cutting checks that require looking at more than a single attrs
|
||||
/// object. Simpler checks should happen when parsing and building the attrs.
|
||||
// Cross-cutting checks that require looking at more than a single attrs object.
|
||||
// Simpler checks should happen when parsing and building the attrs.
|
||||
pub fn check(cx: &Ctxt, cont: &mut Container, derive: Derive) {
|
||||
check_default_on_tuple(cx, cont);
|
||||
check_remote_generic(cx, cont);
|
||||
check_getter(cx, cont);
|
||||
check_flatten(cx, cont);
|
||||
@@ -17,18 +18,51 @@ pub fn check(cx: &Ctxt, cont: &mut Container, derive: Derive) {
|
||||
check_from_and_try_from(cx, cont);
|
||||
}
|
||||
|
||||
/// Remote derive definition type must have either all of the generics of the
|
||||
/// remote type:
|
||||
///
|
||||
/// #[serde(remote = "Generic")]
|
||||
/// struct Generic<T> {…}
|
||||
///
|
||||
/// or none of them, i.e. defining impls for one concrete instantiation of the
|
||||
/// remote type only:
|
||||
///
|
||||
/// #[serde(remote = "Generic<T>")]
|
||||
/// struct ConcreteDef {…}
|
||||
///
|
||||
// If some field of a tuple struct is marked #[serde(default)] then all fields
|
||||
// after it must also be marked with that attribute, or the struct must have a
|
||||
// container-level serde(default) attribute. A field's default value is only
|
||||
// used for tuple fields if the sequence is exhausted at that point; that means
|
||||
// all subsequent fields will fail to deserialize if they don't have their own
|
||||
// default.
|
||||
fn check_default_on_tuple(cx: &Ctxt, cont: &Container) {
|
||||
if let Default::None = cont.attrs.default() {
|
||||
if let Data::Struct(Style::Tuple, fields) = &cont.data {
|
||||
let mut first_default_index = None;
|
||||
for (i, field) in fields.iter().enumerate() {
|
||||
// Skipped fields automatically get the #[serde(default)]
|
||||
// attribute. We are interested only on non-skipped fields here.
|
||||
if field.attrs.skip_deserializing() {
|
||||
continue;
|
||||
}
|
||||
if let Default::None = field.attrs.default() {
|
||||
if let Some(first) = first_default_index {
|
||||
cx.error_spanned_by(
|
||||
field.ty,
|
||||
format!("field must have #[serde(default)] because previous field {} has #[serde(default)]", first),
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if first_default_index.is_none() {
|
||||
first_default_index = Some(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remote derive definition type must have either all of the generics of the
|
||||
// remote type:
|
||||
//
|
||||
// #[serde(remote = "Generic")]
|
||||
// struct Generic<T> {…}
|
||||
//
|
||||
// or none of them, i.e. defining impls for one concrete instantiation of the
|
||||
// remote type only:
|
||||
//
|
||||
// #[serde(remote = "Generic<T>")]
|
||||
// struct ConcreteDef {…}
|
||||
//
|
||||
fn check_remote_generic(cx: &Ctxt, cont: &Container) {
|
||||
if let Some(remote) = cont.attrs.remote() {
|
||||
let local_has_generic = !cont.generics.params.is_empty();
|
||||
@@ -39,8 +73,8 @@ fn check_remote_generic(cx: &Ctxt, cont: &Container) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Getters are only allowed inside structs (not enums) with the `remote`
|
||||
/// attribute.
|
||||
// Getters are only allowed inside structs (not enums) with the `remote`
|
||||
// attribute.
|
||||
fn check_getter(cx: &Ctxt, cont: &Container) {
|
||||
match cont.data {
|
||||
Data::Enum(_) => {
|
||||
@@ -62,7 +96,7 @@ fn check_getter(cx: &Ctxt, cont: &Container) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Flattening has some restrictions we can test.
|
||||
// Flattening has some restrictions we can test.
|
||||
fn check_flatten(cx: &Ctxt, cont: &Container) {
|
||||
match &cont.data {
|
||||
Data::Enum(variants) => {
|
||||
@@ -101,18 +135,16 @@ fn check_flatten_field(cx: &Ctxt, style: Style, field: &Field) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `other` attribute must be used at most once and it must be the last
|
||||
/// variant of an enum.
|
||||
///
|
||||
/// Inside a `variant_identifier` all variants must be unit variants. Inside a
|
||||
/// `field_identifier` all but possibly one variant must be unit variants. The
|
||||
/// last variant may be a newtype variant which is an implicit "other" case.
|
||||
// The `other` attribute must be used at most once and it must be the last
|
||||
// variant of an enum.
|
||||
//
|
||||
// Inside a `variant_identifier` all variants must be unit variants. Inside a
|
||||
// `field_identifier` all but possibly one variant must be unit variants. The
|
||||
// last variant may be a newtype variant which is an implicit "other" case.
|
||||
fn check_identifier(cx: &Ctxt, cont: &Container) {
|
||||
let variants = match &cont.data {
|
||||
Data::Enum(variants) => variants,
|
||||
Data::Struct(_, _) => {
|
||||
return;
|
||||
}
|
||||
Data::Struct(_, _) => return,
|
||||
};
|
||||
|
||||
for (i, variant) in variants.iter().enumerate() {
|
||||
@@ -189,17 +221,15 @@ fn check_identifier(cx: &Ctxt, cont: &Container) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Skip-(de)serializing attributes are not allowed on variants marked
|
||||
/// (de)serialize_with.
|
||||
// Skip-(de)serializing attributes are not allowed on variants marked
|
||||
// (de)serialize_with.
|
||||
fn check_variant_skip_attrs(cx: &Ctxt, cont: &Container) {
|
||||
let variants = match &cont.data {
|
||||
Data::Enum(variants) => variants,
|
||||
Data::Struct(_, _) => {
|
||||
return;
|
||||
}
|
||||
Data::Struct(_, _) => return,
|
||||
};
|
||||
|
||||
for variant in variants.iter() {
|
||||
for variant in variants {
|
||||
if variant.attrs.serialize_with().is_some() {
|
||||
if variant.attrs.skip_serializing() {
|
||||
cx.error_spanned_by(
|
||||
@@ -264,10 +294,9 @@ fn check_variant_skip_attrs(cx: &Ctxt, cont: &Container) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The tag of an internally-tagged struct variant must not be
|
||||
/// the same as either one of its fields, as this would result in
|
||||
/// duplicate keys in the serialized output and/or ambiguity in
|
||||
/// the to-be-deserialized input.
|
||||
// The tag of an internally-tagged struct variant must not be the same as either
|
||||
// one of its fields, as this would result in duplicate keys in the serialized
|
||||
// output and/or ambiguity in the to-be-deserialized input.
|
||||
fn check_internal_tag_field_name_conflict(cx: &Ctxt, cont: &Container) {
|
||||
let variants = match &cont.data {
|
||||
Data::Enum(variants) => variants,
|
||||
@@ -289,9 +318,14 @@ fn check_internal_tag_field_name_conflict(cx: &Ctxt, cont: &Container) {
|
||||
for variant in variants {
|
||||
match variant.style {
|
||||
Style::Struct => {
|
||||
if variant.attrs.untagged() {
|
||||
continue;
|
||||
}
|
||||
for field in &variant.fields {
|
||||
let check_ser = !field.attrs.skip_serializing();
|
||||
let check_de = !field.attrs.skip_deserializing();
|
||||
let check_ser =
|
||||
!(field.attrs.skip_serializing() || variant.attrs.skip_serializing());
|
||||
let check_de =
|
||||
!(field.attrs.skip_deserializing() || variant.attrs.skip_deserializing());
|
||||
let name = field.attrs.name();
|
||||
let ser_name = name.serialize_name();
|
||||
|
||||
@@ -313,8 +347,8 @@ fn check_internal_tag_field_name_conflict(cx: &Ctxt, cont: &Container) {
|
||||
}
|
||||
}
|
||||
|
||||
/// In the case of adjacently-tagged enums, the type and the
|
||||
/// contents tag must differ, for the same reason.
|
||||
// In the case of adjacently-tagged enums, the type and the contents tag must
|
||||
// differ, for the same reason.
|
||||
fn check_adjacent_tag_conflict(cx: &Ctxt, cont: &Container) {
|
||||
let (type_tag, content_tag) = match cont.attrs.tag() {
|
||||
TagType::Adjacent { tag, content } => (tag, content),
|
||||
@@ -332,7 +366,7 @@ fn check_adjacent_tag_conflict(cx: &Ctxt, cont: &Container) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Enums and unit structs cannot be transparent.
|
||||
// Enums and unit structs cannot be transparent.
|
||||
fn check_transparent(cx: &Ctxt, cont: &mut Container, derive: Derive) {
|
||||
if !cont.attrs.transparent() {
|
||||
return;
|
||||
|
||||
@@ -2,7 +2,6 @@ use quote::ToTokens;
|
||||
use std::cell::RefCell;
|
||||
use std::fmt::Display;
|
||||
use std::thread;
|
||||
use syn;
|
||||
|
||||
/// A type to collect errors together and format them.
|
||||
///
|
||||
@@ -44,12 +43,19 @@ impl Ctxt {
|
||||
}
|
||||
|
||||
/// Consume this object, producing a formatted error string if there are errors.
|
||||
pub fn check(self) -> Result<(), Vec<syn::Error>> {
|
||||
let errors = self.errors.borrow_mut().take().unwrap();
|
||||
match errors.len() {
|
||||
0 => Ok(()),
|
||||
_ => Err(errors),
|
||||
pub fn check(self) -> syn::Result<()> {
|
||||
let mut errors = self.errors.borrow_mut().take().unwrap().into_iter();
|
||||
|
||||
let mut combined = match errors.next() {
|
||||
Some(first) => first,
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
for rest in errors {
|
||||
combined.combine(rest);
|
||||
}
|
||||
|
||||
Err(combined)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
pub mod ast;
|
||||
pub mod attr;
|
||||
|
||||
mod ctxt;
|
||||
pub use self::ctxt::Ctxt;
|
||||
|
||||
mod receiver;
|
||||
pub use self::receiver::replace_receiver;
|
||||
|
||||
mod case;
|
||||
mod check;
|
||||
mod ctxt;
|
||||
mod receiver;
|
||||
mod respan;
|
||||
mod symbol;
|
||||
|
||||
use syn::Type;
|
||||
|
||||
pub use self::ctxt::Ctxt;
|
||||
pub use self::receiver::replace_receiver;
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub enum Derive {
|
||||
Serialize,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use internals::respan::respan;
|
||||
use crate::internals::respan::respan;
|
||||
use proc_macro2::Span;
|
||||
use quote::ToTokens;
|
||||
use std::mem;
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::{
|
||||
parse_quote, Data, DeriveInput, Expr, ExprPath, GenericArgument, GenericParam, Generics, Macro,
|
||||
Path, PathArguments, QSelf, ReturnType, Type, TypeParamBound, TypePath, WherePredicate,
|
||||
Path, PathArguments, QSelf, ReturnType, Token, Type, TypeParamBound, TypePath, WherePredicate,
|
||||
};
|
||||
|
||||
pub fn replace_receiver(input: &mut DeriveInput) {
|
||||
@@ -84,7 +84,7 @@ impl ReplaceReceiver<'_> {
|
||||
self.visit_type_mut_impl(ty);
|
||||
return;
|
||||
};
|
||||
*ty = self.self_ty(span).into();
|
||||
*ty = Type::Path(self.self_ty(span));
|
||||
}
|
||||
|
||||
// `Self::Assoc` -> `<Receiver>::Assoc`
|
||||
@@ -107,6 +107,7 @@ impl ReplaceReceiver<'_> {
|
||||
|
||||
fn visit_type_mut_impl(&mut self, ty: &mut Type) {
|
||||
match ty {
|
||||
#![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
Type::Array(ty) => {
|
||||
self.visit_type_mut(&mut ty.elem);
|
||||
self.visit_expr_mut(&mut ty.len);
|
||||
@@ -147,7 +148,6 @@ impl ReplaceReceiver<'_> {
|
||||
|
||||
Type::Infer(_) | Type::Never(_) | Type::Verbatim(_) => {}
|
||||
|
||||
#[cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -178,13 +178,13 @@ impl ReplaceReceiver<'_> {
|
||||
PathArguments::AngleBracketed(arguments) => {
|
||||
for arg in &mut arguments.args {
|
||||
match arg {
|
||||
#![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
GenericArgument::Type(arg) => self.visit_type_mut(arg),
|
||||
GenericArgument::AssocType(arg) => self.visit_type_mut(&mut arg.ty),
|
||||
GenericArgument::Lifetime(_)
|
||||
| GenericArgument::Const(_)
|
||||
| GenericArgument::AssocConst(_)
|
||||
| GenericArgument::Constraint(_) => {}
|
||||
#[cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -207,9 +207,9 @@ impl ReplaceReceiver<'_> {
|
||||
|
||||
fn visit_type_param_bound_mut(&mut self, bound: &mut TypeParamBound) {
|
||||
match bound {
|
||||
#![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
TypeParamBound::Trait(bound) => self.visit_path_mut(&mut bound.path),
|
||||
TypeParamBound::Lifetime(_) | TypeParamBound::Verbatim(_) => {}
|
||||
#[cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -228,6 +228,7 @@ impl ReplaceReceiver<'_> {
|
||||
if let Some(where_clause) = &mut generics.where_clause {
|
||||
for predicate in &mut where_clause.predicates {
|
||||
match predicate {
|
||||
#![cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
WherePredicate::Type(predicate) => {
|
||||
self.visit_type_mut(&mut predicate.bounded_ty);
|
||||
for bound in &mut predicate.bounds {
|
||||
@@ -235,7 +236,6 @@ impl ReplaceReceiver<'_> {
|
||||
}
|
||||
}
|
||||
WherePredicate::Lifetime(_) => {}
|
||||
#[cfg_attr(all(test, exhaustive), deny(non_exhaustive_omitted_patterns))]
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,10 +19,12 @@ pub const FLATTEN: Symbol = Symbol("flatten");
|
||||
pub const FROM: Symbol = Symbol("from");
|
||||
pub const GETTER: Symbol = Symbol("getter");
|
||||
pub const INTO: Symbol = Symbol("into");
|
||||
pub const NON_EXHAUSTIVE: Symbol = Symbol("non_exhaustive");
|
||||
pub const OTHER: Symbol = Symbol("other");
|
||||
pub const REMOTE: Symbol = Symbol("remote");
|
||||
pub const RENAME: Symbol = Symbol("rename");
|
||||
pub const RENAME_ALL: Symbol = Symbol("rename_all");
|
||||
pub const RENAME_ALL_FIELDS: Symbol = Symbol("rename_all_fields");
|
||||
pub const REPR: Symbol = Symbol("repr");
|
||||
pub const SERDE: Symbol = Symbol("serde");
|
||||
pub const SERIALIZE: Symbol = Symbol("serialize");
|
||||
|
||||
+8
-16
@@ -1,7 +1,7 @@
|
||||
//! This crate provides Serde's two derive macros.
|
||||
//!
|
||||
//! ```edition2018
|
||||
//! # use serde_derive::{Serialize, Deserialize};
|
||||
//! ```edition2021
|
||||
//! # use serde_derive::{Deserialize, Serialize};
|
||||
//! #
|
||||
//! #[derive(Serialize, Deserialize)]
|
||||
//! # struct S;
|
||||
@@ -13,8 +13,8 @@
|
||||
//!
|
||||
//! [https://serde.rs/derive.html]: https://serde.rs/derive.html
|
||||
|
||||
#![doc(html_root_url = "https://docs.rs/serde_derive/1.0.157")]
|
||||
#![allow(unknown_lints, bare_trait_objects)]
|
||||
#![doc(html_root_url = "https://docs.rs/serde_derive/1.0.204")]
|
||||
#![cfg_attr(not(check_cfg), allow(unexpected_cfgs))]
|
||||
// Ignored clippy lints
|
||||
#![allow(
|
||||
// clippy false positive: https://github.com/rust-lang/rust-clippy/issues/7054
|
||||
@@ -51,7 +51,6 @@
|
||||
clippy::match_wildcard_for_single_variants,
|
||||
clippy::module_name_repetitions,
|
||||
clippy::must_use_candidate,
|
||||
clippy::option_if_let_else,
|
||||
clippy::similar_names,
|
||||
clippy::single_match_else,
|
||||
clippy::struct_excessive_bools,
|
||||
@@ -63,17 +62,16 @@
|
||||
)]
|
||||
#![cfg_attr(all(test, exhaustive), feature(non_exhaustive_omitted_patterns_lint))]
|
||||
|
||||
#[macro_use]
|
||||
extern crate proc_macro2;
|
||||
extern crate quote;
|
||||
#[macro_use]
|
||||
extern crate syn;
|
||||
|
||||
extern crate proc_macro;
|
||||
extern crate proc_macro2;
|
||||
|
||||
mod internals;
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
use syn::parse_macro_input;
|
||||
use syn::DeriveInput;
|
||||
|
||||
#[macro_use]
|
||||
@@ -86,13 +84,12 @@ mod dummy;
|
||||
mod pretend;
|
||||
mod ser;
|
||||
mod this;
|
||||
mod try;
|
||||
|
||||
#[proc_macro_derive(Serialize, attributes(serde))]
|
||||
pub fn derive_serialize(input: TokenStream) -> TokenStream {
|
||||
let mut input = parse_macro_input!(input as DeriveInput);
|
||||
ser::expand_derive_serialize(&mut input)
|
||||
.unwrap_or_else(to_compile_errors)
|
||||
.unwrap_or_else(syn::Error::into_compile_error)
|
||||
.into()
|
||||
}
|
||||
|
||||
@@ -100,11 +97,6 @@ pub fn derive_serialize(input: TokenStream) -> TokenStream {
|
||||
pub fn derive_deserialize(input: TokenStream) -> TokenStream {
|
||||
let mut input = parse_macro_input!(input as DeriveInput);
|
||||
de::expand_derive_deserialize(&mut input)
|
||||
.unwrap_or_else(to_compile_errors)
|
||||
.unwrap_or_else(syn::Error::into_compile_error)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn to_compile_errors(errors: Vec<syn::Error>) -> proc_macro2::TokenStream {
|
||||
let compile_errors = errors.iter().map(syn::Error::to_compile_error);
|
||||
quote!(#(#compile_errors)*)
|
||||
}
|
||||
|
||||
+13
-29
@@ -1,7 +1,6 @@
|
||||
use crate::internals::ast::{Container, Data, Field, Style, Variant};
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::format_ident;
|
||||
|
||||
use internals::ast::{Container, Data, Field, Style, Variant};
|
||||
use quote::{format_ident, quote};
|
||||
|
||||
// Suppress dead_code warnings that would otherwise appear when using a remote
|
||||
// derive. Other than this pretend code, a struct annotated with remote derive
|
||||
@@ -65,14 +64,14 @@ pub fn pretend_used(cont: &Container, is_packed: bool) -> TokenStream {
|
||||
fn pretend_fields_used(cont: &Container, is_packed: bool) -> TokenStream {
|
||||
match &cont.data {
|
||||
Data::Enum(variants) => pretend_fields_used_enum(cont, variants),
|
||||
Data::Struct(Style::Struct, fields) => {
|
||||
Data::Struct(Style::Struct | Style::Tuple | Style::Newtype, fields) => {
|
||||
if is_packed {
|
||||
pretend_fields_used_struct_packed(cont, fields)
|
||||
} else {
|
||||
pretend_fields_used_struct(cont, fields)
|
||||
}
|
||||
}
|
||||
Data::Struct(_, _) => quote!(),
|
||||
Data::Struct(Style::Unit, _) => quote!(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,29 +96,14 @@ fn pretend_fields_used_struct_packed(cont: &Container, fields: &[Field]) -> Toke
|
||||
|
||||
let members = fields.iter().map(|field| &field.member).collect::<Vec<_>>();
|
||||
|
||||
#[cfg(not(no_ptr_addr_of))]
|
||||
{
|
||||
quote! {
|
||||
match _serde::__private::None::<&#type_ident #ty_generics> {
|
||||
_serde::__private::Some(__v @ #type_ident { #(#members: _),* }) => {
|
||||
#(
|
||||
let _ = _serde::__private::ptr::addr_of!(__v.#members);
|
||||
)*
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(no_ptr_addr_of)]
|
||||
{
|
||||
let placeholders = (0usize..).map(|i| format_ident!("__v{}", i));
|
||||
|
||||
quote! {
|
||||
match _serde::__private::None::<#type_ident #ty_generics> {
|
||||
_serde::__private::Some(#type_ident { #(#members: #placeholders),* }) => {}
|
||||
_ => {}
|
||||
quote! {
|
||||
match _serde::__private::None::<&#type_ident #ty_generics> {
|
||||
_serde::__private::Some(__v @ #type_ident { #(#members: _),* }) => {
|
||||
#(
|
||||
let _ = _serde::__private::ptr::addr_of!(__v.#members);
|
||||
)*
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -131,13 +115,13 @@ fn pretend_fields_used_enum(cont: &Container, variants: &[Variant]) -> TokenStre
|
||||
let patterns = variants
|
||||
.iter()
|
||||
.filter_map(|variant| match variant.style {
|
||||
Style::Struct => {
|
||||
Style::Struct | Style::Tuple | Style::Newtype => {
|
||||
let variant_ident = &variant.ident;
|
||||
let members = variant.fields.iter().map(|field| &field.member);
|
||||
let placeholders = (0usize..).map(|i| format_ident!("__v{}", i));
|
||||
Some(quote!(#type_ident::#variant_ident { #(#members: #placeholders),* }))
|
||||
}
|
||||
_ => None,
|
||||
Style::Unit => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
|
||||
+101
-82
@@ -1,18 +1,13 @@
|
||||
use crate::fragment::{Fragment, Match, Stmts};
|
||||
use crate::internals::ast::{Container, Data, Field, Style, Variant};
|
||||
use crate::internals::{attr, replace_receiver, Ctxt, Derive};
|
||||
use crate::{bound, dummy, pretend, this};
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use quote::{quote, quote_spanned};
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{self, Ident, Index, Member};
|
||||
use syn::{parse_quote, Ident, Index, Member};
|
||||
|
||||
use bound;
|
||||
use dummy;
|
||||
use fragment::{Fragment, Match, Stmts};
|
||||
use internals::ast::{Container, Data, Field, Style, Variant};
|
||||
use internals::{attr, replace_receiver, Ctxt, Derive};
|
||||
use pretend;
|
||||
use this;
|
||||
|
||||
pub fn expand_derive_serialize(
|
||||
input: &mut syn::DeriveInput,
|
||||
) -> Result<TokenStream, Vec<syn::Error>> {
|
||||
pub fn expand_derive_serialize(input: &mut syn::DeriveInput) -> syn::Result<TokenStream> {
|
||||
replace_receiver(input);
|
||||
|
||||
let ctxt = Ctxt::new();
|
||||
@@ -59,8 +54,6 @@ pub fn expand_derive_serialize(
|
||||
|
||||
Ok(dummy::wrap_in_const(
|
||||
cont.attrs.custom_serde_path(),
|
||||
"SERIALIZE",
|
||||
ident,
|
||||
impl_block,
|
||||
))
|
||||
}
|
||||
@@ -289,14 +282,14 @@ fn serialize_tuple_struct(
|
||||
.fold(quote!(0), |sum, expr| quote!(#sum + #expr));
|
||||
|
||||
quote_block! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple_struct(__serializer, #type_name, #len));
|
||||
let #let_mut __serde_state = _serde::Serializer::serialize_tuple_struct(__serializer, #type_name, #len)?;
|
||||
#(#serialize_stmts)*
|
||||
_serde::ser::SerializeTupleStruct::end(__serde_state)
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_struct(params: &Parameters, fields: &[Field], cattrs: &attr::Container) -> Fragment {
|
||||
assert!(fields.len() as u64 <= u64::from(u32::max_value()));
|
||||
assert!(fields.len() as u64 <= u64::from(u32::MAX));
|
||||
|
||||
if cattrs.has_flatten() {
|
||||
serialize_struct_as_map(params, fields, cattrs)
|
||||
@@ -311,7 +304,7 @@ fn serialize_struct_tag_field(cattrs: &attr::Container, struct_trait: &StructTra
|
||||
let type_name = cattrs.name().serialize_name();
|
||||
let func = struct_trait.serialize_field(Span::call_site());
|
||||
quote! {
|
||||
try!(#func(&mut __serde_state, #tag, #type_name));
|
||||
#func(&mut __serde_state, #tag, #type_name)?;
|
||||
}
|
||||
}
|
||||
_ => quote! {},
|
||||
@@ -352,7 +345,7 @@ fn serialize_struct_as_struct(
|
||||
);
|
||||
|
||||
quote_block! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct(__serializer, #type_name, #len));
|
||||
let #let_mut __serde_state = _serde::Serializer::serialize_struct(__serializer, #type_name, #len)?;
|
||||
#tag_field
|
||||
#(#serialize_fields)*
|
||||
_serde::ser::SerializeStruct::end(__serde_state)
|
||||
@@ -396,7 +389,7 @@ fn serialize_struct_as_map(
|
||||
};
|
||||
|
||||
quote_block! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_map(__serializer, #len));
|
||||
let #let_mut __serde_state = _serde::Serializer::serialize_map(__serializer, #len)?;
|
||||
#tag_field
|
||||
#(#serialize_fields)*
|
||||
_serde::ser::SerializeMap::end(__serde_state)
|
||||
@@ -404,11 +397,11 @@ fn serialize_struct_as_map(
|
||||
}
|
||||
|
||||
fn serialize_enum(params: &Parameters, variants: &[Variant], cattrs: &attr::Container) -> Fragment {
|
||||
assert!(variants.len() as u64 <= u64::from(u32::max_value()));
|
||||
assert!(variants.len() as u64 <= u64::from(u32::MAX));
|
||||
|
||||
let self_var = ¶ms.self_var;
|
||||
|
||||
let arms: Vec<_> = variants
|
||||
let mut arms: Vec<_> = variants
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(variant_index, variant)| {
|
||||
@@ -416,6 +409,12 @@ fn serialize_enum(params: &Parameters, variants: &[Variant], cattrs: &attr::Cont
|
||||
})
|
||||
.collect();
|
||||
|
||||
if cattrs.remote().is_some() && cattrs.non_exhaustive() {
|
||||
arms.push(quote! {
|
||||
ref unrecognized => _serde::__private::Err(_serde::ser::Error::custom(_serde::__private::ser::CannotSerializeVariant(unrecognized))),
|
||||
});
|
||||
}
|
||||
|
||||
quote_expr! {
|
||||
match *#self_var {
|
||||
#(#arms)*
|
||||
@@ -477,17 +476,26 @@ fn serialize_variant(
|
||||
}
|
||||
};
|
||||
|
||||
let body = Match(match cattrs.tag() {
|
||||
attr::TagType::External => {
|
||||
let body = Match(match (cattrs.tag(), variant.attrs.untagged()) {
|
||||
(attr::TagType::External, false) => {
|
||||
serialize_externally_tagged_variant(params, variant, variant_index, cattrs)
|
||||
}
|
||||
attr::TagType::Internal { tag } => {
|
||||
(attr::TagType::Internal { tag }, false) => {
|
||||
serialize_internally_tagged_variant(params, variant, cattrs, tag)
|
||||
}
|
||||
attr::TagType::Adjacent { tag, content } => {
|
||||
serialize_adjacently_tagged_variant(params, variant, cattrs, tag, content)
|
||||
(attr::TagType::Adjacent { tag, content }, false) => {
|
||||
serialize_adjacently_tagged_variant(
|
||||
params,
|
||||
variant,
|
||||
cattrs,
|
||||
variant_index,
|
||||
tag,
|
||||
content,
|
||||
)
|
||||
}
|
||||
(attr::TagType::None, _) | (_, true) => {
|
||||
serialize_untagged_variant(params, variant, cattrs)
|
||||
}
|
||||
attr::TagType::None => serialize_untagged_variant(params, variant, cattrs),
|
||||
});
|
||||
|
||||
quote! {
|
||||
@@ -564,7 +572,7 @@ fn serialize_externally_tagged_variant(
|
||||
},
|
||||
params,
|
||||
&variant.fields,
|
||||
&type_name,
|
||||
type_name,
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -598,10 +606,10 @@ fn serialize_internally_tagged_variant(
|
||||
match effective_style(variant) {
|
||||
Style::Unit => {
|
||||
quote_block! {
|
||||
let mut __struct = try!(_serde::Serializer::serialize_struct(
|
||||
__serializer, #type_name, 1));
|
||||
try!(_serde::ser::SerializeStruct::serialize_field(
|
||||
&mut __struct, #tag, #variant_name));
|
||||
let mut __struct = _serde::Serializer::serialize_struct(
|
||||
__serializer, #type_name, 1)?;
|
||||
_serde::ser::SerializeStruct::serialize_field(
|
||||
&mut __struct, #tag, #variant_name)?;
|
||||
_serde::ser::SerializeStruct::end(__struct)
|
||||
}
|
||||
}
|
||||
@@ -629,7 +637,7 @@ fn serialize_internally_tagged_variant(
|
||||
StructVariant::InternallyTagged { tag, variant_name },
|
||||
params,
|
||||
&variant.fields,
|
||||
&type_name,
|
||||
type_name,
|
||||
),
|
||||
Style::Tuple => unreachable!("checked in serde_derive_internals"),
|
||||
}
|
||||
@@ -639,12 +647,20 @@ fn serialize_adjacently_tagged_variant(
|
||||
params: &Parameters,
|
||||
variant: &Variant,
|
||||
cattrs: &attr::Container,
|
||||
variant_index: u32,
|
||||
tag: &str,
|
||||
content: &str,
|
||||
) -> Fragment {
|
||||
let this_type = ¶ms.this_type;
|
||||
let type_name = cattrs.name().serialize_name();
|
||||
let variant_name = variant.attrs.name().serialize_name();
|
||||
let serialize_variant = quote! {
|
||||
&_serde::__private::ser::AdjacentlyTaggedEnumVariant {
|
||||
enum_name: #type_name,
|
||||
variant_index: #variant_index,
|
||||
variant_name: #variant_name,
|
||||
}
|
||||
};
|
||||
|
||||
let inner = Stmts(if let Some(path) = variant.attrs.serialize_with() {
|
||||
let ser = wrap_serialize_variant_with(params, path, variant);
|
||||
@@ -655,10 +671,10 @@ fn serialize_adjacently_tagged_variant(
|
||||
match effective_style(variant) {
|
||||
Style::Unit => {
|
||||
return quote_block! {
|
||||
let mut __struct = try!(_serde::Serializer::serialize_struct(
|
||||
__serializer, #type_name, 1));
|
||||
try!(_serde::ser::SerializeStruct::serialize_field(
|
||||
&mut __struct, #tag, #variant_name));
|
||||
let mut __struct = _serde::Serializer::serialize_struct(
|
||||
__serializer, #type_name, 1)?;
|
||||
_serde::ser::SerializeStruct::serialize_field(
|
||||
&mut __struct, #tag, #serialize_variant)?;
|
||||
_serde::ser::SerializeStruct::end(__struct)
|
||||
};
|
||||
}
|
||||
@@ -672,12 +688,12 @@ fn serialize_adjacently_tagged_variant(
|
||||
let span = field.original.span();
|
||||
let func = quote_spanned!(span=> _serde::ser::SerializeStruct::serialize_field);
|
||||
return quote_block! {
|
||||
let mut __struct = try!(_serde::Serializer::serialize_struct(
|
||||
__serializer, #type_name, 2));
|
||||
try!(_serde::ser::SerializeStruct::serialize_field(
|
||||
&mut __struct, #tag, #variant_name));
|
||||
try!(#func(
|
||||
&mut __struct, #content, #field_expr));
|
||||
let mut __struct = _serde::Serializer::serialize_struct(
|
||||
__serializer, #type_name, 2)?;
|
||||
_serde::ser::SerializeStruct::serialize_field(
|
||||
&mut __struct, #tag, #serialize_variant)?;
|
||||
#func(
|
||||
&mut __struct, #content, #field_expr)?;
|
||||
_serde::ser::SerializeStruct::end(__struct)
|
||||
};
|
||||
}
|
||||
@@ -688,13 +704,13 @@ fn serialize_adjacently_tagged_variant(
|
||||
StructVariant::Untagged,
|
||||
params,
|
||||
&variant.fields,
|
||||
&variant_name,
|
||||
variant_name,
|
||||
),
|
||||
}
|
||||
});
|
||||
|
||||
let fields_ty = variant.fields.iter().map(|f| &f.ty);
|
||||
let fields_ident: &Vec<_> = &match variant.style {
|
||||
let fields_ident: &[_] = &match variant.style {
|
||||
Style::Unit => {
|
||||
if variant.attrs.serialize_with().is_some() {
|
||||
vec![]
|
||||
@@ -719,6 +735,7 @@ fn serialize_adjacently_tagged_variant(
|
||||
let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl();
|
||||
|
||||
quote_block! {
|
||||
#[doc(hidden)]
|
||||
struct __AdjacentlyTagged #wrapper_generics #where_clause {
|
||||
data: (#(&'__a #fields_ty,)*),
|
||||
phantom: _serde::__private::PhantomData<#this_type #ty_generics>,
|
||||
@@ -736,15 +753,15 @@ fn serialize_adjacently_tagged_variant(
|
||||
}
|
||||
}
|
||||
|
||||
let mut __struct = try!(_serde::Serializer::serialize_struct(
|
||||
__serializer, #type_name, 2));
|
||||
try!(_serde::ser::SerializeStruct::serialize_field(
|
||||
&mut __struct, #tag, #variant_name));
|
||||
try!(_serde::ser::SerializeStruct::serialize_field(
|
||||
let mut __struct = _serde::Serializer::serialize_struct(
|
||||
__serializer, #type_name, 2)?;
|
||||
_serde::ser::SerializeStruct::serialize_field(
|
||||
&mut __struct, #tag, #serialize_variant)?;
|
||||
_serde::ser::SerializeStruct::serialize_field(
|
||||
&mut __struct, #content, &__AdjacentlyTagged {
|
||||
data: (#(#fields_ident,)*),
|
||||
phantom: _serde::__private::PhantomData::<#this_type #ty_generics>,
|
||||
}));
|
||||
})?;
|
||||
_serde::ser::SerializeStruct::end(__struct)
|
||||
}
|
||||
}
|
||||
@@ -783,16 +800,16 @@ fn serialize_untagged_variant(
|
||||
Style::Tuple => serialize_tuple_variant(TupleVariant::Untagged, params, &variant.fields),
|
||||
Style::Struct => {
|
||||
let type_name = cattrs.name().serialize_name();
|
||||
serialize_struct_variant(StructVariant::Untagged, params, &variant.fields, &type_name)
|
||||
serialize_struct_variant(StructVariant::Untagged, params, &variant.fields, type_name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum TupleVariant {
|
||||
enum TupleVariant<'a> {
|
||||
ExternallyTagged {
|
||||
type_name: String,
|
||||
type_name: &'a str,
|
||||
variant_index: u32,
|
||||
variant_name: String,
|
||||
variant_name: &'a str,
|
||||
},
|
||||
Untagged,
|
||||
}
|
||||
@@ -834,21 +851,21 @@ fn serialize_tuple_variant(
|
||||
variant_name,
|
||||
} => {
|
||||
quote_block! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple_variant(
|
||||
let #let_mut __serde_state = _serde::Serializer::serialize_tuple_variant(
|
||||
__serializer,
|
||||
#type_name,
|
||||
#variant_index,
|
||||
#variant_name,
|
||||
#len));
|
||||
#len)?;
|
||||
#(#serialize_stmts)*
|
||||
_serde::ser::SerializeTupleVariant::end(__serde_state)
|
||||
}
|
||||
}
|
||||
TupleVariant::Untagged => {
|
||||
quote_block! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple(
|
||||
let #let_mut __serde_state = _serde::Serializer::serialize_tuple(
|
||||
__serializer,
|
||||
#len));
|
||||
#len)?;
|
||||
#(#serialize_stmts)*
|
||||
_serde::ser::SerializeTuple::end(__serde_state)
|
||||
}
|
||||
@@ -859,11 +876,11 @@ fn serialize_tuple_variant(
|
||||
enum StructVariant<'a> {
|
||||
ExternallyTagged {
|
||||
variant_index: u32,
|
||||
variant_name: String,
|
||||
variant_name: &'a str,
|
||||
},
|
||||
InternallyTagged {
|
||||
tag: &'a str,
|
||||
variant_name: String,
|
||||
variant_name: &'a str,
|
||||
},
|
||||
Untagged,
|
||||
}
|
||||
@@ -911,40 +928,40 @@ fn serialize_struct_variant(
|
||||
variant_name,
|
||||
} => {
|
||||
quote_block! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct_variant(
|
||||
let #let_mut __serde_state = _serde::Serializer::serialize_struct_variant(
|
||||
__serializer,
|
||||
#name,
|
||||
#variant_index,
|
||||
#variant_name,
|
||||
#len,
|
||||
));
|
||||
)?;
|
||||
#(#serialize_fields)*
|
||||
_serde::ser::SerializeStructVariant::end(__serde_state)
|
||||
}
|
||||
}
|
||||
StructVariant::InternallyTagged { tag, variant_name } => {
|
||||
quote_block! {
|
||||
let mut __serde_state = try!(_serde::Serializer::serialize_struct(
|
||||
let mut __serde_state = _serde::Serializer::serialize_struct(
|
||||
__serializer,
|
||||
#name,
|
||||
#len + 1,
|
||||
));
|
||||
try!(_serde::ser::SerializeStruct::serialize_field(
|
||||
)?;
|
||||
_serde::ser::SerializeStruct::serialize_field(
|
||||
&mut __serde_state,
|
||||
#tag,
|
||||
#variant_name,
|
||||
));
|
||||
)?;
|
||||
#(#serialize_fields)*
|
||||
_serde::ser::SerializeStruct::end(__serde_state)
|
||||
}
|
||||
}
|
||||
StructVariant::Untagged => {
|
||||
quote_block! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct(
|
||||
let #let_mut __serde_state = _serde::Serializer::serialize_struct(
|
||||
__serializer,
|
||||
#name,
|
||||
#len,
|
||||
));
|
||||
)?;
|
||||
#(#serialize_fields)*
|
||||
_serde::ser::SerializeStruct::end(__serde_state)
|
||||
}
|
||||
@@ -982,6 +999,7 @@ fn serialize_struct_variant_with_flatten(
|
||||
let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl();
|
||||
|
||||
quote_block! {
|
||||
#[doc(hidden)]
|
||||
struct __EnumFlatten #wrapper_generics #where_clause {
|
||||
data: (#(&'__a #fields_ty,)*),
|
||||
phantom: _serde::__private::PhantomData<#this_type #ty_generics>,
|
||||
@@ -993,9 +1011,9 @@ fn serialize_struct_variant_with_flatten(
|
||||
__S: _serde::Serializer,
|
||||
{
|
||||
let (#(#members,)*) = self.data;
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_map(
|
||||
let #let_mut __serde_state = _serde::Serializer::serialize_map(
|
||||
__serializer,
|
||||
_serde::__private::None));
|
||||
_serde::__private::None)?;
|
||||
#(#serialize_fields)*
|
||||
_serde::ser::SerializeMap::end(__serde_state)
|
||||
}
|
||||
@@ -1014,23 +1032,23 @@ fn serialize_struct_variant_with_flatten(
|
||||
}
|
||||
StructVariant::InternallyTagged { tag, variant_name } => {
|
||||
quote_block! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_map(
|
||||
let #let_mut __serde_state = _serde::Serializer::serialize_map(
|
||||
__serializer,
|
||||
_serde::__private::None));
|
||||
try!(_serde::ser::SerializeMap::serialize_entry(
|
||||
_serde::__private::None)?;
|
||||
_serde::ser::SerializeMap::serialize_entry(
|
||||
&mut __serde_state,
|
||||
#tag,
|
||||
#variant_name,
|
||||
));
|
||||
)?;
|
||||
#(#serialize_fields)*
|
||||
_serde::ser::SerializeMap::end(__serde_state)
|
||||
}
|
||||
}
|
||||
StructVariant::Untagged => {
|
||||
quote_block! {
|
||||
let #let_mut __serde_state = try!(_serde::Serializer::serialize_map(
|
||||
let #let_mut __serde_state = _serde::Serializer::serialize_map(
|
||||
__serializer,
|
||||
_serde::__private::None));
|
||||
_serde::__private::None)?;
|
||||
#(#serialize_fields)*
|
||||
_serde::ser::SerializeMap::end(__serde_state)
|
||||
}
|
||||
@@ -1075,7 +1093,7 @@ fn serialize_tuple_struct_visitor(
|
||||
let span = field.original.span();
|
||||
let func = tuple_trait.serialize_element(span);
|
||||
let ser = quote! {
|
||||
try!(#func(&mut __serde_state, #field_expr));
|
||||
#func(&mut __serde_state, #field_expr)?;
|
||||
};
|
||||
|
||||
match skip {
|
||||
@@ -1119,12 +1137,12 @@ fn serialize_struct_visitor(
|
||||
let ser = if field.attrs.flatten() {
|
||||
let func = quote_spanned!(span=> _serde::Serialize::serialize);
|
||||
quote! {
|
||||
try!(#func(&#field_expr, _serde::__private::ser::FlatMapSerializer(&mut __serde_state)));
|
||||
#func(&#field_expr, _serde::__private::ser::FlatMapSerializer(&mut __serde_state))?;
|
||||
}
|
||||
} else {
|
||||
let func = struct_trait.serialize_field(span);
|
||||
quote! {
|
||||
try!(#func(&mut __serde_state, #key_expr, #field_expr));
|
||||
#func(&mut __serde_state, #key_expr, #field_expr)?;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1136,7 +1154,7 @@ fn serialize_struct_visitor(
|
||||
if !#skip {
|
||||
#ser
|
||||
} else {
|
||||
try!(#skip_func(&mut __serde_state, #key_expr));
|
||||
#skip_func(&mut __serde_state, #key_expr)?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -1212,6 +1230,7 @@ fn wrap_serialize_with(
|
||||
});
|
||||
|
||||
quote!({
|
||||
#[doc(hidden)]
|
||||
struct __SerializeWith #wrapper_impl_generics #where_clause {
|
||||
values: (#(&'__a #field_tys, )*),
|
||||
phantom: _serde::__private::PhantomData<#this_type #ty_generics>,
|
||||
@@ -1235,7 +1254,7 @@ fn wrap_serialize_with(
|
||||
|
||||
// Serialization of an empty struct results in code like:
|
||||
//
|
||||
// let mut __serde_state = try!(serializer.serialize_struct("S", 0));
|
||||
// let mut __serde_state = serializer.serialize_struct("S", 0)?;
|
||||
// _serde::ser::SerializeStruct::end(__serde_state)
|
||||
//
|
||||
// where we want to omit the `mut` to avoid a warning.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use internals::ast::Container;
|
||||
use crate::internals::ast::Container;
|
||||
use syn::{Path, PathArguments, Token};
|
||||
|
||||
pub fn this_type(cont: &Container) -> Path {
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
use proc_macro2::{Punct, Spacing, TokenStream};
|
||||
|
||||
// None of our generated code requires the `From::from` error conversion
|
||||
// performed by the standard library's `try!` macro. With this simplified macro
|
||||
// we see a significant improvement in type checking and borrow checking time of
|
||||
// the generated code and a slight improvement in binary size.
|
||||
pub fn replacement() -> TokenStream {
|
||||
// Cannot pass `$expr` to `quote!` prior to Rust 1.17.0 so interpolate it.
|
||||
let dollar = Punct::new('$', Spacing::Alone);
|
||||
|
||||
quote! {
|
||||
#[allow(unused_macros)]
|
||||
macro_rules! try {
|
||||
(#dollar __expr:expr) => {
|
||||
match #dollar __expr {
|
||||
_serde::__private::Ok(__val) => __val,
|
||||
_serde::__private::Err(__err) => {
|
||||
return _serde::__private::Err(__err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
msrv = "1.31.0"
|
||||
@@ -1,11 +1,12 @@
|
||||
[package]
|
||||
name = "serde_derive_internals"
|
||||
version = "0.26.0" # remember to update html_root_url
|
||||
version = "0.29.1"
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"]
|
||||
description = "AST representation used by Serde derive macros. Unstable."
|
||||
documentation = "https://docs.rs/serde_derive_internals"
|
||||
edition = "2015"
|
||||
exclude = ["build.rs"]
|
||||
homepage = "https://serde.rs"
|
||||
include = ["lib.rs", "src/**/*.rs", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
keywords = ["serde", "serialization"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
@@ -15,9 +16,10 @@ rust-version = "1.56"
|
||||
path = "lib.rs"
|
||||
|
||||
[dependencies]
|
||||
proc-macro2 = "1.0"
|
||||
quote = "1.0"
|
||||
syn = { version = "2.0", default-features = false, features = ["derive", "parsing", "printing", "clone-impls"] }
|
||||
proc-macro2 = { workspace = true }
|
||||
quote = { workspace = true }
|
||||
syn = { workspace = true, features = ["clone-impls", "derive", "parsing", "printing"] }
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
rustdoc-args = ["--generate-link-to-definition"]
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
use std::path::Path;
|
||||
|
||||
fn main() {
|
||||
// Warning: build.rs is not published to crates.io.
|
||||
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo:rerun-if-changed=src/mod.rs");
|
||||
|
||||
println!("cargo:rustc-cfg=check_cfg");
|
||||
println!("cargo:rustc-check-cfg=cfg(check_cfg)");
|
||||
println!("cargo:rustc-check-cfg=cfg(exhaustive)");
|
||||
println!("cargo:rustc-check-cfg=cfg(serde_build_from_git)");
|
||||
println!("cargo:rustc-check-cfg=cfg(feature, values(\"deserialize_in_place\"))");
|
||||
|
||||
// Sometimes on Windows the git checkout does not correctly wire up the
|
||||
// symlink from serde_derive_internals/src to serde_derive/src/internals.
|
||||
// When this happens we'll just build based on relative paths within the git
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#![doc(html_root_url = "https://docs.rs/serde_derive_internals/0.26.0")]
|
||||
#![allow(unknown_lints, bare_trait_objects)]
|
||||
#![doc(html_root_url = "https://docs.rs/serde_derive_internals/0.29.1")]
|
||||
#![cfg_attr(not(check_cfg), allow(unexpected_cfgs))]
|
||||
// Ignored clippy lints
|
||||
#![allow(
|
||||
clippy::cognitive_complexity,
|
||||
@@ -30,6 +30,7 @@
|
||||
clippy::missing_errors_doc,
|
||||
clippy::module_name_repetitions,
|
||||
clippy::must_use_candidate,
|
||||
clippy::return_self_not_must_use,
|
||||
clippy::similar_names,
|
||||
clippy::single_match_else,
|
||||
clippy::struct_excessive_bools,
|
||||
@@ -38,11 +39,9 @@
|
||||
clippy::wildcard_imports
|
||||
)]
|
||||
|
||||
#[macro_use]
|
||||
extern crate syn;
|
||||
|
||||
extern crate proc_macro2;
|
||||
extern crate quote;
|
||||
extern crate syn;
|
||||
|
||||
#[cfg_attr(serde_build_from_git, path = "../serde_derive/src/internals/mod.rs")]
|
||||
#[cfg_attr(not(serde_build_from_git), path = "src/mod.rs")]
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
msrv = "1.13.0"
|
||||
@@ -1,28 +0,0 @@
|
||||
[package]
|
||||
name = "serde_test"
|
||||
version = "1.0.157" # remember to update html_root_url
|
||||
authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"]
|
||||
build = "build.rs"
|
||||
categories = ["development-tools::testing"]
|
||||
description = "Token De/Serializer for testing De/Serialize implementations"
|
||||
documentation = "https://docs.rs/serde_test"
|
||||
homepage = "https://serde.rs"
|
||||
include = ["build.rs", "src/**/*.rs", "crates-io.md", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
|
||||
keywords = ["serde", "serialization", "testing", "dev-dependencies"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
readme = "crates-io.md"
|
||||
repository = "https://github.com/serde-rs/serde"
|
||||
rust-version = "1.19"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0.60", path = "../serde" }
|
||||
|
||||
[dev-dependencies]
|
||||
serde = { version = "1.0", path = "../serde" }
|
||||
serde_derive = { version = "1.0", path = "../serde_derive" }
|
||||
|
||||
[lib]
|
||||
doc-scrape-examples = false
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
@@ -1 +0,0 @@
|
||||
../LICENSE-APACHE
|
||||
@@ -1 +0,0 @@
|
||||
../LICENSE-MIT
|
||||
@@ -1 +0,0 @@
|
||||
../README.md
|
||||
@@ -1,50 +0,0 @@
|
||||
use std::env;
|
||||
use std::process::Command;
|
||||
use std::str::{self, FromStr};
|
||||
|
||||
// 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");
|
||||
|
||||
let minor = match rustc_minor_version() {
|
||||
Some(minor) => minor,
|
||||
None => return,
|
||||
};
|
||||
|
||||
// #[track_caller] stabilized in Rust 1.46:
|
||||
// https://blog.rust-lang.org/2020/08/27/Rust-1.46.0.html#track_caller
|
||||
if minor < 46 {
|
||||
println!("cargo:rustc-cfg=no_track_caller");
|
||||
}
|
||||
}
|
||||
|
||||
fn rustc_minor_version() -> Option<u32> {
|
||||
let rustc = match env::var_os("RUSTC") {
|
||||
Some(rustc) => rustc,
|
||||
None => return None,
|
||||
};
|
||||
|
||||
let output = match Command::new(rustc).arg("--version").output() {
|
||||
Ok(output) => output,
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
||||
let version = match str::from_utf8(&output.stdout) {
|
||||
Ok(version) => version,
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
||||
let mut pieces = version.split('.');
|
||||
if pieces.next() != Some("rustc 1") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let next = match pieces.next() {
|
||||
Some(next) => next,
|
||||
None => return None,
|
||||
};
|
||||
|
||||
u32::from_str(next).ok()
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
../crates-io.md
|
||||
@@ -1,223 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use de::Deserializer;
|
||||
use ser::Serializer;
|
||||
use token::Token;
|
||||
|
||||
use std::fmt::Debug;
|
||||
|
||||
/// Runs both `assert_ser_tokens` and `assert_de_tokens`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::{Serialize, Deserialize};
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
/// struct S {
|
||||
/// a: u8,
|
||||
/// b: u8,
|
||||
/// }
|
||||
///
|
||||
/// let s = S { a: 0, b: 0 };
|
||||
/// assert_tokens(&s, &[
|
||||
/// Token::Struct { name: "S", len: 2 },
|
||||
/// Token::Str("a"),
|
||||
/// Token::U8(0),
|
||||
/// Token::Str("b"),
|
||||
/// Token::U8(0),
|
||||
/// Token::StructEnd,
|
||||
/// ]);
|
||||
/// ```
|
||||
#[cfg_attr(not(no_track_caller), track_caller)]
|
||||
pub fn assert_tokens<'de, T>(value: &T, tokens: &'de [Token])
|
||||
where
|
||||
T: Serialize + Deserialize<'de> + PartialEq + Debug,
|
||||
{
|
||||
assert_ser_tokens(value, tokens);
|
||||
assert_de_tokens(value, tokens);
|
||||
}
|
||||
|
||||
/// Asserts that `value` serializes to the given `tokens`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::{Serialize, Deserialize};
|
||||
/// # use serde_test::{assert_ser_tokens, Token};
|
||||
/// #
|
||||
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
/// struct S {
|
||||
/// a: u8,
|
||||
/// b: u8,
|
||||
/// }
|
||||
///
|
||||
/// let s = S { a: 0, b: 0 };
|
||||
/// assert_ser_tokens(&s, &[
|
||||
/// Token::Struct { name: "S", len: 2 },
|
||||
/// Token::Str("a"),
|
||||
/// Token::U8(0),
|
||||
/// Token::Str("b"),
|
||||
/// Token::U8(0),
|
||||
/// Token::StructEnd,
|
||||
/// ]);
|
||||
/// ```
|
||||
#[cfg_attr(not(no_track_caller), track_caller)]
|
||||
pub fn assert_ser_tokens<T: ?Sized>(value: &T, tokens: &[Token])
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
let mut ser = Serializer::new(tokens);
|
||||
match value.serialize(&mut ser) {
|
||||
Ok(_) => {}
|
||||
Err(err) => panic!("value failed to serialize: {}", err),
|
||||
}
|
||||
|
||||
if ser.remaining() > 0 {
|
||||
panic!("{} remaining tokens", ser.remaining());
|
||||
}
|
||||
}
|
||||
|
||||
/// Asserts that `value` serializes to the given `tokens`, and then yields
|
||||
/// `error`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// use std::sync::{Arc, Mutex};
|
||||
/// use std::thread;
|
||||
///
|
||||
/// use serde::Serialize;
|
||||
/// use serde_test::{assert_ser_tokens_error, Token};
|
||||
///
|
||||
/// #[derive(Serialize)]
|
||||
/// struct Example {
|
||||
/// lock: Arc<Mutex<u32>>,
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let example = Example { lock: Arc::new(Mutex::new(0)) };
|
||||
/// let lock = example.lock.clone();
|
||||
///
|
||||
/// let _ = thread::spawn(move || {
|
||||
/// // This thread will acquire the mutex first, unwrapping the result
|
||||
/// // of `lock` because the lock has not been poisoned.
|
||||
/// let _guard = lock.lock().unwrap();
|
||||
///
|
||||
/// // This panic while holding the lock (`_guard` is in scope) will
|
||||
/// // poison the mutex.
|
||||
/// panic!()
|
||||
/// }).join();
|
||||
///
|
||||
/// let expected = &[
|
||||
/// Token::Struct { name: "Example", len: 1 },
|
||||
/// Token::Str("lock"),
|
||||
/// ];
|
||||
/// let error = "lock poison error while serializing";
|
||||
/// assert_ser_tokens_error(&example, expected, error);
|
||||
/// }
|
||||
/// ```
|
||||
#[cfg_attr(not(no_track_caller), track_caller)]
|
||||
pub fn assert_ser_tokens_error<T: ?Sized>(value: &T, tokens: &[Token], error: &str)
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
let mut ser = Serializer::new(tokens);
|
||||
match value.serialize(&mut ser) {
|
||||
Ok(_) => panic!("value serialized successfully"),
|
||||
Err(e) => assert_eq!(e, *error),
|
||||
}
|
||||
|
||||
if ser.remaining() > 0 {
|
||||
panic!("{} remaining tokens", ser.remaining());
|
||||
}
|
||||
}
|
||||
|
||||
/// Asserts that the given `tokens` deserialize into `value`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::{Serialize, Deserialize};
|
||||
/// # use serde_test::{assert_de_tokens, Token};
|
||||
/// #
|
||||
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
/// struct S {
|
||||
/// a: u8,
|
||||
/// b: u8,
|
||||
/// }
|
||||
///
|
||||
/// let s = S { a: 0, b: 0 };
|
||||
/// assert_de_tokens(&s, &[
|
||||
/// Token::Struct { name: "S", len: 2 },
|
||||
/// Token::Str("a"),
|
||||
/// Token::U8(0),
|
||||
/// Token::Str("b"),
|
||||
/// Token::U8(0),
|
||||
/// Token::StructEnd,
|
||||
/// ]);
|
||||
/// ```
|
||||
#[cfg_attr(not(no_track_caller), track_caller)]
|
||||
pub fn assert_de_tokens<'de, T>(value: &T, tokens: &'de [Token])
|
||||
where
|
||||
T: Deserialize<'de> + PartialEq + Debug,
|
||||
{
|
||||
let mut de = Deserializer::new(tokens);
|
||||
let mut deserialized_val = match T::deserialize(&mut de) {
|
||||
Ok(v) => {
|
||||
assert_eq!(v, *value);
|
||||
v
|
||||
}
|
||||
Err(e) => panic!("tokens failed to deserialize: {}", e),
|
||||
};
|
||||
if de.remaining() > 0 {
|
||||
panic!("{} remaining tokens", de.remaining());
|
||||
}
|
||||
|
||||
// Do the same thing for deserialize_in_place. This isn't *great* because a
|
||||
// no-op impl of deserialize_in_place can technically succeed here. Still,
|
||||
// this should catch a lot of junk.
|
||||
let mut de = Deserializer::new(tokens);
|
||||
match T::deserialize_in_place(&mut de, &mut deserialized_val) {
|
||||
Ok(()) => {
|
||||
assert_eq!(deserialized_val, *value);
|
||||
}
|
||||
Err(e) => panic!("tokens failed to deserialize_in_place: {}", e),
|
||||
}
|
||||
if de.remaining() > 0 {
|
||||
panic!("{} remaining tokens", de.remaining());
|
||||
}
|
||||
}
|
||||
|
||||
/// Asserts that the given `tokens` yield `error` when deserializing.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::{Serialize, Deserialize};
|
||||
/// # use serde_test::{assert_de_tokens_error, Token};
|
||||
/// #
|
||||
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
/// #[serde(deny_unknown_fields)]
|
||||
/// struct S {
|
||||
/// a: u8,
|
||||
/// b: u8,
|
||||
/// }
|
||||
///
|
||||
/// assert_de_tokens_error::<S>(
|
||||
/// &[
|
||||
/// Token::Struct { name: "S", len: 2 },
|
||||
/// Token::Str("x"),
|
||||
/// ],
|
||||
/// "unknown field `x`, expected `a` or `b`",
|
||||
/// );
|
||||
/// ```
|
||||
#[cfg_attr(not(no_track_caller), track_caller)]
|
||||
pub fn assert_de_tokens_error<'de, T>(tokens: &'de [Token], error: &str)
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
let mut de = Deserializer::new(tokens);
|
||||
match T::deserialize(&mut de) {
|
||||
Ok(_) => panic!("tokens deserialized successfully"),
|
||||
Err(e) => assert_eq!(e, *error),
|
||||
}
|
||||
|
||||
// There may be one token left if a peek caused the error
|
||||
de.next_token_opt();
|
||||
|
||||
if de.remaining() > 0 {
|
||||
panic!("{} remaining tokens", de.remaining());
|
||||
}
|
||||
}
|
||||
@@ -1,847 +0,0 @@
|
||||
use std::fmt;
|
||||
|
||||
use serde::ser::{
|
||||
SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
|
||||
SerializeTupleStruct, SerializeTupleVariant,
|
||||
};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct Readable<T: ?Sized>(T);
|
||||
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct Compact<T: ?Sized>(T);
|
||||
|
||||
/// Trait to determine whether a value is represented in human-readable or
|
||||
/// compact form.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
/// use serde_test::{assert_tokens, Configure, Token};
|
||||
///
|
||||
/// #[derive(Debug, PartialEq)]
|
||||
/// struct Example(u8, u8);
|
||||
///
|
||||
/// impl Serialize for Example {
|
||||
/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
/// where
|
||||
/// S: Serializer,
|
||||
/// {
|
||||
/// if serializer.is_human_readable() {
|
||||
/// format!("{}.{}", self.0, self.1).serialize(serializer)
|
||||
/// } else {
|
||||
/// (self.0, self.1).serialize(serializer)
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// impl<'de> Deserialize<'de> for Example {
|
||||
/// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
/// where
|
||||
/// D: Deserializer<'de>,
|
||||
/// {
|
||||
/// use serde::de::Error;
|
||||
/// if deserializer.is_human_readable() {
|
||||
/// let s = String::deserialize(deserializer)?;
|
||||
/// let parts: Vec<_> = s.split('.').collect();
|
||||
/// Ok(Example(
|
||||
/// parts[0].parse().map_err(D::Error::custom)?,
|
||||
/// parts[1].parse().map_err(D::Error::custom)?,
|
||||
/// ))
|
||||
/// } else {
|
||||
/// let (x, y) = Deserialize::deserialize(deserializer)?;
|
||||
/// Ok(Example(x, y))
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// assert_tokens(
|
||||
/// &Example(1, 0).compact(),
|
||||
/// &[
|
||||
/// Token::Tuple { len: 2 },
|
||||
/// Token::U8(1),
|
||||
/// Token::U8(0),
|
||||
/// Token::TupleEnd,
|
||||
/// ],
|
||||
/// );
|
||||
/// assert_tokens(&Example(1, 0).readable(), &[Token::Str("1.0")]);
|
||||
/// }
|
||||
/// ```
|
||||
pub trait Configure {
|
||||
/// Marks `self` as using `is_human_readable == true`
|
||||
fn readable(self) -> Readable<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Readable(self)
|
||||
}
|
||||
/// Marks `self` as using `is_human_readable == false`
|
||||
fn compact(self) -> Compact<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Compact(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ?Sized> Configure for T {}
|
||||
|
||||
impl<T: ?Sized> Serialize for Readable<T>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
self.0.serialize(Readable(serializer))
|
||||
}
|
||||
}
|
||||
impl<T: ?Sized> Serialize for Compact<T>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
#[inline]
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
self.0.serialize(Compact(serializer))
|
||||
}
|
||||
}
|
||||
impl<'de, T> Deserialize<'de> for Readable<T>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
T::deserialize(Readable(deserializer)).map(Readable)
|
||||
}
|
||||
}
|
||||
impl<'de, T> Deserialize<'de> for Compact<T>
|
||||
where
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
T::deserialize(Compact(deserializer)).map(Compact)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, T> DeserializeSeed<'de> for Readable<T>
|
||||
where
|
||||
T: DeserializeSeed<'de>,
|
||||
{
|
||||
type Value = T::Value;
|
||||
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
self.0.deserialize(Readable(deserializer))
|
||||
}
|
||||
}
|
||||
impl<'de, T> DeserializeSeed<'de> for Compact<T>
|
||||
where
|
||||
T: DeserializeSeed<'de>,
|
||||
{
|
||||
type Value = T::Value;
|
||||
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
self.0.deserialize(Compact(deserializer))
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! forward_method {
|
||||
($name: ident (self $(, $arg: ident : $arg_type: ty)* ) -> $return_type: ty) => {
|
||||
fn $name (self $(, $arg : $arg_type)* ) -> $return_type {
|
||||
(self.0).$name( $($arg),* )
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! forward_serialize_methods {
|
||||
( $( $name: ident $arg_type: ty ),* ) => {
|
||||
$(
|
||||
forward_method!($name(self, v : $arg_type) -> Result<Self::Ok, Self::Error>);
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! impl_serializer {
|
||||
($wrapper:ident, $is_human_readable:expr) => {
|
||||
impl<S> Serializer for $wrapper<S>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
|
||||
type SerializeSeq = $wrapper<S::SerializeSeq>;
|
||||
type SerializeTuple = $wrapper<S::SerializeTuple>;
|
||||
type SerializeTupleStruct = $wrapper<S::SerializeTupleStruct>;
|
||||
type SerializeTupleVariant = $wrapper<S::SerializeTupleVariant>;
|
||||
type SerializeMap = $wrapper<S::SerializeMap>;
|
||||
type SerializeStruct = $wrapper<S::SerializeStruct>;
|
||||
type SerializeStructVariant = $wrapper<S::SerializeStructVariant>;
|
||||
|
||||
fn is_human_readable(&self) -> bool {
|
||||
$is_human_readable
|
||||
}
|
||||
|
||||
forward_serialize_methods! {
|
||||
serialize_bool bool,
|
||||
serialize_i8 i8,
|
||||
serialize_i16 i16,
|
||||
serialize_i32 i32,
|
||||
serialize_i64 i64,
|
||||
serialize_u8 u8,
|
||||
serialize_u16 u16,
|
||||
serialize_u32 u32,
|
||||
serialize_u64 u64,
|
||||
serialize_f32 f32,
|
||||
serialize_f64 f64,
|
||||
serialize_char char,
|
||||
serialize_str &str,
|
||||
serialize_bytes &[u8],
|
||||
serialize_unit_struct &'static str
|
||||
|
||||
}
|
||||
|
||||
fn serialize_unit(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize_unit()
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: u32,
|
||||
variant: &'static str,
|
||||
) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize_unit_variant(name, variant_index, variant)
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized>(
|
||||
self,
|
||||
name: &'static str,
|
||||
value: &T,
|
||||
) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_newtype_struct(name, &$wrapper(value))
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: ?Sized>(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: u32,
|
||||
variant: &'static str,
|
||||
value: &T,
|
||||
) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0
|
||||
.serialize_newtype_variant(name, variant_index, variant, &$wrapper(value))
|
||||
}
|
||||
|
||||
fn serialize_none(self) -> Result<S::Ok, Self::Error> {
|
||||
self.0.serialize_none()
|
||||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<S::Ok, Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_some(&$wrapper(value))
|
||||
}
|
||||
|
||||
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
|
||||
self.0.serialize_seq(len).map($wrapper)
|
||||
}
|
||||
|
||||
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
|
||||
self.0.serialize_tuple(len).map($wrapper)
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(
|
||||
self,
|
||||
name: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTupleStruct, Self::Error> {
|
||||
self.0.serialize_tuple_struct(name, len).map($wrapper)
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: u32,
|
||||
variant: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTupleVariant, Self::Error> {
|
||||
self.0
|
||||
.serialize_tuple_variant(name, variant_index, variant, len)
|
||||
.map($wrapper)
|
||||
}
|
||||
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
|
||||
self.0.serialize_map(len).map($wrapper)
|
||||
}
|
||||
|
||||
fn serialize_struct(
|
||||
self,
|
||||
name: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStruct, Self::Error> {
|
||||
self.0.serialize_struct(name, len).map($wrapper)
|
||||
}
|
||||
|
||||
fn serialize_struct_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
variant_index: u32,
|
||||
variant: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStructVariant, Self::Error> {
|
||||
self.0
|
||||
.serialize_struct_variant(name, variant_index, variant, len)
|
||||
.map($wrapper)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SerializeSeq for $wrapper<S>
|
||||
where
|
||||
S: SerializeSeq,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_element(&$wrapper(value))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SerializeTuple for $wrapper<S>
|
||||
where
|
||||
S: SerializeTuple,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_element(&$wrapper(value))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SerializeTupleStruct for $wrapper<S>
|
||||
where
|
||||
S: SerializeTupleStruct,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_field(&$wrapper(value))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SerializeTupleVariant for $wrapper<S>
|
||||
where
|
||||
S: SerializeTupleVariant,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_field(&$wrapper(value))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SerializeMap for $wrapper<S>
|
||||
where
|
||||
S: SerializeMap,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_key(&$wrapper(key))
|
||||
}
|
||||
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_value(&$wrapper(value))
|
||||
}
|
||||
fn serialize_entry<K: ?Sized, V: ?Sized>(
|
||||
&mut self,
|
||||
key: &K,
|
||||
value: &V,
|
||||
) -> Result<(), S::Error>
|
||||
where
|
||||
K: Serialize,
|
||||
V: Serialize,
|
||||
{
|
||||
self.0.serialize_entry(key, &$wrapper(value))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SerializeStruct for $wrapper<S>
|
||||
where
|
||||
S: SerializeStruct,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_field<T: ?Sized>(
|
||||
&mut self,
|
||||
name: &'static str,
|
||||
field: &T,
|
||||
) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_field(name, &$wrapper(field))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SerializeStructVariant for $wrapper<S>
|
||||
where
|
||||
S: SerializeStructVariant,
|
||||
{
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_field<T: ?Sized>(
|
||||
&mut self,
|
||||
name: &'static str,
|
||||
field: &T,
|
||||
) -> Result<(), S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
self.0.serialize_field(name, &$wrapper(field))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl_serializer!(Readable, true);
|
||||
impl_serializer!(Compact, false);
|
||||
|
||||
use serde::de::{DeserializeSeed, EnumAccess, Error, MapAccess, SeqAccess, VariantAccess, Visitor};
|
||||
|
||||
macro_rules! forward_deserialize_methods {
|
||||
( $wrapper : ident ( $( $name: ident ),* ) ) => {
|
||||
$(
|
||||
fn $name<V>(self, visitor: V) -> Result<V::Value, D::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
(self.0).$name($wrapper(visitor))
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! impl_deserializer {
|
||||
($wrapper:ident, $is_human_readable:expr) => {
|
||||
impl<'de, D> Deserializer<'de> for $wrapper<D>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
type Error = D::Error;
|
||||
|
||||
forward_deserialize_methods! {
|
||||
$wrapper (
|
||||
deserialize_any,
|
||||
deserialize_bool,
|
||||
deserialize_u8,
|
||||
deserialize_u16,
|
||||
deserialize_u32,
|
||||
deserialize_u64,
|
||||
deserialize_i8,
|
||||
deserialize_i16,
|
||||
deserialize_i32,
|
||||
deserialize_i64,
|
||||
deserialize_f32,
|
||||
deserialize_f64,
|
||||
deserialize_char,
|
||||
deserialize_str,
|
||||
deserialize_string,
|
||||
deserialize_bytes,
|
||||
deserialize_byte_buf,
|
||||
deserialize_option,
|
||||
deserialize_unit,
|
||||
deserialize_seq,
|
||||
deserialize_map,
|
||||
deserialize_identifier,
|
||||
deserialize_ignored_any
|
||||
)
|
||||
}
|
||||
|
||||
fn deserialize_unit_struct<V>(
|
||||
self,
|
||||
name: &'static str,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, D::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
self.0.deserialize_unit_struct(name, $wrapper(visitor))
|
||||
}
|
||||
fn deserialize_newtype_struct<V>(
|
||||
self,
|
||||
name: &'static str,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, D::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
self.0.deserialize_newtype_struct(name, $wrapper(visitor))
|
||||
}
|
||||
fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, D::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
self.0.deserialize_tuple(len, $wrapper(visitor))
|
||||
}
|
||||
fn deserialize_tuple_struct<V>(
|
||||
self,
|
||||
name: &'static str,
|
||||
len: usize,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, D::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
self.0
|
||||
.deserialize_tuple_struct(name, len, $wrapper(visitor))
|
||||
}
|
||||
fn deserialize_struct<V>(
|
||||
self,
|
||||
name: &'static str,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, D::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
self.0.deserialize_struct(name, fields, $wrapper(visitor))
|
||||
}
|
||||
fn deserialize_enum<V>(
|
||||
self,
|
||||
name: &'static str,
|
||||
variants: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, D::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
self.0.deserialize_enum(name, variants, $wrapper(visitor))
|
||||
}
|
||||
|
||||
fn is_human_readable(&self) -> bool {
|
||||
$is_human_readable
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, D> Visitor<'de> for $wrapper<D>
|
||||
where
|
||||
D: Visitor<'de>,
|
||||
{
|
||||
type Value = D::Value;
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.0.expecting(formatter)
|
||||
}
|
||||
fn visit_bool<E>(self, v: bool) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_bool(v)
|
||||
}
|
||||
fn visit_i8<E>(self, v: i8) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_i8(v)
|
||||
}
|
||||
fn visit_i16<E>(self, v: i16) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_i16(v)
|
||||
}
|
||||
fn visit_i32<E>(self, v: i32) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_i32(v)
|
||||
}
|
||||
fn visit_i64<E>(self, v: i64) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_i64(v)
|
||||
}
|
||||
fn visit_u8<E>(self, v: u8) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_u8(v)
|
||||
}
|
||||
fn visit_u16<E>(self, v: u16) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_u16(v)
|
||||
}
|
||||
fn visit_u32<E>(self, v: u32) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_u32(v)
|
||||
}
|
||||
fn visit_u64<E>(self, v: u64) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_u64(v)
|
||||
}
|
||||
fn visit_f32<E>(self, v: f32) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_f32(v)
|
||||
}
|
||||
fn visit_f64<E>(self, v: f64) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_f64(v)
|
||||
}
|
||||
fn visit_char<E>(self, v: char) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_char(v)
|
||||
}
|
||||
fn visit_str<E>(self, v: &str) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_str(v)
|
||||
}
|
||||
fn visit_borrowed_str<E>(self, v: &'de str) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_borrowed_str(v)
|
||||
}
|
||||
fn visit_string<E>(self, v: String) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_string(v)
|
||||
}
|
||||
fn visit_bytes<E>(self, v: &[u8]) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_bytes(v)
|
||||
}
|
||||
fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_borrowed_bytes(v)
|
||||
}
|
||||
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_byte_buf(v)
|
||||
}
|
||||
fn visit_none<E>(self) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_none()
|
||||
}
|
||||
fn visit_some<D2>(self, deserializer: D2) -> Result<Self::Value, D2::Error>
|
||||
where
|
||||
D2: Deserializer<'de>,
|
||||
{
|
||||
self.0.visit_some($wrapper(deserializer))
|
||||
}
|
||||
fn visit_unit<E>(self) -> Result<D::Value, E>
|
||||
where
|
||||
E: Error,
|
||||
{
|
||||
self.0.visit_unit()
|
||||
}
|
||||
fn visit_newtype_struct<D2>(self, deserializer: D2) -> Result<Self::Value, D2::Error>
|
||||
where
|
||||
D2: Deserializer<'de>,
|
||||
{
|
||||
self.0.visit_newtype_struct($wrapper(deserializer))
|
||||
}
|
||||
fn visit_seq<V>(self, seq: V) -> Result<D::Value, V::Error>
|
||||
where
|
||||
V: SeqAccess<'de>,
|
||||
{
|
||||
self.0.visit_seq($wrapper(seq))
|
||||
}
|
||||
fn visit_map<V>(self, map: V) -> Result<D::Value, V::Error>
|
||||
where
|
||||
V: MapAccess<'de>,
|
||||
{
|
||||
self.0.visit_map($wrapper(map))
|
||||
}
|
||||
fn visit_enum<V>(self, data: V) -> Result<D::Value, V::Error>
|
||||
where
|
||||
V: EnumAccess<'de>,
|
||||
{
|
||||
self.0.visit_enum($wrapper(data))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, D> SeqAccess<'de> for $wrapper<D>
|
||||
where
|
||||
D: SeqAccess<'de>,
|
||||
{
|
||||
type Error = D::Error;
|
||||
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, D::Error>
|
||||
where
|
||||
T: DeserializeSeed<'de>,
|
||||
{
|
||||
self.0.next_element_seed($wrapper(seed))
|
||||
}
|
||||
fn size_hint(&self) -> Option<usize> {
|
||||
self.0.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, D> MapAccess<'de> for $wrapper<D>
|
||||
where
|
||||
D: MapAccess<'de>,
|
||||
{
|
||||
type Error = D::Error;
|
||||
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, D::Error>
|
||||
where
|
||||
K: DeserializeSeed<'de>,
|
||||
{
|
||||
self.0.next_key_seed($wrapper(seed))
|
||||
}
|
||||
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, D::Error>
|
||||
where
|
||||
V: DeserializeSeed<'de>,
|
||||
{
|
||||
self.0.next_value_seed($wrapper(seed))
|
||||
}
|
||||
fn next_entry_seed<K, V>(
|
||||
&mut self,
|
||||
kseed: K,
|
||||
vseed: V,
|
||||
) -> Result<Option<(K::Value, V::Value)>, D::Error>
|
||||
where
|
||||
K: DeserializeSeed<'de>,
|
||||
V: DeserializeSeed<'de>,
|
||||
{
|
||||
self.0.next_entry_seed($wrapper(kseed), $wrapper(vseed))
|
||||
}
|
||||
fn size_hint(&self) -> Option<usize> {
|
||||
self.0.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, D> EnumAccess<'de> for $wrapper<D>
|
||||
where
|
||||
D: EnumAccess<'de>,
|
||||
{
|
||||
type Error = D::Error;
|
||||
type Variant = $wrapper<D::Variant>;
|
||||
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
|
||||
where
|
||||
V: DeserializeSeed<'de>,
|
||||
{
|
||||
self.0
|
||||
.variant_seed($wrapper(seed))
|
||||
.map(|(value, variant)| (value, $wrapper(variant)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, D> VariantAccess<'de> for $wrapper<D>
|
||||
where
|
||||
D: VariantAccess<'de>,
|
||||
{
|
||||
type Error = D::Error;
|
||||
fn unit_variant(self) -> Result<(), D::Error> {
|
||||
self.0.unit_variant()
|
||||
}
|
||||
fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, D::Error>
|
||||
where
|
||||
T: DeserializeSeed<'de>,
|
||||
{
|
||||
self.0.newtype_variant_seed($wrapper(seed))
|
||||
}
|
||||
fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, D::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
self.0.tuple_variant(len, $wrapper(visitor))
|
||||
}
|
||||
fn struct_variant<V>(
|
||||
self,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, D::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
self.0.struct_variant(fields, $wrapper(visitor))
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl_deserializer!(Readable, true);
|
||||
impl_deserializer!(Compact, false);
|
||||
@@ -1,683 +0,0 @@
|
||||
use serde::de::value::{MapAccessDeserializer, SeqAccessDeserializer};
|
||||
use serde::de::{
|
||||
self, Deserialize, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess,
|
||||
VariantAccess, Visitor,
|
||||
};
|
||||
|
||||
use error::Error;
|
||||
use token::Token;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Deserializer<'de> {
|
||||
tokens: &'de [Token],
|
||||
}
|
||||
|
||||
macro_rules! assert_next_token {
|
||||
($de:expr, $expected:expr) => {
|
||||
match $de.next_token_opt() {
|
||||
Some(token) if token == $expected => {}
|
||||
Some(other) => panic!(
|
||||
"expected Token::{} but deserialization wants Token::{}",
|
||||
other, $expected
|
||||
),
|
||||
None => panic!(
|
||||
"end of tokens but deserialization wants Token::{}",
|
||||
$expected
|
||||
),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! unexpected {
|
||||
($token:expr) => {
|
||||
panic!("deserialization did not expect this token: {}", $token)
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! end_of_tokens {
|
||||
() => {
|
||||
panic!("ran out of tokens to deserialize")
|
||||
};
|
||||
}
|
||||
|
||||
impl<'de> Deserializer<'de> {
|
||||
pub fn new(tokens: &'de [Token]) -> Self {
|
||||
Deserializer { tokens: tokens }
|
||||
}
|
||||
|
||||
fn peek_token_opt(&self) -> Option<Token> {
|
||||
self.tokens.first().cloned()
|
||||
}
|
||||
|
||||
fn peek_token(&self) -> Token {
|
||||
match self.peek_token_opt() {
|
||||
Some(token) => token,
|
||||
None => end_of_tokens!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn next_token_opt(&mut self) -> Option<Token> {
|
||||
match self.tokens.split_first() {
|
||||
Some((&first, rest)) => {
|
||||
self.tokens = rest;
|
||||
Some(first)
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn next_token(&mut self) -> Token {
|
||||
match self.tokens.split_first() {
|
||||
Some((&first, rest)) => {
|
||||
self.tokens = rest;
|
||||
first
|
||||
}
|
||||
None => end_of_tokens!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remaining(&self) -> usize {
|
||||
self.tokens.len()
|
||||
}
|
||||
|
||||
fn visit_seq<V>(
|
||||
&mut self,
|
||||
len: Option<usize>,
|
||||
end: Token,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
let value = visitor.visit_seq(DeserializerSeqVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
end: end,
|
||||
})?;
|
||||
assert_next_token!(self, end);
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn visit_map<V>(
|
||||
&mut self,
|
||||
len: Option<usize>,
|
||||
end: Token,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
let value = visitor.visit_map(DeserializerMapVisitor {
|
||||
de: self,
|
||||
len: len,
|
||||
end: end,
|
||||
})?;
|
||||
assert_next_token!(self, end);
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
|
||||
type Error = Error;
|
||||
|
||||
forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
|
||||
bytes byte_buf unit seq map identifier ignored_any
|
||||
}
|
||||
|
||||
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
let token = self.next_token();
|
||||
match token {
|
||||
Token::Bool(v) => visitor.visit_bool(v),
|
||||
Token::I8(v) => visitor.visit_i8(v),
|
||||
Token::I16(v) => visitor.visit_i16(v),
|
||||
Token::I32(v) => visitor.visit_i32(v),
|
||||
Token::I64(v) => visitor.visit_i64(v),
|
||||
Token::U8(v) => visitor.visit_u8(v),
|
||||
Token::U16(v) => visitor.visit_u16(v),
|
||||
Token::U32(v) => visitor.visit_u32(v),
|
||||
Token::U64(v) => visitor.visit_u64(v),
|
||||
Token::F32(v) => visitor.visit_f32(v),
|
||||
Token::F64(v) => visitor.visit_f64(v),
|
||||
Token::Char(v) => visitor.visit_char(v),
|
||||
Token::Str(v) => visitor.visit_str(v),
|
||||
Token::BorrowedStr(v) => visitor.visit_borrowed_str(v),
|
||||
Token::String(v) => visitor.visit_string(v.to_owned()),
|
||||
Token::Bytes(v) => visitor.visit_bytes(v),
|
||||
Token::BorrowedBytes(v) => visitor.visit_borrowed_bytes(v),
|
||||
Token::ByteBuf(v) => visitor.visit_byte_buf(v.to_vec()),
|
||||
Token::None => visitor.visit_none(),
|
||||
Token::Some => visitor.visit_some(self),
|
||||
Token::Unit | Token::UnitStruct { .. } => visitor.visit_unit(),
|
||||
Token::NewtypeStruct { .. } => visitor.visit_newtype_struct(self),
|
||||
Token::Seq { len } => self.visit_seq(len, Token::SeqEnd, visitor),
|
||||
Token::Tuple { len } => self.visit_seq(Some(len), Token::TupleEnd, visitor),
|
||||
Token::TupleStruct { len, .. } => {
|
||||
self.visit_seq(Some(len), Token::TupleStructEnd, visitor)
|
||||
}
|
||||
Token::Map { len } => self.visit_map(len, Token::MapEnd, visitor),
|
||||
Token::Struct { len, .. } => self.visit_map(Some(len), Token::StructEnd, visitor),
|
||||
Token::Enum { .. } => {
|
||||
let variant = self.next_token();
|
||||
let next = self.peek_token();
|
||||
match (variant, next) {
|
||||
(Token::Str(variant), Token::Unit) => {
|
||||
self.next_token();
|
||||
visitor.visit_str(variant)
|
||||
}
|
||||
(Token::BorrowedStr(variant), Token::Unit) => {
|
||||
self.next_token();
|
||||
visitor.visit_borrowed_str(variant)
|
||||
}
|
||||
(Token::String(variant), Token::Unit) => {
|
||||
self.next_token();
|
||||
visitor.visit_string(variant.to_string())
|
||||
}
|
||||
(Token::Bytes(variant), Token::Unit) => {
|
||||
self.next_token();
|
||||
visitor.visit_bytes(variant)
|
||||
}
|
||||
(Token::BorrowedBytes(variant), Token::Unit) => {
|
||||
self.next_token();
|
||||
visitor.visit_borrowed_bytes(variant)
|
||||
}
|
||||
(Token::ByteBuf(variant), Token::Unit) => {
|
||||
self.next_token();
|
||||
visitor.visit_byte_buf(variant.to_vec())
|
||||
}
|
||||
(Token::U8(variant), Token::Unit) => {
|
||||
self.next_token();
|
||||
visitor.visit_u8(variant)
|
||||
}
|
||||
(Token::U16(variant), Token::Unit) => {
|
||||
self.next_token();
|
||||
visitor.visit_u16(variant)
|
||||
}
|
||||
(Token::U32(variant), Token::Unit) => {
|
||||
self.next_token();
|
||||
visitor.visit_u32(variant)
|
||||
}
|
||||
(Token::U64(variant), Token::Unit) => {
|
||||
self.next_token();
|
||||
visitor.visit_u64(variant)
|
||||
}
|
||||
(variant, Token::Unit) => unexpected!(variant),
|
||||
(variant, _) => {
|
||||
visitor.visit_map(EnumMapVisitor::new(self, variant, EnumFormat::Any))
|
||||
}
|
||||
}
|
||||
}
|
||||
Token::UnitVariant { variant, .. } => visitor.visit_str(variant),
|
||||
Token::NewtypeVariant { variant, .. } => visitor.visit_map(EnumMapVisitor::new(
|
||||
self,
|
||||
Token::Str(variant),
|
||||
EnumFormat::Any,
|
||||
)),
|
||||
Token::TupleVariant { variant, .. } => visitor.visit_map(EnumMapVisitor::new(
|
||||
self,
|
||||
Token::Str(variant),
|
||||
EnumFormat::Seq,
|
||||
)),
|
||||
Token::StructVariant { variant, .. } => visitor.visit_map(EnumMapVisitor::new(
|
||||
self,
|
||||
Token::Str(variant),
|
||||
EnumFormat::Map,
|
||||
)),
|
||||
Token::SeqEnd
|
||||
| Token::TupleEnd
|
||||
| Token::TupleStructEnd
|
||||
| Token::MapEnd
|
||||
| Token::StructEnd
|
||||
| Token::TupleVariantEnd
|
||||
| Token::StructVariantEnd => {
|
||||
unexpected!(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
match self.peek_token() {
|
||||
Token::Unit | Token::None => {
|
||||
self.next_token();
|
||||
visitor.visit_none()
|
||||
}
|
||||
Token::Some => {
|
||||
self.next_token();
|
||||
visitor.visit_some(self)
|
||||
}
|
||||
_ => self.deserialize_any(visitor),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(
|
||||
self,
|
||||
name: &'static str,
|
||||
_variants: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
match self.peek_token() {
|
||||
Token::Enum { name: n } if name == n => {
|
||||
self.next_token();
|
||||
|
||||
visitor.visit_enum(DeserializerEnumVisitor { de: self })
|
||||
}
|
||||
Token::UnitVariant { name: n, .. }
|
||||
| Token::NewtypeVariant { name: n, .. }
|
||||
| Token::TupleVariant { name: n, .. }
|
||||
| Token::StructVariant { name: n, .. }
|
||||
if name == n =>
|
||||
{
|
||||
visitor.visit_enum(DeserializerEnumVisitor { de: self })
|
||||
}
|
||||
_ => self.deserialize_any(visitor),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_unit_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value, Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
match self.peek_token() {
|
||||
Token::UnitStruct { .. } => {
|
||||
assert_next_token!(self, Token::UnitStruct { name: name });
|
||||
visitor.visit_unit()
|
||||
}
|
||||
_ => self.deserialize_any(visitor),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(
|
||||
self,
|
||||
name: &'static str,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
match self.peek_token() {
|
||||
Token::NewtypeStruct { .. } => {
|
||||
assert_next_token!(self, Token::NewtypeStruct { name: name });
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
_ => self.deserialize_any(visitor),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
match self.peek_token() {
|
||||
Token::Unit | Token::UnitStruct { .. } => {
|
||||
self.next_token();
|
||||
visitor.visit_unit()
|
||||
}
|
||||
Token::Seq { .. } => {
|
||||
self.next_token();
|
||||
self.visit_seq(Some(len), Token::SeqEnd, visitor)
|
||||
}
|
||||
Token::Tuple { .. } => {
|
||||
self.next_token();
|
||||
self.visit_seq(Some(len), Token::TupleEnd, visitor)
|
||||
}
|
||||
Token::TupleStruct { .. } => {
|
||||
self.next_token();
|
||||
self.visit_seq(Some(len), Token::TupleStructEnd, visitor)
|
||||
}
|
||||
_ => self.deserialize_any(visitor),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_tuple_struct<V>(
|
||||
self,
|
||||
name: &'static str,
|
||||
len: usize,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
match self.peek_token() {
|
||||
Token::Unit => {
|
||||
self.next_token();
|
||||
visitor.visit_unit()
|
||||
}
|
||||
Token::UnitStruct { .. } => {
|
||||
assert_next_token!(self, Token::UnitStruct { name: name });
|
||||
visitor.visit_unit()
|
||||
}
|
||||
Token::Seq { .. } => {
|
||||
self.next_token();
|
||||
self.visit_seq(Some(len), Token::SeqEnd, visitor)
|
||||
}
|
||||
Token::Tuple { .. } => {
|
||||
self.next_token();
|
||||
self.visit_seq(Some(len), Token::TupleEnd, visitor)
|
||||
}
|
||||
Token::TupleStruct { len: n, .. } => {
|
||||
assert_next_token!(self, Token::TupleStruct { name: name, len: n });
|
||||
self.visit_seq(Some(len), Token::TupleStructEnd, visitor)
|
||||
}
|
||||
_ => self.deserialize_any(visitor),
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_struct<V>(
|
||||
self,
|
||||
name: &'static str,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
match self.peek_token() {
|
||||
Token::Struct { len: n, .. } => {
|
||||
assert_next_token!(self, Token::Struct { name: name, len: n });
|
||||
self.visit_map(Some(fields.len()), Token::StructEnd, visitor)
|
||||
}
|
||||
Token::Map { .. } => {
|
||||
self.next_token();
|
||||
self.visit_map(Some(fields.len()), Token::MapEnd, visitor)
|
||||
}
|
||||
_ => self.deserialize_any(visitor),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_human_readable(&self) -> bool {
|
||||
panic!(
|
||||
"Types which have different human-readable and compact representations \
|
||||
must explicitly mark their test cases with `serde_test::Configure`"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerSeqVisitor<'a, 'de: 'a> {
|
||||
de: &'a mut Deserializer<'de>,
|
||||
len: Option<usize>,
|
||||
end: Token,
|
||||
}
|
||||
|
||||
impl<'de, 'a> SeqAccess<'de> for DeserializerSeqVisitor<'a, 'de> {
|
||||
type Error = Error;
|
||||
|
||||
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
|
||||
where
|
||||
T: DeserializeSeed<'de>,
|
||||
{
|
||||
if self.de.peek_token_opt() == Some(self.end) {
|
||||
return Ok(None);
|
||||
}
|
||||
self.len = self.len.map(|len| len.saturating_sub(1));
|
||||
seed.deserialize(&mut *self.de).map(Some)
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> Option<usize> {
|
||||
self.len
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerMapVisitor<'a, 'de: 'a> {
|
||||
de: &'a mut Deserializer<'de>,
|
||||
len: Option<usize>,
|
||||
end: Token,
|
||||
}
|
||||
|
||||
impl<'de, 'a> MapAccess<'de> for DeserializerMapVisitor<'a, 'de> {
|
||||
type Error = Error;
|
||||
|
||||
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
|
||||
where
|
||||
K: DeserializeSeed<'de>,
|
||||
{
|
||||
if self.de.peek_token_opt() == Some(self.end) {
|
||||
return Ok(None);
|
||||
}
|
||||
self.len = self.len.map(|len| len.saturating_sub(1));
|
||||
seed.deserialize(&mut *self.de).map(Some)
|
||||
}
|
||||
|
||||
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
|
||||
where
|
||||
V: DeserializeSeed<'de>,
|
||||
{
|
||||
seed.deserialize(&mut *self.de)
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> Option<usize> {
|
||||
self.len
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct DeserializerEnumVisitor<'a, 'de: 'a> {
|
||||
de: &'a mut Deserializer<'de>,
|
||||
}
|
||||
|
||||
impl<'de, 'a> EnumAccess<'de> for DeserializerEnumVisitor<'a, 'de> {
|
||||
type Error = Error;
|
||||
type Variant = Self;
|
||||
|
||||
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self), Error>
|
||||
where
|
||||
V: DeserializeSeed<'de>,
|
||||
{
|
||||
match self.de.peek_token() {
|
||||
Token::UnitVariant { variant: v, .. }
|
||||
| Token::NewtypeVariant { variant: v, .. }
|
||||
| Token::TupleVariant { variant: v, .. }
|
||||
| Token::StructVariant { variant: v, .. } => {
|
||||
let de = v.into_deserializer();
|
||||
let value = seed.deserialize(de)?;
|
||||
Ok((value, self))
|
||||
}
|
||||
_ => {
|
||||
let value = seed.deserialize(&mut *self.de)?;
|
||||
Ok((value, self))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, 'a> VariantAccess<'de> for DeserializerEnumVisitor<'a, 'de> {
|
||||
type Error = Error;
|
||||
|
||||
fn unit_variant(self) -> Result<(), Error> {
|
||||
match self.de.peek_token() {
|
||||
Token::UnitVariant { .. } => {
|
||||
self.de.next_token();
|
||||
Ok(())
|
||||
}
|
||||
_ => Deserialize::deserialize(self.de),
|
||||
}
|
||||
}
|
||||
|
||||
fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
|
||||
where
|
||||
T: DeserializeSeed<'de>,
|
||||
{
|
||||
match self.de.peek_token() {
|
||||
Token::NewtypeVariant { .. } => {
|
||||
self.de.next_token();
|
||||
seed.deserialize(self.de)
|
||||
}
|
||||
_ => seed.deserialize(self.de),
|
||||
}
|
||||
}
|
||||
|
||||
fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
match self.de.peek_token() {
|
||||
Token::TupleVariant { len: enum_len, .. } => {
|
||||
let token = self.de.next_token();
|
||||
|
||||
if len == enum_len {
|
||||
self.de
|
||||
.visit_seq(Some(len), Token::TupleVariantEnd, visitor)
|
||||
} else {
|
||||
unexpected!(token);
|
||||
}
|
||||
}
|
||||
Token::Seq {
|
||||
len: Some(enum_len),
|
||||
} => {
|
||||
let token = self.de.next_token();
|
||||
|
||||
if len == enum_len {
|
||||
self.de.visit_seq(Some(len), Token::SeqEnd, visitor)
|
||||
} else {
|
||||
unexpected!(token);
|
||||
}
|
||||
}
|
||||
_ => de::Deserializer::deserialize_any(self.de, visitor),
|
||||
}
|
||||
}
|
||||
|
||||
fn struct_variant<V>(
|
||||
self,
|
||||
fields: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
match self.de.peek_token() {
|
||||
Token::StructVariant { len: enum_len, .. } => {
|
||||
let token = self.de.next_token();
|
||||
|
||||
if fields.len() == enum_len {
|
||||
self.de
|
||||
.visit_map(Some(fields.len()), Token::StructVariantEnd, visitor)
|
||||
} else {
|
||||
unexpected!(token);
|
||||
}
|
||||
}
|
||||
Token::Map {
|
||||
len: Some(enum_len),
|
||||
} => {
|
||||
let token = self.de.next_token();
|
||||
|
||||
if fields.len() == enum_len {
|
||||
self.de
|
||||
.visit_map(Some(fields.len()), Token::MapEnd, visitor)
|
||||
} else {
|
||||
unexpected!(token);
|
||||
}
|
||||
}
|
||||
_ => de::Deserializer::deserialize_any(self.de, visitor),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct EnumMapVisitor<'a, 'de: 'a> {
|
||||
de: &'a mut Deserializer<'de>,
|
||||
variant: Option<Token>,
|
||||
format: EnumFormat,
|
||||
}
|
||||
|
||||
enum EnumFormat {
|
||||
Seq,
|
||||
Map,
|
||||
Any,
|
||||
}
|
||||
|
||||
impl<'a, 'de> EnumMapVisitor<'a, 'de> {
|
||||
fn new(de: &'a mut Deserializer<'de>, variant: Token, format: EnumFormat) -> Self {
|
||||
EnumMapVisitor {
|
||||
de: de,
|
||||
variant: Some(variant),
|
||||
format: format,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, 'a> MapAccess<'de> for EnumMapVisitor<'a, 'de> {
|
||||
type Error = Error;
|
||||
|
||||
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
|
||||
where
|
||||
K: DeserializeSeed<'de>,
|
||||
{
|
||||
match self.variant.take() {
|
||||
Some(Token::Str(variant)) => seed.deserialize(variant.into_deserializer()).map(Some),
|
||||
Some(Token::Bytes(variant)) => seed
|
||||
.deserialize(BytesDeserializer { value: variant })
|
||||
.map(Some),
|
||||
Some(Token::U32(variant)) => seed.deserialize(variant.into_deserializer()).map(Some),
|
||||
Some(other) => unexpected!(other),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
|
||||
where
|
||||
V: DeserializeSeed<'de>,
|
||||
{
|
||||
match self.format {
|
||||
EnumFormat::Seq => {
|
||||
let value = {
|
||||
let visitor = DeserializerSeqVisitor {
|
||||
de: self.de,
|
||||
len: None,
|
||||
end: Token::TupleVariantEnd,
|
||||
};
|
||||
seed.deserialize(SeqAccessDeserializer::new(visitor))?
|
||||
};
|
||||
assert_next_token!(self.de, Token::TupleVariantEnd);
|
||||
Ok(value)
|
||||
}
|
||||
EnumFormat::Map => {
|
||||
let value = {
|
||||
let visitor = DeserializerMapVisitor {
|
||||
de: self.de,
|
||||
len: None,
|
||||
end: Token::StructVariantEnd,
|
||||
};
|
||||
seed.deserialize(MapAccessDeserializer::new(visitor))?
|
||||
};
|
||||
assert_next_token!(self.de, Token::StructVariantEnd);
|
||||
Ok(value)
|
||||
}
|
||||
EnumFormat::Any => seed.deserialize(&mut *self.de),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct BytesDeserializer {
|
||||
value: &'static [u8],
|
||||
}
|
||||
|
||||
impl<'de> de::Deserializer<'de> for BytesDeserializer {
|
||||
type Error = Error;
|
||||
|
||||
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: de::Visitor<'de>,
|
||||
{
|
||||
visitor.visit_bytes(self.value)
|
||||
}
|
||||
|
||||
forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
|
||||
bytes byte_buf option unit unit_struct newtype_struct seq tuple
|
||||
tuple_struct map struct enum identifier ignored_any
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
use std::error;
|
||||
use std::fmt::{self, Display};
|
||||
|
||||
use serde::{de, ser};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Error {
|
||||
msg: String,
|
||||
}
|
||||
|
||||
impl ser::Error for Error {
|
||||
fn custom<T: Display>(msg: T) -> Self {
|
||||
Error {
|
||||
msg: msg.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl de::Error for Error {
|
||||
fn custom<T: Display>(msg: T) -> Self {
|
||||
Error {
|
||||
msg: msg.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str(&self.msg)
|
||||
}
|
||||
}
|
||||
|
||||
impl error::Error for Error {
|
||||
fn description(&self) -> &str {
|
||||
&self.msg
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq<str> for Error {
|
||||
fn eq(&self, other: &str) -> bool {
|
||||
self.msg == other
|
||||
}
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
//! This crate provides a convenient concise way to write unit tests for
|
||||
//! implementations of [`Serialize`] and [`Deserialize`].
|
||||
//!
|
||||
//! [`Serialize`]: serde::ser::Serialize
|
||||
//! [`Deserialize`]: serde::de::Deserialize
|
||||
//!
|
||||
//! The `Serialize` impl for a value can be characterized by the sequence of
|
||||
//! [`Serializer`] calls that are made in the course of serializing the value,
|
||||
//! so `serde_test` provides a [`Token`] abstraction which corresponds roughly
|
||||
//! to `Serializer` method calls. There is an [`assert_ser_tokens`] function to
|
||||
//! test that a value serializes to a particular sequence of method calls, an
|
||||
//! [`assert_de_tokens`] function to test that a value can be deserialized from
|
||||
//! a particular sequence of method calls, and an [`assert_tokens`] function to
|
||||
//! test both directions. There are also functions to test expected failure
|
||||
//! conditions.
|
||||
//!
|
||||
//! [`Serializer`]: serde::ser::Serializer
|
||||
//!
|
||||
//! Here is an example from the [`linked-hash-map`] crate.
|
||||
//!
|
||||
//! [`linked-hash-map`]: https://github.com/contain-rs/linked-hash-map
|
||||
//!
|
||||
//! ```edition2018
|
||||
//! # const IGNORE: &str = stringify! {
|
||||
//! use linked_hash_map::LinkedHashMap;
|
||||
//! # };
|
||||
//! use serde_test::{Token, assert_tokens};
|
||||
//!
|
||||
//! # use std::fmt;
|
||||
//! # use std::marker::PhantomData;
|
||||
//! #
|
||||
//! # use serde::ser::{Serialize, Serializer, SerializeMap};
|
||||
//! # use serde::de::{Deserialize, Deserializer, Visitor, MapAccess};
|
||||
//! #
|
||||
//! # // Dumb imitation of LinkedHashMap.
|
||||
//! # #[derive(PartialEq, Debug)]
|
||||
//! # struct LinkedHashMap<K, V>(Vec<(K, V)>);
|
||||
//! #
|
||||
//! # impl<K, V> LinkedHashMap<K, V> {
|
||||
//! # fn new() -> Self {
|
||||
//! # LinkedHashMap(Vec::new())
|
||||
//! # }
|
||||
//! #
|
||||
//! # fn insert(&mut self, k: K, v: V) {
|
||||
//! # self.0.push((k, v));
|
||||
//! # }
|
||||
//! # }
|
||||
//! #
|
||||
//! # impl<K, V> Serialize for LinkedHashMap<K, V>
|
||||
//! # where
|
||||
//! # K: Serialize,
|
||||
//! # V: Serialize,
|
||||
//! # {
|
||||
//! # fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
//! # where
|
||||
//! # S: Serializer,
|
||||
//! # {
|
||||
//! # let mut map = serializer.serialize_map(Some(self.0.len()))?;
|
||||
//! # for &(ref k, ref v) in &self.0 {
|
||||
//! # map.serialize_entry(k, v)?;
|
||||
//! # }
|
||||
//! # map.end()
|
||||
//! # }
|
||||
//! # }
|
||||
//! #
|
||||
//! # struct LinkedHashMapVisitor<K, V>(PhantomData<(K, V)>);
|
||||
//! #
|
||||
//! # impl<'de, K, V> Visitor<'de> for LinkedHashMapVisitor<K, V>
|
||||
//! # where
|
||||
//! # K: Deserialize<'de>,
|
||||
//! # V: Deserialize<'de>,
|
||||
//! # {
|
||||
//! # type Value = LinkedHashMap<K, V>;
|
||||
//! #
|
||||
//! # fn expecting(&self, _: &mut fmt::Formatter) -> fmt::Result {
|
||||
//! # unimplemented!()
|
||||
//! # }
|
||||
//! #
|
||||
//! # fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
|
||||
//! # where
|
||||
//! # M: MapAccess<'de>,
|
||||
//! # {
|
||||
//! # let mut map = LinkedHashMap::new();
|
||||
//! # while let Some((key, value)) = access.next_entry()? {
|
||||
//! # map.insert(key, value);
|
||||
//! # }
|
||||
//! # Ok(map)
|
||||
//! # }
|
||||
//! # }
|
||||
//! #
|
||||
//! # impl<'de, K, V> Deserialize<'de> for LinkedHashMap<K, V>
|
||||
//! # where
|
||||
//! # K: Deserialize<'de>,
|
||||
//! # V: Deserialize<'de>,
|
||||
//! # {
|
||||
//! # fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
//! # where
|
||||
//! # D: Deserializer<'de>,
|
||||
//! # {
|
||||
//! # deserializer.deserialize_map(LinkedHashMapVisitor(PhantomData))
|
||||
//! # }
|
||||
//! # }
|
||||
//! #
|
||||
//! #[test]
|
||||
//! # fn not_a_test_ser_de_empty() {}
|
||||
//! fn test_ser_de_empty() {
|
||||
//! let map = LinkedHashMap::<char, u32>::new();
|
||||
//!
|
||||
//! assert_tokens(&map, &[
|
||||
//! Token::Map { len: Some(0) },
|
||||
//! Token::MapEnd,
|
||||
//! ]);
|
||||
//! }
|
||||
//!
|
||||
//! #[test]
|
||||
//! # fn not_a_test_ser_de() {}
|
||||
//! fn test_ser_de() {
|
||||
//! let mut map = LinkedHashMap::new();
|
||||
//! map.insert('b', 20);
|
||||
//! map.insert('a', 10);
|
||||
//! map.insert('c', 30);
|
||||
//!
|
||||
//! assert_tokens(&map, &[
|
||||
//! Token::Map { len: Some(3) },
|
||||
//! Token::Char('b'),
|
||||
//! Token::I32(20),
|
||||
//!
|
||||
//! Token::Char('a'),
|
||||
//! Token::I32(10),
|
||||
//!
|
||||
//! Token::Char('c'),
|
||||
//! Token::I32(30),
|
||||
//! Token::MapEnd,
|
||||
//! ]);
|
||||
//! }
|
||||
//! #
|
||||
//! # fn main() {
|
||||
//! # test_ser_de_empty();
|
||||
//! # test_ser_de();
|
||||
//! # }
|
||||
//! ```
|
||||
|
||||
#![doc(html_root_url = "https://docs.rs/serde_test/1.0.157")]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))]
|
||||
// Ignored clippy lints
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(float_cmp, needless_doctest_main))]
|
||||
// Ignored clippy_pedantic lints
|
||||
#![cfg_attr(
|
||||
feature = "cargo-clippy",
|
||||
allow(
|
||||
cloned_instead_of_copied,
|
||||
doc_link_with_quotes, // https://github.com/rust-lang/rust-clippy/issues/8961
|
||||
empty_line_after_outer_attr,
|
||||
manual_assert,
|
||||
missing_docs_in_private_items,
|
||||
missing_panics_doc,
|
||||
module_name_repetitions,
|
||||
must_use_candidate,
|
||||
redundant_field_names,
|
||||
too_many_lines,
|
||||
type_repetition_in_bounds, // https://github.com/rust-lang/rust-clippy/issues/8772
|
||||
use_debug,
|
||||
use_self
|
||||
)
|
||||
)]
|
||||
|
||||
#[macro_use]
|
||||
extern crate serde;
|
||||
|
||||
mod de;
|
||||
mod error;
|
||||
mod ser;
|
||||
|
||||
mod assert;
|
||||
mod configure;
|
||||
mod token;
|
||||
|
||||
pub use assert::{
|
||||
assert_de_tokens, assert_de_tokens_error, assert_ser_tokens, assert_ser_tokens_error,
|
||||
assert_tokens,
|
||||
};
|
||||
pub use token::Token;
|
||||
|
||||
pub use configure::{Compact, Configure, Readable};
|
||||
|
||||
// Not public API.
|
||||
#[doc(hidden)]
|
||||
pub use de::Deserializer;
|
||||
@@ -1,464 +0,0 @@
|
||||
use serde::{ser, Serialize};
|
||||
|
||||
use error::Error;
|
||||
use token::Token;
|
||||
|
||||
/// A `Serializer` that ensures that a value serializes to a given list of
|
||||
/// tokens.
|
||||
#[derive(Debug)]
|
||||
pub struct Serializer<'a> {
|
||||
tokens: &'a [Token],
|
||||
}
|
||||
|
||||
impl<'a> Serializer<'a> {
|
||||
/// Creates the serializer.
|
||||
pub fn new(tokens: &'a [Token]) -> Self {
|
||||
Serializer { tokens: tokens }
|
||||
}
|
||||
|
||||
/// Pulls the next token off of the serializer, ignoring it.
|
||||
fn next_token(&mut self) -> Option<Token> {
|
||||
if let Some((&first, rest)) = self.tokens.split_first() {
|
||||
self.tokens = rest;
|
||||
Some(first)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remaining(&self) -> usize {
|
||||
self.tokens.len()
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! assert_next_token {
|
||||
($ser:expr, $actual:ident) => {{
|
||||
assert_next_token!($ser, stringify!($actual), Token::$actual, true);
|
||||
}};
|
||||
($ser:expr, $actual:ident($v:expr)) => {{
|
||||
assert_next_token!(
|
||||
$ser,
|
||||
format_args!(concat!(stringify!($actual), "({:?})"), $v),
|
||||
Token::$actual(v),
|
||||
v == $v
|
||||
);
|
||||
}};
|
||||
($ser:expr, $actual:ident { $($k:ident),* }) => {{
|
||||
let compare = ($($k,)*);
|
||||
let field_format = || {
|
||||
use std::fmt::Write;
|
||||
let mut buffer = String::new();
|
||||
$(
|
||||
write!(&mut buffer, concat!(stringify!($k), ": {:?}, "), $k).unwrap();
|
||||
)*
|
||||
buffer
|
||||
};
|
||||
assert_next_token!(
|
||||
$ser,
|
||||
format_args!(concat!(stringify!($actual), " {{ {}}}"), field_format()),
|
||||
Token::$actual { $($k),* },
|
||||
($($k,)*) == compare
|
||||
);
|
||||
}};
|
||||
($ser:expr, $actual:expr, $pat:pat, $guard:expr) => {
|
||||
match $ser.next_token() {
|
||||
Some($pat) if $guard => {}
|
||||
Some(expected) => {
|
||||
panic!("expected Token::{} but serialized as {}",
|
||||
expected, $actual);
|
||||
}
|
||||
None => {
|
||||
panic!("expected end of tokens, but {} was serialized",
|
||||
$actual);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl<'s, 'a> ser::Serializer for &'s mut Serializer<'a> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
type SerializeSeq = Self;
|
||||
type SerializeTuple = Self;
|
||||
type SerializeTupleStruct = Self;
|
||||
type SerializeTupleVariant = Variant<'s, 'a>;
|
||||
type SerializeMap = Self;
|
||||
type SerializeStruct = Self;
|
||||
type SerializeStructVariant = Variant<'s, 'a>;
|
||||
|
||||
fn serialize_bool(self, v: bool) -> Result<(), Error> {
|
||||
assert_next_token!(self, Bool(v));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_i8(self, v: i8) -> Result<(), Error> {
|
||||
assert_next_token!(self, I8(v));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_i16(self, v: i16) -> Result<(), Error> {
|
||||
assert_next_token!(self, I16(v));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_i32(self, v: i32) -> Result<(), Error> {
|
||||
assert_next_token!(self, I32(v));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_i64(self, v: i64) -> Result<(), Error> {
|
||||
assert_next_token!(self, I64(v));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_u8(self, v: u8) -> Result<(), Error> {
|
||||
assert_next_token!(self, U8(v));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_u16(self, v: u16) -> Result<(), Error> {
|
||||
assert_next_token!(self, U16(v));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_u32(self, v: u32) -> Result<(), Error> {
|
||||
assert_next_token!(self, U32(v));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_u64(self, v: u64) -> Result<(), Error> {
|
||||
assert_next_token!(self, U64(v));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_f32(self, v: f32) -> Result<(), Error> {
|
||||
assert_next_token!(self, F32(v));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_f64(self, v: f64) -> Result<(), Error> {
|
||||
assert_next_token!(self, F64(v));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_char(self, v: char) -> Result<(), Error> {
|
||||
assert_next_token!(self, Char(v));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_str(self, v: &str) -> Result<(), Error> {
|
||||
match self.tokens.first() {
|
||||
Some(&Token::BorrowedStr(_)) => assert_next_token!(self, BorrowedStr(v)),
|
||||
Some(&Token::String(_)) => assert_next_token!(self, String(v)),
|
||||
_ => assert_next_token!(self, Str(v)),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_bytes(self, v: &[u8]) -> Result<(), Self::Error> {
|
||||
match self.tokens.first() {
|
||||
Some(&Token::BorrowedBytes(_)) => assert_next_token!(self, BorrowedBytes(v)),
|
||||
Some(&Token::ByteBuf(_)) => assert_next_token!(self, ByteBuf(v)),
|
||||
_ => assert_next_token!(self, Bytes(v)),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_unit(self) -> Result<(), Error> {
|
||||
assert_next_token!(self, Unit);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_unit_struct(self, name: &'static str) -> Result<(), Error> {
|
||||
assert_next_token!(self, UnitStruct { name });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
_variant_index: u32,
|
||||
variant: &'static str,
|
||||
) -> Result<(), Error> {
|
||||
if self.tokens.first() == Some(&Token::Enum { name: name }) {
|
||||
self.next_token();
|
||||
assert_next_token!(self, Str(variant));
|
||||
assert_next_token!(self, Unit);
|
||||
} else {
|
||||
assert_next_token!(self, UnitVariant { name, variant });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: ?Sized>(self, name: &'static str, value: &T) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
assert_next_token!(self, NewtypeStruct { name });
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: ?Sized>(
|
||||
self,
|
||||
name: &'static str,
|
||||
_variant_index: u32,
|
||||
variant: &'static str,
|
||||
value: &T,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
if self.tokens.first() == Some(&Token::Enum { name: name }) {
|
||||
self.next_token();
|
||||
assert_next_token!(self, Str(variant));
|
||||
} else {
|
||||
assert_next_token!(self, NewtypeVariant { name, variant });
|
||||
}
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_none(self) -> Result<(), Error> {
|
||||
assert_next_token!(self, None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
assert_next_token!(self, Some);
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_seq(self, len: Option<usize>) -> Result<Self, Error> {
|
||||
assert_next_token!(self, Seq { len });
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn serialize_tuple(self, len: usize) -> Result<Self, Error> {
|
||||
assert_next_token!(self, Tuple { len });
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(self, name: &'static str, len: usize) -> Result<Self, Error> {
|
||||
assert_next_token!(self, TupleStruct { name, len });
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
_variant_index: u32,
|
||||
variant: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeTupleVariant, Error> {
|
||||
if self.tokens.first() == Some(&Token::Enum { name: name }) {
|
||||
self.next_token();
|
||||
assert_next_token!(self, Str(variant));
|
||||
let len = Some(len);
|
||||
assert_next_token!(self, Seq { len });
|
||||
Ok(Variant {
|
||||
ser: self,
|
||||
end: Token::SeqEnd,
|
||||
})
|
||||
} else {
|
||||
assert_next_token!(self, TupleVariant { name, variant, len });
|
||||
Ok(Variant {
|
||||
ser: self,
|
||||
end: Token::TupleVariantEnd,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self, Error> {
|
||||
assert_next_token!(self, Map { len });
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self, Error> {
|
||||
assert_next_token!(self, Struct { name, len });
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
fn serialize_struct_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
_variant_index: u32,
|
||||
variant: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStructVariant, Error> {
|
||||
if self.tokens.first() == Some(&Token::Enum { name: name }) {
|
||||
self.next_token();
|
||||
assert_next_token!(self, Str(variant));
|
||||
let len = Some(len);
|
||||
assert_next_token!(self, Map { len });
|
||||
Ok(Variant {
|
||||
ser: self,
|
||||
end: Token::MapEnd,
|
||||
})
|
||||
} else {
|
||||
assert_next_token!(self, StructVariant { name, variant, len });
|
||||
Ok(Variant {
|
||||
ser: self,
|
||||
end: Token::StructVariantEnd,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn is_human_readable(&self) -> bool {
|
||||
panic!(
|
||||
"Types which have different human-readable and compact representations \
|
||||
must explicitly mark their test cases with `serde_test::Configure`"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Variant<'s, 'a: 's> {
|
||||
ser: &'s mut Serializer<'a>,
|
||||
end: Token,
|
||||
}
|
||||
|
||||
impl<'s, 'a> ser::SerializeSeq for &'s mut Serializer<'a> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
value.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Error> {
|
||||
assert_next_token!(self, SeqEnd);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a> ser::SerializeTuple for &'s mut Serializer<'a> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
value.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Error> {
|
||||
assert_next_token!(self, TupleEnd);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a> ser::SerializeTupleStruct for &'s mut Serializer<'a> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
value.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Error> {
|
||||
assert_next_token!(self, TupleStructEnd);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a> ser::SerializeTupleVariant for Variant<'s, 'a> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Error> {
|
||||
match self.end {
|
||||
Token::TupleVariantEnd => assert_next_token!(self.ser, TupleVariantEnd),
|
||||
Token::SeqEnd => assert_next_token!(self.ser, SeqEnd),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a> ser::SerializeMap for &'s mut Serializer<'a> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
key.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
value.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Self::Error> {
|
||||
assert_next_token!(self, MapEnd);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a> ser::SerializeStruct for &'s mut Serializer<'a> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(
|
||||
&mut self,
|
||||
key: &'static str,
|
||||
value: &T,
|
||||
) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
key.serialize(&mut **self)?;
|
||||
value.serialize(&mut **self)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Self::Error> {
|
||||
assert_next_token!(self, StructEnd);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'a> ser::SerializeStructVariant for Variant<'s, 'a> {
|
||||
type Ok = ();
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: ?Sized>(
|
||||
&mut self,
|
||||
key: &'static str,
|
||||
value: &T,
|
||||
) -> Result<(), Self::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
key.serialize(&mut *self.ser)?;
|
||||
value.serialize(&mut *self.ser)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<(), Self::Error> {
|
||||
match self.end {
|
||||
Token::StructVariantEnd => assert_next_token!(self.ser, StructVariantEnd),
|
||||
Token::MapEnd => assert_next_token!(self.ser, MapEnd),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,519 +0,0 @@
|
||||
use std::fmt::{self, Debug, Display};
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Debug)]
|
||||
pub enum Token {
|
||||
/// A serialized `bool`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// assert_tokens(&true, &[Token::Bool(true)]);
|
||||
/// ```
|
||||
Bool(bool),
|
||||
|
||||
/// A serialized `i8`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// assert_tokens(&0i8, &[Token::I8(0)]);
|
||||
/// ```
|
||||
I8(i8),
|
||||
|
||||
/// A serialized `i16`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// assert_tokens(&0i16, &[Token::I16(0)]);
|
||||
/// ```
|
||||
I16(i16),
|
||||
|
||||
/// A serialized `i32`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// assert_tokens(&0i32, &[Token::I32(0)]);
|
||||
/// ```
|
||||
I32(i32),
|
||||
|
||||
/// A serialized `i64`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// assert_tokens(&0i64, &[Token::I64(0)]);
|
||||
/// ```
|
||||
I64(i64),
|
||||
|
||||
/// A serialized `u8`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// assert_tokens(&0u8, &[Token::U8(0)]);
|
||||
/// ```
|
||||
U8(u8),
|
||||
|
||||
/// A serialized `u16`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// assert_tokens(&0u16, &[Token::U16(0)]);
|
||||
/// ```
|
||||
U16(u16),
|
||||
|
||||
/// A serialized `u32`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// assert_tokens(&0u32, &[Token::U32(0)]);
|
||||
/// ```
|
||||
U32(u32),
|
||||
|
||||
/// A serialized `u64`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// assert_tokens(&0u64, &[Token::U64(0)]);
|
||||
/// ```
|
||||
U64(u64),
|
||||
|
||||
/// A serialized `f32`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// assert_tokens(&0f32, &[Token::F32(0.0)]);
|
||||
/// ```
|
||||
F32(f32),
|
||||
|
||||
/// A serialized `f64`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// assert_tokens(&0f64, &[Token::F64(0.0)]);
|
||||
/// ```
|
||||
F64(f64),
|
||||
|
||||
/// A serialized `char`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// assert_tokens(&'\n', &[Token::Char('\n')]);
|
||||
/// ```
|
||||
Char(char),
|
||||
|
||||
/// A serialized `str`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// let s = String::from("transient");
|
||||
/// assert_tokens(&s, &[Token::Str("transient")]);
|
||||
/// ```
|
||||
Str(&'static str),
|
||||
|
||||
/// A borrowed `str`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// let s: &str = "borrowed";
|
||||
/// assert_tokens(&s, &[Token::BorrowedStr("borrowed")]);
|
||||
/// ```
|
||||
BorrowedStr(&'static str),
|
||||
|
||||
/// A serialized `String`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// let s = String::from("owned");
|
||||
/// assert_tokens(&s, &[Token::String("owned")]);
|
||||
/// ```
|
||||
String(&'static str),
|
||||
|
||||
/// A serialized `[u8]`
|
||||
Bytes(&'static [u8]),
|
||||
|
||||
/// A borrowed `[u8]`.
|
||||
BorrowedBytes(&'static [u8]),
|
||||
|
||||
/// A serialized `ByteBuf`
|
||||
ByteBuf(&'static [u8]),
|
||||
|
||||
/// A serialized `Option<T>` containing none.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// let opt = None::<char>;
|
||||
/// assert_tokens(&opt, &[Token::None]);
|
||||
/// ```
|
||||
None,
|
||||
|
||||
/// The header to a serialized `Option<T>` containing some value.
|
||||
///
|
||||
/// The tokens of the value follow after this header.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// let opt = Some('c');
|
||||
/// assert_tokens(&opt, &[
|
||||
/// Token::Some,
|
||||
/// Token::Char('c'),
|
||||
/// ]);
|
||||
/// ```
|
||||
Some,
|
||||
|
||||
/// A serialized `()`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// assert_tokens(&(), &[Token::Unit]);
|
||||
/// ```
|
||||
Unit,
|
||||
|
||||
/// A serialized unit struct of the given name.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::{Serialize, Deserialize};
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// # fn main() {
|
||||
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
/// struct X;
|
||||
///
|
||||
/// assert_tokens(&X, &[Token::UnitStruct { name: "X" }]);
|
||||
/// # }
|
||||
/// ```
|
||||
UnitStruct { name: &'static str },
|
||||
|
||||
/// A unit variant of an enum.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::{Serialize, Deserialize};
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// # fn main() {
|
||||
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
/// enum E {
|
||||
/// A,
|
||||
/// }
|
||||
///
|
||||
/// let a = E::A;
|
||||
/// assert_tokens(&a, &[Token::UnitVariant { name: "E", variant: "A" }]);
|
||||
/// # }
|
||||
/// ```
|
||||
UnitVariant {
|
||||
name: &'static str,
|
||||
variant: &'static str,
|
||||
},
|
||||
|
||||
/// The header to a serialized newtype struct of the given name.
|
||||
///
|
||||
/// After this header is the value contained in the newtype struct.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::{Serialize, Deserialize};
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// # fn main() {
|
||||
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
/// struct N(String);
|
||||
///
|
||||
/// let n = N("newtype".to_owned());
|
||||
/// assert_tokens(&n, &[
|
||||
/// Token::NewtypeStruct { name: "N" },
|
||||
/// Token::String("newtype"),
|
||||
/// ]);
|
||||
/// # }
|
||||
/// ```
|
||||
NewtypeStruct { name: &'static str },
|
||||
|
||||
/// The header to a newtype variant of an enum.
|
||||
///
|
||||
/// After this header is the value contained in the newtype variant.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::{Serialize, Deserialize};
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// # fn main() {
|
||||
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
/// enum E {
|
||||
/// B(u8),
|
||||
/// }
|
||||
///
|
||||
/// let b = E::B(0);
|
||||
/// assert_tokens(&b, &[
|
||||
/// Token::NewtypeVariant { name: "E", variant: "B" },
|
||||
/// Token::U8(0),
|
||||
/// ]);
|
||||
/// # }
|
||||
/// ```
|
||||
NewtypeVariant {
|
||||
name: &'static str,
|
||||
variant: &'static str,
|
||||
},
|
||||
|
||||
/// The header to a sequence.
|
||||
///
|
||||
/// After this header are the elements of the sequence, followed by
|
||||
/// `SeqEnd`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// let vec = vec!['a', 'b', 'c'];
|
||||
/// assert_tokens(&vec, &[
|
||||
/// Token::Seq { len: Some(3) },
|
||||
/// Token::Char('a'),
|
||||
/// Token::Char('b'),
|
||||
/// Token::Char('c'),
|
||||
/// Token::SeqEnd,
|
||||
/// ]);
|
||||
/// ```
|
||||
Seq { len: Option<usize> },
|
||||
|
||||
/// An indicator of the end of a sequence.
|
||||
SeqEnd,
|
||||
|
||||
/// The header to a tuple.
|
||||
///
|
||||
/// After this header are the elements of the tuple, followed by `TupleEnd`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// let tuple = ('a', 100);
|
||||
/// assert_tokens(&tuple, &[
|
||||
/// Token::Tuple { len: 2 },
|
||||
/// Token::Char('a'),
|
||||
/// Token::I32(100),
|
||||
/// Token::TupleEnd,
|
||||
/// ]);
|
||||
/// ```
|
||||
Tuple { len: usize },
|
||||
|
||||
/// An indicator of the end of a tuple.
|
||||
TupleEnd,
|
||||
|
||||
/// The header to a tuple struct.
|
||||
///
|
||||
/// After this header are the fields of the tuple struct, followed by
|
||||
/// `TupleStructEnd`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::{Serialize, Deserialize};
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// # fn main() {
|
||||
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
/// struct T(u8, u8);
|
||||
///
|
||||
/// let t = T(0, 0);
|
||||
/// assert_tokens(&t, &[
|
||||
/// Token::TupleStruct { name: "T", len: 2 },
|
||||
/// Token::U8(0),
|
||||
/// Token::U8(0),
|
||||
/// Token::TupleStructEnd,
|
||||
/// ]);
|
||||
/// # }
|
||||
/// ```
|
||||
TupleStruct { name: &'static str, len: usize },
|
||||
|
||||
/// An indicator of the end of a tuple struct.
|
||||
TupleStructEnd,
|
||||
|
||||
/// The header to a tuple variant of an enum.
|
||||
///
|
||||
/// After this header are the fields of the tuple variant, followed by
|
||||
/// `TupleVariantEnd`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::{Serialize, Deserialize};
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// # fn main() {
|
||||
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
/// enum E {
|
||||
/// C(u8, u8),
|
||||
/// }
|
||||
///
|
||||
/// let c = E::C(0, 0);
|
||||
/// assert_tokens(&c, &[
|
||||
/// Token::TupleVariant { name: "E", variant: "C", len: 2 },
|
||||
/// Token::U8(0),
|
||||
/// Token::U8(0),
|
||||
/// Token::TupleVariantEnd,
|
||||
/// ]);
|
||||
/// # }
|
||||
/// ```
|
||||
TupleVariant {
|
||||
name: &'static str,
|
||||
variant: &'static str,
|
||||
len: usize,
|
||||
},
|
||||
|
||||
/// An indicator of the end of a tuple variant.
|
||||
TupleVariantEnd,
|
||||
|
||||
/// The header to a map.
|
||||
///
|
||||
/// After this header are the entries of the map, followed by `MapEnd`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// use std::collections::BTreeMap;
|
||||
///
|
||||
/// let mut map = BTreeMap::new();
|
||||
/// map.insert('A', 65);
|
||||
/// map.insert('Z', 90);
|
||||
///
|
||||
/// assert_tokens(&map, &[
|
||||
/// Token::Map { len: Some(2) },
|
||||
/// Token::Char('A'),
|
||||
/// Token::I32(65),
|
||||
/// Token::Char('Z'),
|
||||
/// Token::I32(90),
|
||||
/// Token::MapEnd,
|
||||
/// ]);
|
||||
/// ```
|
||||
Map { len: Option<usize> },
|
||||
|
||||
/// An indicator of the end of a map.
|
||||
MapEnd,
|
||||
|
||||
/// The header of a struct.
|
||||
///
|
||||
/// After this header are the fields of the struct, followed by `StructEnd`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::{Serialize, Deserialize};
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// # fn main() {
|
||||
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
/// struct S {
|
||||
/// a: u8,
|
||||
/// b: u8,
|
||||
/// }
|
||||
///
|
||||
/// let s = S { a: 0, b: 0 };
|
||||
/// assert_tokens(&s, &[
|
||||
/// Token::Struct { name: "S", len: 2 },
|
||||
/// Token::Str("a"),
|
||||
/// Token::U8(0),
|
||||
/// Token::Str("b"),
|
||||
/// Token::U8(0),
|
||||
/// Token::StructEnd,
|
||||
/// ]);
|
||||
/// # }
|
||||
/// ```
|
||||
Struct { name: &'static str, len: usize },
|
||||
|
||||
/// An indicator of the end of a struct.
|
||||
StructEnd,
|
||||
|
||||
/// The header of a struct variant of an enum.
|
||||
///
|
||||
/// After this header are the fields of the struct variant, followed by
|
||||
/// `StructVariantEnd`.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::{Serialize, Deserialize};
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// # fn main() {
|
||||
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
/// enum E {
|
||||
/// D { d: u8 },
|
||||
/// }
|
||||
///
|
||||
/// let d = E::D { d: 0 };
|
||||
/// assert_tokens(&d, &[
|
||||
/// Token::StructVariant { name: "E", variant: "D", len: 1 },
|
||||
/// Token::Str("d"),
|
||||
/// Token::U8(0),
|
||||
/// Token::StructVariantEnd,
|
||||
/// ]);
|
||||
/// # }
|
||||
/// ```
|
||||
StructVariant {
|
||||
name: &'static str,
|
||||
variant: &'static str,
|
||||
len: usize,
|
||||
},
|
||||
|
||||
/// An indicator of the end of a struct variant.
|
||||
StructVariantEnd,
|
||||
|
||||
/// The header to an enum of the given name.
|
||||
///
|
||||
/// ```edition2018
|
||||
/// # use serde::{Serialize, Deserialize};
|
||||
/// # use serde_test::{assert_tokens, Token};
|
||||
/// #
|
||||
/// # fn main() {
|
||||
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
/// enum E {
|
||||
/// A,
|
||||
/// B(u8),
|
||||
/// C(u8, u8),
|
||||
/// D { d: u8 },
|
||||
/// }
|
||||
///
|
||||
/// let a = E::A;
|
||||
/// assert_tokens(&a, &[
|
||||
/// Token::Enum { name: "E" },
|
||||
/// Token::Str("A"),
|
||||
/// Token::Unit,
|
||||
/// ]);
|
||||
///
|
||||
/// let b = E::B(0);
|
||||
/// assert_tokens(&b, &[
|
||||
/// Token::Enum { name: "E" },
|
||||
/// Token::Str("B"),
|
||||
/// Token::U8(0),
|
||||
/// ]);
|
||||
///
|
||||
/// let c = E::C(0, 0);
|
||||
/// assert_tokens(&c, &[
|
||||
/// Token::Enum { name: "E" },
|
||||
/// Token::Str("C"),
|
||||
/// Token::Seq { len: Some(2) },
|
||||
/// Token::U8(0),
|
||||
/// Token::U8(0),
|
||||
/// Token::SeqEnd,
|
||||
/// ]);
|
||||
///
|
||||
/// let d = E::D { d: 0 };
|
||||
/// assert_tokens(&d, &[
|
||||
/// Token::Enum { name: "E" },
|
||||
/// Token::Str("D"),
|
||||
/// Token::Map { len: Some(1) },
|
||||
/// Token::Str("d"),
|
||||
/// Token::U8(0),
|
||||
/// Token::MapEnd,
|
||||
/// ]);
|
||||
/// # }
|
||||
/// ```
|
||||
Enum { name: &'static str },
|
||||
}
|
||||
|
||||
impl Display for Token {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
Debug::fmt(self, formatter)
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,10 @@ unstable = ["serde/unstable"]
|
||||
serde = { path = "../serde" }
|
||||
|
||||
[dev-dependencies]
|
||||
automod = "1.0"
|
||||
automod = "1.0.1"
|
||||
fnv = "1.0"
|
||||
rustversion = "1.0"
|
||||
serde = { path = "../serde", features = ["rc", "derive"] }
|
||||
serde = { path = "../serde", features = ["rc"] }
|
||||
serde_derive = { path = "../serde_derive", features = ["deserialize_in_place"] }
|
||||
serde_test = { path = "../serde_test" }
|
||||
trybuild = { version = "1.0.66", features = ["diff"] }
|
||||
serde_test = "1.0.176"
|
||||
trybuild = { version = "1.0.97", features = ["diff"] }
|
||||
|
||||
@@ -7,6 +7,7 @@ publish = false
|
||||
|
||||
[dependencies]
|
||||
libc = { version = "0.2", default-features = false }
|
||||
serde = { path = "../../serde", default-features = false, features = ["derive"] }
|
||||
serde = { path = "../../serde", default-features = false }
|
||||
serde_derive = { path = "../../serde_derive" }
|
||||
|
||||
[workspace]
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#![allow(internal_features)]
|
||||
#![feature(lang_items, start)]
|
||||
#![no_std]
|
||||
|
||||
@@ -19,7 +20,7 @@ fn panic(_info: &core::panic::PanicInfo) -> ! {
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
use serde::{Serialize, Deserialize};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Unit;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#[cfg_attr(target_os = "emscripten", ignore)]
|
||||
#[rustversion::attr(not(nightly), ignore)]
|
||||
#[cfg_attr(miri, ignore)]
|
||||
#[cfg_attr(target_os = "emscripten", ignore = "disabled on Emscripten")]
|
||||
#[rustversion::attr(not(nightly), ignore = "requires nightly")]
|
||||
#[cfg_attr(miri, ignore = "incompatible with miri")]
|
||||
#[allow(unused_attributes)]
|
||||
#[test]
|
||||
fn ui() {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use serde::Deserialize;
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Nested;
|
||||
@@ -7,7 +7,9 @@ pub struct Nested;
|
||||
pub enum ExternallyTagged {
|
||||
Flatten {
|
||||
#[serde(flatten)]
|
||||
#[allow(dead_code)]
|
||||
nested: Nested,
|
||||
#[allow(dead_code)]
|
||||
string: &'static str,
|
||||
},
|
||||
}
|
||||
@@ -17,7 +19,9 @@ pub enum ExternallyTagged {
|
||||
pub enum InternallyTagged {
|
||||
Flatten {
|
||||
#[serde(flatten)]
|
||||
#[allow(dead_code)]
|
||||
nested: Nested,
|
||||
#[allow(dead_code)]
|
||||
string: &'static str,
|
||||
},
|
||||
}
|
||||
@@ -27,7 +31,9 @@ pub enum InternallyTagged {
|
||||
pub enum AdjacentlyTagged {
|
||||
Flatten {
|
||||
#[serde(flatten)]
|
||||
#[allow(dead_code)]
|
||||
nested: Nested,
|
||||
#[allow(dead_code)]
|
||||
string: &'static str,
|
||||
},
|
||||
}
|
||||
@@ -37,7 +43,9 @@ pub enum AdjacentlyTagged {
|
||||
pub enum UntaggedWorkaround {
|
||||
Flatten {
|
||||
#[serde(flatten)]
|
||||
#[allow(dead_code)]
|
||||
nested: Nested,
|
||||
#[allow(dead_code)]
|
||||
string: &'static str,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
macro_rules! bug {
|
||||
($serde_path:literal) => {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(crate = $serde_path)]
|
||||
pub struct Struct;
|
||||
};
|
||||
}
|
||||
|
||||
bug!("serde");
|
||||
@@ -0,0 +1,5 @@
|
||||
use serde_derive::Serialize;
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde()]
|
||||
pub struct S;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,9 +4,10 @@
|
||||
clippy::used_underscore_binding
|
||||
)]
|
||||
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use serde::de::value::{BorrowedStrDeserializer, MapDeserializer};
|
||||
use serde::de::{Deserialize, Deserializer, IntoDeserializer};
|
||||
use serde_derive::Deserialize;
|
||||
use serde_test::{assert_de_tokens, assert_de_tokens_error, Token};
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[test]
|
||||
@@ -130,20 +131,22 @@ fn test_cow() {
|
||||
borrowed: Cow<'b, str>,
|
||||
}
|
||||
|
||||
let tokens = &[
|
||||
Token::Struct {
|
||||
name: "Cows",
|
||||
len: 2,
|
||||
},
|
||||
Token::Str("copied"),
|
||||
Token::BorrowedStr("copied"),
|
||||
Token::Str("borrowed"),
|
||||
Token::BorrowedStr("borrowed"),
|
||||
Token::StructEnd,
|
||||
];
|
||||
struct BorrowedStr(&'static str);
|
||||
|
||||
let mut de = serde_test::Deserializer::new(tokens);
|
||||
let cows = Cows::deserialize(&mut de).unwrap();
|
||||
impl<'de> IntoDeserializer<'de> for BorrowedStr {
|
||||
type Deserializer = BorrowedStrDeserializer<'de, serde::de::value::Error>;
|
||||
|
||||
fn into_deserializer(self) -> Self::Deserializer {
|
||||
BorrowedStrDeserializer::new(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
let de = MapDeserializer::new(IntoIterator::into_iter([
|
||||
("copied", BorrowedStr("copied")),
|
||||
("borrowed", BorrowedStr("borrowed")),
|
||||
]));
|
||||
|
||||
let cows = Cows::deserialize(de).unwrap();
|
||||
|
||||
match cows.copied {
|
||||
Cow::Owned(ref s) if s == "copied" => {}
|
||||
|
||||
+137
-32
@@ -10,14 +10,20 @@
|
||||
)]
|
||||
#![cfg_attr(feature = "unstable", feature(never_type))]
|
||||
|
||||
use fnv::FnvHasher;
|
||||
use serde::de::value::{F32Deserializer, F64Deserializer};
|
||||
use serde::de::{Deserialize, DeserializeOwned, Deserializer, IntoDeserializer};
|
||||
use serde_derive::Deserialize;
|
||||
use serde_test::{assert_de_tokens, Configure, Token};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::default::Default;
|
||||
use std::ffi::{CStr, CString, OsString};
|
||||
use std::fmt::Debug;
|
||||
use std::iter;
|
||||
use std::net;
|
||||
use std::num::{
|
||||
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
|
||||
NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, Wrapping,
|
||||
NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, Saturating, Wrapping,
|
||||
};
|
||||
use std::ops::Bound;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -26,16 +32,10 @@ use std::sync::atomic::{
|
||||
AtomicBool, AtomicI16, AtomicI32, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, AtomicU8,
|
||||
AtomicUsize, Ordering,
|
||||
};
|
||||
use std::sync::{Arc, Weak as ArcWeak};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
use std::sync::atomic::{AtomicI64, AtomicU64};
|
||||
|
||||
use fnv::FnvHasher;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use serde_test::{assert_de_tokens, Configure, Token};
|
||||
use std::sync::{Arc, Weak as ArcWeak};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
#[macro_use]
|
||||
mod macros;
|
||||
@@ -45,6 +45,9 @@ mod macros;
|
||||
#[derive(Copy, Clone, PartialEq, Debug, Deserialize)]
|
||||
struct UnitStruct;
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Debug, Deserialize)]
|
||||
struct GenericUnitStruct<const N: u8>;
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
struct NewtypeStruct(i32);
|
||||
|
||||
@@ -199,12 +202,11 @@ fn assert_de_tokens_ignore(ignorable_tokens: &[Token]) {
|
||||
]
|
||||
.into_iter()
|
||||
.chain(ignorable_tokens.iter().copied())
|
||||
.chain(vec![Token::MapEnd].into_iter())
|
||||
.chain(iter::once(Token::MapEnd))
|
||||
.collect();
|
||||
|
||||
let mut de = serde_test::Deserializer::new(&concated_tokens);
|
||||
let base = IgnoreBase::deserialize(&mut de).unwrap();
|
||||
assert_eq!(base, IgnoreBase { a: 1 });
|
||||
let expected = IgnoreBase { a: 1 };
|
||||
assert_de_tokens(&expected, &concated_tokens);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
@@ -831,6 +833,26 @@ fn test_f64() {
|
||||
test(1.11, &[Token::F64(1.11)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nan() {
|
||||
let f32_deserializer = F32Deserializer::<serde::de::value::Error>::new;
|
||||
let f64_deserializer = F64Deserializer::<serde::de::value::Error>::new;
|
||||
|
||||
let pos_f32_nan = f32_deserializer(f32::NAN.copysign(1.0));
|
||||
let pos_f64_nan = f64_deserializer(f64::NAN.copysign(1.0));
|
||||
assert!(f32::deserialize(pos_f32_nan).unwrap().is_sign_positive());
|
||||
assert!(f32::deserialize(pos_f64_nan).unwrap().is_sign_positive());
|
||||
assert!(f64::deserialize(pos_f32_nan).unwrap().is_sign_positive());
|
||||
assert!(f64::deserialize(pos_f64_nan).unwrap().is_sign_positive());
|
||||
|
||||
let neg_f32_nan = f32_deserializer(f32::NAN.copysign(-1.0));
|
||||
let neg_f64_nan = f64_deserializer(f64::NAN.copysign(-1.0));
|
||||
assert!(f32::deserialize(neg_f32_nan).unwrap().is_sign_negative());
|
||||
assert!(f32::deserialize(neg_f64_nan).unwrap().is_sign_negative());
|
||||
assert!(f64::deserialize(neg_f32_nan).unwrap().is_sign_negative());
|
||||
assert!(f64::deserialize(neg_f64_nan).unwrap().is_sign_negative());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_char() {
|
||||
test('a', &[Token::Char('a')]);
|
||||
@@ -883,6 +905,17 @@ fn test_unit_struct() {
|
||||
test(UnitStruct, &[Token::UnitStruct { name: "UnitStruct" }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generic_unit_struct() {
|
||||
test(GenericUnitStruct::<8>, &[Token::Unit]);
|
||||
test(
|
||||
GenericUnitStruct::<8>,
|
||||
&[Token::UnitStruct {
|
||||
name: "GenericUnitStruct",
|
||||
}],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_newtype_struct() {
|
||||
test(
|
||||
@@ -1865,6 +1898,46 @@ fn test_range_inclusive() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_range_from() {
|
||||
test(
|
||||
1u32..,
|
||||
&[
|
||||
Token::Struct {
|
||||
name: "RangeFrom",
|
||||
len: 1,
|
||||
},
|
||||
Token::Str("start"),
|
||||
Token::U32(1),
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
test(
|
||||
1u32..,
|
||||
&[Token::Seq { len: Some(1) }, Token::U32(1), Token::SeqEnd],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_range_to() {
|
||||
test(
|
||||
..2u32,
|
||||
&[
|
||||
Token::Struct {
|
||||
name: "RangeTo",
|
||||
len: 1,
|
||||
},
|
||||
Token::Str("end"),
|
||||
Token::U32(2),
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
test(
|
||||
..2u32,
|
||||
&[Token::Seq { len: Some(1) }, Token::U32(2), Token::SeqEnd],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bound() {
|
||||
test(
|
||||
@@ -1992,6 +2065,43 @@ fn test_wrapping() {
|
||||
test(Wrapping(1usize), &[Token::U64(1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_saturating() {
|
||||
test(Saturating(1usize), &[Token::U32(1)]);
|
||||
test(Saturating(1usize), &[Token::U64(1)]);
|
||||
test(Saturating(0u8), &[Token::I8(0)]);
|
||||
test(Saturating(0u16), &[Token::I16(0)]);
|
||||
|
||||
// saturate input values at the minimum or maximum value
|
||||
test(Saturating(u8::MAX), &[Token::U16(u16::MAX)]);
|
||||
test(Saturating(u8::MAX), &[Token::U16(u8::MAX as u16 + 1)]);
|
||||
test(Saturating(u16::MAX), &[Token::U32(u32::MAX)]);
|
||||
test(Saturating(u32::MAX), &[Token::U64(u64::MAX)]);
|
||||
test(Saturating(u8::MIN), &[Token::I8(i8::MIN)]);
|
||||
test(Saturating(u16::MIN), &[Token::I16(i16::MIN)]);
|
||||
test(Saturating(u32::MIN), &[Token::I32(i32::MIN)]);
|
||||
test(Saturating(i8::MIN), &[Token::I16(i16::MIN)]);
|
||||
test(Saturating(i16::MIN), &[Token::I32(i32::MIN)]);
|
||||
test(Saturating(i32::MIN), &[Token::I64(i64::MIN)]);
|
||||
|
||||
test(Saturating(u8::MIN), &[Token::I8(-1)]);
|
||||
test(Saturating(u16::MIN), &[Token::I16(-1)]);
|
||||
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
{
|
||||
test(Saturating(usize::MIN), &[Token::U64(u64::MIN)]);
|
||||
test(Saturating(usize::MAX), &[Token::U64(u64::MAX)]);
|
||||
test(Saturating(isize::MIN), &[Token::I64(i64::MIN)]);
|
||||
test(Saturating(isize::MAX), &[Token::I64(i64::MAX)]);
|
||||
test(Saturating(0usize), &[Token::I64(i64::MIN)]);
|
||||
|
||||
test(
|
||||
Saturating(9_223_372_036_854_775_807usize),
|
||||
&[Token::I64(i64::MAX)],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rc_dst() {
|
||||
test(Rc::<str>::from("s"), &[Token::Str("s")]);
|
||||
@@ -2245,39 +2355,34 @@ fn test_cstr() {
|
||||
|
||||
#[test]
|
||||
fn test_atomics() {
|
||||
fn test<L, A, T>(load: L, val: T, token: Token)
|
||||
fn test<L, A, T>(load: L, val: T)
|
||||
where
|
||||
L: Fn(&A, Ordering) -> T,
|
||||
A: DeserializeOwned,
|
||||
T: PartialEq + Debug,
|
||||
T: PartialEq + Debug + Copy + for<'de> IntoDeserializer<'de>,
|
||||
{
|
||||
let tokens = &[token];
|
||||
let mut de = serde_test::Deserializer::new(tokens);
|
||||
match A::deserialize(&mut de) {
|
||||
match A::deserialize(val.into_deserializer()) {
|
||||
Ok(v) => {
|
||||
let loaded = load(&v, Ordering::Relaxed);
|
||||
assert_eq!(val, loaded);
|
||||
}
|
||||
Err(e) => panic!("tokens failed to deserialize: {}", e),
|
||||
};
|
||||
if de.remaining() > 0 {
|
||||
panic!("{} remaining tokens", de.remaining());
|
||||
}
|
||||
}
|
||||
|
||||
test(AtomicBool::load, true, Token::Bool(true));
|
||||
test(AtomicI8::load, -127, Token::I8(-127i8));
|
||||
test(AtomicI16::load, -510, Token::I16(-510i16));
|
||||
test(AtomicI32::load, -131072, Token::I32(-131072i32));
|
||||
test(AtomicIsize::load, -131072isize, Token::I32(-131072));
|
||||
test(AtomicU8::load, 127, Token::U8(127u8));
|
||||
test(AtomicU16::load, 510u16, Token::U16(510u16));
|
||||
test(AtomicU32::load, 131072u32, Token::U32(131072u32));
|
||||
test(AtomicUsize::load, 131072usize, Token::U32(131072));
|
||||
test(AtomicBool::load, true);
|
||||
test(AtomicI8::load, -127i8);
|
||||
test(AtomicI16::load, -510i16);
|
||||
test(AtomicI32::load, -131072i32);
|
||||
test(AtomicIsize::load, -131072isize);
|
||||
test(AtomicU8::load, 127u8);
|
||||
test(AtomicU16::load, 510u16);
|
||||
test(AtomicU32::load, 131072u32);
|
||||
test(AtomicUsize::load, 131072usize);
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
{
|
||||
test(AtomicI64::load, -8589934592, Token::I64(-8589934592));
|
||||
test(AtomicU64::load, 8589934592u64, Token::U64(8589934592));
|
||||
test(AtomicI64::load, -8589934592i64);
|
||||
test(AtomicU64::load, 8589934592u64);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
)]
|
||||
#![cfg_attr(feature = "unstable", feature(never_type))]
|
||||
|
||||
use serde::de::IntoDeserializer;
|
||||
use serde::Deserialize;
|
||||
use serde::de::{Deserialize, IntoDeserializer};
|
||||
use serde_derive::Deserialize;
|
||||
use serde_test::{assert_de_tokens_error, Token};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::ffi::{CStr, CString};
|
||||
@@ -1434,7 +1434,15 @@ fn test_number_from_string() {
|
||||
fn test_integer_from_float() {
|
||||
assert_de_tokens_error::<isize>(
|
||||
&[Token::F32(0.0)],
|
||||
"invalid type: floating point `0`, expected isize",
|
||||
"invalid type: floating point `0.0`, expected isize",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nan_no_decimal_point() {
|
||||
assert_de_tokens_error::<isize>(
|
||||
&[Token::F32(f32::NAN)],
|
||||
"invalid type: floating point `NaN`, expected isize",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1459,7 +1467,7 @@ fn test_duration_overflow_seq() {
|
||||
assert_de_tokens_error::<Duration>(
|
||||
&[
|
||||
Token::Seq { len: Some(2) },
|
||||
Token::U64(u64::max_value()),
|
||||
Token::U64(u64::MAX),
|
||||
Token::U32(1_000_000_000),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
@@ -1476,7 +1484,7 @@ fn test_duration_overflow_struct() {
|
||||
len: 2,
|
||||
},
|
||||
Token::Str("secs"),
|
||||
Token::U64(u64::max_value()),
|
||||
Token::U64(u64::MAX),
|
||||
Token::Str("nanos"),
|
||||
Token::U32(1_000_000_000),
|
||||
Token::StructEnd,
|
||||
@@ -1490,7 +1498,7 @@ fn test_systemtime_overflow_seq() {
|
||||
assert_de_tokens_error::<SystemTime>(
|
||||
&[
|
||||
Token::Seq { len: Some(2) },
|
||||
Token::U64(u64::max_value()),
|
||||
Token::U64(u64::MAX),
|
||||
Token::U32(1_000_000_000),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
@@ -1507,7 +1515,7 @@ fn test_systemtime_overflow_struct() {
|
||||
len: 2,
|
||||
},
|
||||
Token::Str("secs_since_epoch"),
|
||||
Token::U64(u64::max_value()),
|
||||
Token::U64(u64::MAX),
|
||||
Token::Str("nanos_since_epoch"),
|
||||
Token::U32(1_000_000_000),
|
||||
Token::StructEnd,
|
||||
@@ -1516,13 +1524,12 @@ fn test_systemtime_overflow_struct() {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(systemtime_checked_add)]
|
||||
#[test]
|
||||
fn test_systemtime_overflow() {
|
||||
assert_de_tokens_error::<SystemTime>(
|
||||
&[
|
||||
Token::Seq { len: Some(2) },
|
||||
Token::U64(u64::max_value()),
|
||||
Token::U64(u64::MAX),
|
||||
Token::U32(0),
|
||||
Token::SeqEnd,
|
||||
],
|
||||
|
||||
@@ -20,9 +20,9 @@
|
||||
clippy::type_repetition_in_bounds
|
||||
)]
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
use serde::de::{Deserialize, DeserializeOwned, Deserializer};
|
||||
use serde::ser::{Serialize, Serializer};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::borrow::Cow;
|
||||
use std::marker::PhantomData;
|
||||
use std::option::Option as StdOption;
|
||||
@@ -404,7 +404,7 @@ fn test_gen() {
|
||||
}
|
||||
|
||||
mod vis {
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
pub struct S;
|
||||
|
||||
@@ -422,6 +422,7 @@ fn test_gen() {
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "Self")]
|
||||
#[allow(dead_code)]
|
||||
struct RemoteSelf;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -636,7 +637,7 @@ fn test_gen() {
|
||||
|
||||
mod restricted {
|
||||
mod inner {
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Restricted {
|
||||
@@ -662,6 +663,7 @@ fn test_gen() {
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ImplicitlyBorrowedOption<'a> {
|
||||
#[allow(dead_code)]
|
||||
option: std::option::Option<&'a str>,
|
||||
}
|
||||
|
||||
@@ -685,14 +687,24 @@ fn test_gen() {
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum UntaggedWithBorrow<'a> {
|
||||
Single(#[serde(borrow)] RelObject<'a>),
|
||||
Many(#[serde(borrow)] Vec<RelObject<'a>>),
|
||||
pub enum UntaggedWithBorrow<'a> {
|
||||
Single(
|
||||
#[serde(borrow)]
|
||||
#[allow(dead_code)]
|
||||
RelObject<'a>,
|
||||
),
|
||||
Many(
|
||||
#[serde(borrow)]
|
||||
#[allow(dead_code)]
|
||||
Vec<RelObject<'a>>,
|
||||
),
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct RelObject<'a> {
|
||||
#[allow(dead_code)]
|
||||
ty: &'a str,
|
||||
#[allow(dead_code)]
|
||||
id: String,
|
||||
}
|
||||
|
||||
@@ -727,6 +739,7 @@ fn test_gen() {
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[repr(packed)]
|
||||
#[allow(dead_code)]
|
||||
struct Packed {
|
||||
x: u8,
|
||||
y: u16,
|
||||
@@ -736,6 +749,7 @@ fn test_gen() {
|
||||
($field:ty) => {
|
||||
#[derive(Deserialize)]
|
||||
struct MacroRules<'a> {
|
||||
#[allow(dead_code)]
|
||||
field: $field,
|
||||
}
|
||||
};
|
||||
@@ -752,14 +766,20 @@ fn test_gen() {
|
||||
#[derive(Deserialize)]
|
||||
struct BorrowLifetimeInsideMacro<'a> {
|
||||
#[serde(borrow = "'a")]
|
||||
#[allow(dead_code)]
|
||||
f: mac!(Cow<'a, str>),
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[allow(dead_code)]
|
||||
struct Struct {
|
||||
#[serde(serialize_with = "vec_first_element")]
|
||||
vec: Vec<Self>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(bound(deserialize = "[&'de str; N]: Copy"))]
|
||||
struct GenericUnitStruct<const N: usize>;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
@@ -834,7 +854,7 @@ pub fn is_zero(n: &u8) -> bool {
|
||||
*n == 0
|
||||
}
|
||||
|
||||
fn vec_first_element<T, S>(vec: &Vec<T>, serializer: S) -> StdResult<S::Ok, S::Error>
|
||||
fn vec_first_element<T, S>(vec: &[T], serializer: S) -> StdResult<S::Ok, S::Error>
|
||||
where
|
||||
T: Serialize,
|
||||
S: Serializer,
|
||||
|
||||
@@ -2,87 +2,187 @@
|
||||
|
||||
#![allow(clippy::derive_partial_eq_without_eq)]
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_test::{assert_de_tokens, Token};
|
||||
use serde_derive::Deserialize;
|
||||
use serde_test::{assert_de_tokens, assert_de_tokens_error, Token};
|
||||
|
||||
mod variant_identifier {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_variant_identifier() {
|
||||
#[derive(Deserialize, Debug, PartialEq)]
|
||||
#[serde(variant_identifier)]
|
||||
enum V {
|
||||
Aaa,
|
||||
#[serde(alias = "Ccc", alias = "Ddd")]
|
||||
Bbb,
|
||||
}
|
||||
|
||||
assert_de_tokens(&V::Aaa, &[Token::U8(0)]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::U16(0)]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::U32(0)]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::U64(0)]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::Str("Aaa")]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::Bytes(b"Aaa")]);
|
||||
#[test]
|
||||
fn variant1() {
|
||||
assert_de_tokens(&V::Aaa, &[Token::U8(0)]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::U16(0)]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::U32(0)]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::U64(0)]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::Str("Aaa")]);
|
||||
assert_de_tokens(&V::Aaa, &[Token::Bytes(b"Aaa")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aliases() {
|
||||
assert_de_tokens(&V::Bbb, &[Token::U8(1)]);
|
||||
assert_de_tokens(&V::Bbb, &[Token::U16(1)]);
|
||||
assert_de_tokens(&V::Bbb, &[Token::U32(1)]);
|
||||
assert_de_tokens(&V::Bbb, &[Token::U64(1)]);
|
||||
|
||||
assert_de_tokens(&V::Bbb, &[Token::Str("Bbb")]);
|
||||
assert_de_tokens(&V::Bbb, &[Token::Bytes(b"Bbb")]);
|
||||
|
||||
assert_de_tokens(&V::Bbb, &[Token::Str("Ccc")]);
|
||||
assert_de_tokens(&V::Bbb, &[Token::Bytes(b"Ccc")]);
|
||||
|
||||
assert_de_tokens(&V::Bbb, &[Token::Str("Ddd")]);
|
||||
assert_de_tokens(&V::Bbb, &[Token::Bytes(b"Ddd")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown() {
|
||||
assert_de_tokens_error::<V>(
|
||||
&[Token::U8(42)],
|
||||
"invalid value: integer `42`, expected variant index 0 <= i < 2",
|
||||
);
|
||||
assert_de_tokens_error::<V>(
|
||||
&[Token::U16(42)],
|
||||
"invalid value: integer `42`, expected variant index 0 <= i < 2",
|
||||
);
|
||||
assert_de_tokens_error::<V>(
|
||||
&[Token::U32(42)],
|
||||
"invalid value: integer `42`, expected variant index 0 <= i < 2",
|
||||
);
|
||||
assert_de_tokens_error::<V>(
|
||||
&[Token::U64(42)],
|
||||
"invalid value: integer `42`, expected variant index 0 <= i < 2",
|
||||
);
|
||||
assert_de_tokens_error::<V>(
|
||||
&[Token::Str("Unknown")],
|
||||
"unknown variant `Unknown`, expected one of `Aaa`, `Bbb`, `Ccc`, `Ddd`",
|
||||
);
|
||||
assert_de_tokens_error::<V>(
|
||||
&[Token::Bytes(b"Unknown")],
|
||||
"unknown variant `Unknown`, expected one of `Aaa`, `Bbb`, `Ccc`, `Ddd`",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_field_identifier() {
|
||||
mod field_identifier {
|
||||
use super::*;
|
||||
|
||||
#[derive(Deserialize, Debug, PartialEq)]
|
||||
#[serde(field_identifier, rename_all = "snake_case")]
|
||||
enum F {
|
||||
Aaa,
|
||||
#[serde(alias = "ccc", alias = "ddd")]
|
||||
Bbb,
|
||||
}
|
||||
|
||||
assert_de_tokens(&F::Aaa, &[Token::U8(0)]);
|
||||
assert_de_tokens(&F::Aaa, &[Token::U16(0)]);
|
||||
assert_de_tokens(&F::Aaa, &[Token::U32(0)]);
|
||||
assert_de_tokens(&F::Aaa, &[Token::U64(0)]);
|
||||
assert_de_tokens(&F::Aaa, &[Token::Str("aaa")]);
|
||||
assert_de_tokens(&F::Aaa, &[Token::Bytes(b"aaa")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unit_fallthrough() {
|
||||
#[derive(Deserialize, Debug, PartialEq)]
|
||||
#[serde(field_identifier, rename_all = "snake_case")]
|
||||
enum F {
|
||||
Aaa,
|
||||
Bbb,
|
||||
#[serde(other)]
|
||||
Other,
|
||||
#[test]
|
||||
fn field1() {
|
||||
assert_de_tokens(&F::Aaa, &[Token::U8(0)]);
|
||||
assert_de_tokens(&F::Aaa, &[Token::U16(0)]);
|
||||
assert_de_tokens(&F::Aaa, &[Token::U32(0)]);
|
||||
assert_de_tokens(&F::Aaa, &[Token::U64(0)]);
|
||||
assert_de_tokens(&F::Aaa, &[Token::Str("aaa")]);
|
||||
assert_de_tokens(&F::Aaa, &[Token::Bytes(b"aaa")]);
|
||||
}
|
||||
|
||||
assert_de_tokens(&F::Other, &[Token::U8(42)]);
|
||||
assert_de_tokens(&F::Other, &[Token::U16(42)]);
|
||||
assert_de_tokens(&F::Other, &[Token::U32(42)]);
|
||||
assert_de_tokens(&F::Other, &[Token::U64(42)]);
|
||||
assert_de_tokens(&F::Other, &[Token::Str("x")]);
|
||||
}
|
||||
#[test]
|
||||
fn aliases() {
|
||||
assert_de_tokens(&F::Bbb, &[Token::U8(1)]);
|
||||
assert_de_tokens(&F::Bbb, &[Token::U16(1)]);
|
||||
assert_de_tokens(&F::Bbb, &[Token::U32(1)]);
|
||||
assert_de_tokens(&F::Bbb, &[Token::U64(1)]);
|
||||
|
||||
#[test]
|
||||
fn test_newtype_fallthrough() {
|
||||
#[derive(Deserialize, Debug, PartialEq)]
|
||||
#[serde(field_identifier, rename_all = "snake_case")]
|
||||
enum F {
|
||||
Aaa,
|
||||
Bbb,
|
||||
Other(String),
|
||||
assert_de_tokens(&F::Bbb, &[Token::Str("bbb")]);
|
||||
assert_de_tokens(&F::Bbb, &[Token::Bytes(b"bbb")]);
|
||||
|
||||
assert_de_tokens(&F::Bbb, &[Token::Str("ccc")]);
|
||||
assert_de_tokens(&F::Bbb, &[Token::Bytes(b"ccc")]);
|
||||
|
||||
assert_de_tokens(&F::Bbb, &[Token::Str("ddd")]);
|
||||
assert_de_tokens(&F::Bbb, &[Token::Bytes(b"ddd")]);
|
||||
}
|
||||
|
||||
assert_de_tokens(&F::Other("x".to_owned()), &[Token::Str("x")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_newtype_fallthrough_generic() {
|
||||
#[derive(Deserialize, Debug, PartialEq)]
|
||||
#[serde(field_identifier, rename_all = "snake_case")]
|
||||
enum F<T> {
|
||||
Aaa,
|
||||
Bbb,
|
||||
Other(T),
|
||||
#[test]
|
||||
fn unknown() {
|
||||
assert_de_tokens_error::<F>(
|
||||
&[Token::U8(42)],
|
||||
"invalid value: integer `42`, expected field index 0 <= i < 2",
|
||||
);
|
||||
assert_de_tokens_error::<F>(
|
||||
&[Token::U16(42)],
|
||||
"invalid value: integer `42`, expected field index 0 <= i < 2",
|
||||
);
|
||||
assert_de_tokens_error::<F>(
|
||||
&[Token::U32(42)],
|
||||
"invalid value: integer `42`, expected field index 0 <= i < 2",
|
||||
);
|
||||
assert_de_tokens_error::<F>(
|
||||
&[Token::U64(42)],
|
||||
"invalid value: integer `42`, expected field index 0 <= i < 2",
|
||||
);
|
||||
assert_de_tokens_error::<F>(
|
||||
&[Token::Str("unknown")],
|
||||
"unknown field `unknown`, expected one of `aaa`, `bbb`, `ccc`, `ddd`",
|
||||
);
|
||||
assert_de_tokens_error::<F>(
|
||||
&[Token::Bytes(b"unknown")],
|
||||
"unknown field `unknown`, expected one of `aaa`, `bbb`, `ccc`, `ddd`",
|
||||
);
|
||||
}
|
||||
|
||||
assert_de_tokens(&F::Other(42u8), &[Token::U8(42)]);
|
||||
assert_de_tokens(&F::Other(42u16), &[Token::U16(42)]);
|
||||
assert_de_tokens(&F::Other(42u32), &[Token::U32(42)]);
|
||||
assert_de_tokens(&F::Other(42u64), &[Token::U64(42)]);
|
||||
assert_de_tokens(&F::Other("x".to_owned()), &[Token::Str("x")]);
|
||||
#[test]
|
||||
fn unit_fallthrough() {
|
||||
#[derive(Deserialize, Debug, PartialEq)]
|
||||
#[serde(field_identifier, rename_all = "snake_case")]
|
||||
enum F {
|
||||
Aaa,
|
||||
Bbb,
|
||||
#[serde(other)]
|
||||
Other,
|
||||
}
|
||||
|
||||
assert_de_tokens(&F::Other, &[Token::U8(42)]);
|
||||
assert_de_tokens(&F::Other, &[Token::U16(42)]);
|
||||
assert_de_tokens(&F::Other, &[Token::U32(42)]);
|
||||
assert_de_tokens(&F::Other, &[Token::U64(42)]);
|
||||
assert_de_tokens(&F::Other, &[Token::Str("x")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newtype_fallthrough() {
|
||||
#[derive(Deserialize, Debug, PartialEq)]
|
||||
#[serde(field_identifier, rename_all = "snake_case")]
|
||||
enum F {
|
||||
Aaa,
|
||||
Bbb,
|
||||
Other(String),
|
||||
}
|
||||
|
||||
assert_de_tokens(&F::Other("x".to_owned()), &[Token::Str("x")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newtype_fallthrough_generic() {
|
||||
#[derive(Deserialize, Debug, PartialEq)]
|
||||
#[serde(field_identifier, rename_all = "snake_case")]
|
||||
enum F<T> {
|
||||
Aaa,
|
||||
Bbb,
|
||||
Other(T),
|
||||
}
|
||||
|
||||
assert_de_tokens(&F::Other(42u8), &[Token::U8(42)]);
|
||||
assert_de_tokens(&F::Other(42u16), &[Token::U16(42)]);
|
||||
assert_de_tokens(&F::Other(42u32), &[Token::U32(42)]);
|
||||
assert_de_tokens(&F::Other(42u64), &[Token::U64(42)]);
|
||||
assert_de_tokens(&F::Other("x".to_owned()), &[Token::Str("x")]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
use serde::de::value::{Error, MapDeserializer, SeqDeserializer};
|
||||
use serde::de::{
|
||||
DeserializeSeed, EnumAccess, IgnoredAny, IntoDeserializer, VariantAccess, Visitor,
|
||||
Deserialize, DeserializeSeed, Deserializer, EnumAccess, IgnoredAny, IntoDeserializer,
|
||||
VariantAccess, Visitor,
|
||||
};
|
||||
use serde::{forward_to_deserialize_any, Deserialize, Deserializer};
|
||||
use serde::forward_to_deserialize_any;
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
#[derive(PartialEq, Debug, Deserialize)]
|
||||
enum Target {
|
||||
|
||||
+324
-18
@@ -8,11 +8,10 @@
|
||||
|
||||
mod bytes;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use serde_test::{
|
||||
assert_de_tokens, assert_de_tokens_error, assert_ser_tokens, assert_tokens, Token,
|
||||
};
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
@@ -473,7 +472,10 @@ fn test_adjacently_tagged_newtype_struct() {
|
||||
},
|
||||
Token::U32(5),
|
||||
Token::Str("t"),
|
||||
Token::Str("Newtype"),
|
||||
Token::UnitVariant {
|
||||
name: "E",
|
||||
variant: "Newtype",
|
||||
},
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
@@ -812,6 +814,100 @@ fn test_internally_tagged_enum() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_internally_tagged_enum_with_untagged_variant() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind")]
|
||||
enum InternallyTagged {
|
||||
Tagged {
|
||||
a: u8,
|
||||
},
|
||||
#[serde(untagged)]
|
||||
Untagged {
|
||||
kind: String,
|
||||
b: u8,
|
||||
},
|
||||
}
|
||||
|
||||
assert_de_tokens(
|
||||
&InternallyTagged::Tagged { a: 1 },
|
||||
&[
|
||||
Token::Map { len: Some(2) },
|
||||
Token::Str("kind"),
|
||||
Token::Str("Tagged"),
|
||||
Token::Str("a"),
|
||||
Token::U8(1),
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::Tagged { a: 1 },
|
||||
&[
|
||||
Token::Struct {
|
||||
name: "InternallyTagged",
|
||||
len: 2,
|
||||
},
|
||||
Token::Str("kind"),
|
||||
Token::Str("Tagged"),
|
||||
Token::Str("a"),
|
||||
Token::U8(1),
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&InternallyTagged::Untagged {
|
||||
kind: "Foo".to_owned(),
|
||||
b: 2,
|
||||
},
|
||||
&[
|
||||
Token::Map { len: Some(2) },
|
||||
Token::Str("kind"),
|
||||
Token::Str("Foo"),
|
||||
Token::Str("b"),
|
||||
Token::U8(2),
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::Untagged {
|
||||
kind: "Foo".to_owned(),
|
||||
b: 2,
|
||||
},
|
||||
&[
|
||||
Token::Struct {
|
||||
name: "InternallyTagged",
|
||||
len: 2,
|
||||
},
|
||||
Token::Str("kind"),
|
||||
Token::Str("Foo"),
|
||||
Token::Str("b"),
|
||||
Token::U8(2),
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&InternallyTagged::Untagged {
|
||||
kind: "Tagged".to_owned(),
|
||||
b: 2,
|
||||
},
|
||||
&[
|
||||
Token::Struct {
|
||||
name: "InternallyTagged",
|
||||
len: 2,
|
||||
},
|
||||
Token::Str("kind"),
|
||||
Token::Str("Tagged"),
|
||||
Token::Str("b"),
|
||||
Token::U8(2),
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_internally_tagged_bytes() {
|
||||
#[derive(Debug, PartialEq, Deserialize)]
|
||||
@@ -985,6 +1081,15 @@ fn test_internally_tagged_struct_variant_containing_unit_variant() {
|
||||
Log { level: Level },
|
||||
}
|
||||
|
||||
assert_de_tokens(
|
||||
&Level::Info,
|
||||
&[
|
||||
Token::Enum { name: "Level" },
|
||||
Token::BorrowedStr("Info"),
|
||||
Token::Unit,
|
||||
],
|
||||
);
|
||||
|
||||
assert_de_tokens(
|
||||
&Message::Log { level: Level::Info },
|
||||
&[
|
||||
@@ -995,7 +1100,9 @@ fn test_internally_tagged_struct_variant_containing_unit_variant() {
|
||||
Token::Str("action"),
|
||||
Token::Str("Log"),
|
||||
Token::Str("level"),
|
||||
Token::Enum { name: "Level" },
|
||||
Token::BorrowedStr("Info"),
|
||||
Token::Unit,
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
@@ -1007,7 +1114,9 @@ fn test_internally_tagged_struct_variant_containing_unit_variant() {
|
||||
Token::Str("action"),
|
||||
Token::Str("Log"),
|
||||
Token::Str("level"),
|
||||
Token::Enum { name: "Level" },
|
||||
Token::BorrowedStr("Info"),
|
||||
Token::Unit,
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
@@ -1017,7 +1126,9 @@ fn test_internally_tagged_struct_variant_containing_unit_variant() {
|
||||
&[
|
||||
Token::Seq { len: Some(2) },
|
||||
Token::Str("Log"),
|
||||
Token::Enum { name: "Level" },
|
||||
Token::BorrowedStr("Info"),
|
||||
Token::Unit,
|
||||
Token::SeqEnd,
|
||||
],
|
||||
);
|
||||
@@ -1067,7 +1178,10 @@ fn test_adjacently_tagged_enum() {
|
||||
len: 1,
|
||||
},
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Unit",
|
||||
},
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
@@ -1081,7 +1195,10 @@ fn test_adjacently_tagged_enum() {
|
||||
len: 2,
|
||||
},
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Unit",
|
||||
},
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
@@ -1095,7 +1212,10 @@ fn test_adjacently_tagged_enum() {
|
||||
len: 2,
|
||||
},
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Unit",
|
||||
},
|
||||
Token::Str("c"),
|
||||
Token::Unit,
|
||||
Token::StructEnd,
|
||||
@@ -1113,7 +1233,10 @@ fn test_adjacently_tagged_enum() {
|
||||
Token::Str("c"),
|
||||
Token::Unit,
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Unit",
|
||||
},
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
@@ -1129,7 +1252,10 @@ fn test_adjacently_tagged_enum() {
|
||||
Token::Str("f"),
|
||||
Token::Unit,
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Unit",
|
||||
},
|
||||
Token::Str("g"),
|
||||
Token::Unit,
|
||||
Token::Str("c"),
|
||||
@@ -1149,7 +1275,10 @@ fn test_adjacently_tagged_enum() {
|
||||
len: 2,
|
||||
},
|
||||
Token::Str("t"),
|
||||
Token::Str("Newtype"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Newtype",
|
||||
},
|
||||
Token::Str("c"),
|
||||
Token::U8(1),
|
||||
Token::StructEnd,
|
||||
@@ -1167,7 +1296,10 @@ fn test_adjacently_tagged_enum() {
|
||||
Token::Str("c"),
|
||||
Token::U8(1),
|
||||
Token::Str("t"),
|
||||
Token::Str("Newtype"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Newtype",
|
||||
},
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
@@ -1181,7 +1313,10 @@ fn test_adjacently_tagged_enum() {
|
||||
len: 1,
|
||||
},
|
||||
Token::Str("t"),
|
||||
Token::Str("Newtype"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Newtype",
|
||||
},
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
@@ -1195,7 +1330,10 @@ fn test_adjacently_tagged_enum() {
|
||||
len: 2,
|
||||
},
|
||||
Token::Str("t"),
|
||||
Token::Str("Tuple"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Tuple",
|
||||
},
|
||||
Token::Str("c"),
|
||||
Token::Tuple { len: 2 },
|
||||
Token::U8(1),
|
||||
@@ -1219,7 +1357,10 @@ fn test_adjacently_tagged_enum() {
|
||||
Token::U8(1),
|
||||
Token::TupleEnd,
|
||||
Token::Str("t"),
|
||||
Token::Str("Tuple"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Tuple",
|
||||
},
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
@@ -1233,7 +1374,10 @@ fn test_adjacently_tagged_enum() {
|
||||
len: 2,
|
||||
},
|
||||
Token::Str("t"),
|
||||
Token::Str("Struct"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Struct",
|
||||
},
|
||||
Token::Str("c"),
|
||||
Token::Struct {
|
||||
name: "Struct",
|
||||
@@ -1263,7 +1407,48 @@ fn test_adjacently_tagged_enum() {
|
||||
Token::U8(1),
|
||||
Token::StructEnd,
|
||||
Token::Str("t"),
|
||||
Token::Str("Struct"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Struct",
|
||||
},
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
|
||||
// integer field keys
|
||||
assert_de_tokens(
|
||||
&AdjacentlyTagged::Newtype::<u8>(1),
|
||||
&[
|
||||
Token::Struct {
|
||||
name: "AdjacentlyTagged",
|
||||
len: 2,
|
||||
},
|
||||
Token::U64(1), // content field
|
||||
Token::U8(1),
|
||||
Token::U64(0), // tag field
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Newtype",
|
||||
},
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
|
||||
// byte-array field keys
|
||||
assert_de_tokens(
|
||||
&AdjacentlyTagged::Newtype::<u8>(1),
|
||||
&[
|
||||
Token::Struct {
|
||||
name: "AdjacentlyTagged",
|
||||
len: 2,
|
||||
},
|
||||
Token::Bytes(b"c"),
|
||||
Token::U8(1),
|
||||
Token::Bytes(b"t"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Newtype",
|
||||
},
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
@@ -1285,7 +1470,10 @@ fn test_adjacently_tagged_enum_deny_unknown_fields() {
|
||||
len: 2,
|
||||
},
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Unit",
|
||||
},
|
||||
Token::Str("c"),
|
||||
Token::Unit,
|
||||
Token::StructEnd,
|
||||
@@ -1299,7 +1487,10 @@ fn test_adjacently_tagged_enum_deny_unknown_fields() {
|
||||
len: 2,
|
||||
},
|
||||
Token::Str("t"),
|
||||
Token::Str("Unit"),
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Unit",
|
||||
},
|
||||
Token::Str("c"),
|
||||
Token::Unit,
|
||||
Token::Str("h"),
|
||||
@@ -1330,6 +1521,35 @@ fn test_adjacently_tagged_enum_deny_unknown_fields() {
|
||||
],
|
||||
r#"invalid value: string "h", expected "t" or "c""#,
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<AdjacentlyTagged>(
|
||||
&[
|
||||
Token::Struct {
|
||||
name: "AdjacentlyTagged",
|
||||
len: 2,
|
||||
},
|
||||
Token::U64(0), // tag field
|
||||
Token::UnitVariant {
|
||||
name: "AdjacentlyTagged",
|
||||
variant: "Unit",
|
||||
},
|
||||
Token::U64(3),
|
||||
],
|
||||
r#"invalid value: integer `3`, expected "t" or "c""#,
|
||||
);
|
||||
|
||||
assert_de_tokens_error::<AdjacentlyTagged>(
|
||||
&[
|
||||
Token::Struct {
|
||||
name: "AdjacentlyTagged",
|
||||
len: 2,
|
||||
},
|
||||
Token::Bytes(b"c"),
|
||||
Token::Unit,
|
||||
Token::Bytes(b"h"),
|
||||
],
|
||||
r#"invalid value: byte array, expected "t" or "c""#,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1372,6 +1592,9 @@ fn test_enum_in_internally_tagged_enum() {
|
||||
],
|
||||
);
|
||||
|
||||
// Reaches crate::private::de::content::VariantDeserializer::tuple_variant
|
||||
// Content::Seq case
|
||||
// via ContentDeserializer::deserialize_enum
|
||||
assert_tokens(
|
||||
&Outer::Inner(Inner::Tuple(1, 1)),
|
||||
&[
|
||||
@@ -1390,6 +1613,9 @@ fn test_enum_in_internally_tagged_enum() {
|
||||
],
|
||||
);
|
||||
|
||||
// Reaches crate::private::de::content::VariantDeserializer::struct_variant
|
||||
// Content::Map case
|
||||
// via ContentDeserializer::deserialize_enum
|
||||
assert_tokens(
|
||||
&Outer::Inner(Inner::Struct { f: 1 }),
|
||||
&[
|
||||
@@ -1407,6 +1633,23 @@ fn test_enum_in_internally_tagged_enum() {
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
|
||||
// Reaches crate::private::de::content::VariantDeserializer::struct_variant
|
||||
// Content::Seq case
|
||||
// via ContentDeserializer::deserialize_enum
|
||||
assert_de_tokens(
|
||||
&Outer::Inner(Inner::Struct { f: 1 }),
|
||||
&[
|
||||
Token::Map { len: Some(2) },
|
||||
Token::Str("type"),
|
||||
Token::Str("Inner"),
|
||||
Token::Str("Struct"),
|
||||
Token::Seq { len: Some(1) },
|
||||
Token::U8(1), // f
|
||||
Token::SeqEnd,
|
||||
Token::MapEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1485,7 +1728,10 @@ fn test_internally_tagged_struct_with_flattened_field() {
|
||||
Token::Str("tag_struct"),
|
||||
Token::Str("Struct"),
|
||||
Token::Str("tag_enum"),
|
||||
Token::Str("A"),
|
||||
Token::UnitVariant {
|
||||
name: "Enum",
|
||||
variant: "A",
|
||||
},
|
||||
Token::Str("content"),
|
||||
Token::U64(0),
|
||||
Token::MapEnd,
|
||||
@@ -1866,6 +2112,62 @@ fn test_rename_all() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rename_all_fields() {
|
||||
#[derive(Serialize, Deserialize, Debug, PartialEq)]
|
||||
#[serde(rename_all_fields = "kebab-case")]
|
||||
enum E {
|
||||
V1,
|
||||
V2(bool),
|
||||
V3 {
|
||||
a_field: bool,
|
||||
another_field: bool,
|
||||
#[serde(rename = "last-field")]
|
||||
yet_another_field: bool,
|
||||
},
|
||||
#[serde(rename_all = "snake_case")]
|
||||
V4 {
|
||||
a_field: bool,
|
||||
},
|
||||
}
|
||||
|
||||
assert_tokens(
|
||||
&E::V3 {
|
||||
a_field: true,
|
||||
another_field: true,
|
||||
yet_another_field: true,
|
||||
},
|
||||
&[
|
||||
Token::StructVariant {
|
||||
name: "E",
|
||||
variant: "V3",
|
||||
len: 3,
|
||||
},
|
||||
Token::Str("a-field"),
|
||||
Token::Bool(true),
|
||||
Token::Str("another-field"),
|
||||
Token::Bool(true),
|
||||
Token::Str("last-field"),
|
||||
Token::Bool(true),
|
||||
Token::StructVariantEnd,
|
||||
],
|
||||
);
|
||||
|
||||
assert_tokens(
|
||||
&E::V4 { a_field: true },
|
||||
&[
|
||||
Token::StructVariant {
|
||||
name: "E",
|
||||
variant: "V4",
|
||||
len: 1,
|
||||
},
|
||||
Token::Str("a_field"),
|
||||
Token::Bool(true),
|
||||
Token::StructVariantEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_untagged_newtype_variant_containing_unit_struct_not_map() {
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -1932,24 +2234,28 @@ fn test_internally_tagged_newtype_variant_containing_unit_struct() {
|
||||
fn test_packed_struct_can_derive_serialize() {
|
||||
#[derive(Copy, Clone, Serialize)]
|
||||
#[repr(packed, C)]
|
||||
#[allow(dead_code)]
|
||||
struct PackedC {
|
||||
t: f32,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Serialize)]
|
||||
#[repr(C, packed)]
|
||||
#[allow(dead_code)]
|
||||
struct CPacked {
|
||||
t: f32,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Serialize)]
|
||||
#[repr(C, packed(2))]
|
||||
#[allow(dead_code)]
|
||||
struct CPacked2 {
|
||||
t: f32,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Serialize)]
|
||||
#[repr(packed(2), C)]
|
||||
#[allow(dead_code)]
|
||||
struct Packed2C {
|
||||
t: f32,
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#![allow(clippy::redundant_field_names)]
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
mod remote {
|
||||
pub struct Unit;
|
||||
@@ -125,6 +125,9 @@ struct Test {
|
||||
|
||||
#[serde(with = "EnumConcrete")]
|
||||
enum_concrete: remote::EnumGeneric<u8>,
|
||||
|
||||
#[serde(with = "ErrorKindDef")]
|
||||
io_error_kind: ErrorKind,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -197,6 +200,23 @@ enum EnumConcrete {
|
||||
Variant(u8),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ErrorKind {
|
||||
NotFound,
|
||||
PermissionDenied,
|
||||
#[allow(dead_code)]
|
||||
ConnectionRefused,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "ErrorKind")]
|
||||
#[non_exhaustive]
|
||||
enum ErrorKindDef {
|
||||
NotFound,
|
||||
PermissionDenied,
|
||||
// ...
|
||||
}
|
||||
|
||||
impl From<PrimitivePrivDef> for remote::PrimitivePriv {
|
||||
fn from(def: PrimitivePrivDef) -> Self {
|
||||
remote::PrimitivePriv::new(def.0)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use serde_test::{assert_tokens, Configure, Token};
|
||||
|
||||
use std::net;
|
||||
|
||||
#[macro_use]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#![allow(clippy::used_underscore_binding)]
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
#[test]
|
||||
fn test_self() {
|
||||
|
||||
@@ -1,29 +1,27 @@
|
||||
#![allow(clippy::derive_partial_eq_without_eq, clippy::unreadable_literal)]
|
||||
#![cfg_attr(feature = "unstable", feature(never_type))]
|
||||
|
||||
use fnv::FnvHasher;
|
||||
use serde_derive::Serialize;
|
||||
use serde_test::{assert_ser_tokens, assert_ser_tokens_error, Configure, Token};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::ffi::CString;
|
||||
use std::net;
|
||||
use std::num::Wrapping;
|
||||
use std::num::{Saturating, Wrapping};
|
||||
use std::ops::Bound;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::{Rc, Weak as RcWeak};
|
||||
#[cfg(unix)]
|
||||
use std::str;
|
||||
use std::sync::atomic::{
|
||||
AtomicBool, AtomicI16, AtomicI32, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, AtomicU8,
|
||||
AtomicUsize,
|
||||
};
|
||||
use std::sync::{Arc, Mutex, RwLock, Weak as ArcWeak};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::str;
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
use std::sync::atomic::{AtomicI64, AtomicU64};
|
||||
|
||||
use fnv::FnvHasher;
|
||||
use serde::Serialize;
|
||||
use serde_test::{assert_ser_tokens, assert_ser_tokens_error, Configure, Token};
|
||||
use std::sync::{Arc, Mutex, RwLock, Weak as ArcWeak};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
#[macro_use]
|
||||
mod macros;
|
||||
@@ -502,6 +500,38 @@ fn test_range_inclusive() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_range_from() {
|
||||
assert_ser_tokens(
|
||||
&(1u32..),
|
||||
&[
|
||||
Token::Struct {
|
||||
name: "RangeFrom",
|
||||
len: 1,
|
||||
},
|
||||
Token::Str("start"),
|
||||
Token::U32(1),
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_range_to() {
|
||||
assert_ser_tokens(
|
||||
&(..2u32),
|
||||
&[
|
||||
Token::Struct {
|
||||
name: "RangeTo",
|
||||
len: 1,
|
||||
},
|
||||
Token::Str("end"),
|
||||
Token::U32(2),
|
||||
Token::StructEnd,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bound() {
|
||||
assert_ser_tokens(
|
||||
@@ -594,6 +624,11 @@ fn test_wrapping() {
|
||||
assert_ser_tokens(&Wrapping(1usize), &[Token::U64(1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_saturating() {
|
||||
assert_ser_tokens(&Saturating(1usize), &[Token::U64(1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rc_dst() {
|
||||
assert_ser_tokens(&Rc::<str>::from("s"), &[Token::Str("s")]);
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
#[test]
|
||||
fn test_gen_custom_serde() {
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
#[derive(serde_derive::Serialize, serde_derive::Deserialize)]
|
||||
#[serde(crate = "fake_serde")]
|
||||
struct Foo;
|
||||
|
||||
@@ -27,19 +27,21 @@ mod fake_serde {
|
||||
{
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub trait Serialize {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>;
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub trait Deserialize<'a>: Sized {
|
||||
fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error>;
|
||||
}
|
||||
}
|
||||
|
||||
trait AssertNotSerdeSerialize {}
|
||||
pub trait AssertNotSerdeSerialize {}
|
||||
|
||||
impl<T: serde::Serialize> AssertNotSerdeSerialize for T {}
|
||||
|
||||
trait AssertNotSerdeDeserialize<'a> {}
|
||||
pub trait AssertNotSerdeDeserialize<'a> {}
|
||||
|
||||
impl<'a, T: serde::Deserialize<'a>> AssertNotSerdeDeserialize<'a> for T {}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#![allow(clippy::derive_partial_eq_without_eq, clippy::similar_names)]
|
||||
|
||||
use serde::de::value::{self, MapAccessDeserializer};
|
||||
use serde::de::{IntoDeserializer, MapAccess, Visitor};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use serde::de::{Deserialize, Deserializer, IntoDeserializer, MapAccess, Visitor};
|
||||
use serde_derive::Deserialize;
|
||||
use serde_test::{assert_de_tokens, Token};
|
||||
use std::fmt;
|
||||
|
||||
@@ -63,7 +63,7 @@ fn test_map_access_to_enum() {
|
||||
type Value = Potential;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "a map")
|
||||
formatter.write_str("a map")
|
||||
}
|
||||
|
||||
fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use serde_derive::Serialize;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
error: #[serde(flatten)] cannot be used on newtype structs
|
||||
--> tests/ui/conflict/flatten-newtype-struct.rs:6:12
|
||||
--> tests/ui/conflict/flatten-newtype-struct.rs:5:12
|
||||
|
|
||||
6 | struct Foo(#[serde(flatten)] HashMap<String, String>);
|
||||
5 | struct Foo(#[serde(flatten)] HashMap<String, String>);
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use serde_derive::Serialize;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
error: #[serde(flatten)] cannot be used on tuple structs
|
||||
--> tests/ui/conflict/flatten-tuple-struct.rs:6:17
|
||||
--> tests/ui/conflict/flatten-tuple-struct.rs:5:17
|
||||
|
|
||||
6 | struct Foo(u32, #[serde(flatten)] HashMap<String, String>);
|
||||
5 | struct Foo(u32, #[serde(flatten)] HashMap<String, String>);
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
error: #[serde(default)] can only be used on structs with named fields
|
||||
--> tests/ui/default-attribute/enum.rs:5:1
|
||||
error: #[serde(default)] can only be used on structs
|
||||
--> tests/ui/default-attribute/enum.rs:4:9
|
||||
|
|
||||
5 | enum E {
|
||||
| ^^^^
|
||||
4 | #[serde(default)]
|
||||
| ^^^^^^^
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
error: #[serde(default = "...")] can only be used on structs with named fields
|
||||
--> tests/ui/default-attribute/enum_path.rs:5:1
|
||||
error: #[serde(default = "...")] can only be used on structs
|
||||
--> tests/ui/default-attribute/enum_path.rs:4:9
|
||||
|
|
||||
5 | enum E {
|
||||
| ^^^^
|
||||
4 | #[serde(default = "default_e")]
|
||||
| ^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(default)]
|
||||
struct T(u8, u8);
|
||||
|
||||
fn main() {}
|
||||
@@ -1,5 +0,0 @@
|
||||
error: #[serde(default)] can only be used on structs with named fields
|
||||
--> tests/ui/default-attribute/nameless_struct_fields.rs:5:9
|
||||
|
|
||||
5 | struct T(u8, u8);
|
||||
| ^^^^^^^^
|
||||
@@ -1,7 +0,0 @@
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(default = "default_t")]
|
||||
struct T(u8, u8);
|
||||
|
||||
fn main() {}
|
||||
@@ -1,5 +0,0 @@
|
||||
error: #[serde(default = "...")] can only be used on structs with named fields
|
||||
--> tests/ui/default-attribute/nameless_struct_fields_path.rs:5:9
|
||||
|
|
||||
5 | struct T(u8, u8);
|
||||
| ^^^^^^^^
|
||||
@@ -0,0 +1,47 @@
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
// No errors expected.
|
||||
#[derive(Deserialize)]
|
||||
struct T0(u8, u8);
|
||||
|
||||
// No errors expected:
|
||||
// - If both fields are provided, both get value from data.
|
||||
// - If only one field is provided, the second gets default value.
|
||||
#[derive(Deserialize)]
|
||||
struct T1(u8, #[serde(default)] u8);
|
||||
|
||||
// ERROR: The first field can get default value only if sequence is empty, but
|
||||
// that mean that all other fields cannot be deserialized without errors.
|
||||
#[derive(Deserialize)]
|
||||
struct T2(#[serde(default)] u8, u8, u8);
|
||||
|
||||
// No errors expected:
|
||||
// - If both fields are provided, both get value from data.
|
||||
// - If only one field is provided, the second gets default value.
|
||||
// - If no fields are provided, both get default value.
|
||||
#[derive(Deserialize)]
|
||||
struct T3(#[serde(default)] u8, #[serde(default)] u8);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// No errors expected -- missing fields get default values.
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct T4(u8, u8);
|
||||
|
||||
// No errors expected -- missing fields get default values.
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct T5(#[serde(default)] u8, u8);
|
||||
|
||||
// No errors expected -- missing fields get default values.
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct T6(u8, #[serde(default)] u8);
|
||||
|
||||
// No errors expected -- missing fields get default values.
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct T7(#[serde(default)] u8, #[serde(default)] u8);
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,11 @@
|
||||
error: field must have #[serde(default)] because previous field 0 has #[serde(default)]
|
||||
--> tests/ui/default-attribute/tuple_struct.rs:16:33
|
||||
|
|
||||
16 | struct T2(#[serde(default)] u8, u8, u8);
|
||||
| ^^
|
||||
|
||||
error: field must have #[serde(default)] because previous field 0 has #[serde(default)]
|
||||
--> tests/ui/default-attribute/tuple_struct.rs:16:37
|
||||
|
|
||||
16 | struct T2(#[serde(default)] u8, u8, u8);
|
||||
| ^^
|
||||
@@ -0,0 +1,76 @@
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
fn d<T>() -> T {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
// No errors expected:
|
||||
// - If both fields are provided, both get value from data.
|
||||
// - If only one field is provided, the second gets default value.
|
||||
#[derive(Deserialize)]
|
||||
struct T1(u8, #[serde(default = "d")] u8);
|
||||
|
||||
// ERROR: The first field can get default value only if sequence is empty, but
|
||||
// that mean that all other fields cannot be deserialized without errors.
|
||||
#[derive(Deserialize)]
|
||||
struct T2(#[serde(default = "d")] u8, u8, u8);
|
||||
|
||||
// No errors expected:
|
||||
// - If both fields are provided, both get value from data.
|
||||
// - If only one field is provided, the second gets default value.
|
||||
// - If no fields are provided, both get default value.
|
||||
#[derive(Deserialize)]
|
||||
struct T3(#[serde(default = "d")] u8, #[serde(default = "d")] u8);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// No errors expected -- missing fields get default values.
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct T1D(#[serde(default = "d")] u8, u8);
|
||||
|
||||
// No errors expected -- missing fields get default values.
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct T2D(u8, #[serde(default = "d")] u8);
|
||||
|
||||
// No errors expected -- missing fields get default values.
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct T3D(#[serde(default = "d")] u8, #[serde(default = "d")] u8);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// No errors expected -- missing fields get default values.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(default = "d")]
|
||||
struct T1Path(#[serde(default)] u8, u8);
|
||||
|
||||
// No errors expected -- missing fields get default values.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(default = "d")]
|
||||
struct T2Path(u8, #[serde(default)] u8);
|
||||
|
||||
// No errors expected -- missing fields get default values.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(default = "d")]
|
||||
struct T3Path(#[serde(default)] u8, #[serde(default)] u8);
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// No errors expected -- missing fields get default values.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(default = "d")]
|
||||
struct T1PathD(#[serde(default = "d")] u8, u8);
|
||||
|
||||
// No errors expected -- missing fields get default values.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(default = "d")]
|
||||
struct T2PathD(u8, #[serde(default = "d")] u8);
|
||||
|
||||
// No errors expected -- missing fields get default values.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(default = "d")]
|
||||
struct T3PathD(#[serde(default = "d")] u8, #[serde(default = "d")] u8);
|
||||
|
||||
fn main() {}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user