monostate-1.0.2/.cargo_vcs_info.json0000644000000001360000000000100130450ustar { "git": { "sha1": "4ddb16092e9310718bb7fe8e2fa62fc0646862c0" }, "path_in_vcs": "" }monostate-1.0.2/.github/FUNDING.yml000064400000000000000000000000201046102023000150020ustar 00000000000000github: dtolnay monostate-1.0.2/.github/workflows/ci.yml000064400000000000000000000052431046102023000163540ustar 00000000000000name: CI on: push: pull_request: workflow_dispatch: schedule: [cron: "40 1 * * *"] permissions: contents: read env: RUSTFLAGS: -Dwarnings jobs: pre_ci: uses: dtolnay/.github/.github/workflows/pre_ci.yml@master test: name: Rust ${{matrix.rust}} needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest strategy: fail-fast: false matrix: rust: [nightly, beta, stable, 1.82.0, 1.79.0] timeout-minutes: 45 steps: - uses: actions/checkout@v5 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{matrix.rust}} - name: Enable type layout randomization run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV if: matrix.rust == 'nightly' - run: cargo test --workspace env: RUSTFLAGS: ${{env.RUSTFLAGS}} ${{matrix.rust == 'nightly' && '--cfg exhaustive' || ''}} - uses: actions/upload-artifact@v4 if: matrix.rust == 'nightly' && always() with: name: Cargo.lock path: Cargo.lock continue-on-error: true minimal: name: Minimal versions needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v5 - uses: dtolnay/rust-toolchain@nightly - run: cargo generate-lockfile -Z minimal-versions - run: cargo check --locked doc: name: Documentation needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 env: RUSTDOCFLAGS: -Dwarnings steps: - uses: actions/checkout@v5 - uses: dtolnay/rust-toolchain@nightly - uses: dtolnay/install@cargo-docs-rs - run: cargo docs-rs clippy: name: Clippy runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v5 - uses: dtolnay/rust-toolchain@clippy - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic miri: name: Miri needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v5 - uses: dtolnay/rust-toolchain@miri - run: cargo miri setup - run: cargo miri test env: MIRIFLAGS: -Zmiri-strict-provenance outdated: name: Outdated runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v5 - uses: dtolnay/rust-toolchain@stable - uses: dtolnay/install@cargo-outdated - run: cargo outdated --workspace --exit-code 1 monostate-1.0.2/.gitignore000064400000000000000000000000251046102023000136220ustar 00000000000000/target/ /Cargo.lock monostate-1.0.2/Cargo.lock0000644000000155030000000000100110240ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "dissimilar" version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8975ffdaa0ef3661bfe02dbdcc06c9f829dfafe6a3c474de366a8d5e44276921" [[package]] name = "equivalent" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "glob" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" [[package]] name = "hashbrown" version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d" [[package]] name = "indexmap" version = "2.11.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b0f83760fb341a774ed326568e19f5a863af4a952def8c39f9ab92fd95b88e5" dependencies = [ "equivalent", "hashbrown", ] [[package]] name = "itoa" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "memchr" version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" [[package]] name = "monostate" version = "1.0.2" dependencies = [ "monostate-impl", "rustversion", "serde", "serde_core", "serde_json", "trybuild", ] [[package]] name = "monostate-impl" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23f5b99488110875b5904839d396c2cdfaf241ff6622638acb879cc7effad5de" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "proc-macro2" version = "1.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.41" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1" dependencies = [ "proc-macro2", ] [[package]] name = "rustversion" version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "ryu" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" [[package]] name = "serde" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ "serde_core", "serde_derive", ] [[package]] name = "serde_core" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.145" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" dependencies = [ "itoa", "memchr", "ryu", "serde", "serde_core", ] [[package]] name = "serde_spanned" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e24345aa0fe688594e73770a5f6d1b216508b4f93484c0026d521acd30134392" dependencies = [ "serde_core", ] [[package]] name = "syn" version = "2.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "target-triple" version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ac9aa371f599d22256307c24a9d748c041e548cbf599f35d890f9d365361790" [[package]] name = "termcolor" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" dependencies = [ "winapi-util", ] [[package]] name = "toml" version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0dc8b1fb61449e27716ec0e1bdf0f6b8f3e8f6b05391e8497b8b6d7804ea6d8" dependencies = [ "indexmap", "serde_core", "serde_spanned", "toml_datetime", "toml_parser", "toml_writer", "winnow", ] [[package]] name = "toml_datetime" version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2cdb639ebbc97961c51720f858597f7f24c4fc295327923af55b74c3c724533" dependencies = [ "serde_core", ] [[package]] name = "toml_parser" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0cbe268d35bdb4bb5a56a2de88d0ad0eb70af5384a99d648cd4b3d04039800e" dependencies = [ "winnow", ] [[package]] name = "toml_writer" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df8b2b54733674ad286d16267dcfc7a71ed5c776e4ac7aa3c3e2561f7c637bf2" [[package]] name = "trybuild" version = "1.0.112" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d66678374d835fe847e0dc8348fde2ceb5be4a7ec204437d8367f0d8df266a5" dependencies = [ "dissimilar", "glob", "serde", "serde_derive", "serde_json", "target-triple", "termcolor", "toml", ] [[package]] name = "unicode-ident" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" [[package]] name = "winapi-util" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ "windows-sys", ] [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] name = "windows-sys" version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ "windows-link", ] [[package]] name = "winnow" version = "0.7.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf" monostate-1.0.2/Cargo.toml0000644000000037220000000000100110470ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.79" name = "monostate" version = "1.0.2" authors = ["David Tolnay "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Type that deserializes only from one specific value" documentation = "https://docs.rs/monostate" readme = "README.md" keywords = [ "serde", "serialization", ] categories = [ "encoding", "rust-patterns", "no-std", "no-std::no-alloc", ] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/monostate" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = [ "--generate-link-to-definition", "--generate-macro-expansion", "--extern-html-root-url=core=https://doc.rust-lang.org", "--extern-html-root-url=alloc=https://doc.rust-lang.org", "--extern-html-root-url=std=https://doc.rust-lang.org", ] [lib] name = "monostate" path = "src/lib.rs" [[test]] name = "compiletest" path = "tests/compiletest.rs" [[test]] name = "test" path = "tests/test.rs" [dependencies.monostate-impl] version = "=1.0.2" [dependencies.serde_core] version = "1.0.220" default-features = false [dev-dependencies.rustversion] version = "1.0.6" [dev-dependencies.serde] version = "1.0.220" features = ["derive"] [dev-dependencies.serde_json] version = "1.0.99" [dev-dependencies.trybuild] version = "1.0.112" features = ["diff"] [target."cfg(any())".dependencies.serde] version = "1.0.220" default-features = false monostate-1.0.2/Cargo.toml.orig000064400000000000000000000022521046102023000145250ustar 00000000000000[package] name = "monostate" version = "1.0.2" authors = ["David Tolnay "] categories = ["encoding", "rust-patterns", "no-std", "no-std::no-alloc"] description = "Type that deserializes only from one specific value" documentation = "https://docs.rs/monostate" edition = "2021" keywords = ["serde", "serialization"] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/monostate" rust-version = "1.79" [dependencies] monostate-impl = { version = "=1.0.2", path = "impl" } serde_core = { version = "1.0.220", default-features = false } [target.'cfg(any())'.dependencies] serde = { version = "1.0.220", default-features = false } [dev-dependencies] rustversion = "1.0.6" serde = { version = "1.0.220", features = ["derive"] } serde_json = "1.0.99" trybuild = { version = "1.0.112", features = ["diff"] } [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = [ "--generate-link-to-definition", "--generate-macro-expansion", "--extern-html-root-url=core=https://doc.rust-lang.org", "--extern-html-root-url=alloc=https://doc.rust-lang.org", "--extern-html-root-url=std=https://doc.rust-lang.org", ] [workspace] monostate-1.0.2/LICENSE-APACHE000064400000000000000000000227731046102023000135740ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS monostate-1.0.2/LICENSE-MIT000064400000000000000000000017771046102023000133050ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. monostate-1.0.2/README.md000064400000000000000000000042631046102023000131210ustar 00000000000000Monostate ========= [github](https://github.com/dtolnay/monostate) [crates.io](https://crates.io/crates/monostate) [docs.rs](https://docs.rs/monostate) [build status](https://github.com/dtolnay/monostate/actions?query=branch%3Amaster) This library implements a type macro for a zero-sized type that is Serde deserializable only from one specific value. ```toml [dependencies] monostate = "1" ```
## Examples ```rust use monostate::MustBe; use serde::Deserialize; #[derive(Deserialize)] struct Example { kind: MustBe!("success"), code: MustBe!(200), } ``` The above struct would deserialize from `{"kind":"success", "code":200}` in JSON, but would fail the deserialization if "kind" or "code" were any other value. This can sometimes be helpful in processing untagged enums in which the variant identification is more convoluted than what is handled by Serde's externally tagged and internally tagged representations, for example because the variant tag has an inconsistent type or key. ```rust use monostate::MustBe; use serde::Deserialize; #[derive(Deserialize)] #[serde(untagged)] pub enum ApiResponse { Success { success: MustBe!(true), }, Error { kind: MustBe!("error"), message: String, }, } ```
#### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. monostate-1.0.2/src/alphabet.rs000064400000000000000000000014451046102023000145560ustar 00000000000000#[doc(hidden)] pub struct len; #[doc(hidden)] pub struct char; macro_rules! letters { ($($letter:ident)*) => { $( #[doc(hidden)] pub type $letter = char<{ stringify!($letter).as_bytes()[0] as core::primitive::char }>; )* }; } letters! { A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z } #[doc(hidden)] pub mod two { #[doc(hidden)] pub struct char; } #[doc(hidden)] pub mod three { #[doc(hidden)] pub struct char; } #[doc(hidden)] pub mod four { #[doc(hidden)] pub struct char; } monostate-1.0.2/src/binary.rs000064400000000000000000000032231046102023000142560ustar 00000000000000use core::fmt::{self, Binary}; impl Binary for crate::MustBePosInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Binary for crate::MustBeNegInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Binary for crate::MustBeU8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Binary for crate::MustBeU16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Binary for crate::MustBeU32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Binary for crate::MustBeU64 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Binary for crate::MustBeU128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Binary for crate::MustBeI8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Binary for crate::MustBeI16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Binary for crate::MustBeI32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Binary for crate::MustBeI64 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Binary for crate::MustBeI128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } monostate-1.0.2/src/debug.rs000064400000000000000000000051641046102023000140660ustar 00000000000000use crate::string::ConstStr; use core::fmt::{self, Debug}; impl Debug for crate::MustBeChar { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({:?})", V) } } impl Debug for crate::MustBePosInt { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({})", V) } } impl Debug for crate::MustBeNegInt { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({})", V) } } impl Debug for crate::MustBeU8 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({}u8)", V) } } impl Debug for crate::MustBeU16 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({}u16)", V) } } impl Debug for crate::MustBeU32 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({}u32)", V) } } impl Debug for crate::MustBeU64 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({}u64)", V) } } impl Debug for crate::MustBeU128 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({}u128)", V) } } impl Debug for crate::MustBeI8 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({}i8)", V) } } impl Debug for crate::MustBeI16 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({}i16)", V) } } impl Debug for crate::MustBeI32 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({}i32)", V) } } impl Debug for crate::MustBeI64 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({}i64)", V) } } impl Debug for crate::MustBeI128 { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({}i128)", V) } } impl Debug for crate::MustBeBool { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({})", V) } } impl Debug for crate::MustBeStr { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "MustBe!({:?})", V::VALUE) } } monostate-1.0.2/src/default.rs000064400000000000000000000034661046102023000144270ustar 00000000000000use crate::string::ConstStr; impl Default for crate::MustBeChar { fn default() -> Self { crate::MustBeChar:: } } impl Default for crate::MustBePosInt { fn default() -> Self { crate::MustBePosInt:: } } impl Default for crate::MustBeNegInt { fn default() -> Self { crate::MustBeNegInt:: } } impl Default for crate::MustBeU8 { fn default() -> Self { crate::MustBeU8:: } } impl Default for crate::MustBeU16 { fn default() -> Self { crate::MustBeU16:: } } impl Default for crate::MustBeU32 { fn default() -> Self { crate::MustBeU32:: } } impl Default for crate::MustBeU64 { fn default() -> Self { crate::MustBeU64:: } } impl Default for crate::MustBeU128 { fn default() -> Self { crate::MustBeU128:: } } impl Default for crate::MustBeI8 { fn default() -> Self { crate::MustBeI8:: } } impl Default for crate::MustBeI16 { fn default() -> Self { crate::MustBeI16:: } } impl Default for crate::MustBeI32 { fn default() -> Self { crate::MustBeI32:: } } impl Default for crate::MustBeI64 { fn default() -> Self { crate::MustBeI64:: } } impl Default for crate::MustBeI128 { fn default() -> Self { crate::MustBeI128:: } } impl Default for crate::MustBeBool { fn default() -> Self { crate::MustBeBool:: } } impl Default for crate::MustBeStr where V: ConstStr, { fn default() -> Self { crate::MustBeStr:: } } monostate-1.0.2/src/deserialize.rs000064400000000000000000000444361046102023000153050ustar 00000000000000use crate::format; use crate::string::ConstStr; use core::fmt::{self, Write as _}; use core::str; use serde::de::{Deserialize, Deserializer, Error, Unexpected, Visitor}; impl<'de, const V: char> Deserialize<'de> for crate::MustBeChar { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBeCharVisitor(char); impl<'de> Visitor<'de> for MustBeCharVisitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "char {:?}", self.0) } fn visit_char(self, v: char) -> Result where E: Error, { if v == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Char(v), &self)) } } } deserializer .deserialize_char(MustBeCharVisitor(V)) .map(|()| crate::MustBeChar) } } impl<'de, const V: u128> Deserialize<'de> for crate::MustBePosInt { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBePosIntVisitor(u128); impl<'de> Visitor<'de> for MustBePosIntVisitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "integer `{}`", self.0) } fn visit_i64(self, v: i64) -> Result where E: Error, { if v >= 0 && v as u128 == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Signed(v), &self)) } } fn visit_i128(self, v: i128) -> Result where E: Error, { if v >= 0 && v as u128 == self.0 { Ok(()) } else { let mut buf = [0u8; 50]; let mut writer = format::Buf::new(&mut buf); write!(writer, "integer `{}`", v).unwrap(); Err(Error::invalid_value( Unexpected::Other(writer.as_str()), &self, )) } } fn visit_u64(self, v: u64) -> Result where E: Error, { if v as u128 == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Unsigned(v), &self)) } } fn visit_u128(self, v: u128) -> Result where E: Error, { if v == self.0 { Ok(()) } else { let mut buf = [0u8; 49]; let mut writer = format::Buf::new(&mut buf); write!(writer, "integer `{}`", v).unwrap(); Err(Error::invalid_value( Unexpected::Other(writer.as_str()), &self, )) } } } deserializer .deserialize_any(MustBePosIntVisitor(V)) .map(|()| crate::MustBePosInt) } } impl<'de, const V: i128> Deserialize<'de> for crate::MustBeNegInt { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBeNegIntVisitor(i128); impl<'de> Visitor<'de> for MustBeNegIntVisitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "integer `{}`", self.0) } fn visit_i64(self, v: i64) -> Result where E: Error, { if v as i128 == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Signed(v), &self)) } } fn visit_i128(self, v: i128) -> Result where E: Error, { if v == self.0 { Ok(()) } else { let mut buf = [0u8; 50]; let mut writer = format::Buf::new(&mut buf); write!(writer, "integer `{}`", v).unwrap(); Err(Error::invalid_value( Unexpected::Other(writer.as_str()), &self, )) } } fn visit_u64(self, v: u64) -> Result where E: Error, { if v as i128 == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Unsigned(v), &self)) } } fn visit_u128(self, v: u128) -> Result where E: Error, { if self.0 >= 0 && v == self.0 as u128 { Ok(()) } else { let mut buf = [0u8; 49]; let mut writer = format::Buf::new(&mut buf); write!(writer, "integer `{}`", v).unwrap(); Err(Error::invalid_value( Unexpected::Other(writer.as_str()), &self, )) } } } deserializer .deserialize_any(MustBeNegIntVisitor(V)) .map(|()| crate::MustBeNegInt) } } impl<'de, const V: u8> Deserialize<'de> for crate::MustBeU8 { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBeU8Visitor(u8); impl<'de> Visitor<'de> for MustBeU8Visitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "integer `{}` as u8", self.0) } fn visit_u8(self, v: u8) -> Result where E: Error, { if v == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Unsigned(v as u64), &self)) } } } deserializer .deserialize_any(MustBeU8Visitor(V)) .map(|()| crate::MustBeU8) } } impl<'de, const V: u16> Deserialize<'de> for crate::MustBeU16 { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBeU16Visitor(u16); impl<'de> Visitor<'de> for MustBeU16Visitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "integer `{}` as u16", self.0) } fn visit_u16(self, v: u16) -> Result where E: Error, { if v == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Unsigned(v as u64), &self)) } } } deserializer .deserialize_any(MustBeU16Visitor(V)) .map(|()| crate::MustBeU16) } } impl<'de, const V: u32> Deserialize<'de> for crate::MustBeU32 { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBeU32Visitor(u32); impl<'de> Visitor<'de> for MustBeU32Visitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "integer `{}` as u32", self.0) } fn visit_u32(self, v: u32) -> Result where E: Error, { if v == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Unsigned(v as u64), &self)) } } } deserializer .deserialize_any(MustBeU32Visitor(V)) .map(|()| crate::MustBeU32) } } impl<'de, const V: u64> Deserialize<'de> for crate::MustBeU64 { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBeU64Visitor(u64); impl<'de> Visitor<'de> for MustBeU64Visitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "integer `{}` as u64", self.0) } fn visit_u8(self, v: u8) -> Result where E: Error, { Err(E::invalid_type(Unexpected::Unsigned(v as u64), &self)) } fn visit_u16(self, v: u16) -> Result where E: Error, { Err(E::invalid_type(Unexpected::Unsigned(v as u64), &self)) } fn visit_u32(self, v: u32) -> Result where E: Error, { Err(E::invalid_type(Unexpected::Unsigned(v as u64), &self)) } fn visit_u64(self, v: u64) -> Result where E: Error, { if v == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Unsigned(v), &self)) } } } deserializer .deserialize_any(MustBeU64Visitor(V)) .map(|()| crate::MustBeU64) } } impl<'de, const V: u128> Deserialize<'de> for crate::MustBeU128 { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBeU128Visitor(u128); impl<'de> Visitor<'de> for MustBeU128Visitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "integer `{}` as u128", self.0) } fn visit_u128(self, v: u128) -> Result where E: Error, { if v == self.0 { Ok(()) } else { let mut buf = [0u8; 49]; let mut writer = format::Buf::new(&mut buf); write!(writer, "integer `{}`", v).unwrap(); Err(Error::invalid_value( Unexpected::Other(writer.as_str()), &self, )) } } } deserializer .deserialize_any(MustBeU128Visitor(V)) .map(|()| crate::MustBeU128) } } impl<'de, const V: i8> Deserialize<'de> for crate::MustBeI8 { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBeI8Visitor(i8); impl<'de> Visitor<'de> for MustBeI8Visitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "integer `{}` as i8", self.0) } fn visit_i8(self, v: i8) -> Result where E: Error, { if v == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Signed(v as i64), &self)) } } } deserializer .deserialize_any(MustBeI8Visitor(V)) .map(|()| crate::MustBeI8) } } impl<'de, const V: i16> Deserialize<'de> for crate::MustBeI16 { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBeI16Visitor(i16); impl<'de> Visitor<'de> for MustBeI16Visitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "integer `{}` as i16", self.0) } fn visit_i16(self, v: i16) -> Result where E: Error, { if v == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Signed(v as i64), &self)) } } } deserializer .deserialize_any(MustBeI16Visitor(V)) .map(|()| crate::MustBeI16) } } impl<'de, const V: i32> Deserialize<'de> for crate::MustBeI32 { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBeI32Visitor(i32); impl<'de> Visitor<'de> for MustBeI32Visitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "integer `{}` as i32", self.0) } fn visit_i32(self, v: i32) -> Result where E: Error, { if v == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Signed(v as i64), &self)) } } } deserializer .deserialize_any(MustBeI32Visitor(V)) .map(|()| crate::MustBeI32) } } impl<'de, const V: i64> Deserialize<'de> for crate::MustBeI64 { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBeI64Visitor(i64); impl<'de> Visitor<'de> for MustBeI64Visitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "integer `{}` as i64", self.0) } fn visit_i8(self, v: i8) -> Result where E: Error, { Err(E::invalid_type(Unexpected::Signed(v as i64), &self)) } fn visit_i16(self, v: i16) -> Result where E: Error, { Err(E::invalid_type(Unexpected::Signed(v as i64), &self)) } fn visit_i32(self, v: i32) -> Result where E: Error, { Err(E::invalid_type(Unexpected::Signed(v as i64), &self)) } fn visit_i64(self, v: i64) -> Result where E: Error, { if v == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Signed(v), &self)) } } } deserializer .deserialize_any(MustBeI64Visitor(V)) .map(|()| crate::MustBeI64) } } impl<'de, const V: i128> Deserialize<'de> for crate::MustBeI128 { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBeI128Visitor(i128); impl<'de> Visitor<'de> for MustBeI128Visitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "integer `{}` as i128", self.0) } fn visit_i128(self, v: i128) -> Result where E: Error, { if v == self.0 { Ok(()) } else { let mut buf = [0u8; 50]; let mut writer = format::Buf::new(&mut buf); write!(writer, "integer `{}`", v).unwrap(); Err(Error::invalid_value( Unexpected::Other(writer.as_str()), &self, )) } } } deserializer .deserialize_any(MustBeI128Visitor(V)) .map(|()| crate::MustBeI128) } } impl<'de, const V: bool> Deserialize<'de> for crate::MustBeBool { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBeBoolVisitor(bool); impl<'de> Visitor<'de> for MustBeBoolVisitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "boolean `{}`", self.0) } fn visit_bool(self, v: bool) -> Result where E: Error, { if v == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Bool(v), &self)) } } } deserializer .deserialize_any(MustBeBoolVisitor(V)) .map(|()| crate::MustBeBool) } } impl<'de, V: ConstStr> Deserialize<'de> for crate::MustBeStr { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct MustBeStrVisitor(&'static str); impl<'de> Visitor<'de> for MustBeStrVisitor { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "string {:?}", self.0) } fn visit_str(self, v: &str) -> Result where E: Error, { if v == self.0 { Ok(()) } else { Err(E::invalid_value(Unexpected::Str(v), &self)) } } } deserializer .deserialize_any(MustBeStrVisitor(V::VALUE)) .map(|()| crate::MustBeStr) } } monostate-1.0.2/src/display.rs000064400000000000000000000041451046102023000144430ustar 00000000000000use crate::string::ConstStr; use core::fmt::{self, Display}; impl Display for crate::MustBeChar { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Display for crate::MustBePosInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Display for crate::MustBeNegInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Display for crate::MustBeU8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Display for crate::MustBeU16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Display for crate::MustBeU32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Display for crate::MustBeU64 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Display for crate::MustBeU128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Display for crate::MustBeI8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Display for crate::MustBeI16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Display for crate::MustBeI32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Display for crate::MustBeI64 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Display for crate::MustBeI128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Display for crate::MustBeBool { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Display for crate::MustBeStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V::VALUE.fmt(f) } } monostate-1.0.2/src/eq.rs000064400000000000000000000014101046102023000133730ustar 00000000000000use crate::string::ConstStr; impl Eq for crate::MustBeChar {} impl Eq for crate::MustBePosInt {} impl Eq for crate::MustBeNegInt {} impl Eq for crate::MustBeU8 {} impl Eq for crate::MustBeU16 {} impl Eq for crate::MustBeU32 {} impl Eq for crate::MustBeU64 {} impl Eq for crate::MustBeU128 {} impl Eq for crate::MustBeI8 {} impl Eq for crate::MustBeI16 {} impl Eq for crate::MustBeI32 {} impl Eq for crate::MustBeI64 {} impl Eq for crate::MustBeI128 {} impl Eq for crate::MustBeBool {} impl Eq for crate::MustBeStr {} monostate-1.0.2/src/format.rs000064400000000000000000000013031046102023000142570ustar 00000000000000use core::fmt::{self, Write}; use core::str; pub struct Buf<'a> { bytes: &'a mut [u8], offset: usize, } impl<'a> Buf<'a> { pub fn new(bytes: &'a mut [u8]) -> Self { Buf { bytes, offset: 0 } } pub fn as_str(&self) -> &str { let slice = &self.bytes[..self.offset]; unsafe { str::from_utf8_unchecked(slice) } } } impl<'a> Write for Buf<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { if self.offset + s.len() > self.bytes.len() { Err(fmt::Error) } else { self.bytes[self.offset..self.offset + s.len()].copy_from_slice(s.as_bytes()); self.offset += s.len(); Ok(()) } } } monostate-1.0.2/src/hash.rs000064400000000000000000000030041046102023000137120ustar 00000000000000use crate::string::ConstStr; use core::hash::{Hash, Hasher}; impl Hash for crate::MustBeChar { fn hash(&self, _: &mut H) {} } impl Hash for crate::MustBePosInt { fn hash(&self, _: &mut H) {} } impl Hash for crate::MustBeNegInt { fn hash(&self, _: &mut H) {} } impl Hash for crate::MustBeU8 { fn hash(&self, _: &mut H) {} } impl Hash for crate::MustBeU16 { fn hash(&self, _: &mut H) {} } impl Hash for crate::MustBeU32 { fn hash(&self, _: &mut H) {} } impl Hash for crate::MustBeU64 { fn hash(&self, _: &mut H) {} } impl Hash for crate::MustBeU128 { fn hash(&self, _: &mut H) {} } impl Hash for crate::MustBeI8 { fn hash(&self, _: &mut H) {} } impl Hash for crate::MustBeI16 { fn hash(&self, _: &mut H) {} } impl Hash for crate::MustBeI32 { fn hash(&self, _: &mut H) {} } impl Hash for crate::MustBeI64 { fn hash(&self, _: &mut H) {} } impl Hash for crate::MustBeI128 { fn hash(&self, _: &mut H) {} } impl Hash for crate::MustBeBool { fn hash(&self, _: &mut H) {} } impl Hash for crate::MustBeStr where V: ConstStr, { fn hash(&self, _: &mut H) {} } monostate-1.0.2/src/lib.rs000064400000000000000000000072551046102023000135510ustar 00000000000000//! [![github]](https://github.com/dtolnay/monostate) [![crates-io]](https://crates.io/crates/monostate) [![docs-rs]](https://docs.rs/monostate) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs //! //!
//! //! This library implements a type macro for a zero-sized type that is Serde //! deserializable only from one specific value. //! //! # Examples //! //! ``` //! use monostate::MustBe; //! use serde::Deserialize; //! //! #[derive(Deserialize)] //! struct Example { //! kind: MustBe!("success"), //! code: MustBe!(200), //! } //! ``` //! //! The above struct would deserialize from `{"kind":"success", "code":200}` in //! JSON, but would fail the deserialization if "kind" or "code" were any other //! value. //! //! This can sometimes be helpful in processing untagged enums in which the //! variant identification is more convoluted than what is handled by Serde's //! externally tagged and internally tagged representations, for example because //! the variant tag has an inconsistent type or key. //! //! ``` //! use monostate::MustBe; //! use serde::Deserialize; //! //! #[derive(Deserialize)] //! #[serde(untagged)] //! pub enum ApiResponse { //! Success { //! success: MustBe!(true), //! }, //! Error { //! kind: MustBe!("error"), //! message: String, //! }, //! } //! ``` #![no_std] #![doc(html_root_url = "https://docs.rs/monostate/1.0.2")] #![allow(non_camel_case_types, non_upper_case_globals)] #![allow( clippy::borrow_as_ptr, clippy::builtin_type_shadow, clippy::cast_lossless, clippy::cast_sign_loss, clippy::derivable_impls, clippy::elidable_lifetime_names, clippy::expl_impl_clone_on_copy, clippy::missing_safety_doc, clippy::module_name_repetitions, clippy::needless_lifetimes, clippy::ptr_as_ptr, clippy::uninhabited_references, clippy::uninlined_format_args )] extern crate serde_core as serde; #[doc(hidden)] pub mod alphabet; mod binary; mod debug; mod default; mod deserialize; mod display; mod eq; mod format; mod hash; mod lower_exp; mod lower_hex; mod octal; mod ord; mod partial_eq; mod partial_ord; mod serialize; mod string; mod upper_exp; mod upper_hex; mod value; pub use crate::string::ConstStr; pub use crate::value::MustBe; pub use monostate_impl::MustBe; #[derive(Copy, Clone)] pub struct MustBeChar; #[derive(Copy, Clone)] #[doc(hidden)] pub struct MustBePosInt; #[derive(Copy, Clone)] #[doc(hidden)] pub struct MustBeNegInt; #[derive(Copy, Clone)] pub struct MustBeU8; #[derive(Copy, Clone)] pub struct MustBeU16; #[derive(Copy, Clone)] pub struct MustBeU32; #[derive(Copy, Clone)] pub struct MustBeU64; #[derive(Copy, Clone)] pub struct MustBeU128; #[derive(Copy, Clone)] pub struct MustBeI8; #[derive(Copy, Clone)] pub struct MustBeI16; #[derive(Copy, Clone)] pub struct MustBeI32; #[derive(Copy, Clone)] pub struct MustBeI64; #[derive(Copy, Clone)] pub struct MustBeI128; #[derive(Copy, Clone)] pub struct MustBeBool; #[allow(type_alias_bounds)] pub type MustBeStr = crate::string::MustBeStr; impl Copy for MustBeStr {} impl Clone for MustBeStr { fn clone(&self) -> Self { *self } } #[doc(hidden)] pub use self::string::value::*; monostate-1.0.2/src/lower_exp.rs000064400000000000000000000032551046102023000150030ustar 00000000000000use core::fmt::{self, LowerExp}; impl LowerExp for crate::MustBePosInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerExp for crate::MustBeNegInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerExp for crate::MustBeU8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerExp for crate::MustBeU16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerExp for crate::MustBeU32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerExp for crate::MustBeU64 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerExp for crate::MustBeU128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerExp for crate::MustBeI8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerExp for crate::MustBeI16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerExp for crate::MustBeI32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerExp for crate::MustBeI64 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerExp for crate::MustBeI128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } monostate-1.0.2/src/lower_hex.rs000064400000000000000000000032551046102023000147730ustar 00000000000000use core::fmt::{self, LowerHex}; impl LowerHex for crate::MustBePosInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerHex for crate::MustBeNegInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerHex for crate::MustBeU8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerHex for crate::MustBeU16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerHex for crate::MustBeU32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerHex for crate::MustBeU64 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerHex for crate::MustBeU128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerHex for crate::MustBeI8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerHex for crate::MustBeI16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerHex for crate::MustBeI32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerHex for crate::MustBeI64 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl LowerHex for crate::MustBeI128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } monostate-1.0.2/src/octal.rs000064400000000000000000000032061046102023000140750ustar 00000000000000use core::fmt::{self, Octal}; impl Octal for crate::MustBePosInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Octal for crate::MustBeNegInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Octal for crate::MustBeU8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Octal for crate::MustBeU16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Octal for crate::MustBeU32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Octal for crate::MustBeU64 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Octal for crate::MustBeU128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Octal for crate::MustBeI8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Octal for crate::MustBeI16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Octal for crate::MustBeI32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Octal for crate::MustBeI64 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl Octal for crate::MustBeI128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } monostate-1.0.2/src/ord.rs000064400000000000000000000036221046102023000135610ustar 00000000000000use crate::string::ConstStr; use core::cmp::Ordering; impl Ord for crate::MustBeChar { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } impl Ord for crate::MustBePosInt { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } impl Ord for crate::MustBeNegInt { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } impl Ord for crate::MustBeU8 { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } impl Ord for crate::MustBeU16 { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } impl Ord for crate::MustBeU32 { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } impl Ord for crate::MustBeU64 { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } impl Ord for crate::MustBeU128 { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } impl Ord for crate::MustBeI8 { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } impl Ord for crate::MustBeI16 { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } impl Ord for crate::MustBeI32 { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } impl Ord for crate::MustBeI64 { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } impl Ord for crate::MustBeI128 { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } impl Ord for crate::MustBeBool { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } impl Ord for crate::MustBeStr where V: ConstStr, { fn cmp(&self, _: &Self) -> Ordering { Ordering::Equal } } monostate-1.0.2/src/partial_eq.rs000064400000000000000000000050271046102023000151170ustar 00000000000000use crate::string::ConstStr; impl PartialEq> for crate::MustBeChar { fn eq(&self, _: &crate::MustBeChar) -> bool { V == W } } impl PartialEq> for crate::MustBePosInt { fn eq(&self, _: &crate::MustBePosInt) -> bool { V == W } } impl PartialEq> for crate::MustBeNegInt { fn eq(&self, _: &crate::MustBeNegInt) -> bool { V == W } } impl PartialEq> for crate::MustBeU8 { fn eq(&self, _: &crate::MustBeU8) -> bool { V == W } } impl PartialEq> for crate::MustBeU16 { fn eq(&self, _: &crate::MustBeU16) -> bool { V == W } } impl PartialEq> for crate::MustBeU32 { fn eq(&self, _: &crate::MustBeU32) -> bool { V == W } } impl PartialEq> for crate::MustBeU64 { fn eq(&self, _: &crate::MustBeU64) -> bool { V == W } } impl PartialEq> for crate::MustBeU128 { fn eq(&self, _: &crate::MustBeU128) -> bool { V == W } } impl PartialEq> for crate::MustBeI8 { fn eq(&self, _: &crate::MustBeI8) -> bool { V == W } } impl PartialEq> for crate::MustBeI16 { fn eq(&self, _: &crate::MustBeI16) -> bool { V == W } } impl PartialEq> for crate::MustBeI32 { fn eq(&self, _: &crate::MustBeI32) -> bool { V == W } } impl PartialEq> for crate::MustBeI64 { fn eq(&self, _: &crate::MustBeI64) -> bool { V == W } } impl PartialEq> for crate::MustBeI128 { fn eq(&self, _: &crate::MustBeI128) -> bool { V == W } } impl PartialEq> for crate::MustBeBool { fn eq(&self, _: &crate::MustBeBool) -> bool { V == W } } impl PartialEq> for crate::MustBeStr where V: ConstStr, W: ConstStr, { fn eq(&self, _: &crate::MustBeStr) -> bool { V::VALUE == W::VALUE } } monostate-1.0.2/src/partial_ord.rs000064400000000000000000000060001046102023000152660ustar 00000000000000use crate::string::ConstStr; use core::cmp::Ordering; impl PartialOrd> for crate::MustBeChar { fn partial_cmp(&self, _: &crate::MustBeChar) -> Option { Some(V.cmp(&W)) } } impl PartialOrd> for crate::MustBePosInt { fn partial_cmp(&self, _: &crate::MustBePosInt) -> Option { Some(V.cmp(&W)) } } impl PartialOrd> for crate::MustBeNegInt { fn partial_cmp(&self, _: &crate::MustBeNegInt) -> Option { Some(V.cmp(&W)) } } impl PartialOrd> for crate::MustBeU8 { fn partial_cmp(&self, _: &crate::MustBeU8) -> Option { Some(V.cmp(&W)) } } impl PartialOrd> for crate::MustBeU16 { fn partial_cmp(&self, _: &crate::MustBeU16) -> Option { Some(V.cmp(&W)) } } impl PartialOrd> for crate::MustBeU32 { fn partial_cmp(&self, _: &crate::MustBeU32) -> Option { Some(V.cmp(&W)) } } impl PartialOrd> for crate::MustBeU64 { fn partial_cmp(&self, _: &crate::MustBeU64) -> Option { Some(V.cmp(&W)) } } impl PartialOrd> for crate::MustBeU128 { fn partial_cmp(&self, _: &crate::MustBeU128) -> Option { Some(V.cmp(&W)) } } impl PartialOrd> for crate::MustBeI8 { fn partial_cmp(&self, _: &crate::MustBeI8) -> Option { Some(V.cmp(&W)) } } impl PartialOrd> for crate::MustBeI16 { fn partial_cmp(&self, _: &crate::MustBeI16) -> Option { Some(V.cmp(&W)) } } impl PartialOrd> for crate::MustBeI32 { fn partial_cmp(&self, _: &crate::MustBeI32) -> Option { Some(V.cmp(&W)) } } impl PartialOrd> for crate::MustBeI64 { fn partial_cmp(&self, _: &crate::MustBeI64) -> Option { Some(V.cmp(&W)) } } impl PartialOrd> for crate::MustBeI128 { fn partial_cmp(&self, _: &crate::MustBeI128) -> Option { Some(V.cmp(&W)) } } impl PartialOrd> for crate::MustBeBool { fn partial_cmp(&self, _: &crate::MustBeBool) -> Option { Some(V.cmp(&W)) } } impl PartialOrd> for crate::MustBeStr where V: ConstStr, W: ConstStr, { fn partial_cmp(&self, _: &crate::MustBeStr) -> Option { Some(V::VALUE.cmp(W::VALUE)) } } monostate-1.0.2/src/serialize.rs000064400000000000000000000053351046102023000147670ustar 00000000000000use crate::string::ConstStr; use serde::{Serialize, Serializer}; impl Serialize for crate::MustBeChar { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_char(V) } } impl Serialize for crate::MustBeU8 { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_u8(V) } } impl Serialize for crate::MustBeU16 { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_u16(V) } } impl Serialize for crate::MustBeU32 { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_u32(V) } } impl Serialize for crate::MustBeU64 { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_u64(V) } } impl Serialize for crate::MustBeU128 { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_u128(V) } } impl Serialize for crate::MustBeI8 { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_i8(V) } } impl Serialize for crate::MustBeI16 { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_i16(V) } } impl Serialize for crate::MustBeI32 { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_i32(V) } } impl Serialize for crate::MustBeI64 { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_i64(V) } } impl Serialize for crate::MustBeI128 { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_i128(V) } } impl Serialize for crate::MustBeBool { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_bool(V) } } impl Serialize for crate::MustBeStr { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_str(V::VALUE) } } monostate-1.0.2/src/string.rs000064400000000000000000000117661046102023000143130ustar 00000000000000use crate::alphabet::{self, len}; use core::mem::{self, ManuallyDrop}; use core::slice; use core::str; // Equivalent to `pub struct MustBeStr;` but using // the type encoding described in impl/src/lib.rs to avoid depending on // #![feature(adt_const_params)] for now. pub enum MustBeStr { #[doc(hidden)] __Phantom(#[doc(hidden)] void::MustBeStr), MustBeStr, } pub mod value { #[doc(hidden)] pub use crate::string::MustBeStr::MustBeStr; } pub trait ConstStr: Sealed { const VALUE: &'static str; } #[doc(hidden)] impl ConstStr for T where T: Sealed, { const VALUE: &'static str = T::__private.0; } pub trait Sealed { #[allow(private_interfaces)] const __private: StringValue; } struct StringValue(&'static str); impl Sealed for (len, T) where T: StringBuffer, { #[allow(private_interfaces)] const __private: StringValue = { const { assert!(N == mem::size_of::()); } StringValue(unsafe { str::from_utf8_unchecked(slice::from_raw_parts( const { &Cast:: { encoded: ManuallyDrop::new(T::BYTES), } .array } .as_ptr(), N, )) }) }; } union Cast { encoded: ManuallyDrop, array: [u8; N], } 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; pub unsafe trait StringBuffer { // SAFETY: Must contain no padding bytes. Must have alignment of 1. type Type: 'static; // SAFETY: Contents viewed as bytes must be a valid UTF-8 encoding. const BYTES: Self::Type; } unsafe impl StringBuffer for alphabet::char { type Type = u8; const BYTES: Self::Type = CH as u8; } unsafe impl StringBuffer for alphabet::two::char { type Type = [u8; 2]; const BYTES: Self::Type = [ ((CH as u32 >> 6) & 0x1F) as u8 | TAG_TWO_B, (CH as u32 & 0x3F) as u8 | TAG_CONT, ]; } unsafe impl StringBuffer for alphabet::three::char { type Type = [u8; 3]; const BYTES: Self::Type = [ ((CH as u32 >> 12) & 0x0F) as u8 | TAG_THREE_B, ((CH as u32 >> 6) & 0x3F) as u8 | TAG_CONT, (CH as u32 & 0x3F) as u8 | TAG_CONT, ]; } unsafe impl StringBuffer for alphabet::four::char { type Type = [u8; 4]; const BYTES: Self::Type = [ ((CH as u32 >> 18) & 0x07) as u8 | TAG_FOUR_B, ((CH as u32 >> 12) & 0x3F) as u8 | TAG_CONT, ((CH as u32 >> 6) & 0x3F) as u8 | TAG_CONT, (CH as u32 & 0x3F) as u8 | TAG_CONT, ]; } unsafe impl StringBuffer for () { type Type = (); const BYTES: Self::Type = (); } #[repr(C)] pub struct Concat2(A, B); unsafe impl StringBuffer for (A, B) where A: StringBuffer, B: StringBuffer, { type Type = Concat2; const BYTES: Self::Type = Concat2(A::BYTES, B::BYTES); } #[repr(C)] pub struct Concat3(A, B, C); unsafe impl StringBuffer for (A, B, C) where A: StringBuffer, B: StringBuffer, C: StringBuffer, { type Type = Concat3; const BYTES: Self::Type = Concat3(A::BYTES, B::BYTES, C::BYTES); } #[repr(C)] pub struct Concat4(A, B, C, D); unsafe impl StringBuffer for (A, B, C, D) where A: StringBuffer, B: StringBuffer, C: StringBuffer, D: StringBuffer, { type Type = Concat4; const BYTES: Self::Type = Concat4(A::BYTES, B::BYTES, C::BYTES, D::BYTES); } #[repr(C)] pub struct Concat5(A, B, C, D, E); unsafe impl StringBuffer for (A, B, C, D, E) where A: StringBuffer, B: StringBuffer, C: StringBuffer, D: StringBuffer, E: StringBuffer, { type Type = Concat5; const BYTES: Self::Type = Concat5(A::BYTES, B::BYTES, C::BYTES, D::BYTES, E::BYTES); } #[repr(C)] pub struct Concat6(A, B, C, D, E, F); unsafe impl StringBuffer for (A, B, C, D, E, F) where A: StringBuffer, B: StringBuffer, C: StringBuffer, D: StringBuffer, E: StringBuffer, F: StringBuffer, { type Type = Concat6; const BYTES: Self::Type = Concat6(A::BYTES, B::BYTES, C::BYTES, D::BYTES, E::BYTES, F::BYTES); } mod void { use core::marker::PhantomData; #[doc(hidden)] pub enum Void {} impl Copy for Void {} impl Clone for Void { fn clone(&self) -> Self { *self } } pub struct MustBeStr(PhantomData, #[doc(hidden)] pub Void); impl Copy for MustBeStr {} impl Clone for MustBeStr { fn clone(&self) -> Self { *self } } } monostate-1.0.2/src/upper_exp.rs000064400000000000000000000032551046102023000150060ustar 00000000000000use core::fmt::{self, UpperExp}; impl UpperExp for crate::MustBePosInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperExp for crate::MustBeNegInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperExp for crate::MustBeU8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperExp for crate::MustBeU16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperExp for crate::MustBeU32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperExp for crate::MustBeU64 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperExp for crate::MustBeU128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperExp for crate::MustBeI8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperExp for crate::MustBeI16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperExp for crate::MustBeI32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperExp for crate::MustBeI64 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperExp for crate::MustBeI128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } monostate-1.0.2/src/upper_hex.rs000064400000000000000000000032551046102023000147760ustar 00000000000000use core::fmt::{self, UpperHex}; impl UpperHex for crate::MustBePosInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperHex for crate::MustBeNegInt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperHex for crate::MustBeU8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperHex for crate::MustBeU16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperHex for crate::MustBeU32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperHex for crate::MustBeU64 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperHex for crate::MustBeU128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperHex for crate::MustBeI8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperHex for crate::MustBeI16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperHex for crate::MustBeI32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperHex for crate::MustBeI64 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } impl UpperHex for crate::MustBeI128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { V.fmt(f) } } monostate-1.0.2/src/value.rs000064400000000000000000000067461046102023000141230ustar 00000000000000use crate::string::ConstStr; use core::fmt::{Debug, Display}; use core::hash::Hash; use core::panic::{RefUnwindSafe, UnwindSafe}; use serde::Serialize; pub trait MustBe: Sealed { type Type: Copy + Debug + Default + Display + Hash + Ord + RefUnwindSafe + Send + Serialize + Sync + Unpin + UnwindSafe; const VALUE: Self::Type; } impl crate::MustBeChar { pub const VALUE: char = V; } impl MustBe for crate::MustBeChar { type Type = char; const VALUE: Self::Type = V; } impl crate::MustBeU8 { pub const VALUE: u8 = V; } impl MustBe for crate::MustBeU8 { type Type = u8; const VALUE: Self::Type = V; } impl crate::MustBeU16 { pub const VALUE: u16 = V; } impl MustBe for crate::MustBeU16 { type Type = u16; const VALUE: Self::Type = V; } impl crate::MustBeU32 { pub const VALUE: u32 = V; } impl MustBe for crate::MustBeU32 { type Type = u32; const VALUE: Self::Type = V; } impl crate::MustBeU64 { pub const VALUE: u64 = V; } impl MustBe for crate::MustBeU64 { type Type = u64; const VALUE: Self::Type = V; } impl crate::MustBeU128 { pub const VALUE: u128 = V; } impl MustBe for crate::MustBeU128 { type Type = u128; const VALUE: Self::Type = V; } impl crate::MustBeI8 { pub const VALUE: i8 = V; } impl MustBe for crate::MustBeI8 { type Type = i8; const VALUE: Self::Type = V; } impl crate::MustBeI16 { pub const VALUE: i16 = V; } impl MustBe for crate::MustBeI16 { type Type = i16; const VALUE: Self::Type = V; } impl crate::MustBeI32 { pub const VALUE: i32 = V; } impl MustBe for crate::MustBeI32 { type Type = i32; const VALUE: Self::Type = V; } impl crate::MustBeI64 { pub const VALUE: i64 = V; } impl MustBe for crate::MustBeI64 { type Type = i64; const VALUE: Self::Type = V; } impl crate::MustBeI128 { pub const VALUE: i128 = V; } impl MustBe for crate::MustBeI128 { type Type = i128; const VALUE: Self::Type = V; } impl crate::MustBeBool { pub const VALUE: bool = V; } impl MustBe for crate::MustBeBool { type Type = bool; const VALUE: Self::Type = V; } impl crate::MustBeStr { pub const VALUE: &'static str = V::VALUE; } impl MustBe for crate::MustBeStr { type Type = &'static str; const VALUE: Self::Type = V::VALUE; } pub trait Sealed {} impl Sealed for crate::MustBeChar {} impl Sealed for crate::MustBeU8 {} impl Sealed for crate::MustBeU16 {} impl Sealed for crate::MustBeU32 {} impl Sealed for crate::MustBeU64 {} impl Sealed for crate::MustBeU128 {} impl Sealed for crate::MustBeI8 {} impl Sealed for crate::MustBeI16 {} impl Sealed for crate::MustBeI32 {} impl Sealed for crate::MustBeI64 {} impl Sealed for crate::MustBeI128 {} impl Sealed for crate::MustBeBool {} impl Sealed for crate::MustBeStr {} monostate-1.0.2/tests/compiletest.rs000064400000000000000000000003261046102023000156760ustar 00000000000000#[rustversion::attr(not(nightly), ignore = "requires nightly")] #[cfg_attr(miri, ignore = "incompatible with miri")] #[test] fn ui() { let t = trybuild::TestCases::new(); t.compile_fail("tests/ui/*.rs"); } monostate-1.0.2/tests/test.rs000064400000000000000000000133671046102023000143360ustar 00000000000000#![allow( clippy::derive_partial_eq_without_eq, clippy::let_underscore_untyped, clippy::uninlined_format_args )] use monostate::MustBe; use serde::{Deserialize, Serialize}; use std::fmt::Debug; use std::mem; #[test] fn test_serialize_deserialize() { #[derive(Deserialize, Serialize, Debug, PartialEq)] struct Struct { kind: MustBe!("Struct"), } let s = Struct { kind: MustBe!("Struct"), }; let j = serde_json::to_string(&s).unwrap(); assert_eq!(j, "{\"kind\":\"Struct\"}"); let s2 = serde_json::from_str::(&j).unwrap(); assert_eq!(s, s2); let bad_j = "{\"kind\":\"unknown\"}"; let err = serde_json::from_str::(bad_j).unwrap_err(); assert_eq!( err.to_string(), "invalid value: string \"unknown\", expected string \"Struct\" at line 1 column 17", ); } #[test] fn test_untagged_enum() { #[derive(Serialize, Deserialize)] #[serde(untagged)] enum ApiResponse { Success { success: MustBe!(true), }, Error { success: MustBe!(false), message: String, }, } let success = "{\"success\":true}"; let response: ApiResponse = serde_json::from_str(success).unwrap(); match response { ApiResponse::Success { success: MustBe!(true), } => {} ApiResponse::Error { .. } => panic!(), } let error = "{\"success\":false,\"message\":\"...\"}"; let response: ApiResponse = serde_json::from_str(error).unwrap(); match response { ApiResponse::Error { success: MustBe!(false), .. } => {} ApiResponse::Success { .. } => panic!(), } } #[test] fn test_debug() { #[track_caller] fn assert_debug(must_be: impl Debug, expected: &str) { assert_eq!(format!("{:?}", must_be), expected); } assert_debug(MustBe!('x'), "MustBe!('x')"); assert_debug(MustBe!(1), "MustBe!(1)"); assert_debug(MustBe!(-1), "MustBe!(-1)"); assert_debug(MustBe!(1u8), "MustBe!(1u8)"); assert_debug(MustBe!(1u16), "MustBe!(1u16)"); assert_debug(MustBe!(1u32), "MustBe!(1u32)"); assert_debug(MustBe!(1u64), "MustBe!(1u64)"); assert_debug(MustBe!(1u128), "MustBe!(1u128)"); assert_debug(MustBe!(1i8), "MustBe!(1i8)"); assert_debug(MustBe!(1i16), "MustBe!(1i16)"); assert_debug(MustBe!(1i32), "MustBe!(1i32)"); assert_debug(MustBe!(1i64), "MustBe!(1i64)"); assert_debug(MustBe!(1i128), "MustBe!(1i128)"); assert_debug(MustBe!(true), "MustBe!(true)"); assert_debug(MustBe!("string"), "MustBe!(\"string\")"); } #[test] fn test_display() { macro_rules! assert_display_eq { ($lit:literal) => { assert_eq!(format!("{}", $lit), format!("{}", MustBe!($lit))); }; } assert_display_eq!('x'); assert_display_eq!(1); assert_display_eq!(-1); assert_display_eq!(1u8); assert_display_eq!(1u16); assert_display_eq!(1u32); assert_display_eq!(1u64); assert_display_eq!(1u128); assert_display_eq!(1i8); assert_display_eq!(1i16); assert_display_eq!(1i32); assert_display_eq!(1i64); assert_display_eq!(1i128); assert_display_eq!(true); assert_display_eq!("string"); } #[test] fn test_cmp() { assert_eq!(MustBe!(4), MustBe!(4)); assert_ne!(MustBe!(4), MustBe!(5)); assert!(MustBe!(4) < MustBe!(5)); } #[test] fn test_long_string() { let _ = MustBe!("\ Rust is blazingly fast and memory-efficient: with no runtime or garbage collector, it can power performance-critical services, run on embedded devices, and easily integrate with other languages. \ Rust’s rich type system and ownership model guarantee memory-safety and thread-safety — enabling you to eliminate many classes of bugs at compile-time. \ Rust has great documentation, a friendly compiler with useful error messages, and top-notch tooling — an integrated package manager and build tool, smart multi-editor support with auto-completion and type inspections, an auto-formatter, and more.\ "); } #[test] fn test_utf8() { let string = "$£€𐍈"; let mut chars = string.chars(); assert_eq!(chars.next().unwrap().len_utf8(), 1); assert_eq!(chars.next().unwrap().len_utf8(), 2); assert_eq!(chars.next().unwrap().len_utf8(), 3); assert_eq!(chars.next().unwrap().len_utf8(), 4); assert!(chars.next().is_none()); let must_be = MustBe!("$£€𐍈"); assert_eq!( serde_json::to_string(string).unwrap(), serde_json::to_string(&must_be).unwrap(), ); } #[test] fn test_layout() { let must_be = MustBe!("s"); assert_eq!(0, mem::size_of_val(&must_be)); assert_eq!(1, mem::align_of_val(&must_be)); let must_be = MustBe!(1); assert_eq!(0, mem::size_of_val(&must_be)); assert_eq!(1, mem::align_of_val(&must_be)); } #[test] fn test_autotraits() { fn assert_send(_: impl Send) {} fn assert_sync(_: impl Sync) {} assert_send(MustBe!("")); assert_sync(MustBe!("")); assert_send(MustBe!(true)); assert_sync(MustBe!(true)); } #[test] fn test_pattern() { let MustBe!('x') = MustBe!('x'); let MustBe!(1) = MustBe!(1); let MustBe!(-1) = MustBe!(-1); let MustBe!(1u8) = MustBe!(1u8); let MustBe!(1u16) = MustBe!(1u16); let MustBe!(1u32) = MustBe!(1u32); let MustBe!(1u64) = MustBe!(1u64); let MustBe!(1u128) = MustBe!(1u128); let MustBe!(1i8) = MustBe!(1i8); let MustBe!(1i16) = MustBe!(1i16); let MustBe!(1i32) = MustBe!(1i32); let MustBe!(1i64) = MustBe!(1i64); let MustBe!(1i128) = MustBe!(1i128); let MustBe!(true) = MustBe!(true); } #[rustversion::since(1.82)] #[test] fn test_string_pattern() { // Since https://github.com/rust-lang/rust/pull/122792 let MustBe!("string") = MustBe!("string"); } monostate-1.0.2/tests/ui/bad_integer.rs000064400000000000000000000001011046102023000162150ustar 00000000000000use monostate::MustBe; fn main() { let _ = MustBe!(1u15); } monostate-1.0.2/tests/ui/bad_integer.stderr000064400000000000000000000002131046102023000171000ustar 00000000000000error: unsupported integers suffix `u15` --> tests/ui/bad_integer.rs:4:21 | 4 | let _ = MustBe!(1u15); | ^^^^ monostate-1.0.2/tests/ui/float.rs000064400000000000000000000001721046102023000150670ustar 00000000000000use monostate::MustBe; fn main() { let _ = MustBe!(1.0); let _ = MustBe!(b"..."); let _ = MustBe!(c"..."); } monostate-1.0.2/tests/ui/float.stderr000064400000000000000000000006321046102023000157470ustar 00000000000000error: unsupported monostate literal kind --> tests/ui/float.rs:4:21 | 4 | let _ = MustBe!(1.0); | ^^^ error: unsupported monostate literal kind --> tests/ui/float.rs:5:21 | 5 | let _ = MustBe!(b"..."); | ^^^^^^ error: unsupported monostate literal kind --> tests/ui/float.rs:6:21 | 6 | let _ = MustBe!(c"..."); | ^^^^^^ monostate-1.0.2/tests/ui/incorrect_len.rs000064400000000000000000000006201046102023000166060ustar 00000000000000// This error should be unreachable using the public API of monostate. Testing // it anyway. type __Private = ( monostate::alphabet::len<8>, ( monostate::alphabet::a, monostate::alphabet::s, monostate::alphabet::d, monostate::alphabet::f, ), ); struct N; fn main() { let _ = N::<{ monostate::MustBeStr::<__Private>::VALUE.len() }>; } monostate-1.0.2/tests/ui/incorrect_len.stderr000064400000000000000000000022321046102023000174660ustar 00000000000000error[E0080]: evaluation panicked: assertion failed: N == mem::size_of::() --> src/string.rs | | assert!(N == mem::size_of::()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `<(monostate::alphabet::len<8>, (monostate::alphabet::char<'a'>, monostate::alphabet::char<'s'>, monostate::alphabet::char<'d'>, monostate::alphabet::char<'f'>)) as monostate::string::Sealed>::__private::{constant#0}` failed here note: erroneous constant encountered --> src/string.rs | | / const { | | assert!(N == mem::size_of::()); | | } | |_________^ note: erroneous constant encountered --> src/string.rs | | const VALUE: &'static str = T::__private.0; | ^^^^^^^^^^^^ note: erroneous constant encountered --> src/value.rs | | pub const VALUE: &'static str = V::VALUE; | ^^^^^^^^ note: erroneous constant encountered --> tests/ui/incorrect_len.rs:16:19 | 16 | let _ = N::<{ monostate::MustBeStr::<__Private>::VALUE.len() }>; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ monostate-1.0.2/tests/ui/overflow.rs000064400000000000000000000001031046102023000156170ustar 00000000000000use monostate::MustBe; fn main() { let _ = MustBe!(1000u8); } monostate-1.0.2/tests/ui/overflow.stderr000064400000000000000000000004341046102023000165050ustar 00000000000000error: literal out of range for `u8` --> tests/ui/overflow.rs:4:21 | 4 | let _ = MustBe!(1000u8); | ^^^^^^ | = note: the literal `1000u8` does not fit into the type `u8` whose range is `0..=255` = note: `#[deny(overflowing_literals)]` on by default monostate-1.0.2/tests/ui/ptrsized.rs000064400000000000000000000001401046102023000156210ustar 00000000000000use monostate::MustBe; fn main() { let _ = MustBe!(1usize); let _ = MustBe!(1isize); } monostate-1.0.2/tests/ui/ptrsized.stderr000064400000000000000000000005431046102023000165070ustar 00000000000000error: serde data model only uses consistently sized integer types, not usize --> tests/ui/ptrsized.rs:4:21 | 4 | let _ = MustBe!(1usize); | ^^^^^^ error: serde data model only uses consistently sized integer types, not isize --> tests/ui/ptrsized.rs:5:21 | 5 | let _ = MustBe!(1isize); | ^^^^^^