My working unpac space for OCaml projects in development
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Merge git/patches/cbor

+7622
+5
vendor/git/cbor/.editorconfig
··· 1 + # see https://editorconfig.org for more options, and setup instructions for yours editor 2 + 3 + [*.rs] 4 + indent_style = space 5 + indent_size = 4
+6
vendor/git/cbor/.github/dependabot.yml
··· 1 + version: 2 2 + updates: 3 + - package-ecosystem: github-actions 4 + directory: / 5 + schedule: 6 + interval: weekly
+57
vendor/git/cbor/.github/workflows/ci.yml
··· 1 + --- 2 + name: CI 3 + 4 + "on": 5 + pull_request: 6 + types: [opened, synchronize, reopened] 7 + push: 8 + branches: [main] 9 + 10 + jobs: 11 + build_and_test: 12 + strategy: 13 + fail-fast: false 14 + matrix: 15 + version: 16 + - { name: msrv, version: '1.81' } 17 + - { name: stable, version: stable } 18 + - { name: nightly, version: nightly } 19 + 20 + name: ${{ matrix.version.name }} 21 + runs-on: ubuntu-latest 22 + 23 + steps: 24 + - uses: actions/checkout@v6 25 + 26 + - name: Install Rust 27 + uses: actions-rust-lang/setup-rust-toolchain@v1.15.2 28 + with: 29 + toolchain: ${{ matrix.version.version }} 30 + 31 + - name: cargo check 32 + run: cargo check --workspace --bins --examples --tests 33 + 34 + - name: cargo test 35 + run: | 36 + cargo test --workspace --all-features --no-fail-fast -- --nocapture 37 + cargo build --features=unsealed_read_write 38 + cargo build --no-default-features --features=unsealed_read_write 39 + 40 + build_and_test_no_std: 41 + name: stable (no_std) 42 + runs-on: ubuntu-latest 43 + 44 + steps: 45 + - uses: actions/checkout@v6 46 + 47 + - name: Install Rust 48 + uses: actions-rust-lang/setup-rust-toolchain@v1.15.2 49 + 50 + - name: Add no_std target 51 + run: rustup target add thumbv7em-none-eabihf 52 + 53 + - name: cargo test 54 + run: | 55 + cargo build --target thumbv7em-none-eabihf --no-default-features --features=alloc 56 + cargo test --no-default-features --lib --tests 57 + cargo build --no-default-features --features=alloc
+52
vendor/git/cbor/.github/workflows/lint.yml
··· 1 + --- 2 + name: Lint 3 + 4 + "on": 5 + pull_request: 6 + types: [opened, synchronize, reopened] 7 + 8 + jobs: 9 + fmt: 10 + runs-on: ubuntu-latest 11 + steps: 12 + - uses: actions/checkout@v6 13 + 14 + - name: Install Rust 15 + uses: actions-rust-lang/setup-rust-toolchain@v1.15.2 16 + with: 17 + components: rustfmt 18 + 19 + - name: Check with Rustfmt 20 + run: cargo fmt --all -- --check 21 + 22 + clippy: 23 + runs-on: ubuntu-latest 24 + steps: 25 + - uses: actions/checkout@v6 26 + 27 + - name: Install Rust 28 + uses: actions-rust-lang/setup-rust-toolchain@v1.15.2 29 + with: 30 + components: clippy 31 + 32 + - name: Check with Clippy 33 + uses: giraffate/clippy-action@v1 34 + with: 35 + reporter: github-pr-check 36 + github_token: ${{ secrets.GITHUB_TOKEN }} 37 + clippy_flags: --workspace --all-features --tests --examples --bins -- -Dclippy::todo -Aunknown_lints 38 + 39 + lint-docs: 40 + runs-on: ubuntu-latest 41 + steps: 42 + - uses: actions/checkout@v6 43 + 44 + - name: Install Rust 45 + uses: actions-rust-lang/setup-rust-toolchain@v1.15.2 46 + with: 47 + components: rust-docs 48 + 49 + - name: Check for broken intra-doc links 50 + env: 51 + RUSTDOCFLAGS: -Dwarnings 52 + run: cargo doc --no-deps --all-features --workspace
+8
vendor/git/cbor/.gitignore
··· 1 + target 2 + Cargo.lock 3 + *.rs.bk 4 + tokamak.toml 5 + .idea 6 + *.iml 7 + examples/ferris.cbor 8 + .cargo/config
+9
vendor/git/cbor/CHANGELOG.md
··· 1 + # Changelog 2 + 3 + ## Unreleased 4 + 5 + - Minimum supported Rust version (MSRV) is now 1.81 due to `half` dependency. 6 + 7 + ## 0.11.0 8 + 9 + - TODO
+29
vendor/git/cbor/CONTRIBUTING.md
··· 1 + # Contributing to Serde CBOR 2 + Thanks for your interest! 3 + There are many ways to help: 4 + 5 + * write an issue about a problem you encountered 6 + * submit a pull request 7 + * add documentation and examples 8 + 9 + ## Pull Requests 10 + 11 + Code should be easy to understand and documented. 12 + For new features and fixed bugs please add a test to one of the files in `test/`. 13 + The tests are run on Travis CI to catch regressions early. 14 + Format your code with `cargo fmt` before committing. 15 + Currently Serde CBOR does not contain `unsafe` code and I would like to keep it this way. 16 + 17 + ## Making a Release 18 + 19 + * [ ] Make sure the crate compiles and all tests pass. 20 + * [ ] (Optional) Test that the fuzzer works and fuzz the crate for some time. 21 + * [ ] Write a list with all changes made since the last release 22 + * [ ] Increment the version number in `Cargo.toml` and the `README.md`. Bugfixes increase the patch version while new features or an increased minimum Rust version require a new minor version. 23 + * [ ] Check that the file `examples/readme.rs` and the example from the `README.md` match. 24 + * [ ] Commit the changes. 25 + * [ ] Add a git tag with the new version number: 26 + `git tag "v42.0.2"` 27 + * [ ] Push the changes: `git push --tags` 28 + * [ ] Run `cargo publish` 29 + * [ ] Add a new release to GitHub with a list of changes.
+34
vendor/git/cbor/Cargo.toml
··· 1 + [package] 2 + name = "serde_cbor_2" 3 + version = "0.13.0" 4 + authors = [ 5 + "William Brown <william@blackhats.net.au>", 6 + "James Hodgkinson <james@terminaloutcomes.com>", 7 + ] 8 + repository = "https://github.com/kanidm/cbor" 9 + license = "MIT OR Apache-2.0" 10 + description = "CBOR support for Serde." 11 + keywords = ["serde", "cbor", "serialization", "no_std"] 12 + categories = ["encoding"] 13 + edition = "2021" 14 + rust-version = "1.81" 15 + 16 + 17 + [badges] 18 + maintenance = { status = "passively-maintained" } 19 + 20 + [features] 21 + default = ["std"] 22 + # Uses `alloc` library and adds support for vector functions with 23 + # `no_std`. 24 + alloc = ["serde/alloc"] 25 + std = ["serde/std"] 26 + unsealed_read_write = [] 27 + tags = [] 28 + 29 + [dependencies] 30 + half = { version = "2", default-features = false } 31 + serde = { version = "1", default-features = false } 32 + 33 + [dev-dependencies] 34 + serde = { version = "1", default-features = false, features = ["derive"] }
+201
vendor/git/cbor/LICENSE-APACHE
··· 1 + Apache License 2 + Version 2.0, January 2004 3 + http://www.apache.org/licenses/ 4 + 5 + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 + 7 + 1. Definitions. 8 + 9 + "License" shall mean the terms and conditions for use, reproduction, 10 + and distribution as defined by Sections 1 through 9 of this document. 11 + 12 + "Licensor" shall mean the copyright owner or entity authorized by 13 + the copyright owner that is granting the License. 14 + 15 + "Legal Entity" shall mean the union of the acting entity and all 16 + other entities that control, are controlled by, or are under common 17 + control with that entity. For the purposes of this definition, 18 + "control" means (i) the power, direct or indirect, to cause the 19 + direction or management of such entity, whether by contract or 20 + otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 + outstanding shares, or (iii) beneficial ownership of such entity. 22 + 23 + "You" (or "Your") shall mean an individual or Legal Entity 24 + exercising permissions granted by this License. 25 + 26 + "Source" form shall mean the preferred form for making modifications, 27 + including but not limited to software source code, documentation 28 + source, and configuration files. 29 + 30 + "Object" form shall mean any form resulting from mechanical 31 + transformation or translation of a Source form, including but 32 + not limited to compiled object code, generated documentation, 33 + and conversions to other media types. 34 + 35 + "Work" shall mean the work of authorship, whether in Source or 36 + Object form, made available under the License, as indicated by a 37 + copyright notice that is included in or attached to the work 38 + (an example is provided in the Appendix below). 39 + 40 + "Derivative Works" shall mean any work, whether in Source or Object 41 + form, that is based on (or derived from) the Work and for which the 42 + editorial revisions, annotations, elaborations, or other modifications 43 + represent, as a whole, an original work of authorship. For the purposes 44 + of this License, Derivative Works shall not include works that remain 45 + separable from, or merely link (or bind by name) to the interfaces of, 46 + the Work and Derivative Works thereof. 47 + 48 + "Contribution" shall mean any work of authorship, including 49 + the original version of the Work and any modifications or additions 50 + to that Work or Derivative Works thereof, that is intentionally 51 + submitted to Licensor for inclusion in the Work by the copyright owner 52 + or by an individual or Legal Entity authorized to submit on behalf of 53 + the copyright owner. For the purposes of this definition, "submitted" 54 + means any form of electronic, verbal, or written communication sent 55 + to the Licensor or its representatives, including but not limited to 56 + communication on electronic mailing lists, source code control systems, 57 + and issue tracking systems that are managed by, or on behalf of, the 58 + Licensor for the purpose of discussing and improving the Work, but 59 + excluding communication that is conspicuously marked or otherwise 60 + designated in writing by the copyright owner as "Not a Contribution." 61 + 62 + "Contributor" shall mean Licensor and any individual or Legal Entity 63 + on behalf of whom a Contribution has been received by Licensor and 64 + subsequently incorporated within the Work. 65 + 66 + 2. Grant of Copyright License. Subject to the terms and conditions of 67 + this License, each Contributor hereby grants to You a perpetual, 68 + worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 + copyright license to reproduce, prepare Derivative Works of, 70 + publicly display, publicly perform, sublicense, and distribute the 71 + Work and such Derivative Works in Source or Object form. 72 + 73 + 3. Grant of Patent License. Subject to the terms and conditions of 74 + this License, each Contributor hereby grants to You a perpetual, 75 + worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 + (except as stated in this section) patent license to make, have made, 77 + use, offer to sell, sell, import, and otherwise transfer the Work, 78 + where such license applies only to those patent claims licensable 79 + by such Contributor that are necessarily infringed by their 80 + Contribution(s) alone or by combination of their Contribution(s) 81 + with the Work to which such Contribution(s) was submitted. If You 82 + institute patent litigation against any entity (including a 83 + cross-claim or counterclaim in a lawsuit) alleging that the Work 84 + or a Contribution incorporated within the Work constitutes direct 85 + or contributory patent infringement, then any patent licenses 86 + granted to You under this License for that Work shall terminate 87 + as of the date such litigation is filed. 88 + 89 + 4. Redistribution. You may reproduce and distribute copies of the 90 + Work or Derivative Works thereof in any medium, with or without 91 + modifications, and in Source or Object form, provided that You 92 + meet the following conditions: 93 + 94 + (a) You must give any other recipients of the Work or 95 + Derivative Works a copy of this License; and 96 + 97 + (b) You must cause any modified files to carry prominent notices 98 + stating that You changed the files; and 99 + 100 + (c) You must retain, in the Source form of any Derivative Works 101 + that You distribute, all copyright, patent, trademark, and 102 + attribution notices from the Source form of the Work, 103 + excluding those notices that do not pertain to any part of 104 + the Derivative Works; and 105 + 106 + (d) If the Work includes a "NOTICE" text file as part of its 107 + distribution, then any Derivative Works that You distribute must 108 + include a readable copy of the attribution notices contained 109 + within such NOTICE file, excluding those notices that do not 110 + pertain to any part of the Derivative Works, in at least one 111 + of the following places: within a NOTICE text file distributed 112 + as part of the Derivative Works; within the Source form or 113 + documentation, if provided along with the Derivative Works; or, 114 + within a display generated by the Derivative Works, if and 115 + wherever such third-party notices normally appear. The contents 116 + of the NOTICE file are for informational purposes only and 117 + do not modify the License. You may add Your own attribution 118 + notices within Derivative Works that You distribute, alongside 119 + or as an addendum to the NOTICE text from the Work, provided 120 + that such additional attribution notices cannot be construed 121 + as modifying the License. 122 + 123 + You may add Your own copyright statement to Your modifications and 124 + may provide additional or different license terms and conditions 125 + for use, reproduction, or distribution of Your modifications, or 126 + for any such Derivative Works as a whole, provided Your use, 127 + reproduction, and distribution of the Work otherwise complies with 128 + the conditions stated in this License. 129 + 130 + 5. Submission of Contributions. Unless You explicitly state otherwise, 131 + any Contribution intentionally submitted for inclusion in the Work 132 + by You to the Licensor shall be under the terms and conditions of 133 + this License, without any additional terms or conditions. 134 + Notwithstanding the above, nothing herein shall supersede or modify 135 + the terms of any separate license agreement you may have executed 136 + with Licensor regarding such Contributions. 137 + 138 + 6. Trademarks. This License does not grant permission to use the trade 139 + names, trademarks, service marks, or product names of the Licensor, 140 + except as required for reasonable and customary use in describing the 141 + origin of the Work and reproducing the content of the NOTICE file. 142 + 143 + 7. Disclaimer of Warranty. Unless required by applicable law or 144 + agreed to in writing, Licensor provides the Work (and each 145 + Contributor provides its Contributions) on an "AS IS" BASIS, 146 + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 + implied, including, without limitation, any warranties or conditions 148 + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 + PARTICULAR PURPOSE. You are solely responsible for determining the 150 + appropriateness of using or redistributing the Work and assume any 151 + risks associated with Your exercise of permissions under this License. 152 + 153 + 8. Limitation of Liability. In no event and under no legal theory, 154 + whether in tort (including negligence), contract, or otherwise, 155 + unless required by applicable law (such as deliberate and grossly 156 + negligent acts) or agreed to in writing, shall any Contributor be 157 + liable to You for damages, including any direct, indirect, special, 158 + incidental, or consequential damages of any character arising as a 159 + result of this License or out of the use or inability to use the 160 + Work (including but not limited to damages for loss of goodwill, 161 + work stoppage, computer failure or malfunction, or any and all 162 + other commercial damages or losses), even if such Contributor 163 + has been advised of the possibility of such damages. 164 + 165 + 9. Accepting Warranty or Additional Liability. While redistributing 166 + the Work or Derivative Works thereof, You may choose to offer, 167 + and charge a fee for, acceptance of support, warranty, indemnity, 168 + or other liability obligations and/or rights consistent with this 169 + License. However, in accepting such obligations, You may act only 170 + on Your own behalf and on Your sole responsibility, not on behalf 171 + of any other Contributor, and only if You agree to indemnify, 172 + defend, and hold each Contributor harmless for any liability 173 + incurred by, or claims asserted against, such Contributor by reason 174 + of your accepting any such warranty or additional liability. 175 + 176 + END OF TERMS AND CONDITIONS 177 + 178 + APPENDIX: How to apply the Apache License to your work. 179 + 180 + To apply the Apache License to your work, attach the following 181 + boilerplate notice, with the fields enclosed by brackets "[]" 182 + replaced with your own identifying information. (Don't include 183 + the brackets!) The text should be enclosed in the appropriate 184 + comment syntax for the file format. We also recommend that a 185 + file or class name and description of purpose be included on the 186 + same "printed page" as the copyright notice for easier 187 + identification within third-party archives. 188 + 189 + Copyright [yyyy] [name of copyright owner] 190 + 191 + Licensed under the Apache License, Version 2.0 (the "License"); 192 + you may not use this file except in compliance with the License. 193 + You may obtain a copy of the License at 194 + 195 + http://www.apache.org/licenses/LICENSE-2.0 196 + 197 + Unless required by applicable law or agreed to in writing, software 198 + distributed under the License is distributed on an "AS IS" BASIS, 199 + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 + See the License for the specific language governing permissions and 201 + limitations under the License.
+19
vendor/git/cbor/LICENSE-MIT
··· 1 + Copyright (c) 2015 Pyfisch 2 + 3 + Permission is hereby granted, free of charge, to any person obtaining a copy 4 + of this software and associated documentation files (the "Software"), to deal 5 + in the Software without restriction, including without limitation the rights 6 + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 + copies of the Software, and to permit persons to whom the Software is 8 + furnished to do so, subject to the following conditions: 9 + 10 + The above copyright notice and this permission notice shall be included in 11 + all copies or substantial portions of the Software. 12 + 13 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 + THE SOFTWARE.
+80
vendor/git/cbor/README.md
··· 1 + # Serde CBOR 2 + 3 + [![CI](https://github.com/kanidm/cbor/actions/workflows/ci.yml/badge.svg)](https://github.com/kanidm/cbor/actions/workflows/ci.yml) 4 + [![crates.io](https://img.shields.io/crates/v/serde_cbor_2.svg?label=latest)](https://crates.io/crates/serde_cbor_2) 5 + [![Documentation](https://docs.rs/serde_cbor_2/badge.svg)](https://docs.rs/serde_cbor_2) 6 + 7 + This crate implements the Concise Binary Object Representation from [RFC 7049][rfc7049]. 8 + It builds on [Serde][serde], the generic serialization framework for Rust. 9 + CBOR provides a binary encoding for a superset of the JSON data model that is small and very fast to parse. 10 + 11 + ## Usage 12 + 13 + Serde CBOR supports Rust 1.81 and up. Add this to your `Cargo.toml`: 14 + 15 + ```toml 16 + [dependencies] 17 + serde_cbor_2 = "0.11.2" 18 + ``` 19 + 20 + Storing and loading Rust types is easy and requires only minimal modifications to the program code. 21 + 22 + ```rust 23 + use std::{error::Error, fs::File}; 24 + use serde::{Deserialize, Serialize}; 25 + 26 + // Types annotated with `Serialize` can be stored as CBOR. 27 + // To be able to load them again add `Deserialize`. 28 + #[derive(Debug, Serialize, Deserialize)] 29 + struct Mascot { 30 + name: String, 31 + species: String, 32 + year_of_birth: u32, 33 + } 34 + 35 + fn main() -> Result<(), Box<dyn Error>> { 36 + let ferris = Mascot { 37 + name: "Ferris".to_owned(), 38 + species: "crab".to_owned(), 39 + year_of_birth: 2015, 40 + }; 41 + 42 + let ferris_file = File::create("examples/ferris.cbor")?; 43 + // Write Ferris to the given file. 44 + // Instead of a file you can use any type that implements `io::Write` 45 + // like a HTTP body, database connection etc. 46 + serde_cbor_2::to_writer(ferris_file, &ferris)?; 47 + 48 + let tux_file = File::open("examples/tux.cbor")?; 49 + // Load Tux from a file. 50 + // Serde CBOR performs roundtrip serialization meaning that 51 + // the data will not change in any way. 52 + let tux: Mascot = serde_cbor_2::from_reader(tux_file)?; 53 + 54 + println!("{tux:?}"); 55 + // prints: Mascot { name: "Tux", species: "penguin", year_of_birth: 1996 } 56 + 57 + Ok(()) 58 + } 59 + ``` 60 + 61 + There are a lot of options available to customize the format. 62 + To operate on untyped CBOR values have a look at the `Value` type. 63 + 64 + ## License 65 + 66 + Licensed under either of 67 + 68 + - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>) 69 + - MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>) 70 + 71 + at your option. 72 + 73 + ### Contribution 74 + 75 + Unless you explicitly state otherwise, any contribution intentionally submitted 76 + for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any 77 + additional terms or conditions. 78 + 79 + [rfc7049]: https://tools.ietf.org/html/rfc7049 80 + [serde]: https://github.com/serde-rs/serde
+38
vendor/git/cbor/examples/readme.rs
··· 1 + // NOTE: This file should be kept in sync with README.md 2 + 3 + use serde::{Deserialize, Serialize}; 4 + use std::{error::Error, fs::File}; 5 + 6 + // Types annotated with `Serialize` can be stored as CBOR. 7 + // To be able to load them again add `Deserialize`. 8 + #[derive(Debug, Serialize, Deserialize)] 9 + struct Mascot { 10 + name: String, 11 + species: String, 12 + year_of_birth: u32, 13 + } 14 + 15 + fn main() -> Result<(), Box<dyn Error>> { 16 + let ferris = Mascot { 17 + name: "Ferris".to_owned(), 18 + species: "crab".to_owned(), 19 + year_of_birth: 2015, 20 + }; 21 + 22 + let ferris_file = File::create("examples/ferris.cbor")?; 23 + // Write Ferris to the given file. 24 + // Instead of a file you can use any type that implements `io::Write` 25 + // like a HTTP body, database connection etc. 26 + serde_cbor_2::to_writer(ferris_file, &ferris)?; 27 + 28 + let tux_file = File::open("examples/tux.cbor")?; 29 + // Load Tux from a file. 30 + // Serde CBOR performs roundtrip serialization meaning that 31 + // the data will not change in any way. 32 + let tux: Mascot = serde_cbor_2::from_reader(tux_file)?; 33 + 34 + println!("{tux:?}"); 35 + // prints: Mascot { name: "Tux", species: "penguin", year_of_birth: 1996 } 36 + 37 + Ok(()) 38 + }
+81
vendor/git/cbor/examples/tags.rs
··· 1 + use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize}; 2 + use serde_cbor_2::{tags::Tagged, Value}; 3 + use std::error::Error; 4 + 5 + /// https://tools.ietf.org/html/rfc7049#section-2.4.1 6 + #[derive(Debug, PartialEq)] 7 + struct Date(String); 8 + 9 + impl Serialize for Date { 10 + fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { 11 + Tagged::new(Some(0), &self.0).serialize(s) 12 + } 13 + } 14 + 15 + impl<'de> Deserialize<'de> for Date { 16 + fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { 17 + let tagged = Tagged::<String>::deserialize(deserializer)?; 18 + match tagged.tag { 19 + Some(0) | None => Ok(Date(tagged.value)), 20 + Some(_) => Err(serde::de::Error::custom("unexpected tag")), 21 + } 22 + } 23 + } 24 + 25 + /// https://tools.ietf.org/html/rfc7049#section-2.4.4.3 26 + #[derive(Debug, PartialEq)] 27 + struct Uri(String); 28 + 29 + impl Serialize for Uri { 30 + fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { 31 + Tagged::new(Some(32), &self.0).serialize(s) 32 + } 33 + } 34 + impl<'de> Deserialize<'de> for Uri { 35 + fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { 36 + let tagged = Tagged::<String>::deserialize(deserializer)?; 37 + match tagged.tag { 38 + // allow deserialization even if there is no tag. Allows roundtrip via other formats such as json 39 + Some(0) | None => Ok(Uri(tagged.value)), 40 + Some(_) => Err(serde::de::Error::custom("unexpected tag")), 41 + } 42 + } 43 + } 44 + 45 + #[derive(Debug, Serialize, Deserialize, PartialEq)] 46 + struct Bookmark { 47 + title: String, 48 + link: Uri, 49 + created: Date, 50 + } 51 + 52 + fn main() -> Result<(), Box<dyn Error>> { 53 + let bookmark = Bookmark { 54 + title: "The Example Domain".into(), 55 + link: Uri("http://example.org/".into()), 56 + created: Date("2003-12-13T18:30:02Z".into()), 57 + }; 58 + 59 + // serialize the struct to bytes 60 + let bytes1 = serde_cbor_2::to_vec(&bookmark)?; 61 + // deserialize to a serde_cbor_2::Value 62 + let value1: Value = serde_cbor_2::from_slice(&bytes1)?; 63 + println!("{value1:?}"); 64 + // serialize the value to bytes 65 + let bytes2 = serde_cbor_2::to_vec(&value1)?; 66 + // deserialize to a serde_cbor_2::Value 67 + let value2: Value = serde_cbor_2::from_slice(&bytes2)?; 68 + println!("{value2:?}"); 69 + // deserialize to a Bookmark 70 + let result: Bookmark = serde_cbor_2::from_slice(&bytes2)?; 71 + 72 + // check that the roundtrip was successful 73 + assert_eq!(value1, value2); 74 + assert_eq!(bookmark, result); 75 + 76 + // check that going via a format that does not support tags does work 77 + // let json = serde_json::to_vec(&bookmark)?; 78 + // let result: Bookmark = serde_json::from_slice(&json)?; 79 + // assert_eq!(bookmark, result); 80 + Ok(()) 81 + }
+1
vendor/git/cbor/examples/tux.cbor
··· 1 + �dnamecTuxgspeciesgpenguinmyear_of_birth�
+4
vendor/git/cbor/fuzz/.gitignore
··· 1 + 2 + target 3 + corpus 4 + artifacts
+26
vendor/git/cbor/fuzz/Cargo.toml
··· 1 + 2 + [package] 3 + name = "serde_cbor-fuzz" 4 + version = "0.0.1" 5 + authors = ["Automatically generated"] 6 + publish = false 7 + 8 + [package.metadata] 9 + cargo-fuzz = true 10 + 11 + [dependencies.serde_cbor] 12 + path = ".." 13 + [dependencies.libfuzzer-sys] 14 + git = "https://github.com/rust-fuzz/libfuzzer-sys.git" 15 + 16 + # Prevent this from interfering with workspaces 17 + [workspace] 18 + members = ["."] 19 + 20 + [[bin]] 21 + name = "from_slice" 22 + path = "fuzz_targets/from_slice.rs" 23 + 24 + [[bin]] 25 + name = "from_reader" 26 + path = "fuzz_targets/from_reader.rs"
+636
vendor/git/cbor/fuzz/appendix_a.json
··· 1 + [ 2 + { 3 + "cbor": "AA==", 4 + "hex": "00", 5 + "roundtrip": true, 6 + "decoded": 0 7 + }, 8 + { 9 + "cbor": "AQ==", 10 + "hex": "01", 11 + "roundtrip": true, 12 + "decoded": 1 13 + }, 14 + { 15 + "cbor": "Cg==", 16 + "hex": "0a", 17 + "roundtrip": true, 18 + "decoded": 10 19 + }, 20 + { 21 + "cbor": "Fw==", 22 + "hex": "17", 23 + "roundtrip": true, 24 + "decoded": 23 25 + }, 26 + { 27 + "cbor": "GBg=", 28 + "hex": "1818", 29 + "roundtrip": true, 30 + "decoded": 24 31 + }, 32 + { 33 + "cbor": "GBk=", 34 + "hex": "1819", 35 + "roundtrip": true, 36 + "decoded": 25 37 + }, 38 + { 39 + "cbor": "GGQ=", 40 + "hex": "1864", 41 + "roundtrip": true, 42 + "decoded": 100 43 + }, 44 + { 45 + "cbor": "GQPo", 46 + "hex": "1903e8", 47 + "roundtrip": true, 48 + "decoded": 1000 49 + }, 50 + { 51 + "cbor": "GgAPQkA=", 52 + "hex": "1a000f4240", 53 + "roundtrip": true, 54 + "decoded": 1000000 55 + }, 56 + { 57 + "cbor": "GwAAAOjUpRAA", 58 + "hex": "1b000000e8d4a51000", 59 + "roundtrip": true, 60 + "decoded": 1000000000000 61 + }, 62 + { 63 + "cbor": "G///////////", 64 + "hex": "1bffffffffffffffff", 65 + "roundtrip": true, 66 + "decoded": 18446744073709551615 67 + }, 68 + { 69 + "cbor": "wkkBAAAAAAAAAAA=", 70 + "hex": "c249010000000000000000", 71 + "roundtrip": true, 72 + "decoded": 18446744073709551616 73 + }, 74 + { 75 + "cbor": "O///////////", 76 + "hex": "3bffffffffffffffff", 77 + "roundtrip": true, 78 + "decoded": -18446744073709551616 79 + }, 80 + { 81 + "cbor": "w0kBAAAAAAAAAAA=", 82 + "hex": "c349010000000000000000", 83 + "roundtrip": true, 84 + "decoded": -18446744073709551617 85 + }, 86 + { 87 + "cbor": "IA==", 88 + "hex": "20", 89 + "roundtrip": true, 90 + "decoded": -1 91 + }, 92 + { 93 + "cbor": "KQ==", 94 + "hex": "29", 95 + "roundtrip": true, 96 + "decoded": -10 97 + }, 98 + { 99 + "cbor": "OGM=", 100 + "hex": "3863", 101 + "roundtrip": true, 102 + "decoded": -100 103 + }, 104 + { 105 + "cbor": "OQPn", 106 + "hex": "3903e7", 107 + "roundtrip": true, 108 + "decoded": -1000 109 + }, 110 + { 111 + "cbor": "+QAA", 112 + "hex": "f90000", 113 + "roundtrip": true, 114 + "decoded": 0.0 115 + }, 116 + { 117 + "cbor": "+YAA", 118 + "hex": "f98000", 119 + "roundtrip": true, 120 + "decoded": -0.0 121 + }, 122 + { 123 + "cbor": "+TwA", 124 + "hex": "f93c00", 125 + "roundtrip": true, 126 + "decoded": 1.0 127 + }, 128 + { 129 + "cbor": "+z/xmZmZmZma", 130 + "hex": "fb3ff199999999999a", 131 + "roundtrip": true, 132 + "decoded": 1.1 133 + }, 134 + { 135 + "cbor": "+T4A", 136 + "hex": "f93e00", 137 + "roundtrip": true, 138 + "decoded": 1.5 139 + }, 140 + { 141 + "cbor": "+Xv/", 142 + "hex": "f97bff", 143 + "roundtrip": true, 144 + "decoded": 65504.0 145 + }, 146 + { 147 + "cbor": "+kfDUAA=", 148 + "hex": "fa47c35000", 149 + "roundtrip": true, 150 + "decoded": 100000.0 151 + }, 152 + { 153 + "cbor": "+n9///8=", 154 + "hex": "fa7f7fffff", 155 + "roundtrip": true, 156 + "decoded": 3.4028234663852886e+38 157 + }, 158 + { 159 + "cbor": "+3435DyIAHWc", 160 + "hex": "fb7e37e43c8800759c", 161 + "roundtrip": true, 162 + "decoded": 1.0e+300 163 + }, 164 + { 165 + "cbor": "+QAB", 166 + "hex": "f90001", 167 + "roundtrip": true, 168 + "decoded": 5.960464477539063e-08 169 + }, 170 + { 171 + "cbor": "+QQA", 172 + "hex": "f90400", 173 + "roundtrip": true, 174 + "decoded": 6.103515625e-05 175 + }, 176 + { 177 + "cbor": "+cQA", 178 + "hex": "f9c400", 179 + "roundtrip": true, 180 + "decoded": -4.0 181 + }, 182 + { 183 + "cbor": "+8AQZmZmZmZm", 184 + "hex": "fbc010666666666666", 185 + "roundtrip": true, 186 + "decoded": -4.1 187 + }, 188 + { 189 + "cbor": "+XwA", 190 + "hex": "f97c00", 191 + "roundtrip": true, 192 + "diagnostic": "Infinity" 193 + }, 194 + { 195 + "cbor": "+X4A", 196 + "hex": "f97e00", 197 + "roundtrip": true, 198 + "diagnostic": "NaN" 199 + }, 200 + { 201 + "cbor": "+fwA", 202 + "hex": "f9fc00", 203 + "roundtrip": true, 204 + "diagnostic": "-Infinity" 205 + }, 206 + { 207 + "cbor": "+n+AAAA=", 208 + "hex": "fa7f800000", 209 + "roundtrip": false, 210 + "diagnostic": "Infinity" 211 + }, 212 + { 213 + "cbor": "+n/AAAA=", 214 + "hex": "fa7fc00000", 215 + "roundtrip": false, 216 + "diagnostic": "NaN" 217 + }, 218 + { 219 + "cbor": "+v+AAAA=", 220 + "hex": "faff800000", 221 + "roundtrip": false, 222 + "diagnostic": "-Infinity" 223 + }, 224 + { 225 + "cbor": "+3/wAAAAAAAA", 226 + "hex": "fb7ff0000000000000", 227 + "roundtrip": false, 228 + "diagnostic": "Infinity" 229 + }, 230 + { 231 + "cbor": "+3/4AAAAAAAA", 232 + "hex": "fb7ff8000000000000", 233 + "roundtrip": false, 234 + "diagnostic": "NaN" 235 + }, 236 + { 237 + "cbor": "+//wAAAAAAAA", 238 + "hex": "fbfff0000000000000", 239 + "roundtrip": false, 240 + "diagnostic": "-Infinity" 241 + }, 242 + { 243 + "cbor": "9A==", 244 + "hex": "f4", 245 + "roundtrip": true, 246 + "decoded": false 247 + }, 248 + { 249 + "cbor": "9Q==", 250 + "hex": "f5", 251 + "roundtrip": true, 252 + "decoded": true 253 + }, 254 + { 255 + "cbor": "9g==", 256 + "hex": "f6", 257 + "roundtrip": true, 258 + "decoded": null 259 + }, 260 + { 261 + "cbor": "9w==", 262 + "hex": "f7", 263 + "roundtrip": true, 264 + "diagnostic": "undefined" 265 + }, 266 + { 267 + "cbor": "8A==", 268 + "hex": "f0", 269 + "roundtrip": true, 270 + "diagnostic": "simple(16)" 271 + }, 272 + { 273 + "cbor": "+Bg=", 274 + "hex": "f818", 275 + "roundtrip": true, 276 + "diagnostic": "simple(24)" 277 + }, 278 + { 279 + "cbor": "+P8=", 280 + "hex": "f8ff", 281 + "roundtrip": true, 282 + "diagnostic": "simple(255)" 283 + }, 284 + { 285 + "cbor": "wHQyMDEzLTAzLTIxVDIwOjA0OjAwWg==", 286 + "hex": "c074323031332d30332d32315432303a30343a30305a", 287 + "roundtrip": true, 288 + "diagnostic": "0(\"2013-03-21T20:04:00Z\")" 289 + }, 290 + { 291 + "cbor": "wRpRS2ew", 292 + "hex": "c11a514b67b0", 293 + "roundtrip": true, 294 + "diagnostic": "1(1363896240)" 295 + }, 296 + { 297 + "cbor": "wftB1FLZ7CAAAA==", 298 + "hex": "c1fb41d452d9ec200000", 299 + "roundtrip": true, 300 + "diagnostic": "1(1363896240.5)" 301 + }, 302 + { 303 + "cbor": "10QBAgME", 304 + "hex": "d74401020304", 305 + "roundtrip": true, 306 + "diagnostic": "23(h'01020304')" 307 + }, 308 + { 309 + "cbor": "2BhFZElFVEY=", 310 + "hex": "d818456449455446", 311 + "roundtrip": true, 312 + "diagnostic": "24(h'6449455446')" 313 + }, 314 + { 315 + "cbor": "2CB2aHR0cDovL3d3dy5leGFtcGxlLmNvbQ==", 316 + "hex": "d82076687474703a2f2f7777772e6578616d706c652e636f6d", 317 + "roundtrip": true, 318 + "diagnostic": "32(\"http://www.example.com\")" 319 + }, 320 + { 321 + "cbor": "QA==", 322 + "hex": "40", 323 + "roundtrip": true, 324 + "diagnostic": "h''" 325 + }, 326 + { 327 + "cbor": "RAECAwQ=", 328 + "hex": "4401020304", 329 + "roundtrip": true, 330 + "diagnostic": "h'01020304'" 331 + }, 332 + { 333 + "cbor": "YA==", 334 + "hex": "60", 335 + "roundtrip": true, 336 + "decoded": "" 337 + }, 338 + { 339 + "cbor": "YWE=", 340 + "hex": "6161", 341 + "roundtrip": true, 342 + "decoded": "a" 343 + }, 344 + { 345 + "cbor": "ZElFVEY=", 346 + "hex": "6449455446", 347 + "roundtrip": true, 348 + "decoded": "IETF" 349 + }, 350 + { 351 + "cbor": "YiJc", 352 + "hex": "62225c", 353 + "roundtrip": true, 354 + "decoded": "\"\\" 355 + }, 356 + { 357 + "cbor": "YsO8", 358 + "hex": "62c3bc", 359 + "roundtrip": true, 360 + "decoded": "ü" 361 + }, 362 + { 363 + "cbor": "Y+awtA==", 364 + "hex": "63e6b0b4", 365 + "roundtrip": true, 366 + "decoded": "水" 367 + }, 368 + { 369 + "cbor": "ZPCQhZE=", 370 + "hex": "64f0908591", 371 + "roundtrip": true, 372 + "decoded": "𐅑" 373 + }, 374 + { 375 + "cbor": "gA==", 376 + "hex": "80", 377 + "roundtrip": true, 378 + "decoded": [ 379 + 380 + ] 381 + }, 382 + { 383 + "cbor": "gwECAw==", 384 + "hex": "83010203", 385 + "roundtrip": true, 386 + "decoded": [ 387 + 1, 388 + 2, 389 + 3 390 + ] 391 + }, 392 + { 393 + "cbor": "gwGCAgOCBAU=", 394 + "hex": "8301820203820405", 395 + "roundtrip": true, 396 + "decoded": [ 397 + 1, 398 + [ 399 + 2, 400 + 3 401 + ], 402 + [ 403 + 4, 404 + 5 405 + ] 406 + ] 407 + }, 408 + { 409 + "cbor": "mBkBAgMEBQYHCAkKCwwNDg8QERITFBUWFxgYGBk=", 410 + "hex": "98190102030405060708090a0b0c0d0e0f101112131415161718181819", 411 + "roundtrip": true, 412 + "decoded": [ 413 + 1, 414 + 2, 415 + 3, 416 + 4, 417 + 5, 418 + 6, 419 + 7, 420 + 8, 421 + 9, 422 + 10, 423 + 11, 424 + 12, 425 + 13, 426 + 14, 427 + 15, 428 + 16, 429 + 17, 430 + 18, 431 + 19, 432 + 20, 433 + 21, 434 + 22, 435 + 23, 436 + 24, 437 + 25 438 + ] 439 + }, 440 + { 441 + "cbor": "oA==", 442 + "hex": "a0", 443 + "roundtrip": true, 444 + "decoded": { 445 + } 446 + }, 447 + { 448 + "cbor": "ogECAwQ=", 449 + "hex": "a201020304", 450 + "roundtrip": true, 451 + "diagnostic": "{1: 2, 3: 4}" 452 + }, 453 + { 454 + "cbor": "omFhAWFiggID", 455 + "hex": "a26161016162820203", 456 + "roundtrip": true, 457 + "decoded": { 458 + "a": 1, 459 + "b": [ 460 + 2, 461 + 3 462 + ] 463 + } 464 + }, 465 + { 466 + "cbor": "gmFhoWFiYWM=", 467 + "hex": "826161a161626163", 468 + "roundtrip": true, 469 + "decoded": [ 470 + "a", 471 + { 472 + "b": "c" 473 + } 474 + ] 475 + }, 476 + { 477 + "cbor": "pWFhYUFhYmFCYWNhQ2FkYURhZWFF", 478 + "hex": "a56161614161626142616361436164614461656145", 479 + "roundtrip": true, 480 + "decoded": { 481 + "a": "A", 482 + "b": "B", 483 + "c": "C", 484 + "d": "D", 485 + "e": "E" 486 + } 487 + }, 488 + { 489 + "cbor": "X0IBAkMDBAX/", 490 + "hex": "5f42010243030405ff", 491 + "roundtrip": false, 492 + "diagnostic": "(_ h'0102', h'030405')" 493 + }, 494 + { 495 + "cbor": "f2VzdHJlYWRtaW5n/w==", 496 + "hex": "7f657374726561646d696e67ff", 497 + "roundtrip": false, 498 + "decoded": "streaming" 499 + }, 500 + { 501 + "cbor": "n/8=", 502 + "hex": "9fff", 503 + "roundtrip": false, 504 + "decoded": [ 505 + 506 + ] 507 + }, 508 + { 509 + "cbor": "nwGCAgOfBAX//w==", 510 + "hex": "9f018202039f0405ffff", 511 + "roundtrip": false, 512 + "decoded": [ 513 + 1, 514 + [ 515 + 2, 516 + 3 517 + ], 518 + [ 519 + 4, 520 + 5 521 + ] 522 + ] 523 + }, 524 + { 525 + "cbor": "nwGCAgOCBAX/", 526 + "hex": "9f01820203820405ff", 527 + "roundtrip": false, 528 + "decoded": [ 529 + 1, 530 + [ 531 + 2, 532 + 3 533 + ], 534 + [ 535 + 4, 536 + 5 537 + ] 538 + ] 539 + }, 540 + { 541 + "cbor": "gwGCAgOfBAX/", 542 + "hex": "83018202039f0405ff", 543 + "roundtrip": false, 544 + "decoded": [ 545 + 1, 546 + [ 547 + 2, 548 + 3 549 + ], 550 + [ 551 + 4, 552 + 5 553 + ] 554 + ] 555 + }, 556 + { 557 + "cbor": "gwGfAgP/ggQF", 558 + "hex": "83019f0203ff820405", 559 + "roundtrip": false, 560 + "decoded": [ 561 + 1, 562 + [ 563 + 2, 564 + 3 565 + ], 566 + [ 567 + 4, 568 + 5 569 + ] 570 + ] 571 + }, 572 + { 573 + "cbor": "nwECAwQFBgcICQoLDA0ODxAREhMUFRYXGBgYGf8=", 574 + "hex": "9f0102030405060708090a0b0c0d0e0f101112131415161718181819ff", 575 + "roundtrip": false, 576 + "decoded": [ 577 + 1, 578 + 2, 579 + 3, 580 + 4, 581 + 5, 582 + 6, 583 + 7, 584 + 8, 585 + 9, 586 + 10, 587 + 11, 588 + 12, 589 + 13, 590 + 14, 591 + 15, 592 + 16, 593 + 17, 594 + 18, 595 + 19, 596 + 20, 597 + 21, 598 + 22, 599 + 23, 600 + 24, 601 + 25 602 + ] 603 + }, 604 + { 605 + "cbor": "v2FhAWFinwID//8=", 606 + "hex": "bf61610161629f0203ffff", 607 + "roundtrip": false, 608 + "decoded": { 609 + "a": 1, 610 + "b": [ 611 + 2, 612 + 3 613 + ] 614 + } 615 + }, 616 + { 617 + "cbor": "gmFhv2FiYWP/", 618 + "hex": "826161bf61626163ff", 619 + "roundtrip": false, 620 + "decoded": [ 621 + "a", 622 + { 623 + "b": "c" 624 + } 625 + ] 626 + }, 627 + { 628 + "cbor": "v2NGdW71Y0FtdCH/", 629 + "hex": "bf6346756ef563416d7421ff", 630 + "roundtrip": false, 631 + "decoded": { 632 + "Fun": true, 633 + "Amt": -2 634 + } 635 + } 636 + ]
+10
vendor/git/cbor/fuzz/fuzz_targets/from_reader.rs
··· 1 + #![no_main] 2 + #[macro_use] extern crate libfuzzer_sys; 3 + extern crate serde_cbor; 4 + 5 + use serde_cbor::Value; 6 + 7 + fuzz_target!(|data: &[u8]| { 8 + let mut data = data; 9 + let _ = serde_cbor::from_reader::<Value, _>(&mut data); 10 + });
+9
vendor/git/cbor/fuzz/fuzz_targets/from_slice.rs
··· 1 + #![no_main] 2 + #[macro_use] extern crate libfuzzer_sys; 3 + extern crate serde_cbor; 4 + 5 + use serde_cbor::Value; 6 + 7 + fuzz_target!(|data: &[u8]| { 8 + let _ = serde_cbor::from_slice::<Value>(data); 9 + });
+17
vendor/git/cbor/fuzz/make_corpus.py
··· 1 + #!/usr/bin/env python 2 + 3 + import base64 4 + import json 5 + import sys 6 + import os.path 7 + 8 + out_dir = sys.argv[1] 9 + os.makedirs(out_dir) 10 + 11 + with open("appendix_a.json") as f: 12 + appendix = json.load(f) 13 + 14 + for i, entry in enumerate(appendix): 15 + buf = base64.b64decode(entry["cbor"]) 16 + with open(os.path.join(out_dir, str(i)), 'wb') as f: 17 + f.write(buf)
+1359
vendor/git/cbor/src/de.rs
··· 1 + //! Deserialization. 2 + 3 + use core::f32; 4 + use core::marker::PhantomData; 5 + use core::result; 6 + use core::str; 7 + use half::f16; 8 + use serde::de; 9 + #[cfg(feature = "std")] 10 + use std::io; 11 + 12 + use crate::error::{Error, ErrorCode, Result}; 13 + #[cfg(not(feature = "unsealed_read_write"))] 14 + use crate::read::EitherLifetime; 15 + #[cfg(feature = "unsealed_read_write")] 16 + pub use crate::read::EitherLifetime; 17 + #[cfg(feature = "std")] 18 + pub use crate::read::IoRead; 19 + use crate::read::Offset; 20 + #[cfg(any(feature = "std", feature = "alloc"))] 21 + pub use crate::read::SliceRead; 22 + pub use crate::read::{MutSliceRead, Read, SliceReadFixed}; 23 + #[cfg(feature = "tags")] 24 + use crate::tags::set_tag; 25 + /// Decodes a value from CBOR data in a slice. 26 + /// 27 + /// # Examples 28 + /// 29 + /// Deserialize a `String` 30 + /// 31 + /// ``` 32 + /// # use serde_cbor_2::de; 33 + /// let v: Vec<u8> = vec![0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]; 34 + /// let value: String = de::from_slice(&v[..]).unwrap(); 35 + /// assert_eq!(value, "foobar"); 36 + /// ``` 37 + /// 38 + /// Deserialize a borrowed string with zero copies. 39 + /// 40 + /// ``` 41 + /// # use serde_cbor_2::de; 42 + /// let v: Vec<u8> = vec![0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]; 43 + /// let value: &str = de::from_slice(&v[..]).unwrap(); 44 + /// assert_eq!(value, "foobar"); 45 + /// ``` 46 + #[cfg(any(feature = "std", feature = "alloc"))] 47 + pub fn from_slice<'a, T>(slice: &'a [u8]) -> Result<T> 48 + where 49 + T: de::Deserialize<'a>, 50 + { 51 + let mut deserializer = Deserializer::from_slice(slice); 52 + let value = de::Deserialize::deserialize(&mut deserializer)?; 53 + deserializer.end()?; 54 + Ok(value) 55 + } 56 + 57 + // When the "std" feature is enabled there should be little to no need to ever use this function, 58 + // as `from_slice` covers all use cases (at the expense of being less efficient). 59 + /// Decode a value from CBOR data in a mutable slice. 60 + /// 61 + /// This can be used in analogy to `from_slice`. Unlike `from_slice`, this will use the slice's 62 + /// mutability to rearrange data in it in order to resolve indefinite byte or text strings without 63 + /// resorting to allocations. 64 + pub fn from_mut_slice<'a, T>(slice: &'a mut [u8]) -> Result<T> 65 + where 66 + T: de::Deserialize<'a>, 67 + { 68 + let mut deserializer = Deserializer::from_mut_slice(slice); 69 + let value = de::Deserialize::deserialize(&mut deserializer)?; 70 + deserializer.end()?; 71 + Ok(value) 72 + } 73 + 74 + // When the "std" feature is enabled there should be little to no need to ever use this function, 75 + // as `from_slice` covers all use cases and is much more reliable (at the expense of being less 76 + // efficient). 77 + /// Decode a value from CBOR data using a scratch buffer. 78 + /// 79 + /// Users should generally prefer to use `from_slice` or `from_mut_slice` over this function, 80 + /// as decoding may fail when the scratch buffer turns out to be too small. 81 + /// 82 + /// A realistic use case for this method would be decoding in a `no_std` environment from an 83 + /// immutable slice that is too large to copy. 84 + pub fn from_slice_with_scratch<'a, 'b, T>(slice: &'a [u8], scratch: &'b mut [u8]) -> Result<T> 85 + where 86 + T: de::Deserialize<'a>, 87 + { 88 + let mut deserializer = Deserializer::from_slice_with_scratch(slice, scratch); 89 + let value = de::Deserialize::deserialize(&mut deserializer)?; 90 + deserializer.end()?; 91 + Ok(value) 92 + } 93 + 94 + /// Decodes a value from CBOR data in a reader. 95 + /// 96 + /// # Examples 97 + /// 98 + /// Deserialize a `String` 99 + /// 100 + /// ``` 101 + /// # use serde_cbor_2::de; 102 + /// let v: Vec<u8> = vec![0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]; 103 + /// let value: String = de::from_reader(&v[..]).unwrap(); 104 + /// assert_eq!(value, "foobar"); 105 + /// ``` 106 + /// 107 + /// Note that `from_reader` cannot borrow data: 108 + /// 109 + /// ```compile_fail 110 + /// # use serde_cbor_2::de; 111 + /// let v: Vec<u8> = vec![0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]; 112 + /// let value: &str = de::from_reader(&v[..]).unwrap(); 113 + /// assert_eq!(value, "foobar"); 114 + /// ``` 115 + #[cfg(feature = "std")] 116 + pub fn from_reader<T, R>(reader: R) -> Result<T> 117 + where 118 + T: de::DeserializeOwned, 119 + R: io::Read, 120 + { 121 + let mut deserializer = Deserializer::from_reader(reader); 122 + let value = de::Deserialize::deserialize(&mut deserializer)?; 123 + deserializer.end()?; 124 + Ok(value) 125 + } 126 + 127 + /// A Serde `Deserialize`r of CBOR data. 128 + #[derive(Debug)] 129 + pub struct Deserializer<R> { 130 + read: R, 131 + remaining_depth: u8, 132 + accept_named: bool, 133 + accept_packed: bool, 134 + accept_standard_enums: bool, 135 + accept_legacy_enums: bool, 136 + } 137 + 138 + #[cfg(feature = "std")] 139 + impl<R> Deserializer<IoRead<R>> 140 + where 141 + R: io::Read, 142 + { 143 + /// Constructs a `Deserializer` which reads from a `Read`er. 144 + pub fn from_reader(reader: R) -> Deserializer<IoRead<R>> { 145 + Deserializer::new(IoRead::new(reader)) 146 + } 147 + } 148 + 149 + #[cfg(any(feature = "std", feature = "alloc"))] 150 + impl<'a> Deserializer<SliceRead<'a>> { 151 + /// Constructs a `Deserializer` which reads from a slice. 152 + /// 153 + /// Borrowed strings and byte slices will be provided when possible. 154 + pub fn from_slice(bytes: &'a [u8]) -> Deserializer<SliceRead<'a>> { 155 + Deserializer::new(SliceRead::new(bytes)) 156 + } 157 + } 158 + 159 + impl<'a> Deserializer<MutSliceRead<'a>> { 160 + /// Constructs a `Deserializer` which reads from a mutable slice that doubles as its own 161 + /// scratch buffer. 162 + /// 163 + /// Borrowed strings and byte slices will be provided even for indefinite strings. 164 + pub fn from_mut_slice(bytes: &'a mut [u8]) -> Deserializer<MutSliceRead<'a>> { 165 + Deserializer::new(MutSliceRead::new(bytes)) 166 + } 167 + } 168 + 169 + impl<'a, 'b> Deserializer<SliceReadFixed<'a, 'b>> { 170 + #[doc(hidden)] 171 + pub fn from_slice_with_scratch( 172 + bytes: &'a [u8], 173 + scratch: &'b mut [u8], 174 + ) -> Deserializer<SliceReadFixed<'a, 'b>> { 175 + Deserializer::new(SliceReadFixed::new(bytes, scratch)) 176 + } 177 + } 178 + 179 + impl<'de, R> Deserializer<R> 180 + where 181 + R: Read<'de>, 182 + { 183 + /// Constructs a `Deserializer` from one of the possible serde_cbor_2 input sources. 184 + /// 185 + /// `from_slice` and `from_reader` should normally be used instead of this method. 186 + pub fn new(read: R) -> Self { 187 + Deserializer { 188 + read, 189 + remaining_depth: 128, 190 + accept_named: true, 191 + accept_packed: true, 192 + accept_standard_enums: true, 193 + accept_legacy_enums: true, 194 + } 195 + } 196 + 197 + /// Don't accept named variants and fields. 198 + pub fn disable_named_format(mut self) -> Self { 199 + self.accept_named = false; 200 + self 201 + } 202 + 203 + /// Don't accept numbered variants and fields. 204 + pub fn disable_packed_format(mut self) -> Self { 205 + self.accept_packed = false; 206 + self 207 + } 208 + 209 + /// Don't accept the new enum format used by `serde_cbor_2` versions >= v0.10. 210 + pub fn disable_standard_enums(mut self) -> Self { 211 + self.accept_standard_enums = false; 212 + self 213 + } 214 + 215 + /// Don't accept the old enum format used by `serde_cbor_2` versions <= v0.9. 216 + pub fn disable_legacy_enums(mut self) -> Self { 217 + self.accept_legacy_enums = false; 218 + self 219 + } 220 + 221 + /// This method should be called after a value has been deserialized to ensure there is no 222 + /// trailing data in the input source. 223 + pub fn end(&mut self) -> Result<()> { 224 + match self.next()? { 225 + Some(_) => Err(self.error(ErrorCode::TrailingData)), 226 + None => Ok(()), 227 + } 228 + } 229 + 230 + /// Turn a CBOR deserializer into an iterator over values of type T. 231 + #[allow(clippy::should_implement_trait)] // Trait doesn't allow unconstrained T. 232 + pub fn into_iter<T>(self) -> StreamDeserializer<'de, R, T> 233 + where 234 + T: de::Deserialize<'de>, 235 + { 236 + StreamDeserializer { 237 + de: self, 238 + output: PhantomData, 239 + lifetime: PhantomData, 240 + } 241 + } 242 + 243 + fn next(&mut self) -> Result<Option<u8>> { 244 + self.read.next() 245 + } 246 + 247 + fn peek(&mut self) -> Result<Option<u8>> { 248 + self.read.peek() 249 + } 250 + 251 + fn consume(&mut self) { 252 + self.read.discard(); 253 + } 254 + 255 + fn error(&self, reason: ErrorCode) -> Error { 256 + let offset = self.read.offset(); 257 + Error::syntax(reason, offset) 258 + } 259 + 260 + fn parse_u8(&mut self) -> Result<u8> { 261 + match self.next()? { 262 + Some(byte) => Ok(byte), 263 + None => Err(self.error(ErrorCode::EofWhileParsingValue)), 264 + } 265 + } 266 + 267 + fn parse_u16(&mut self) -> Result<u16> { 268 + let mut buf = [0; 2]; 269 + self.read 270 + .read_into(&mut buf) 271 + .map(|()| u16::from_be_bytes(buf)) 272 + } 273 + 274 + fn parse_u32(&mut self) -> Result<u32> { 275 + let mut buf = [0; 4]; 276 + self.read 277 + .read_into(&mut buf) 278 + .map(|()| u32::from_be_bytes(buf)) 279 + } 280 + 281 + fn parse_u64(&mut self) -> Result<u64> { 282 + let mut buf = [0; 8]; 283 + self.read 284 + .read_into(&mut buf) 285 + .map(|()| u64::from_be_bytes(buf)) 286 + } 287 + 288 + fn parse_bytes<V>(&mut self, len: usize, visitor: V) -> Result<V::Value> 289 + where 290 + V: de::Visitor<'de>, 291 + { 292 + match self.read.read(len)? { 293 + EitherLifetime::Long(buf) => visitor.visit_borrowed_bytes(buf), 294 + EitherLifetime::Short(buf) => visitor.visit_bytes(buf), 295 + } 296 + } 297 + 298 + fn parse_indefinite_bytes<V>(&mut self, visitor: V) -> Result<V::Value> 299 + where 300 + V: de::Visitor<'de>, 301 + { 302 + self.read.clear_buffer(); 303 + loop { 304 + let byte = self.parse_u8()?; 305 + let len = match byte { 306 + 0x40..=0x57 => byte as usize - 0x40, 307 + 0x58 => self.parse_u8()? as usize, 308 + 0x59 => self.parse_u16()? as usize, 309 + 0x5a => self.parse_u32()? as usize, 310 + 0x5b => { 311 + let len = self.parse_u64()?; 312 + if len > usize::MAX as u64 { 313 + return Err(self.error(ErrorCode::LengthOutOfRange)); 314 + } 315 + len as usize 316 + } 317 + 0xff => break, 318 + _ => return Err(self.error(ErrorCode::UnexpectedCode)), 319 + }; 320 + 321 + self.read.read_to_buffer(len)?; 322 + } 323 + 324 + match self.read.take_buffer() { 325 + EitherLifetime::Long(buf) => visitor.visit_borrowed_bytes(buf), 326 + EitherLifetime::Short(buf) => visitor.visit_bytes(buf), 327 + } 328 + } 329 + 330 + fn convert_str(buf: &[u8], buf_end_offset: u64) -> Result<&str> { 331 + match str::from_utf8(buf) { 332 + Ok(s) => Ok(s), 333 + Err(e) => { 334 + let shift = buf.len() - e.valid_up_to(); 335 + let offset = buf_end_offset - shift as u64; 336 + Err(Error::syntax(ErrorCode::InvalidUtf8, offset)) 337 + } 338 + } 339 + } 340 + 341 + fn parse_str<V>(&mut self, len: usize, visitor: V) -> Result<V::Value> 342 + where 343 + V: de::Visitor<'de>, 344 + { 345 + if let Some(offset) = self.read.offset().checked_add(len as u64) { 346 + match self.read.read(len)? { 347 + EitherLifetime::Long(buf) => { 348 + let s = Self::convert_str(buf, offset)?; 349 + visitor.visit_borrowed_str(s) 350 + } 351 + EitherLifetime::Short(buf) => { 352 + let s = Self::convert_str(buf, offset)?; 353 + visitor.visit_str(s) 354 + } 355 + } 356 + } else { 357 + // An overflow would have occured. 358 + Err(Error::syntax( 359 + ErrorCode::LengthOutOfRange, 360 + self.read.offset(), 361 + )) 362 + } 363 + } 364 + 365 + fn parse_indefinite_str<V>(&mut self, visitor: V) -> Result<V::Value> 366 + where 367 + V: de::Visitor<'de>, 368 + { 369 + self.read.clear_buffer(); 370 + loop { 371 + let byte = self.parse_u8()?; 372 + let len = match byte { 373 + 0x60..=0x77 => byte as usize - 0x60, 374 + 0x78 => self.parse_u8()? as usize, 375 + 0x79 => self.parse_u16()? as usize, 376 + 0x7a => self.parse_u32()? as usize, 377 + 0x7b => { 378 + let len = self.parse_u64()?; 379 + if len > usize::MAX as u64 { 380 + return Err(self.error(ErrorCode::LengthOutOfRange)); 381 + } 382 + len as usize 383 + } 384 + 0xff => break, 385 + _ => return Err(self.error(ErrorCode::UnexpectedCode)), 386 + }; 387 + 388 + self.read.read_to_buffer(len)?; 389 + } 390 + 391 + let offset = self.read.offset(); 392 + match self.read.take_buffer() { 393 + EitherLifetime::Long(buf) => { 394 + let s = Self::convert_str(buf, offset)?; 395 + visitor.visit_borrowed_str(s) 396 + } 397 + EitherLifetime::Short(buf) => { 398 + let s = Self::convert_str(buf, offset)?; 399 + visitor.visit_str(s) 400 + } 401 + } 402 + } 403 + 404 + #[cfg(feature = "tags")] 405 + fn handle_tagged_value<V>(&mut self, tag: u64, visitor: V) -> Result<V::Value> 406 + where 407 + V: de::Visitor<'de>, 408 + { 409 + self.recursion_checked(|d| { 410 + set_tag(Some(tag)); 411 + let r = visitor.visit_newtype_struct(d); 412 + set_tag(None); 413 + r 414 + }) 415 + } 416 + 417 + #[cfg(not(feature = "tags"))] 418 + fn handle_tagged_value<V>(&mut self, _tag: u64, visitor: V) -> Result<V::Value> 419 + where 420 + V: de::Visitor<'de>, 421 + { 422 + self.recursion_checked(|de| de.parse_value(visitor)) 423 + } 424 + 425 + fn recursion_checked<F, T>(&mut self, f: F) -> Result<T> 426 + where 427 + F: FnOnce(&mut Deserializer<R>) -> Result<T>, 428 + { 429 + self.remaining_depth -= 1; 430 + if self.remaining_depth == 0 { 431 + return Err(self.error(ErrorCode::RecursionLimitExceeded)); 432 + } 433 + let r = f(self); 434 + self.remaining_depth += 1; 435 + r 436 + } 437 + 438 + fn parse_array<V>(&mut self, mut len: usize, visitor: V) -> Result<V::Value> 439 + where 440 + V: de::Visitor<'de>, 441 + { 442 + self.recursion_checked(|de| { 443 + let value = visitor.visit_seq(SeqAccess { de, len: &mut len })?; 444 + 445 + if len != 0 { 446 + Err(de.error(ErrorCode::TrailingData)) 447 + } else { 448 + Ok(value) 449 + } 450 + }) 451 + } 452 + 453 + fn parse_indefinite_array<V>(&mut self, visitor: V) -> Result<V::Value> 454 + where 455 + V: de::Visitor<'de>, 456 + { 457 + self.recursion_checked(|de| { 458 + let value = visitor.visit_seq(IndefiniteSeqAccess { de })?; 459 + match de.next()? { 460 + Some(0xff) => Ok(value), 461 + Some(_) => Err(de.error(ErrorCode::TrailingData)), 462 + None => Err(de.error(ErrorCode::EofWhileParsingArray)), 463 + } 464 + }) 465 + } 466 + 467 + fn parse_map<V>(&mut self, mut len: usize, visitor: V) -> Result<V::Value> 468 + where 469 + V: de::Visitor<'de>, 470 + { 471 + let accept_packed = self.accept_packed; 472 + let accept_named = self.accept_named; 473 + self.recursion_checked(|de| { 474 + let value = visitor.visit_map(MapAccess { 475 + de, 476 + len: &mut len, 477 + accept_named, 478 + accept_packed, 479 + })?; 480 + 481 + if len != 0 { 482 + Err(de.error(ErrorCode::TrailingData)) 483 + } else { 484 + Ok(value) 485 + } 486 + }) 487 + } 488 + 489 + fn parse_indefinite_map<V>(&mut self, visitor: V) -> Result<V::Value> 490 + where 491 + V: de::Visitor<'de>, 492 + { 493 + let accept_named = self.accept_named; 494 + let accept_packed = self.accept_packed; 495 + self.recursion_checked(|de| { 496 + let value = visitor.visit_map(IndefiniteMapAccess { 497 + de, 498 + accept_packed, 499 + accept_named, 500 + })?; 501 + match de.next()? { 502 + Some(0xff) => Ok(value), 503 + Some(_) => Err(de.error(ErrorCode::TrailingData)), 504 + None => Err(de.error(ErrorCode::EofWhileParsingMap)), 505 + } 506 + }) 507 + } 508 + 509 + fn parse_enum<V>(&mut self, mut len: usize, visitor: V) -> Result<V::Value> 510 + where 511 + V: de::Visitor<'de>, 512 + { 513 + self.recursion_checked(|de| { 514 + let value = visitor.visit_enum(VariantAccess { 515 + seq: SeqAccess { de, len: &mut len }, 516 + })?; 517 + 518 + if len != 0 { 519 + Err(de.error(ErrorCode::TrailingData)) 520 + } else { 521 + Ok(value) 522 + } 523 + }) 524 + } 525 + 526 + fn parse_enum_map<V>(&mut self, visitor: V) -> Result<V::Value> 527 + where 528 + V: de::Visitor<'de>, 529 + { 530 + let accept_named = self.accept_named; 531 + let accept_packed = self.accept_packed; 532 + self.recursion_checked(|de| { 533 + let mut len = 1; 534 + let value = visitor.visit_enum(VariantAccessMap { 535 + map: MapAccess { 536 + de, 537 + len: &mut len, 538 + accept_packed, 539 + accept_named, 540 + }, 541 + })?; 542 + 543 + if len != 0 { 544 + Err(de.error(ErrorCode::TrailingData)) 545 + } else { 546 + Ok(value) 547 + } 548 + }) 549 + } 550 + 551 + fn parse_indefinite_enum<V>(&mut self, visitor: V) -> Result<V::Value> 552 + where 553 + V: de::Visitor<'de>, 554 + { 555 + self.recursion_checked(|de| { 556 + let value = visitor.visit_enum(VariantAccess { 557 + seq: IndefiniteSeqAccess { de }, 558 + })?; 559 + match de.next()? { 560 + Some(0xff) => Ok(value), 561 + Some(_) => Err(de.error(ErrorCode::TrailingData)), 562 + None => Err(de.error(ErrorCode::EofWhileParsingArray)), 563 + } 564 + }) 565 + } 566 + 567 + fn parse_f16(&mut self) -> Result<f32> { 568 + Ok(f32::from(f16::from_bits(self.parse_u16()?))) 569 + } 570 + 571 + fn parse_f32(&mut self) -> Result<f32> { 572 + self.parse_u32().map(f32::from_bits) 573 + } 574 + 575 + fn parse_f64(&mut self) -> Result<f64> { 576 + self.parse_u64().map(f64::from_bits) 577 + } 578 + 579 + // Don't warn about the `unreachable!` in case 580 + // exhaustive integer pattern matching is enabled. 581 + #[allow(unreachable_patterns)] 582 + fn parse_value<V>(&mut self, visitor: V) -> Result<V::Value> 583 + where 584 + V: de::Visitor<'de>, 585 + { 586 + let byte = self.parse_u8()?; 587 + match byte { 588 + // Major type 0: an unsigned integer 589 + 0x00..=0x17 => visitor.visit_u8(byte), 590 + 0x18 => { 591 + let value = self.parse_u8()?; 592 + visitor.visit_u8(value) 593 + } 594 + 0x19 => { 595 + let value = self.parse_u16()?; 596 + visitor.visit_u16(value) 597 + } 598 + 0x1a => { 599 + let value = self.parse_u32()?; 600 + visitor.visit_u32(value) 601 + } 602 + 0x1b => { 603 + let value = self.parse_u64()?; 604 + visitor.visit_u64(value) 605 + } 606 + 0x1c..=0x1f => Err(self.error(ErrorCode::UnassignedCode)), 607 + 608 + // Major type 1: a negative integer 609 + 0x20..=0x37 => visitor.visit_i8(-1 - (byte - 0x20) as i8), 610 + 0x38 => { 611 + let value = self.parse_u8()?; 612 + visitor.visit_i16(-1 - i16::from(value)) 613 + } 614 + 0x39 => { 615 + let value = self.parse_u16()?; 616 + visitor.visit_i32(-1 - i32::from(value)) 617 + } 618 + 0x3a => { 619 + let value = self.parse_u32()?; 620 + visitor.visit_i64(-1 - i64::from(value)) 621 + } 622 + 0x3b => { 623 + let value = self.parse_u64()?; 624 + if value > i64::MAX as u64 { 625 + return visitor.visit_i128(-1 - i128::from(value)); 626 + } 627 + visitor.visit_i64(-1 - value as i64) 628 + } 629 + 0x3c..=0x3f => Err(self.error(ErrorCode::UnassignedCode)), 630 + 631 + // Major type 2: a byte string 632 + 0x40..=0x57 => self.parse_bytes(byte as usize - 0x40, visitor), 633 + 0x58 => { 634 + let len = self.parse_u8()?; 635 + self.parse_bytes(len as usize, visitor) 636 + } 637 + 0x59 => { 638 + let len = self.parse_u16()?; 639 + self.parse_bytes(len as usize, visitor) 640 + } 641 + 0x5a => { 642 + let len = self.parse_u32()?; 643 + self.parse_bytes(len as usize, visitor) 644 + } 645 + 0x5b => { 646 + let len = self.parse_u64()?; 647 + if len > usize::MAX as u64 { 648 + return Err(self.error(ErrorCode::LengthOutOfRange)); 649 + } 650 + self.parse_bytes(len as usize, visitor) 651 + } 652 + 0x5c..=0x5e => Err(self.error(ErrorCode::UnassignedCode)), 653 + 0x5f => self.parse_indefinite_bytes(visitor), 654 + 655 + // Major type 3: a text string 656 + 0x60..=0x77 => self.parse_str(byte as usize - 0x60, visitor), 657 + 0x78 => { 658 + let len = self.parse_u8()?; 659 + self.parse_str(len as usize, visitor) 660 + } 661 + 0x79 => { 662 + let len = self.parse_u16()?; 663 + self.parse_str(len as usize, visitor) 664 + } 665 + 0x7a => { 666 + let len = self.parse_u32()?; 667 + self.parse_str(len as usize, visitor) 668 + } 669 + 0x7b => { 670 + let len = self.parse_u64()?; 671 + if len > usize::MAX as u64 { 672 + return Err(self.error(ErrorCode::LengthOutOfRange)); 673 + } 674 + self.parse_str(len as usize, visitor) 675 + } 676 + 0x7c..=0x7e => Err(self.error(ErrorCode::UnassignedCode)), 677 + 0x7f => self.parse_indefinite_str(visitor), 678 + 679 + // Major type 4: an array of data items 680 + 0x80..=0x97 => self.parse_array(byte as usize - 0x80, visitor), 681 + 0x98 => { 682 + let len = self.parse_u8()?; 683 + self.parse_array(len as usize, visitor) 684 + } 685 + 0x99 => { 686 + let len = self.parse_u16()?; 687 + self.parse_array(len as usize, visitor) 688 + } 689 + 0x9a => { 690 + let len = self.parse_u32()?; 691 + self.parse_array(len as usize, visitor) 692 + } 693 + 0x9b => { 694 + let len = self.parse_u64()?; 695 + if len > usize::MAX as u64 { 696 + return Err(self.error(ErrorCode::LengthOutOfRange)); 697 + } 698 + self.parse_array(len as usize, visitor) 699 + } 700 + 0x9c..=0x9e => Err(self.error(ErrorCode::UnassignedCode)), 701 + 0x9f => self.parse_indefinite_array(visitor), 702 + 703 + // Major type 5: a map of pairs of data items 704 + 0xa0..=0xb7 => self.parse_map(byte as usize - 0xa0, visitor), 705 + 0xb8 => { 706 + let len = self.parse_u8()?; 707 + self.parse_map(len as usize, visitor) 708 + } 709 + 0xb9 => { 710 + let len = self.parse_u16()?; 711 + self.parse_map(len as usize, visitor) 712 + } 713 + 0xba => { 714 + let len = self.parse_u32()?; 715 + self.parse_map(len as usize, visitor) 716 + } 717 + 0xbb => { 718 + let len = self.parse_u64()?; 719 + if len > usize::MAX as u64 { 720 + return Err(self.error(ErrorCode::LengthOutOfRange)); 721 + } 722 + self.parse_map(len as usize, visitor) 723 + } 724 + 0xbc..=0xbe => Err(self.error(ErrorCode::UnassignedCode)), 725 + 0xbf => self.parse_indefinite_map(visitor), 726 + 727 + // Major type 6: optional semantic tagging of other major types 728 + 0xc0..=0xd7 => { 729 + let tag = u64::from(byte) - 0xc0; 730 + self.handle_tagged_value(tag, visitor) 731 + } 732 + 0xd8 => { 733 + let tag = self.parse_u8()?; 734 + self.handle_tagged_value(tag.into(), visitor) 735 + } 736 + 0xd9 => { 737 + let tag = self.parse_u16()?; 738 + self.handle_tagged_value(tag.into(), visitor) 739 + } 740 + 0xda => { 741 + let tag = self.parse_u32()?; 742 + self.handle_tagged_value(tag.into(), visitor) 743 + } 744 + 0xdb => { 745 + let tag = self.parse_u64()?; 746 + self.handle_tagged_value(tag, visitor) 747 + } 748 + 0xdc..=0xdf => Err(self.error(ErrorCode::UnassignedCode)), 749 + 750 + // Major type 7: floating-point numbers and other simple data types that need no content 751 + 0xe0..=0xf3 => Err(self.error(ErrorCode::UnassignedCode)), 752 + 0xf4 => visitor.visit_bool(false), 753 + 0xf5 => visitor.visit_bool(true), 754 + 0xf6 => visitor.visit_unit(), 755 + 0xf7 => visitor.visit_unit(), 756 + 0xf8 => Err(self.error(ErrorCode::UnassignedCode)), 757 + 0xf9 => { 758 + let value = self.parse_f16()?; 759 + visitor.visit_f32(value) 760 + } 761 + 0xfa => { 762 + let value = self.parse_f32()?; 763 + visitor.visit_f32(value) 764 + } 765 + 0xfb => { 766 + let value = self.parse_f64()?; 767 + visitor.visit_f64(value) 768 + } 769 + 0xfc..=0xfe => Err(self.error(ErrorCode::UnassignedCode)), 770 + 0xff => Err(self.error(ErrorCode::UnexpectedCode)), 771 + 772 + _ => unreachable!(), 773 + } 774 + } 775 + } 776 + 777 + impl<'de, R> de::Deserializer<'de> for &mut Deserializer<R> 778 + where 779 + R: Read<'de>, 780 + { 781 + type Error = Error; 782 + 783 + #[inline] 784 + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> 785 + where 786 + V: de::Visitor<'de>, 787 + { 788 + self.parse_value(visitor) 789 + } 790 + 791 + #[inline] 792 + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> 793 + where 794 + V: de::Visitor<'de>, 795 + { 796 + match self.peek()? { 797 + Some(0xf6) => { 798 + self.consume(); 799 + visitor.visit_none() 800 + } 801 + _ => visitor.visit_some(self), 802 + } 803 + } 804 + 805 + #[inline] 806 + fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value> 807 + where 808 + V: de::Visitor<'de>, 809 + { 810 + visitor.visit_newtype_struct(self) 811 + } 812 + 813 + // Unit variants are encoded as just the variant identifier. 814 + // Tuple variants are encoded as an array of the variant identifier followed by the fields. 815 + // Struct variants are encoded as an array of the variant identifier followed by the struct. 816 + #[inline] 817 + fn deserialize_enum<V>( 818 + self, 819 + _name: &str, 820 + _variants: &'static [&'static str], 821 + visitor: V, 822 + ) -> Result<V::Value> 823 + where 824 + V: de::Visitor<'de>, 825 + { 826 + match self.peek()? { 827 + Some(byte @ 0x80..=0x9f) => { 828 + if !self.accept_legacy_enums { 829 + return Err(self.error(ErrorCode::WrongEnumFormat)); 830 + } 831 + self.consume(); 832 + match byte { 833 + 0x80..=0x97 => self.parse_enum(byte as usize - 0x80, visitor), 834 + 0x98 => { 835 + let len = self.parse_u8()?; 836 + self.parse_enum(len as usize, visitor) 837 + } 838 + 0x99 => { 839 + let len = self.parse_u16()?; 840 + self.parse_enum(len as usize, visitor) 841 + } 842 + 0x9a => { 843 + let len = self.parse_u32()?; 844 + self.parse_enum(len as usize, visitor) 845 + } 846 + 0x9b => { 847 + let len = self.parse_u64()?; 848 + if len > usize::MAX as u64 { 849 + return Err(self.error(ErrorCode::LengthOutOfRange)); 850 + } 851 + self.parse_enum(len as usize, visitor) 852 + } 853 + 0x9c..=0x9e => Err(self.error(ErrorCode::UnassignedCode)), 854 + 0x9f => self.parse_indefinite_enum(visitor), 855 + 856 + _ => unreachable!(), 857 + } 858 + } 859 + Some(0xa1) => { 860 + if !self.accept_standard_enums { 861 + return Err(self.error(ErrorCode::WrongEnumFormat)); 862 + } 863 + self.consume(); 864 + self.parse_enum_map(visitor) 865 + } 866 + None => Err(self.error(ErrorCode::EofWhileParsingValue)), 867 + _ => { 868 + if !self.accept_standard_enums && !self.accept_legacy_enums { 869 + return Err(self.error(ErrorCode::WrongEnumFormat)); 870 + } 871 + visitor.visit_enum(UnitVariantAccess { de: self }) 872 + } 873 + } 874 + } 875 + 876 + #[inline] 877 + fn is_human_readable(&self) -> bool { 878 + false 879 + } 880 + 881 + serde::forward_to_deserialize_any! { 882 + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string unit 883 + unit_struct seq tuple tuple_struct map struct identifier ignored_any 884 + bytes byte_buf 885 + } 886 + } 887 + 888 + impl<R> Deserializer<R> 889 + where 890 + R: Offset, 891 + { 892 + /// Return the current offset in the reader 893 + #[inline] 894 + pub fn byte_offset(&self) -> usize { 895 + self.read.byte_offset() 896 + } 897 + } 898 + 899 + trait MakeError { 900 + fn error(&self, code: ErrorCode) -> Error; 901 + } 902 + 903 + struct SeqAccess<'a, R> { 904 + de: &'a mut Deserializer<R>, 905 + len: &'a mut usize, 906 + } 907 + 908 + impl<'de, R> de::SeqAccess<'de> for SeqAccess<'_, R> 909 + where 910 + R: Read<'de>, 911 + { 912 + type Error = Error; 913 + 914 + fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> 915 + where 916 + T: de::DeserializeSeed<'de>, 917 + { 918 + if *self.len == 0 { 919 + return Ok(None); 920 + } 921 + *self.len -= 1; 922 + 923 + let value = seed.deserialize(&mut *self.de)?; 924 + Ok(Some(value)) 925 + } 926 + 927 + fn size_hint(&self) -> Option<usize> { 928 + Some(*self.len) 929 + } 930 + } 931 + 932 + impl<'de, R> MakeError for SeqAccess<'_, R> 933 + where 934 + R: Read<'de>, 935 + { 936 + fn error(&self, code: ErrorCode) -> Error { 937 + self.de.error(code) 938 + } 939 + } 940 + 941 + struct IndefiniteSeqAccess<'a, R> { 942 + de: &'a mut Deserializer<R>, 943 + } 944 + 945 + impl<'de, R> de::SeqAccess<'de> for IndefiniteSeqAccess<'_, R> 946 + where 947 + R: Read<'de>, 948 + { 949 + type Error = Error; 950 + 951 + fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> 952 + where 953 + T: de::DeserializeSeed<'de>, 954 + { 955 + match self.de.peek()? { 956 + Some(0xff) => return Ok(None), 957 + Some(_) => {} 958 + None => return Err(self.de.error(ErrorCode::EofWhileParsingArray)), 959 + } 960 + 961 + let value = seed.deserialize(&mut *self.de)?; 962 + Ok(Some(value)) 963 + } 964 + } 965 + 966 + impl<'de, R> MakeError for IndefiniteSeqAccess<'_, R> 967 + where 968 + R: Read<'de>, 969 + { 970 + fn error(&self, code: ErrorCode) -> Error { 971 + self.de.error(code) 972 + } 973 + } 974 + 975 + struct MapAccess<'a, R> { 976 + de: &'a mut Deserializer<R>, 977 + len: &'a mut usize, 978 + accept_named: bool, 979 + accept_packed: bool, 980 + } 981 + 982 + impl<'de, R> de::MapAccess<'de> for MapAccess<'_, R> 983 + where 984 + R: Read<'de>, 985 + { 986 + type Error = Error; 987 + 988 + fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> 989 + where 990 + K: de::DeserializeSeed<'de>, 991 + { 992 + if *self.len == 0 { 993 + return Ok(None); 994 + } 995 + *self.len -= 1; 996 + 997 + match self.de.peek()? { 998 + Some(_byte @ 0x00..=0x1b) if !self.accept_packed => { 999 + return Err(self.de.error(ErrorCode::WrongStructFormat)); 1000 + } 1001 + Some(_byte @ 0x60..=0x7f) if !self.accept_named => { 1002 + return Err(self.de.error(ErrorCode::WrongStructFormat)); 1003 + } 1004 + _ => {} 1005 + }; 1006 + 1007 + let value = seed.deserialize(&mut *self.de)?; 1008 + Ok(Some(value)) 1009 + } 1010 + 1011 + fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value> 1012 + where 1013 + V: de::DeserializeSeed<'de>, 1014 + { 1015 + seed.deserialize(&mut *self.de) 1016 + } 1017 + 1018 + fn size_hint(&self) -> Option<usize> { 1019 + Some(*self.len) 1020 + } 1021 + } 1022 + 1023 + impl<'de, R> MakeError for MapAccess<'_, R> 1024 + where 1025 + R: Read<'de>, 1026 + { 1027 + fn error(&self, code: ErrorCode) -> Error { 1028 + self.de.error(code) 1029 + } 1030 + } 1031 + 1032 + struct IndefiniteMapAccess<'a, R> { 1033 + de: &'a mut Deserializer<R>, 1034 + accept_packed: bool, 1035 + accept_named: bool, 1036 + } 1037 + 1038 + impl<'de, R> de::MapAccess<'de> for IndefiniteMapAccess<'_, R> 1039 + where 1040 + R: Read<'de>, 1041 + { 1042 + type Error = Error; 1043 + 1044 + fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> 1045 + where 1046 + K: de::DeserializeSeed<'de>, 1047 + { 1048 + match self.de.peek()? { 1049 + Some(_byte @ 0x00..=0x1b) if !self.accept_packed => { 1050 + return Err(self.de.error(ErrorCode::WrongStructFormat)) 1051 + } 1052 + Some(_byte @ 0x60..=0x7f) if !self.accept_named => { 1053 + return Err(self.de.error(ErrorCode::WrongStructFormat)) 1054 + } 1055 + Some(0xff) => return Ok(None), 1056 + Some(_) => {} 1057 + None => return Err(self.de.error(ErrorCode::EofWhileParsingMap)), 1058 + } 1059 + 1060 + let value = seed.deserialize(&mut *self.de)?; 1061 + Ok(Some(value)) 1062 + } 1063 + 1064 + fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value> 1065 + where 1066 + V: de::DeserializeSeed<'de>, 1067 + { 1068 + seed.deserialize(&mut *self.de) 1069 + } 1070 + } 1071 + 1072 + struct UnitVariantAccess<'a, R> { 1073 + de: &'a mut Deserializer<R>, 1074 + } 1075 + 1076 + impl<'de, 'a, R> de::EnumAccess<'de> for UnitVariantAccess<'a, R> 1077 + where 1078 + R: Read<'de>, 1079 + { 1080 + type Error = Error; 1081 + type Variant = UnitVariantAccess<'a, R>; 1082 + 1083 + fn variant_seed<V>(self, seed: V) -> Result<(V::Value, UnitVariantAccess<'a, R>)> 1084 + where 1085 + V: de::DeserializeSeed<'de>, 1086 + { 1087 + let variant = seed.deserialize(&mut *self.de)?; 1088 + Ok((variant, self)) 1089 + } 1090 + } 1091 + 1092 + impl<'de, R> de::VariantAccess<'de> for UnitVariantAccess<'_, R> 1093 + where 1094 + R: Read<'de>, 1095 + { 1096 + type Error = Error; 1097 + 1098 + fn unit_variant(self) -> Result<()> { 1099 + Ok(()) 1100 + } 1101 + 1102 + fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value> 1103 + where 1104 + T: de::DeserializeSeed<'de>, 1105 + { 1106 + Err(de::Error::invalid_type( 1107 + de::Unexpected::UnitVariant, 1108 + &"newtype variant", 1109 + )) 1110 + } 1111 + 1112 + fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value> 1113 + where 1114 + V: de::Visitor<'de>, 1115 + { 1116 + Err(de::Error::invalid_type( 1117 + de::Unexpected::UnitVariant, 1118 + &"tuple variant", 1119 + )) 1120 + } 1121 + 1122 + fn struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value> 1123 + where 1124 + V: de::Visitor<'de>, 1125 + { 1126 + Err(de::Error::invalid_type( 1127 + de::Unexpected::UnitVariant, 1128 + &"struct variant", 1129 + )) 1130 + } 1131 + } 1132 + 1133 + struct VariantAccess<T> { 1134 + seq: T, 1135 + } 1136 + 1137 + impl<'de, T> de::EnumAccess<'de> for VariantAccess<T> 1138 + where 1139 + T: de::SeqAccess<'de, Error = Error> + MakeError, 1140 + { 1141 + type Error = Error; 1142 + type Variant = VariantAccess<T>; 1143 + 1144 + fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, VariantAccess<T>)> 1145 + where 1146 + V: de::DeserializeSeed<'de>, 1147 + { 1148 + let variant = match self.seq.next_element_seed(seed) { 1149 + Ok(Some(variant)) => variant, 1150 + Ok(None) => return Err(self.seq.error(ErrorCode::ArrayTooShort)), 1151 + Err(e) => return Err(e), 1152 + }; 1153 + Ok((variant, self)) 1154 + } 1155 + } 1156 + 1157 + impl<'de, T> de::VariantAccess<'de> for VariantAccess<T> 1158 + where 1159 + T: de::SeqAccess<'de, Error = Error> + MakeError, 1160 + { 1161 + type Error = Error; 1162 + 1163 + fn unit_variant(mut self) -> Result<()> { 1164 + match self.seq.next_element() { 1165 + Ok(Some(())) => Ok(()), 1166 + Ok(None) => Err(self.seq.error(ErrorCode::ArrayTooLong)), 1167 + Err(e) => Err(e), 1168 + } 1169 + } 1170 + 1171 + fn newtype_variant_seed<S>(mut self, seed: S) -> Result<S::Value> 1172 + where 1173 + S: de::DeserializeSeed<'de>, 1174 + { 1175 + match self.seq.next_element_seed(seed) { 1176 + Ok(Some(variant)) => Ok(variant), 1177 + Ok(None) => Err(self.seq.error(ErrorCode::ArrayTooShort)), 1178 + Err(e) => Err(e), 1179 + } 1180 + } 1181 + 1182 + fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value> 1183 + where 1184 + V: de::Visitor<'de>, 1185 + { 1186 + visitor.visit_seq(self.seq) 1187 + } 1188 + 1189 + fn struct_variant<V>(mut self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value> 1190 + where 1191 + V: de::Visitor<'de>, 1192 + { 1193 + let seed = StructVariantSeed { visitor }; 1194 + match self.seq.next_element_seed(seed) { 1195 + Ok(Some(variant)) => Ok(variant), 1196 + Ok(None) => Err(self.seq.error(ErrorCode::ArrayTooShort)), 1197 + Err(e) => Err(e), 1198 + } 1199 + } 1200 + } 1201 + 1202 + struct StructVariantSeed<V> { 1203 + visitor: V, 1204 + } 1205 + 1206 + impl<'de, V> de::DeserializeSeed<'de> for StructVariantSeed<V> 1207 + where 1208 + V: de::Visitor<'de>, 1209 + { 1210 + type Value = V::Value; 1211 + 1212 + fn deserialize<D>(self, de: D) -> result::Result<V::Value, D::Error> 1213 + where 1214 + D: de::Deserializer<'de>, 1215 + { 1216 + de.deserialize_any(self.visitor) 1217 + } 1218 + } 1219 + 1220 + /// Iterator that deserializes a stream into multiple CBOR values. 1221 + /// 1222 + /// A stream deserializer can be created from any CBOR deserializer using the 1223 + /// `Deserializer::into_iter` method. 1224 + /// 1225 + /// ``` 1226 + /// use serde_cbor_2::de::Deserializer; 1227 + /// use serde_cbor_2::value::Value; 1228 + /// 1229 + /// # fn main() { 1230 + /// let data: Vec<u8> = vec![ 1231 + /// 0x01, 0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, 1232 + /// ]; 1233 + /// let mut it = Deserializer::from_slice(&data[..]).into_iter::<Value>(); 1234 + /// assert_eq!( 1235 + /// Value::Integer(1), 1236 + /// it.next().unwrap().unwrap() 1237 + /// ); 1238 + /// assert_eq!( 1239 + /// Value::Text("foobar".to_string()), 1240 + /// it.next().unwrap().unwrap() 1241 + /// ); 1242 + /// # } 1243 + /// ``` 1244 + #[derive(Debug)] 1245 + pub struct StreamDeserializer<'de, R, T> { 1246 + de: Deserializer<R>, 1247 + output: PhantomData<T>, 1248 + lifetime: PhantomData<&'de ()>, 1249 + } 1250 + 1251 + impl<'de, R, T> StreamDeserializer<'de, R, T> 1252 + where 1253 + R: Read<'de>, 1254 + T: de::Deserialize<'de>, 1255 + { 1256 + /// Create a new CBOR stream deserializer from one of the possible 1257 + /// serde_cbor_2 input sources. 1258 + /// 1259 + /// Typically it is more convenient to use one of these methods instead: 1260 + /// 1261 + /// * `Deserializer::from_slice(...).into_iter()` 1262 + /// * `Deserializer::from_reader(...).into_iter()` 1263 + pub fn new(read: R) -> StreamDeserializer<'de, R, T> { 1264 + StreamDeserializer { 1265 + de: Deserializer::new(read), 1266 + output: PhantomData, 1267 + lifetime: PhantomData, 1268 + } 1269 + } 1270 + } 1271 + 1272 + impl<'de, R, T> StreamDeserializer<'de, R, T> 1273 + where 1274 + R: Offset, 1275 + T: de::Deserialize<'de>, 1276 + { 1277 + /// Return the current offset in the reader 1278 + #[inline] 1279 + pub fn byte_offset(&self) -> usize { 1280 + self.de.byte_offset() 1281 + } 1282 + } 1283 + 1284 + impl<'de, R, T> Iterator for StreamDeserializer<'de, R, T> 1285 + where 1286 + R: Read<'de>, 1287 + T: de::Deserialize<'de>, 1288 + { 1289 + type Item = Result<T>; 1290 + 1291 + fn next(&mut self) -> Option<Result<T>> { 1292 + match self.de.peek() { 1293 + Ok(Some(_)) => Some(T::deserialize(&mut self.de)), 1294 + Ok(None) => None, 1295 + Err(e) => Some(Err(e)), 1296 + } 1297 + } 1298 + } 1299 + 1300 + struct VariantAccessMap<T> { 1301 + map: T, 1302 + } 1303 + 1304 + impl<'de, T> de::EnumAccess<'de> for VariantAccessMap<T> 1305 + where 1306 + T: de::MapAccess<'de, Error = Error> + MakeError, 1307 + { 1308 + type Error = Error; 1309 + type Variant = VariantAccessMap<T>; 1310 + 1311 + fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, VariantAccessMap<T>)> 1312 + where 1313 + V: de::DeserializeSeed<'de>, 1314 + { 1315 + let variant = match self.map.next_key_seed(seed) { 1316 + Ok(Some(variant)) => variant, 1317 + Ok(None) => return Err(self.map.error(ErrorCode::ArrayTooShort)), 1318 + Err(e) => return Err(e), 1319 + }; 1320 + Ok((variant, self)) 1321 + } 1322 + } 1323 + 1324 + impl<'de, T> de::VariantAccess<'de> for VariantAccessMap<T> 1325 + where 1326 + T: de::MapAccess<'de, Error = Error> + MakeError, 1327 + { 1328 + type Error = Error; 1329 + 1330 + fn unit_variant(mut self) -> Result<()> { 1331 + match self.map.next_value() { 1332 + Ok(()) => Ok(()), 1333 + Err(e) => Err(e), 1334 + } 1335 + } 1336 + 1337 + fn newtype_variant_seed<S>(mut self, seed: S) -> Result<S::Value> 1338 + where 1339 + S: de::DeserializeSeed<'de>, 1340 + { 1341 + self.map.next_value_seed(seed) 1342 + } 1343 + 1344 + fn tuple_variant<V>(mut self, _len: usize, visitor: V) -> Result<V::Value> 1345 + where 1346 + V: de::Visitor<'de>, 1347 + { 1348 + let seed = StructVariantSeed { visitor }; 1349 + self.map.next_value_seed(seed) 1350 + } 1351 + 1352 + fn struct_variant<V>(mut self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value> 1353 + where 1354 + V: de::Visitor<'de>, 1355 + { 1356 + let seed = StructVariantSeed { visitor }; 1357 + self.map.next_value_seed(seed) 1358 + } 1359 + }
+303
vendor/git/cbor/src/error.rs
··· 1 + //! When serializing or deserializing CBOR goes wrong. 2 + use core::fmt; 3 + use core::result; 4 + use serde::de; 5 + use serde::ser; 6 + #[cfg(feature = "std")] 7 + use std::error; 8 + #[cfg(feature = "std")] 9 + use std::io; 10 + 11 + /// This type represents all possible errors that can occur when serializing or deserializing CBOR 12 + /// data. 13 + pub struct Error(ErrorImpl); 14 + 15 + /// Alias for a `Result` with the error type `serde_cbor::Error`. 16 + pub type Result<T> = result::Result<T, Error>; 17 + 18 + /// Categorizes the cause of a `serde_cbor::Error`. 19 + #[derive(Copy, Clone, Debug, Eq, PartialEq)] 20 + pub enum Category { 21 + /// The error was caused by a failure to read or write bytes on an IO stream. 22 + Io, 23 + /// The error was caused by input that was not syntactically valid CBOR. 24 + Syntax, 25 + /// The error was caused by input data that was semantically incorrect. 26 + Data, 27 + /// The error was caused by prematurely reaching the end of the input data. 28 + Eof, 29 + } 30 + 31 + impl Error { 32 + /// The byte offset at which the error occurred. 33 + pub fn offset(&self) -> u64 { 34 + self.0.offset 35 + } 36 + 37 + pub(crate) fn syntax(code: ErrorCode, offset: u64) -> Error { 38 + Error(ErrorImpl { code, offset }) 39 + } 40 + 41 + #[cfg(feature = "std")] 42 + pub(crate) fn io(error: io::Error) -> Error { 43 + Error(ErrorImpl { 44 + code: ErrorCode::Io(error), 45 + offset: 0, 46 + }) 47 + } 48 + 49 + #[cfg(all(not(feature = "std"), feature = "unsealed_read_write"))] 50 + /// Creates an error signalling that the underlying `Read` encountered an I/O error. 51 + pub fn io() -> Error { 52 + Error(ErrorImpl { 53 + code: ErrorCode::Io, 54 + offset: 0, 55 + }) 56 + } 57 + 58 + #[cfg(feature = "unsealed_read_write")] 59 + /// Creates an error signalling that the scratch buffer was too small to fit the data. 60 + pub fn scratch_too_small(offset: u64) -> Error { 61 + Error(ErrorImpl { 62 + code: ErrorCode::ScratchTooSmall, 63 + offset, 64 + }) 65 + } 66 + 67 + #[cfg(not(feature = "unsealed_read_write"))] 68 + pub(crate) fn scratch_too_small(offset: u64) -> Error { 69 + Error(ErrorImpl { 70 + code: ErrorCode::ScratchTooSmall, 71 + offset, 72 + }) 73 + } 74 + 75 + #[cfg(feature = "unsealed_read_write")] 76 + /// Creates an error with a custom message. 77 + /// 78 + /// **Note**: When the "std" feature is disabled, the message will be discarded. 79 + pub fn message<T: fmt::Display>(_msg: T) -> Error { 80 + #[cfg(not(feature = "std"))] 81 + { 82 + Error(ErrorImpl { 83 + code: ErrorCode::Message, 84 + offset: 0, 85 + }) 86 + } 87 + #[cfg(feature = "std")] 88 + { 89 + Error(ErrorImpl { 90 + code: ErrorCode::Message(_msg.to_string()), 91 + offset: 0, 92 + }) 93 + } 94 + } 95 + 96 + #[cfg(not(feature = "unsealed_read_write"))] 97 + pub(crate) fn message<T: fmt::Display>(_msg: T) -> Error { 98 + #[cfg(not(feature = "std"))] 99 + { 100 + Error(ErrorImpl { 101 + code: ErrorCode::Message, 102 + offset: 0, 103 + }) 104 + } 105 + #[cfg(feature = "std")] 106 + { 107 + Error(ErrorImpl { 108 + code: ErrorCode::Message(_msg.to_string()), 109 + offset: 0, 110 + }) 111 + } 112 + } 113 + 114 + #[cfg(feature = "unsealed_read_write")] 115 + /// Creates an error signalling that the underlying read 116 + /// encountered an end of input. 117 + pub fn eof(offset: u64) -> Error { 118 + Error(ErrorImpl { 119 + code: ErrorCode::EofWhileParsingValue, 120 + offset, 121 + }) 122 + } 123 + 124 + /// Categorizes the cause of this error. 125 + pub fn classify(&self) -> Category { 126 + match self.0.code { 127 + #[cfg(feature = "std")] 128 + ErrorCode::Message(_) => Category::Data, 129 + #[cfg(not(feature = "std"))] 130 + ErrorCode::Message => Category::Data, 131 + #[cfg(feature = "std")] 132 + ErrorCode::Io(_) => Category::Io, 133 + #[cfg(not(feature = "std"))] 134 + ErrorCode::Io => Category::Io, 135 + ErrorCode::ScratchTooSmall => Category::Io, 136 + ErrorCode::EofWhileParsingValue 137 + | ErrorCode::EofWhileParsingArray 138 + | ErrorCode::EofWhileParsingMap => Category::Eof, 139 + ErrorCode::LengthOutOfRange 140 + | ErrorCode::InvalidUtf8 141 + | ErrorCode::UnassignedCode 142 + | ErrorCode::UnexpectedCode 143 + | ErrorCode::TrailingData 144 + | ErrorCode::ArrayTooShort 145 + | ErrorCode::ArrayTooLong 146 + | ErrorCode::RecursionLimitExceeded 147 + | ErrorCode::WrongEnumFormat 148 + | ErrorCode::WrongStructFormat => Category::Syntax, 149 + } 150 + } 151 + 152 + /// Returns true if this error was caused by a failure to read or write bytes on an IO stream. 153 + pub fn is_io(&self) -> bool { 154 + matches!(self.classify(), Category::Io) 155 + } 156 + 157 + /// Returns true if this error was caused by input that was not syntactically valid CBOR. 158 + pub fn is_syntax(&self) -> bool { 159 + matches!(self.classify(), Category::Syntax) 160 + } 161 + 162 + /// Returns true if this error was caused by data that was semantically incorrect. 163 + pub fn is_data(&self) -> bool { 164 + matches!(self.classify(), Category::Data) 165 + } 166 + 167 + /// Returns true if this error was caused by prematurely reaching the end of the input data. 168 + pub fn is_eof(&self) -> bool { 169 + matches!(self.classify(), Category::Eof) 170 + } 171 + 172 + /// Returns true if this error was caused by the scratch buffer being too small. 173 + /// 174 + /// Note this being `true` implies that `is_io()` is also `true`. 175 + pub fn is_scratch_too_small(&self) -> bool { 176 + matches!(self.0.code, ErrorCode::ScratchTooSmall) 177 + } 178 + } 179 + 180 + #[cfg(feature = "std")] 181 + impl error::Error for Error { 182 + fn source(&self) -> Option<&(dyn error::Error + 'static)> { 183 + match self.0.code { 184 + ErrorCode::Io(ref err) => Some(err), 185 + _ => None, 186 + } 187 + } 188 + } 189 + 190 + impl fmt::Display for Error { 191 + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 192 + if self.0.offset == 0 { 193 + fmt::Display::fmt(&self.0.code, f) 194 + } else { 195 + write!(f, "{} at offset {}", self.0.code, self.0.offset) 196 + } 197 + } 198 + } 199 + 200 + impl fmt::Debug for Error { 201 + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 202 + fmt::Debug::fmt(&self.0, fmt) 203 + } 204 + } 205 + 206 + impl de::Error for Error { 207 + fn custom<T: fmt::Display>(msg: T) -> Error { 208 + Error::message(msg) 209 + } 210 + 211 + fn invalid_type(unexp: de::Unexpected<'_>, exp: &dyn de::Expected) -> Error { 212 + if let de::Unexpected::Unit = unexp { 213 + Error::custom(format_args!("invalid type: null, expected {exp}")) 214 + } else { 215 + Error::custom(format_args!("invalid type: {unexp}, expected {exp}")) 216 + } 217 + } 218 + } 219 + 220 + impl ser::Error for Error { 221 + fn custom<T: fmt::Display>(msg: T) -> Error { 222 + Error::message(msg) 223 + } 224 + } 225 + 226 + #[cfg(feature = "std")] 227 + impl From<io::Error> for Error { 228 + fn from(e: io::Error) -> Error { 229 + Error::io(e) 230 + } 231 + } 232 + 233 + #[cfg(not(feature = "std"))] 234 + impl From<core::fmt::Error> for Error { 235 + fn from(_: core::fmt::Error) -> Error { 236 + Error(ErrorImpl { 237 + code: ErrorCode::Message, 238 + offset: 0, 239 + }) 240 + } 241 + } 242 + 243 + #[derive(Debug)] 244 + struct ErrorImpl { 245 + code: ErrorCode, 246 + offset: u64, 247 + } 248 + 249 + #[derive(Debug)] 250 + pub(crate) enum ErrorCode { 251 + #[cfg(feature = "std")] 252 + Message(String), 253 + #[cfg(not(feature = "std"))] 254 + Message, 255 + #[cfg(feature = "std")] 256 + Io(io::Error), 257 + #[allow(unused)] 258 + #[cfg(not(feature = "std"))] 259 + Io, 260 + ScratchTooSmall, 261 + EofWhileParsingValue, 262 + EofWhileParsingArray, 263 + EofWhileParsingMap, 264 + LengthOutOfRange, 265 + InvalidUtf8, 266 + UnassignedCode, 267 + UnexpectedCode, 268 + TrailingData, 269 + ArrayTooShort, 270 + ArrayTooLong, 271 + RecursionLimitExceeded, 272 + WrongEnumFormat, 273 + WrongStructFormat, 274 + } 275 + 276 + impl fmt::Display for ErrorCode { 277 + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 278 + match *self { 279 + #[cfg(feature = "std")] 280 + ErrorCode::Message(ref msg) => f.write_str(msg), 281 + #[cfg(not(feature = "std"))] 282 + ErrorCode::Message => f.write_str("Unknown error"), 283 + #[cfg(feature = "std")] 284 + ErrorCode::Io(ref err) => fmt::Display::fmt(err, f), 285 + #[cfg(not(feature = "std"))] 286 + ErrorCode::Io => f.write_str("Unknown I/O error"), 287 + ErrorCode::ScratchTooSmall => f.write_str("Scratch buffer too small"), 288 + ErrorCode::EofWhileParsingValue => f.write_str("EOF while parsing a value"), 289 + ErrorCode::EofWhileParsingArray => f.write_str("EOF while parsing an array"), 290 + ErrorCode::EofWhileParsingMap => f.write_str("EOF while parsing a map"), 291 + ErrorCode::LengthOutOfRange => f.write_str("length out of range"), 292 + ErrorCode::InvalidUtf8 => f.write_str("invalid UTF-8"), 293 + ErrorCode::UnassignedCode => f.write_str("unassigned type"), 294 + ErrorCode::UnexpectedCode => f.write_str("unexpected code"), 295 + ErrorCode::TrailingData => f.write_str("trailing data"), 296 + ErrorCode::ArrayTooShort => f.write_str("array too short"), 297 + ErrorCode::ArrayTooLong => f.write_str("array too long"), 298 + ErrorCode::RecursionLimitExceeded => f.write_str("recursion limit exceeded"), 299 + ErrorCode::WrongEnumFormat => f.write_str("wrong enum format"), 300 + ErrorCode::WrongStructFormat => f.write_str("wrong struct format"), 301 + } 302 + } 303 + }
+377
vendor/git/cbor/src/lib.rs
··· 1 + //! CBOR and serialization. 2 + //! 3 + //! # Usage 4 + //! 5 + //! Serde CBOR 2 supports Rust 1.62 and up. Add this to your `Cargo.toml`: 6 + //! 7 + //! ```toml 8 + //! [dependencies] 9 + //! serde_cbor_2 = "0.12" 10 + //! ``` 11 + //! 12 + //! Serde CBOR 2 can be used as a 'drop in' replacement of `serde_cbor` 13 + //! 14 + //! ```toml 15 + //! [dependencies] 16 + //! serde_cbor = { version = "0.12", package = "serde_cbor_2" } 17 + //! ``` 18 + //! 19 + //! Storing and loading Rust types is easy and requires only 20 + //! minimal modifications to the program code. 21 + //! 22 + //! ```rust 23 + //! # use serde::{Deserialize, Serialize}; 24 + //! use std::error::Error; 25 + //! use std::fs::File; 26 + //! 27 + //! // Types annotated with `Serialize` can be stored as CBOR. 28 + //! // To be able to load them again add `Deserialize`. 29 + //! #[derive(Debug, Serialize, Deserialize)] 30 + //! struct Mascot { 31 + //! name: String, 32 + //! species: String, 33 + //! year_of_birth: u32, 34 + //! } 35 + //! 36 + //! fn main() -> Result<(), Box<dyn Error>> { 37 + //! let ferris = Mascot { 38 + //! name: "Ferris".to_owned(), 39 + //! species: "crab".to_owned(), 40 + //! year_of_birth: 2015, 41 + //! }; 42 + //! 43 + //! let ferris_file = File::create("examples/ferris.cbor")?; 44 + //! // Write Ferris to the given file. 45 + //! // Instead of a file you can use any type that implements `io::Write` 46 + //! // like a HTTP body, database connection etc. 47 + //! serde_cbor_2::to_writer(ferris_file, &ferris)?; 48 + //! 49 + //! let tux_file = File::open("examples/tux.cbor")?; 50 + //! // Load Tux from a file. 51 + //! // Serde CBOR performs roundtrip serialization meaning that 52 + //! // the data will not change in any way. 53 + //! let tux: Mascot = serde_cbor_2::from_reader(tux_file)?; 54 + //! 55 + //! println!("{:?}", tux); 56 + //! // prints: Mascot { name: "Tux", species: "penguin", year_of_birth: 1996 } 57 + //! 58 + //! Ok(()) 59 + //! } 60 + //! ``` 61 + //! 62 + //! There are a lot of options available to customize the format. 63 + //! To operate on untyped CBOR values have a look at the `Value` type. 64 + //! 65 + //! # Type-based Serialization and Deserialization 66 + //! Serde provides a mechanism for low boilerplate serialization & deserialization of values to and 67 + //! from CBOR via the serialization API. To be able to serialize a piece of data, it must implement 68 + //! the `serde::Serialize` trait. To be able to deserialize a piece of data, it must implement the 69 + //! `serde::Deserialize` trait. Serde provides an annotation to automatically generate the 70 + //! code for these traits: `#[derive(Serialize, Deserialize)]`. 71 + //! 72 + //! The CBOR API also provides an enum `serde_cbor_2::Value`. 73 + //! 74 + //! # Packed Encoding 75 + //! When serializing structs or enums in CBOR the keys or enum variant names will be serialized 76 + //! as string keys to a map. Especially in embedded environments this can increase the file 77 + //! size too much. In packed encoding all struct keys, as well as any enum variant that has no data, 78 + //! will be serialized as variable sized integers. The first 24 entries in any struct consume only a 79 + //! single byte! Packed encoding uses serde's preferred [externally tagged enum 80 + //! format](https://serde.rs/enum-representations.html) and therefore serializes enum variant names 81 + //! as string keys when that variant contains data. So, in the packed encoding example, `FirstVariant` 82 + //! encodes to a single byte, but encoding `SecondVariant` requires 16 bytes. 83 + //! 84 + //! To serialize a document in this format use `Serializer::new(writer).packed_format()` or 85 + //! the shorthand `ser::to_vec_packed`. The deserialization works without any changes. 86 + //! 87 + //! If you would like to omit the enum variant encoding for all variants, including ones that 88 + //! contain data, you can add `legacy_enums()` in addition to `packed_format()`, as can seen 89 + //! in the Serialize using minimal encoding example. 90 + //! 91 + //! # Self describing documents 92 + //! In some contexts different formats are used but there is no way to declare the format used 93 + //! out of band. For this reason CBOR has a magic number that may be added before any document. 94 + //! Self describing documents are created with `serializer.self_describe()`. 95 + //! 96 + //! # Examples 97 + //! Read a CBOR value that is known to be a map of string keys to string values and print it. 98 + //! 99 + //! ```rust 100 + //! use std::collections::BTreeMap; 101 + //! use serde_cbor_2::from_slice; 102 + //! 103 + //! let slice = b"\xa5aaaAabaBacaCadaDaeaE"; 104 + //! let value: BTreeMap<String, String> = from_slice(slice).unwrap(); 105 + //! println!("{:?}", value); // {"e": "E", "d": "D", "a": "A", "c": "C", "b": "B"} 106 + //! ``` 107 + //! 108 + //! Read a general CBOR value with an unknown content. 109 + //! 110 + //! ```rust 111 + //! use serde_cbor_2::from_slice; 112 + //! use serde_cbor_2::value::Value; 113 + //! 114 + //! let slice = b"\x82\x01\xa1aaab"; 115 + //! let value: Value = from_slice(slice).unwrap(); 116 + //! println!("{:?}", value); // Array([U64(1), Object({String("a"): String("b")})]) 117 + //! ``` 118 + //! 119 + //! Serialize an object. 120 + //! 121 + //! ```rust 122 + //! use std::collections::BTreeMap; 123 + //! use serde_cbor_2::to_vec; 124 + //! 125 + //! let mut programming_languages = BTreeMap::new(); 126 + //! programming_languages.insert("rust", vec!["safe", "concurrent", "fast"]); 127 + //! programming_languages.insert("python", vec!["powerful", "friendly", "open"]); 128 + //! programming_languages.insert("js", vec!["lightweight", "interpreted", "object-oriented"]); 129 + //! let encoded = to_vec(&programming_languages); 130 + //! assert_eq!(encoded.unwrap().len(), 103); 131 + //! ``` 132 + //! 133 + //! Deserializing data in the middle of a slice 134 + //! ``` 135 + //! use serde_cbor_2::Deserializer; 136 + //! 137 + //! # fn main() { 138 + //! let data: Vec<u8> = vec![ 139 + //! 0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, 0x66, 0x66, 0x6f, 0x6f, 0x62, 140 + //! 0x61, 0x72, 141 + //! ]; 142 + //! let mut deserializer = Deserializer::from_slice(&data); 143 + //! let value: &str = serde::de::Deserialize::deserialize(&mut deserializer) 144 + //! .unwrap(); 145 + //! let rest = &data[deserializer.byte_offset()..]; 146 + //! assert_eq!(value, "foobar"); 147 + //! assert_eq!(rest, &[0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]); 148 + //! # } 149 + //! ``` 150 + //! 151 + //! Serialize using packed encoding 152 + //! 153 + //! ```rust 154 + //! # use serde::{Deserialize, Serialize}; 155 + //! use serde_cbor_2::ser::to_vec_packed; 156 + //! 157 + //! #[derive(Debug, Serialize, Deserialize)] 158 + //! enum WithTwoVariants { 159 + //! FirstVariant, 160 + //! SecondVariant(u8), 161 + //! } 162 + //! 163 + //! use WithTwoVariants::*; 164 + //! 165 + //! let cbor = to_vec_packed(&FirstVariant).unwrap(); 166 + //! assert_eq!(cbor.len(), 1); 167 + //! 168 + //! let cbor = to_vec_packed(&SecondVariant(0)).unwrap(); 169 + //! assert_eq!(cbor.len(), 16); // Includes 13 bytes of "SecondVariant" 170 + //! ``` 171 + //! 172 + //! Serialize using minimal encoding 173 + //! 174 + //! ```rust 175 + //! # use serde::{Deserialize, Serialize}; 176 + //! use serde_cbor_2::{Result, Serializer, ser::{self, IoWrite}}; 177 + //! 178 + //! fn to_vec_minimal<T>(value: &T) -> Result<Vec<u8>> 179 + //! where 180 + //! T: serde::Serialize, 181 + //! { 182 + //! let mut vec = Vec::new(); 183 + //! value.serialize(&mut Serializer::new(&mut IoWrite::new(&mut vec)).packed_format().legacy_enums())?; 184 + //! Ok(vec) 185 + //! } 186 + //! 187 + //! #[derive(Debug, Serialize, Deserialize)] 188 + //! enum WithTwoVariants { 189 + //! FirstVariant, 190 + //! SecondVariant(u8), 191 + //! } 192 + //! 193 + //! use WithTwoVariants::*; 194 + //! 195 + //! let cbor = to_vec_minimal(&FirstVariant).unwrap(); 196 + //! assert_eq!(cbor.len(), 1); 197 + //! 198 + //! let cbor = to_vec_minimal(&SecondVariant(0)).unwrap(); 199 + //! assert_eq!(cbor.len(), 3); 200 + //! ``` 201 + //! 202 + //! # `no-std` support 203 + //! 204 + //! Serde CBOR supports building in a `no_std` context, use the following lines 205 + //! in your `Cargo.toml` dependencies: 206 + //! ``` toml 207 + //! [dependencies] 208 + //! serde = { version = "1.0", default-features = false } 209 + //! serde_cbor = { version = "0.10", default-features = false } 210 + //! ``` 211 + //! 212 + //! Without the `std` feature the functions [from_reader], [from_slice], [to_vec], and [to_writer] 213 + //! are not exported. To export [from_slice] and [to_vec] enable the `alloc` feature. The `alloc` 214 + //! feature uses the [`alloc` library][alloc-lib] and requires at least version 1.36.0 of Rust. 215 + //! 216 + //! [alloc-lib]: https://doc.rust-lang.org/alloc/ 217 + //! 218 + //! *Note*: to use derive macros in serde you will need to declare `serde` 219 + //! dependency like so: 220 + //! ``` toml 221 + //! serde = { version = "1.0", default-features = false, features = ["derive"] } 222 + //! ``` 223 + //! 224 + //! Serialize an object with `no_std` and without `alloc`. 225 + //! ``` rust 226 + //! # fn main() -> Result<(), serde_cbor_2::Error> { 227 + //! # use serde::Serialize; 228 + //! use serde_cbor_2::Serializer; 229 + //! use serde_cbor_2::ser::SliceWrite; 230 + //! 231 + //! #[derive(Serialize)] 232 + //! struct User { 233 + //! user_id: u32, 234 + //! password_hash: [u8; 4], 235 + //! } 236 + //! 237 + //! let mut buf = [0u8; 100]; 238 + //! let writer = SliceWrite::new(&mut buf[..]); 239 + //! let mut ser = Serializer::new(writer); 240 + //! let user = User { 241 + //! user_id: 42, 242 + //! password_hash: [1, 2, 3, 4], 243 + //! }; 244 + //! user.serialize(&mut ser)?; 245 + //! let writer = ser.into_inner(); 246 + //! let size = writer.bytes_written(); 247 + //! let expected = [ 248 + //! 0xa2, 0x67, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x2a, 0x6d, 249 + //! 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x5f, 0x68, 0x61, 0x73, 250 + //! 0x68, 0x84, 0x1, 0x2, 0x3, 0x4 251 + //! ]; 252 + //! assert_eq!(&buf[..size], expected); 253 + //! # Ok(()) 254 + //! # } 255 + //! ``` 256 + //! 257 + //! Deserialize an object. 258 + //! ``` rust 259 + //! # use serde::Deserialize; 260 + //! # fn main() -> Result<(), serde_cbor_2::Error> { 261 + //! #[derive(Debug, PartialEq, Deserialize)] 262 + //! struct User { 263 + //! user_id: u32, 264 + //! password_hash: [u8; 4], 265 + //! } 266 + //! 267 + //! let value = [ 268 + //! 0xa2, 0x67, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x2a, 0x6d, 269 + //! 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x5f, 0x68, 0x61, 0x73, 270 + //! 0x68, 0x84, 0x1, 0x2, 0x3, 0x4 271 + //! ]; 272 + //! 273 + //! // from_slice_with_scratch will not alter input data, use it whenever you 274 + //! // borrow from somewhere else. 275 + //! // You will have to size your scratch according to the input data you 276 + //! // expect. 277 + //! use serde_cbor_2::de::from_slice_with_scratch; 278 + //! let mut scratch = [0u8; 32]; 279 + //! let user: User = from_slice_with_scratch(&value[..], &mut scratch)?; 280 + //! assert_eq!(user, User { 281 + //! user_id: 42, 282 + //! password_hash: [1, 2, 3, 4], 283 + //! }); 284 + //! 285 + //! let mut value = [ 286 + //! 0xa2, 0x67, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x2a, 0x6d, 287 + //! 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x5f, 0x68, 0x61, 0x73, 288 + //! 0x68, 0x84, 0x1, 0x2, 0x3, 0x4 289 + //! ]; 290 + //! 291 + //! // from_mut_slice will move data around the input slice, you may only use it 292 + //! // on data you may own or can modify. 293 + //! use serde_cbor_2::de::from_mut_slice; 294 + //! let user: User = from_mut_slice(&mut value[..])?; 295 + //! assert_eq!(user, User { 296 + //! user_id: 42, 297 + //! password_hash: [1, 2, 3, 4], 298 + //! }); 299 + //! # Ok(()) 300 + //! # } 301 + //! ``` 302 + //! 303 + //! # Limitations 304 + //! 305 + //! While Serde CBOR strives to support all features of Serde and CBOR 306 + //! there are a few limitations. 307 + //! 308 + //! * [Tags] are ignored during deserialization and can't be emitted during 309 + //! serialization. This is because Serde has no concept of tagged 310 + //! values. See:&nbsp;[#3] 311 + //! * Unknown [simple values] cause an `UnassignedCode` error. 312 + //! The simple values *False* and *True* are recognized and parsed as bool. 313 + //! *Null* and *Undefined* are both deserialized as *unit*. 314 + //! The *unit* type is serialized as *Null*. See:&nbsp;[#86] 315 + //! * [128-bit integers] can't be directly encoded in CBOR. If you need them 316 + //! store them as a byte string. See:&nbsp;[#77] 317 + //! 318 + //! [Tags]: https://tools.ietf.org/html/rfc7049#section-2.4.4 319 + //! [#3]: https://github.com/pyfisch/cbor/issues/3 320 + //! [simple values]: https://tools.ietf.org/html/rfc7049#section-3.5 321 + //! [#86]: https://github.com/pyfisch/cbor/issues/86 322 + //! [128-bit integers]: https://doc.rust-lang.org/std/primitive.u128.html 323 + //! [#77]: https://github.com/pyfisch/cbor/issues/77 324 + 325 + #![deny(missing_docs)] 326 + #![cfg_attr(not(feature = "std"), no_std)] 327 + 328 + // When we are running tests in no_std mode we need to explicitly link std, because `cargo test` 329 + // will not work without it. 330 + #[cfg(all(not(feature = "std"), test))] 331 + extern crate std; 332 + 333 + #[cfg(feature = "alloc")] 334 + extern crate alloc; 335 + 336 + pub mod de; 337 + pub mod error; 338 + mod read; 339 + pub mod ser; 340 + pub mod tags; 341 + mod write; 342 + 343 + #[cfg(feature = "std")] 344 + pub mod value; 345 + 346 + // Re-export the [items recommended by serde](https://serde.rs/conventions.html). 347 + #[doc(inline)] 348 + pub use crate::de::{Deserializer, StreamDeserializer}; 349 + 350 + #[doc(inline)] 351 + pub use crate::error::{Error, Result}; 352 + 353 + #[doc(inline)] 354 + pub use crate::ser::Serializer; 355 + 356 + // Convenience functions for serialization and deserialization. 357 + // These functions are only available in `std` mode. 358 + #[cfg(feature = "std")] 359 + #[doc(inline)] 360 + pub use crate::de::from_reader; 361 + 362 + #[cfg(any(feature = "std", feature = "alloc"))] 363 + #[doc(inline)] 364 + pub use crate::de::from_slice; 365 + 366 + #[cfg(any(feature = "std", feature = "alloc"))] 367 + #[doc(inline)] 368 + pub use crate::ser::to_vec; 369 + 370 + #[cfg(feature = "std")] 371 + #[doc(inline)] 372 + pub use crate::ser::to_writer; 373 + 374 + // Re-export the value type like serde_json 375 + #[cfg(feature = "std")] 376 + #[doc(inline)] 377 + pub use crate::value::Value;
+637
vendor/git/cbor/src/read.rs
··· 1 + #[cfg(feature = "alloc")] 2 + use alloc::{vec, vec::Vec}; 3 + #[cfg(feature = "std")] 4 + use core::cmp; 5 + use core::mem; 6 + 7 + #[cfg(feature = "std")] 8 + use std::io::{self, Read as StdRead}; 9 + 10 + use crate::error::{Error, ErrorCode, Result}; 11 + 12 + #[cfg(not(feature = "unsealed_read_write"))] 13 + /// Trait used by the deserializer for iterating over input. 14 + /// 15 + /// This trait is sealed by default, enabling the `unsealed_read_write` feature removes this bound 16 + /// to allow objects outside of this crate to implement this trait. 17 + pub trait Read<'de>: private::Sealed { 18 + #[doc(hidden)] 19 + /// Read n bytes from the input. 20 + /// 21 + /// Implementations that can are asked to return a slice with a Long lifetime that outlives the 22 + /// decoder, but others (eg. ones that need to allocate the data into a temporary buffer) can 23 + /// return it with a Short lifetime that just lives for the time of read's mutable borrow of 24 + /// the reader. 25 + /// 26 + /// This may, as a side effect, clear the reader's scratch buffer (as the provided 27 + /// implementation does). 28 + /// 29 + /// A more appropriate lifetime setup for this (that would allow the Deserializer::convert_str 30 + /// to stay a function) would be something like `fn read<'a, 'r: 'a>(&'a mut 'r immut self, ...) -> ... 31 + /// EitherLifetime<'r, 'de>>`, which borrows self mutably for the duration of the function and 32 + /// downgrates that reference to an immutable one that outlives the result (protecting the 33 + /// scratch buffer from changes), but alas, that can't be expressed (yet?). 34 + fn read<'a>(&'a mut self, n: usize) -> Result<EitherLifetime<'a, 'de>> { 35 + self.clear_buffer(); 36 + self.read_to_buffer(n)?; 37 + 38 + Ok(self.take_buffer()) 39 + } 40 + 41 + #[doc(hidden)] 42 + fn next(&mut self) -> Result<Option<u8>>; 43 + 44 + #[doc(hidden)] 45 + fn peek(&mut self) -> Result<Option<u8>>; 46 + 47 + #[doc(hidden)] 48 + fn clear_buffer(&mut self); 49 + 50 + #[doc(hidden)] 51 + fn read_to_buffer(&mut self, n: usize) -> Result<()>; 52 + 53 + #[doc(hidden)] 54 + fn take_buffer<'a>(&'a mut self) -> EitherLifetime<'a, 'de>; 55 + 56 + #[doc(hidden)] 57 + fn read_into(&mut self, buf: &mut [u8]) -> Result<()>; 58 + 59 + #[doc(hidden)] 60 + fn discard(&mut self); 61 + 62 + #[doc(hidden)] 63 + fn offset(&self) -> u64; 64 + } 65 + 66 + #[cfg(feature = "unsealed_read_write")] 67 + /// Trait used by the deserializer for iterating over input. 68 + pub trait Read<'de> { 69 + /// Read n bytes from the input. 70 + /// 71 + /// Implementations that can are asked to return a slice with a Long lifetime that outlives the 72 + /// decoder, but others (eg. ones that need to allocate the data into a temporary buffer) can 73 + /// return it with a Short lifetime that just lives for the time of read's mutable borrow of 74 + /// the reader. 75 + /// 76 + /// This may, as a side effect, clear the reader's scratch buffer (as the provided 77 + /// implementation does). 78 + 79 + // A more appropriate lifetime setup for this (that would allow the Deserializer::convert_str 80 + // to stay a function) would be something like `fn read<'a, 'r: 'a>(&'a mut 'r immut self, ...) -> ... 81 + // EitherLifetime<'r, 'de>>`, which borrows self mutably for the duration of the function and 82 + // downgrates that reference to an immutable one that outlives the result (protecting the 83 + // scratch buffer from changes), but alas, that can't be expressed (yet?). 84 + fn read<'a>(&'a mut self, n: usize) -> Result<EitherLifetime<'a, 'de>> { 85 + self.clear_buffer(); 86 + self.read_to_buffer(n)?; 87 + 88 + Ok(self.take_buffer()) 89 + } 90 + 91 + /// Read the next byte from the input, if any. 92 + fn next(&mut self) -> Result<Option<u8>>; 93 + 94 + /// Peek at the next byte of the input, if any. This does not advance the reader, so the result 95 + /// of this function will remain the same until a read or clear occurs. 96 + fn peek(&mut self) -> Result<Option<u8>>; 97 + 98 + /// Clear the underlying scratch buffer 99 + fn clear_buffer(&mut self); 100 + 101 + /// Append n bytes from the reader to the reader's scratch buffer (without clearing it) 102 + fn read_to_buffer(&mut self, n: usize) -> Result<()>; 103 + 104 + /// Read out everything accumulated in the reader's scratch buffer. This may, as a side effect, 105 + /// clear it. 106 + fn take_buffer<'a>(&'a mut self) -> EitherLifetime<'a, 'de>; 107 + 108 + /// Read from the input until `buf` is full or end of input is encountered. 109 + fn read_into(&mut self, buf: &mut [u8]) -> Result<()>; 110 + 111 + /// Discard any data read by `peek`. 112 + fn discard(&mut self); 113 + 114 + /// Returns the offset from the start of the reader. 115 + fn offset(&self) -> u64; 116 + } 117 + 118 + /// Represents a reader that can return its current position 119 + pub trait Offset { 120 + fn byte_offset(&self) -> usize; 121 + } 122 + 123 + /// Represents a buffer with one of two lifetimes. 124 + pub enum EitherLifetime<'short, 'long> { 125 + /// The short lifetime 126 + Short(&'short [u8]), 127 + /// The long lifetime 128 + Long(&'long [u8]), 129 + } 130 + 131 + #[cfg(not(feature = "unsealed_read_write"))] 132 + mod private { 133 + pub trait Sealed {} 134 + } 135 + 136 + /// CBOR input source that reads from a std::io input stream. 137 + #[cfg(feature = "std")] 138 + #[derive(Debug)] 139 + pub struct IoRead<R> 140 + where 141 + R: io::Read, 142 + { 143 + reader: OffsetReader<R>, 144 + scratch: Vec<u8>, 145 + ch: Option<u8>, 146 + } 147 + 148 + #[cfg(feature = "std")] 149 + impl<R> IoRead<R> 150 + where 151 + R: io::Read, 152 + { 153 + /// Creates a new CBOR input source to read from a std::io input stream. 154 + pub fn new(reader: R) -> IoRead<R> { 155 + IoRead { 156 + reader: OffsetReader { reader, offset: 0 }, 157 + scratch: vec![], 158 + ch: None, 159 + } 160 + } 161 + 162 + #[inline] 163 + fn next_inner(&mut self) -> Result<Option<u8>> { 164 + let mut buf = [0; 1]; 165 + loop { 166 + match self.reader.read(&mut buf) { 167 + Ok(0) => return Ok(None), 168 + Ok(_) => return Ok(Some(buf[0])), 169 + Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {} 170 + Err(e) => return Err(Error::io(e)), 171 + } 172 + } 173 + } 174 + } 175 + 176 + #[cfg(all(feature = "std", not(feature = "unsealed_read_write")))] 177 + impl<R> private::Sealed for IoRead<R> where R: io::Read {} 178 + 179 + #[cfg(feature = "std")] 180 + impl<'de, R> Read<'de> for IoRead<R> 181 + where 182 + R: io::Read, 183 + { 184 + #[inline] 185 + fn next(&mut self) -> Result<Option<u8>> { 186 + match self.ch.take() { 187 + Some(ch) => Ok(Some(ch)), 188 + None => self.next_inner(), 189 + } 190 + } 191 + 192 + #[inline] 193 + fn peek(&mut self) -> Result<Option<u8>> { 194 + match self.ch { 195 + Some(ch) => Ok(Some(ch)), 196 + None => { 197 + self.ch = self.next_inner()?; 198 + Ok(self.ch) 199 + } 200 + } 201 + } 202 + 203 + fn read_to_buffer(&mut self, mut n: usize) -> Result<()> { 204 + // defend against malicious input pretending to be huge strings by limiting growth 205 + self.scratch.reserve(cmp::min(n, 16 * 1024)); 206 + 207 + if n == 0 { 208 + return Ok(()); 209 + } 210 + 211 + if let Some(ch) = self.ch.take() { 212 + self.scratch.push(ch); 213 + n -= 1; 214 + } 215 + 216 + // n == 0 is OK here and needs no further special treatment 217 + 218 + let transfer_result = { 219 + // Prepare for take() (which consumes its reader) by creating a reference adaptor 220 + // that'll only live in this block 221 + let reference = self.reader.by_ref(); 222 + // Append the first n bytes of the reader to the scratch vector (or up to 223 + // an error or EOF indicated by a shorter read) 224 + let mut taken = reference.take(n as u64); 225 + taken.read_to_end(&mut self.scratch) 226 + }; 227 + 228 + match transfer_result { 229 + Ok(r) if r == n => Ok(()), 230 + Ok(_) => Err(Error::syntax( 231 + ErrorCode::EofWhileParsingValue, 232 + self.offset(), 233 + )), 234 + Err(e) => Err(Error::io(e)), 235 + } 236 + } 237 + 238 + fn clear_buffer(&mut self) { 239 + self.scratch.clear(); 240 + } 241 + 242 + fn take_buffer<'a>(&'a mut self) -> EitherLifetime<'a, 'de> { 243 + EitherLifetime::Short(&self.scratch) 244 + } 245 + 246 + fn read_into(&mut self, buf: &mut [u8]) -> Result<()> { 247 + self.reader.read_exact(buf).map_err(|e| { 248 + if e.kind() == io::ErrorKind::UnexpectedEof { 249 + Error::syntax(ErrorCode::EofWhileParsingValue, self.offset()) 250 + } else { 251 + Error::io(e) 252 + } 253 + }) 254 + } 255 + 256 + #[inline] 257 + fn discard(&mut self) { 258 + self.ch = None; 259 + } 260 + 261 + fn offset(&self) -> u64 { 262 + self.reader.offset 263 + } 264 + } 265 + 266 + #[cfg(feature = "std")] 267 + impl<R> Offset for IoRead<R> 268 + where 269 + R: std::io::Read, 270 + { 271 + fn byte_offset(&self) -> usize { 272 + self.offset() as usize 273 + } 274 + } 275 + 276 + #[cfg(feature = "std")] 277 + #[derive(Debug)] 278 + struct OffsetReader<R> { 279 + reader: R, 280 + offset: u64, 281 + } 282 + 283 + #[cfg(feature = "std")] 284 + impl<R> io::Read for OffsetReader<R> 285 + where 286 + R: io::Read, 287 + { 288 + #[inline] 289 + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { 290 + let r = self.reader.read(buf); 291 + if let Ok(count) = r { 292 + self.offset += count as u64; 293 + } 294 + r 295 + } 296 + } 297 + 298 + /// A CBOR input source that reads from a slice of bytes. 299 + #[cfg(any(feature = "std", feature = "alloc"))] 300 + #[derive(Debug)] 301 + pub struct SliceRead<'a> { 302 + slice: &'a [u8], 303 + scratch: Vec<u8>, 304 + index: usize, 305 + } 306 + 307 + #[cfg(any(feature = "std", feature = "alloc"))] 308 + impl<'a> SliceRead<'a> { 309 + /// Creates a CBOR input source to read from a slice of bytes. 310 + pub fn new(slice: &'a [u8]) -> SliceRead<'a> { 311 + SliceRead { 312 + slice, 313 + scratch: vec![], 314 + index: 0, 315 + } 316 + } 317 + 318 + fn end(&self, n: usize) -> Result<usize> { 319 + match self.index.checked_add(n) { 320 + Some(end) if end <= self.slice.len() => Ok(end), 321 + _ => Err(Error::syntax( 322 + ErrorCode::EofWhileParsingValue, 323 + self.slice.len() as u64, 324 + )), 325 + } 326 + } 327 + } 328 + 329 + #[cfg(any(feature = "std", feature = "alloc"))] 330 + impl Offset for SliceRead<'_> { 331 + #[inline] 332 + fn byte_offset(&self) -> usize { 333 + self.index 334 + } 335 + } 336 + 337 + #[cfg(all( 338 + any(feature = "std", feature = "alloc"), 339 + not(feature = "unsealed_read_write") 340 + ))] 341 + impl private::Sealed for SliceRead<'_> {} 342 + 343 + #[cfg(any(feature = "std", feature = "alloc"))] 344 + impl<'a> Read<'a> for SliceRead<'a> { 345 + #[inline] 346 + fn next(&mut self) -> Result<Option<u8>> { 347 + Ok(if self.index < self.slice.len() { 348 + let ch = self.slice[self.index]; 349 + self.index += 1; 350 + Some(ch) 351 + } else { 352 + None 353 + }) 354 + } 355 + 356 + #[inline] 357 + fn peek(&mut self) -> Result<Option<u8>> { 358 + Ok(if self.index < self.slice.len() { 359 + Some(self.slice[self.index]) 360 + } else { 361 + None 362 + }) 363 + } 364 + 365 + fn clear_buffer(&mut self) { 366 + self.scratch.clear(); 367 + } 368 + 369 + fn read_to_buffer(&mut self, n: usize) -> Result<()> { 370 + let end = self.end(n)?; 371 + let slice = &self.slice[self.index..end]; 372 + self.scratch.extend_from_slice(slice); 373 + self.index = end; 374 + 375 + Ok(()) 376 + } 377 + 378 + #[inline] 379 + fn read<'b>(&'b mut self, n: usize) -> Result<EitherLifetime<'b, 'a>> { 380 + let end = self.end(n)?; 381 + let slice = &self.slice[self.index..end]; 382 + self.index = end; 383 + Ok(EitherLifetime::Long(slice)) 384 + } 385 + 386 + fn take_buffer<'b>(&'b mut self) -> EitherLifetime<'b, 'a> { 387 + EitherLifetime::Short(&self.scratch) 388 + } 389 + 390 + #[inline] 391 + fn read_into(&mut self, buf: &mut [u8]) -> Result<()> { 392 + let end = self.end(buf.len())?; 393 + buf.copy_from_slice(&self.slice[self.index..end]); 394 + self.index = end; 395 + Ok(()) 396 + } 397 + 398 + #[inline] 399 + fn discard(&mut self) { 400 + self.index += 1; 401 + } 402 + 403 + fn offset(&self) -> u64 { 404 + self.index as u64 405 + } 406 + } 407 + 408 + /// A CBOR input source that reads from a slice of bytes using a fixed size scratch buffer. 409 + /// 410 + /// [`SliceRead`](struct.SliceRead.html) and [`MutSliceRead`](struct.MutSliceRead.html) are usually 411 + /// preferred over this, as they can handle indefinite length items. 412 + #[derive(Debug)] 413 + pub struct SliceReadFixed<'a, 'b> { 414 + slice: &'a [u8], 415 + scratch: &'b mut [u8], 416 + index: usize, 417 + scratch_index: usize, 418 + } 419 + 420 + impl<'a, 'b> SliceReadFixed<'a, 'b> { 421 + /// Creates a CBOR input source to read from a slice of bytes, backed by a scratch buffer. 422 + pub fn new(slice: &'a [u8], scratch: &'b mut [u8]) -> SliceReadFixed<'a, 'b> { 423 + SliceReadFixed { 424 + slice, 425 + scratch, 426 + index: 0, 427 + scratch_index: 0, 428 + } 429 + } 430 + 431 + fn end(&self, n: usize) -> Result<usize> { 432 + match self.index.checked_add(n) { 433 + Some(end) if end <= self.slice.len() => Ok(end), 434 + _ => Err(Error::syntax( 435 + ErrorCode::EofWhileParsingValue, 436 + self.slice.len() as u64, 437 + )), 438 + } 439 + } 440 + 441 + fn scratch_end(&self, n: usize) -> Result<usize> { 442 + match self.scratch_index.checked_add(n) { 443 + Some(end) if end <= self.scratch.len() => Ok(end), 444 + _ => Err(Error::scratch_too_small(self.index as u64)), 445 + } 446 + } 447 + } 448 + 449 + #[cfg(not(feature = "unsealed_read_write"))] 450 + impl private::Sealed for SliceReadFixed<'_, '_> {} 451 + 452 + impl<'a> Read<'a> for SliceReadFixed<'a, '_> { 453 + #[inline] 454 + fn next(&mut self) -> Result<Option<u8>> { 455 + Ok(if self.index < self.slice.len() { 456 + let ch = self.slice[self.index]; 457 + self.index += 1; 458 + Some(ch) 459 + } else { 460 + None 461 + }) 462 + } 463 + 464 + #[inline] 465 + fn peek(&mut self) -> Result<Option<u8>> { 466 + Ok(if self.index < self.slice.len() { 467 + Some(self.slice[self.index]) 468 + } else { 469 + None 470 + }) 471 + } 472 + 473 + fn clear_buffer(&mut self) { 474 + self.scratch_index = 0; 475 + } 476 + 477 + fn read_to_buffer(&mut self, n: usize) -> Result<()> { 478 + let end = self.end(n)?; 479 + let scratch_end = self.scratch_end(n)?; 480 + let slice = &self.slice[self.index..end]; 481 + self.scratch[self.scratch_index..scratch_end].copy_from_slice(slice); 482 + self.index = end; 483 + self.scratch_index = scratch_end; 484 + 485 + Ok(()) 486 + } 487 + 488 + fn read<'c>(&'c mut self, n: usize) -> Result<EitherLifetime<'c, 'a>> { 489 + let end = self.end(n)?; 490 + let slice = &self.slice[self.index..end]; 491 + self.index = end; 492 + Ok(EitherLifetime::Long(slice)) 493 + } 494 + 495 + fn take_buffer<'c>(&'c mut self) -> EitherLifetime<'c, 'a> { 496 + EitherLifetime::Short(&self.scratch[0..self.scratch_index]) 497 + } 498 + 499 + #[inline] 500 + fn read_into(&mut self, buf: &mut [u8]) -> Result<()> { 501 + let end = self.end(buf.len())?; 502 + buf.copy_from_slice(&self.slice[self.index..end]); 503 + self.index = end; 504 + Ok(()) 505 + } 506 + 507 + #[inline] 508 + fn discard(&mut self) { 509 + self.index += 1; 510 + } 511 + 512 + fn offset(&self) -> u64 { 513 + self.index as u64 514 + } 515 + } 516 + 517 + #[cfg(any(feature = "std", feature = "alloc"))] 518 + impl Offset for SliceReadFixed<'_, '_> { 519 + #[inline] 520 + fn byte_offset(&self) -> usize { 521 + self.index 522 + } 523 + } 524 + 525 + /// A CBOR input source that reads from a slice of bytes, and can move data around internally to 526 + /// reassemble indefinite strings without the need of an allocated scratch buffer. 527 + #[derive(Debug)] 528 + pub struct MutSliceRead<'a> { 529 + /// A complete view of the reader's data. It is promised that bytes before buffer_end are not 530 + /// mutated any more. 531 + slice: &'a mut [u8], 532 + /// Read cursor position in slice 533 + index: usize, 534 + /// Number of bytes already discarded from the slice 535 + before: usize, 536 + /// End of the buffer area that contains all bytes read_into_buffer. This is always <= index. 537 + buffer_end: usize, 538 + } 539 + 540 + impl<'a> MutSliceRead<'a> { 541 + /// Creates a CBOR input source to read from a slice of bytes. 542 + pub fn new(slice: &'a mut [u8]) -> MutSliceRead<'a> { 543 + MutSliceRead { 544 + slice, 545 + index: 0, 546 + before: 0, 547 + buffer_end: 0, 548 + } 549 + } 550 + 551 + fn end(&self, n: usize) -> Result<usize> { 552 + match self.index.checked_add(n) { 553 + Some(end) if end <= self.slice.len() => Ok(end), 554 + _ => Err(Error::syntax( 555 + ErrorCode::EofWhileParsingValue, 556 + self.slice.len() as u64, 557 + )), 558 + } 559 + } 560 + } 561 + 562 + #[cfg(not(feature = "unsealed_read_write"))] 563 + impl private::Sealed for MutSliceRead<'_> {} 564 + 565 + impl<'a> Read<'a> for MutSliceRead<'a> { 566 + #[inline] 567 + fn next(&mut self) -> Result<Option<u8>> { 568 + // This is duplicated from SliceRead, can that be eased? 569 + Ok(if self.index < self.slice.len() { 570 + let ch = self.slice[self.index]; 571 + self.index += 1; 572 + Some(ch) 573 + } else { 574 + None 575 + }) 576 + } 577 + 578 + #[inline] 579 + fn peek(&mut self) -> Result<Option<u8>> { 580 + // This is duplicated from SliceRead, can that be eased? 581 + Ok(if self.index < self.slice.len() { 582 + Some(self.slice[self.index]) 583 + } else { 584 + None 585 + }) 586 + } 587 + 588 + fn clear_buffer(&mut self) { 589 + self.slice = &mut mem::take(&mut self.slice)[self.index..]; 590 + self.before += self.index; 591 + self.index = 0; 592 + self.buffer_end = 0; 593 + } 594 + 595 + fn read_to_buffer(&mut self, n: usize) -> Result<()> { 596 + let end = self.end(n)?; 597 + debug_assert!( 598 + self.buffer_end <= self.index, 599 + "MutSliceRead invariant violated: scratch buffer exceeds index" 600 + ); 601 + self.slice[self.buffer_end..end].rotate_left(self.index - self.buffer_end); 602 + self.buffer_end += n; 603 + self.index = end; 604 + 605 + Ok(()) 606 + } 607 + 608 + fn take_buffer<'b>(&'b mut self) -> EitherLifetime<'b, 'a> { 609 + let (left, right) = mem::take(&mut self.slice).split_at_mut(self.index); 610 + self.slice = right; 611 + self.before += self.index; 612 + self.index = 0; 613 + 614 + let left = &left[..self.buffer_end]; 615 + self.buffer_end = 0; 616 + 617 + EitherLifetime::Long(left) 618 + } 619 + 620 + #[inline] 621 + fn read_into(&mut self, buf: &mut [u8]) -> Result<()> { 622 + // This is duplicated from SliceRead, can that be eased? 623 + let end = self.end(buf.len())?; 624 + buf.copy_from_slice(&self.slice[self.index..end]); 625 + self.index = end; 626 + Ok(()) 627 + } 628 + 629 + #[inline] 630 + fn discard(&mut self) { 631 + self.index += 1; 632 + } 633 + 634 + fn offset(&self) -> u64 { 635 + (self.before + self.index) as u64 636 + } 637 + }
+747
vendor/git/cbor/src/ser.rs
··· 1 + //! Serialize a Rust data structure to CBOR data. 2 + 3 + #[cfg(feature = "alloc")] 4 + use alloc::vec::Vec; 5 + 6 + #[cfg(feature = "std")] 7 + pub use crate::write::IoWrite; 8 + pub use crate::write::{SliceWrite, Write}; 9 + 10 + use crate::error::{Error, Result}; 11 + use half::f16; 12 + use serde::ser::{self, Serialize}; 13 + #[cfg(feature = "std")] 14 + use std::io; 15 + 16 + use crate::tags::{get_tag, CBOR_NEWTYPE_NAME}; 17 + 18 + /// Serializes a value to a vector. 19 + #[cfg(any(feature = "std", feature = "alloc"))] 20 + pub fn to_vec<T>(value: &T) -> Result<Vec<u8>> 21 + where 22 + T: ser::Serialize, 23 + { 24 + let mut vec = Vec::new(); 25 + value.serialize(&mut Serializer::new(&mut vec))?; 26 + Ok(vec) 27 + } 28 + 29 + /// Serializes a value to a vector in packed format. 30 + #[cfg(feature = "std")] 31 + pub fn to_vec_packed<T>(value: &T) -> Result<Vec<u8>> 32 + where 33 + T: ser::Serialize, 34 + { 35 + let mut vec = Vec::new(); 36 + value.serialize(&mut Serializer::new(&mut IoWrite::new(&mut vec)).packed_format())?; 37 + Ok(vec) 38 + } 39 + 40 + /// Serializes a value to a writer. 41 + #[cfg(feature = "std")] 42 + pub fn to_writer<W, T>(writer: W, value: &T) -> Result<()> 43 + where 44 + W: io::Write, 45 + T: ser::Serialize, 46 + { 47 + value.serialize(&mut Serializer::new(&mut IoWrite::new(writer))) 48 + } 49 + 50 + /// A structure for serializing Rust values to CBOR. 51 + #[derive(Debug)] 52 + pub struct Serializer<W> { 53 + writer: W, 54 + packed: bool, 55 + enum_as_map: bool, 56 + } 57 + 58 + impl<W> Serializer<W> 59 + where 60 + W: Write, 61 + { 62 + /// Creates a new CBOR serializer. 63 + /// 64 + /// `to_vec` and `to_writer` should normally be used instead of this method. 65 + #[inline] 66 + pub fn new(writer: W) -> Self { 67 + Serializer { 68 + writer, 69 + packed: false, 70 + enum_as_map: true, 71 + } 72 + } 73 + 74 + /// Choose concise/packed format for serializer. 75 + /// 76 + /// In the packed format enum variant names and field names 77 + /// are replaced with numeric indizes to conserve space. 78 + pub fn packed_format(mut self) -> Self { 79 + self.packed = true; 80 + self 81 + } 82 + 83 + /// Enable old enum format used by `serde_cbor` versions <= v0.9. 84 + /// 85 + /// The `legacy_enums` option determines how enums are encoded. 86 + /// 87 + /// This makes no difference when encoding and decoding enums using 88 + /// this crate, but it shows up when decoding to a `Value` or decoding 89 + /// in other languages. 90 + /// 91 + /// # Examples 92 + /// 93 + /// Given the following enum 94 + /// 95 + /// ```rust 96 + /// enum Enum { 97 + /// Unit, 98 + /// NewType(i32), 99 + /// Tuple(String, bool), 100 + /// Struct{ x: i32, y: i32 }, 101 + /// } 102 + /// ``` 103 + /// we will give the `Value` with the same encoding for each case using 104 + /// JSON notation. 105 + /// 106 + /// ## Default encodings 107 + /// 108 + /// * `Enum::Unit` encodes as `"Unit"` 109 + /// * `Enum::NewType(10)` encodes as `{"NewType": 10}` 110 + /// * `Enum::Tuple("x", true)` encodes as `{"Tuple": ["x", true]}` 111 + /// 112 + /// ## Legacy encodings 113 + /// 114 + /// * `Enum::Unit` encodes as `"Unit"` 115 + /// * `Enum::NewType(10)` encodes as `["NewType", 10]` 116 + /// * `Enum::Tuple("x", true)` encodes as `["Tuple", "x", true]` 117 + /// * `Enum::Struct{ x: 5, y: -5 }` encodes as `["Struct", {"x": 5, "y": -5}]` 118 + pub fn legacy_enums(mut self) -> Self { 119 + self.enum_as_map = false; 120 + self 121 + } 122 + 123 + /// Writes a CBOR self-describe tag to the stream. 124 + /// 125 + /// Tagging allows a decoder to distinguish different file formats based on their content 126 + /// without further information. 127 + #[inline] 128 + pub fn self_describe(&mut self) -> Result<()> { 129 + let mut buf = [(6 << 5) | 25, 0, 0]; 130 + buf[1..].copy_from_slice(&55799u16.to_be_bytes()); 131 + self.writer.write_all(&buf).map_err(|e| e.into()) 132 + } 133 + 134 + /// Unwrap the `Writer` from the `Serializer`. 135 + #[inline] 136 + pub fn into_inner(self) -> W { 137 + self.writer 138 + } 139 + 140 + #[inline] 141 + fn write_u8(&mut self, major: u8, value: u8) -> Result<()> { 142 + if value <= 0x17 { 143 + self.writer.write_all(&[(major << 5) | value]) 144 + } else { 145 + let buf = [(major << 5) | 24, value]; 146 + self.writer.write_all(&buf) 147 + } 148 + .map_err(|e| e.into()) 149 + } 150 + 151 + #[inline] 152 + fn write_u16(&mut self, major: u8, value: u16) -> Result<()> { 153 + if value <= u16::from(u8::MAX) { 154 + self.write_u8(major, value as u8) 155 + } else { 156 + let mut buf = [(major << 5) | 25, 0, 0]; 157 + buf[1..].copy_from_slice(&value.to_be_bytes()); 158 + self.writer.write_all(&buf).map_err(|e| e.into()) 159 + } 160 + } 161 + 162 + #[inline] 163 + fn write_u32(&mut self, major: u8, value: u32) -> Result<()> { 164 + if value <= u32::from(u16::MAX) { 165 + self.write_u16(major, value as u16) 166 + } else { 167 + let mut buf = [(major << 5) | 26, 0, 0, 0, 0]; 168 + buf[1..].copy_from_slice(&value.to_be_bytes()); 169 + self.writer.write_all(&buf).map_err(|e| e.into()) 170 + } 171 + } 172 + 173 + #[inline] 174 + fn write_u64(&mut self, major: u8, value: u64) -> Result<()> { 175 + if value <= u64::from(u32::MAX) { 176 + self.write_u32(major, value as u32) 177 + } else { 178 + let mut buf = [(major << 5) | 27, 0, 0, 0, 0, 0, 0, 0, 0]; 179 + buf[1..].copy_from_slice(&value.to_be_bytes()); 180 + self.writer.write_all(&buf).map_err(|e| e.into()) 181 + } 182 + } 183 + 184 + #[inline] 185 + fn serialize_collection( 186 + &mut self, 187 + major: u8, 188 + len: Option<usize>, 189 + ) -> Result<CollectionSerializer<'_, W>> { 190 + let needs_eof = match len { 191 + Some(len) => { 192 + self.write_u64(major, len as u64)?; 193 + false 194 + } 195 + None => { 196 + self.writer 197 + .write_all(&[(major << 5) | 31]) 198 + .map_err(|e| e.into())?; 199 + true 200 + } 201 + }; 202 + 203 + Ok(CollectionSerializer { 204 + ser: self, 205 + needs_eof, 206 + }) 207 + } 208 + } 209 + 210 + impl<'a, W> ser::Serializer for &'a mut Serializer<W> 211 + where 212 + W: Write, 213 + { 214 + type Ok = (); 215 + type Error = Error; 216 + 217 + type SerializeSeq = CollectionSerializer<'a, W>; 218 + type SerializeTuple = &'a mut Serializer<W>; 219 + type SerializeTupleStruct = &'a mut Serializer<W>; 220 + type SerializeTupleVariant = &'a mut Serializer<W>; 221 + type SerializeMap = CollectionSerializer<'a, W>; 222 + type SerializeStruct = StructSerializer<'a, W>; 223 + type SerializeStructVariant = StructSerializer<'a, W>; 224 + 225 + #[inline] 226 + fn serialize_bool(self, value: bool) -> Result<()> { 227 + let value = if value { 0xf5 } else { 0xf4 }; 228 + self.writer.write_all(&[value]).map_err(|e| e.into()) 229 + } 230 + 231 + #[inline] 232 + fn serialize_i8(self, value: i8) -> Result<()> { 233 + if value < 0 { 234 + self.write_u8(1, -(value + 1) as u8) 235 + } else { 236 + self.write_u8(0, value as u8) 237 + } 238 + } 239 + 240 + #[inline] 241 + fn serialize_i16(self, value: i16) -> Result<()> { 242 + if value < 0 { 243 + self.write_u16(1, -(value + 1) as u16) 244 + } else { 245 + self.write_u16(0, value as u16) 246 + } 247 + } 248 + 249 + #[inline] 250 + fn serialize_i32(self, value: i32) -> Result<()> { 251 + if value < 0 { 252 + self.write_u32(1, -(value + 1) as u32) 253 + } else { 254 + self.write_u32(0, value as u32) 255 + } 256 + } 257 + 258 + #[inline] 259 + fn serialize_i64(self, value: i64) -> Result<()> { 260 + if value < 0 { 261 + self.write_u64(1, -(value + 1) as u64) 262 + } else { 263 + self.write_u64(0, value as u64) 264 + } 265 + } 266 + 267 + #[inline] 268 + fn serialize_i128(self, value: i128) -> Result<()> { 269 + if value < 0 { 270 + if -(value + 1) > i128::from(u64::MAX) { 271 + return Err(Error::message("The number can't be stored in CBOR")); 272 + } 273 + self.write_u64(1, -(value + 1) as u64) 274 + } else { 275 + if value > i128::from(u64::MAX) { 276 + return Err(Error::message("The number can't be stored in CBOR")); 277 + } 278 + self.write_u64(0, value as u64) 279 + } 280 + } 281 + 282 + #[inline] 283 + fn serialize_u8(self, value: u8) -> Result<()> { 284 + self.write_u8(0, value) 285 + } 286 + 287 + #[inline] 288 + fn serialize_u16(self, value: u16) -> Result<()> { 289 + self.write_u16(0, value) 290 + } 291 + 292 + #[inline] 293 + fn serialize_u32(self, value: u32) -> Result<()> { 294 + self.write_u32(0, value) 295 + } 296 + 297 + #[inline] 298 + fn serialize_u64(self, value: u64) -> Result<()> { 299 + self.write_u64(0, value) 300 + } 301 + 302 + #[inline] 303 + fn serialize_u128(self, value: u128) -> Result<()> { 304 + if value > u128::from(u64::MAX) { 305 + return Err(Error::message("The number can't be stored in CBOR")); 306 + } 307 + self.write_u64(0, value as u64) 308 + } 309 + 310 + #[inline] 311 + #[allow(clippy::float_cmp)] 312 + fn serialize_f32(self, value: f32) -> Result<()> { 313 + if value.is_infinite() { 314 + if value.is_sign_positive() { 315 + self.writer.write_all(&[0xf9, 0x7c, 0x00]) 316 + } else { 317 + self.writer.write_all(&[0xf9, 0xfc, 0x00]) 318 + } 319 + } else if value.is_nan() { 320 + self.writer.write_all(&[0xf9, 0x7e, 0x00]) 321 + } else if f32::from(f16::from_f32(value)) == value { 322 + let mut buf = [0xf9, 0, 0]; 323 + buf[1..].copy_from_slice(&f16::from_f32(value).to_bits().to_be_bytes()); 324 + self.writer.write_all(&buf) 325 + } else { 326 + let mut buf = [0xfa, 0, 0, 0, 0]; 327 + buf[1..].copy_from_slice(&value.to_bits().to_be_bytes()); 328 + self.writer.write_all(&buf) 329 + } 330 + .map_err(|e| e.into()) 331 + } 332 + 333 + #[inline] 334 + #[allow(clippy::float_cmp)] 335 + fn serialize_f64(self, value: f64) -> Result<()> { 336 + if !value.is_finite() || f64::from(value as f32) == value { 337 + self.serialize_f32(value as f32) 338 + } else { 339 + let mut buf = [0xfb, 0, 0, 0, 0, 0, 0, 0, 0]; 340 + buf[1..].copy_from_slice(&value.to_bits().to_be_bytes()); 341 + self.writer.write_all(&buf).map_err(|e| e.into()) 342 + } 343 + } 344 + 345 + #[inline] 346 + fn serialize_char(self, value: char) -> Result<()> { 347 + // A char encoded as UTF-8 takes 4 bytes at most. 348 + let mut buf = [0; 4]; 349 + self.serialize_str(value.encode_utf8(&mut buf)) 350 + } 351 + 352 + #[inline] 353 + fn serialize_str(self, value: &str) -> Result<()> { 354 + self.write_u64(3, value.len() as u64)?; 355 + self.writer 356 + .write_all(value.as_bytes()) 357 + .map_err(|e| e.into()) 358 + } 359 + 360 + #[inline] 361 + fn serialize_bytes(self, value: &[u8]) -> Result<()> { 362 + self.write_u64(2, value.len() as u64)?; 363 + self.writer.write_all(value).map_err(|e| e.into()) 364 + } 365 + 366 + #[inline] 367 + fn serialize_unit(self) -> Result<()> { 368 + self.serialize_none() 369 + } 370 + 371 + #[inline] 372 + fn serialize_some<T>(self, value: &T) -> Result<()> 373 + where 374 + T: ?Sized + ser::Serialize, 375 + { 376 + value.serialize(self) 377 + } 378 + 379 + #[inline] 380 + fn serialize_none(self) -> Result<()> { 381 + self.writer.write_all(&[0xf6]).map_err(|e| e.into()) 382 + } 383 + 384 + #[inline] 385 + fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { 386 + self.serialize_unit() 387 + } 388 + 389 + #[inline] 390 + fn serialize_unit_variant( 391 + self, 392 + _name: &'static str, 393 + variant_index: u32, 394 + variant: &'static str, 395 + ) -> Result<()> { 396 + if self.packed { 397 + self.serialize_u32(variant_index) 398 + } else { 399 + self.serialize_str(variant) 400 + } 401 + } 402 + 403 + #[inline] 404 + fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<()> 405 + where 406 + T: ?Sized + ser::Serialize, 407 + { 408 + if name == CBOR_NEWTYPE_NAME { 409 + if let Some(tag) = get_tag() { 410 + self.write_u64(6, tag)?; 411 + } 412 + } 413 + value.serialize(self) 414 + } 415 + 416 + #[inline] 417 + fn serialize_newtype_variant<T>( 418 + self, 419 + name: &'static str, 420 + variant_index: u32, 421 + variant: &'static str, 422 + value: &T, 423 + ) -> Result<()> 424 + where 425 + T: ?Sized + ser::Serialize, 426 + { 427 + if self.enum_as_map { 428 + self.write_u64(5, 1u64)?; 429 + variant.serialize(&mut *self)?; 430 + } else { 431 + self.writer 432 + .write_all(&[(4 << 5) | 2]) 433 + .map_err(|e| e.into())?; 434 + self.serialize_unit_variant(name, variant_index, variant)?; 435 + } 436 + value.serialize(self) 437 + } 438 + 439 + #[inline] 440 + fn serialize_seq(self, len: Option<usize>) -> Result<CollectionSerializer<'a, W>> { 441 + self.serialize_collection(4, len) 442 + } 443 + 444 + #[inline] 445 + fn serialize_tuple(self, len: usize) -> Result<&'a mut Serializer<W>> { 446 + self.write_u64(4, len as u64)?; 447 + Ok(self) 448 + } 449 + 450 + #[inline] 451 + fn serialize_tuple_struct( 452 + self, 453 + _name: &'static str, 454 + len: usize, 455 + ) -> Result<&'a mut Serializer<W>> { 456 + self.serialize_tuple(len) 457 + } 458 + 459 + #[inline] 460 + fn serialize_tuple_variant( 461 + self, 462 + name: &'static str, 463 + variant_index: u32, 464 + variant: &'static str, 465 + len: usize, 466 + ) -> Result<&'a mut Serializer<W>> { 467 + if self.enum_as_map { 468 + self.write_u64(5, 1u64)?; 469 + variant.serialize(&mut *self)?; 470 + self.serialize_tuple(len) 471 + } else { 472 + self.write_u64(4, (len + 1) as u64)?; 473 + self.serialize_unit_variant(name, variant_index, variant)?; 474 + Ok(self) 475 + } 476 + } 477 + 478 + #[inline] 479 + fn serialize_map(self, len: Option<usize>) -> Result<CollectionSerializer<'a, W>> { 480 + self.serialize_collection(5, len) 481 + } 482 + 483 + #[cfg(not(feature = "std"))] 484 + fn collect_str<T: ?Sized>(self, value: &T) -> Result<()> 485 + where 486 + T: core::fmt::Display, 487 + { 488 + use crate::write::FmtWrite; 489 + use core::fmt::Write; 490 + 491 + let mut w = FmtWrite::new(&mut self.writer); 492 + write!(w, "{}", value)?; 493 + Ok(()) 494 + } 495 + 496 + #[inline] 497 + fn serialize_struct(self, _name: &'static str, len: usize) -> Result<StructSerializer<'a, W>> { 498 + self.write_u64(5, len as u64)?; 499 + Ok(StructSerializer { ser: self, idx: 0 }) 500 + } 501 + 502 + #[inline] 503 + fn serialize_struct_variant( 504 + self, 505 + name: &'static str, 506 + variant_index: u32, 507 + variant: &'static str, 508 + len: usize, 509 + ) -> Result<StructSerializer<'a, W>> { 510 + if self.enum_as_map { 511 + self.write_u64(5, 1u64)?; 512 + } else { 513 + self.writer 514 + .write_all(&[(4 << 5) | 2]) 515 + .map_err(|e| e.into())?; 516 + } 517 + self.serialize_unit_variant(name, variant_index, variant)?; 518 + self.serialize_struct(name, len) 519 + } 520 + 521 + #[inline] 522 + fn is_human_readable(&self) -> bool { 523 + false 524 + } 525 + } 526 + 527 + impl<W> ser::SerializeTuple for &mut Serializer<W> 528 + where 529 + W: Write, 530 + { 531 + type Ok = (); 532 + type Error = Error; 533 + 534 + #[inline] 535 + fn serialize_element<T>(&mut self, value: &T) -> Result<()> 536 + where 537 + T: ?Sized + ser::Serialize, 538 + { 539 + value.serialize(&mut **self) 540 + } 541 + 542 + #[inline] 543 + fn end(self) -> Result<()> { 544 + Ok(()) 545 + } 546 + } 547 + 548 + impl<W> ser::SerializeTupleStruct for &mut Serializer<W> 549 + where 550 + W: Write, 551 + { 552 + type Ok = (); 553 + type Error = Error; 554 + 555 + #[inline] 556 + fn serialize_field<T>(&mut self, value: &T) -> Result<()> 557 + where 558 + T: ?Sized + ser::Serialize, 559 + { 560 + value.serialize(&mut **self) 561 + } 562 + 563 + #[inline] 564 + fn end(self) -> Result<()> { 565 + Ok(()) 566 + } 567 + } 568 + 569 + impl<W> ser::SerializeTupleVariant for &mut Serializer<W> 570 + where 571 + W: Write, 572 + { 573 + type Ok = (); 574 + type Error = Error; 575 + 576 + #[inline] 577 + fn serialize_field<T>(&mut self, value: &T) -> Result<()> 578 + where 579 + T: ?Sized + ser::Serialize, 580 + { 581 + value.serialize(&mut **self) 582 + } 583 + 584 + #[inline] 585 + fn end(self) -> Result<()> { 586 + Ok(()) 587 + } 588 + } 589 + 590 + #[doc(hidden)] 591 + pub struct StructSerializer<'a, W> { 592 + ser: &'a mut Serializer<W>, 593 + idx: u32, 594 + } 595 + 596 + impl<W> StructSerializer<'_, W> 597 + where 598 + W: Write, 599 + { 600 + #[inline] 601 + fn serialize_field_inner<T>(&mut self, key: &'static str, value: &T) -> Result<()> 602 + where 603 + T: ?Sized + ser::Serialize, 604 + { 605 + if self.ser.packed { 606 + self.idx.serialize(&mut *self.ser)?; 607 + } else { 608 + key.serialize(&mut *self.ser)?; 609 + } 610 + value.serialize(&mut *self.ser)?; 611 + self.idx += 1; 612 + Ok(()) 613 + } 614 + 615 + #[inline] 616 + fn skip_field_inner(&mut self, _: &'static str) -> Result<()> { 617 + self.idx += 1; 618 + Ok(()) 619 + } 620 + 621 + #[inline] 622 + fn end_inner(self) -> Result<()> { 623 + Ok(()) 624 + } 625 + } 626 + 627 + impl<W> ser::SerializeStruct for StructSerializer<'_, W> 628 + where 629 + W: Write, 630 + { 631 + type Ok = (); 632 + type Error = Error; 633 + 634 + #[inline] 635 + fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()> 636 + where 637 + T: ?Sized + ser::Serialize, 638 + { 639 + self.serialize_field_inner(key, value) 640 + } 641 + 642 + #[inline] 643 + fn skip_field(&mut self, key: &'static str) -> Result<()> { 644 + self.skip_field_inner(key) 645 + } 646 + 647 + #[inline] 648 + fn end(self) -> Result<()> { 649 + self.end_inner() 650 + } 651 + } 652 + 653 + impl<W> ser::SerializeStructVariant for StructSerializer<'_, W> 654 + where 655 + W: Write, 656 + { 657 + type Ok = (); 658 + type Error = Error; 659 + 660 + #[inline] 661 + fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()> 662 + where 663 + T: ?Sized + ser::Serialize, 664 + { 665 + self.serialize_field_inner(key, value) 666 + } 667 + 668 + #[inline] 669 + fn skip_field(&mut self, key: &'static str) -> Result<()> { 670 + self.skip_field_inner(key) 671 + } 672 + 673 + #[inline] 674 + fn end(self) -> Result<()> { 675 + self.end_inner() 676 + } 677 + } 678 + 679 + #[doc(hidden)] 680 + pub struct CollectionSerializer<'a, W> { 681 + ser: &'a mut Serializer<W>, 682 + needs_eof: bool, 683 + } 684 + 685 + impl<W> CollectionSerializer<'_, W> 686 + where 687 + W: Write, 688 + { 689 + #[inline] 690 + fn end_inner(self) -> Result<()> { 691 + if self.needs_eof { 692 + self.ser.writer.write_all(&[0xff]).map_err(|e| e.into()) 693 + } else { 694 + Ok(()) 695 + } 696 + } 697 + } 698 + 699 + impl<W> ser::SerializeSeq for CollectionSerializer<'_, W> 700 + where 701 + W: Write, 702 + { 703 + type Ok = (); 704 + type Error = Error; 705 + 706 + #[inline] 707 + fn serialize_element<T>(&mut self, value: &T) -> Result<()> 708 + where 709 + T: ?Sized + ser::Serialize, 710 + { 711 + value.serialize(&mut *self.ser) 712 + } 713 + 714 + #[inline] 715 + fn end(self) -> Result<()> { 716 + self.end_inner() 717 + } 718 + } 719 + 720 + impl<W> ser::SerializeMap for CollectionSerializer<'_, W> 721 + where 722 + W: Write, 723 + { 724 + type Ok = (); 725 + type Error = Error; 726 + 727 + #[inline] 728 + fn serialize_key<T>(&mut self, key: &T) -> Result<()> 729 + where 730 + T: ?Sized + ser::Serialize, 731 + { 732 + key.serialize(&mut *self.ser) 733 + } 734 + 735 + #[inline] 736 + fn serialize_value<T>(&mut self, value: &T) -> Result<()> 737 + where 738 + T: ?Sized + ser::Serialize, 739 + { 740 + value.serialize(&mut *self.ser) 741 + } 742 + 743 + #[inline] 744 + fn end(self) -> Result<()> { 745 + self.end_inner() 746 + } 747 + }
+220
vendor/git/cbor/src/tags.rs
··· 1 + //! Support for cbor tags 2 + use core::fmt; 3 + use core::marker::PhantomData; 4 + use serde::de::{ 5 + Deserialize, Deserializer, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, Visitor, 6 + }; 7 + use serde::forward_to_deserialize_any; 8 + use serde::ser::{Serialize, Serializer}; 9 + 10 + /// signals that a newtype is from a CBOR tag 11 + pub(crate) const CBOR_NEWTYPE_NAME: &str = "\0cbor_tag"; 12 + 13 + /// A value that is optionally tagged with a cbor tag 14 + /// 15 + /// this only serves as an intermediate helper for tag serialization or deserialization 16 + pub struct Tagged<T> { 17 + /// cbor tag 18 + pub tag: Option<u64>, 19 + /// value 20 + pub value: T, 21 + } 22 + 23 + impl<T> Tagged<T> { 24 + /// Create a new tagged value 25 + pub fn new(tag: Option<u64>, value: T) -> Self { 26 + Self { tag, value } 27 + } 28 + } 29 + 30 + impl<T: Serialize> Serialize for Tagged<T> { 31 + fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { 32 + set_tag(self.tag); 33 + let r = s.serialize_newtype_struct(CBOR_NEWTYPE_NAME, &self.value); 34 + set_tag(None); 35 + r 36 + } 37 + } 38 + 39 + fn untagged<T>(value: T) -> Tagged<T> { 40 + Tagged::new(None, value) 41 + } 42 + 43 + macro_rules! delegate { 44 + ($name: ident, $type: ty) => { 45 + fn $name<E: serde::de::Error>(self, v: $type) -> Result<Self::Value, E> { 46 + T::deserialize(v.into_deserializer()).map(untagged) 47 + } 48 + }; 49 + } 50 + 51 + struct EnumDeserializer<A>(A); 52 + 53 + impl<'de, A> Deserializer<'de> for EnumDeserializer<A> 54 + where 55 + A: EnumAccess<'de>, 56 + { 57 + type Error = A::Error; 58 + 59 + fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> { 60 + visitor.visit_enum(self.0) 61 + } 62 + 63 + forward_to_deserialize_any! { 64 + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string 65 + bytes byte_buf option unit unit_struct newtype_struct seq tuple 66 + tuple_struct map struct enum identifier ignored_any 67 + } 68 + } 69 + 70 + struct NoneDeserializer<E>(PhantomData<E>); 71 + 72 + impl<'de, E> Deserializer<'de> for NoneDeserializer<E> 73 + where 74 + E: serde::de::Error, 75 + { 76 + type Error = E; 77 + 78 + fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> { 79 + visitor.visit_none() 80 + } 81 + 82 + forward_to_deserialize_any! { 83 + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string 84 + bytes byte_buf option unit unit_struct newtype_struct seq tuple 85 + tuple_struct map struct enum identifier ignored_any 86 + } 87 + } 88 + 89 + struct BytesDeserializer<'a, E>(&'a [u8], PhantomData<E>); 90 + 91 + impl<'de, E> Deserializer<'de> for BytesDeserializer<'_, E> 92 + where 93 + E: serde::de::Error, 94 + { 95 + type Error = E; 96 + 97 + fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> { 98 + visitor.visit_bytes(self.0) 99 + } 100 + 101 + forward_to_deserialize_any! { 102 + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string 103 + bytes byte_buf option unit unit_struct newtype_struct seq tuple 104 + tuple_struct map struct enum identifier ignored_any 105 + } 106 + } 107 + 108 + /// A visitor that intercepts *just* visit_newtype_struct and passes through everything else. 109 + struct MaybeTaggedVisitor<T>(PhantomData<T>); 110 + 111 + impl<'de, T: Deserialize<'de>> Visitor<'de> for MaybeTaggedVisitor<T> { 112 + type Value = Tagged<T>; 113 + 114 + fn expecting(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { 115 + fmt.write_str("a cbor tag newtype") 116 + } 117 + 118 + delegate!(visit_bool, bool); 119 + 120 + delegate!(visit_i8, i8); 121 + delegate!(visit_i16, i16); 122 + delegate!(visit_i32, i32); 123 + delegate!(visit_i64, i64); 124 + 125 + delegate!(visit_u8, u8); 126 + delegate!(visit_u16, u16); 127 + delegate!(visit_u32, u32); 128 + delegate!(visit_u64, u64); 129 + 130 + delegate!(visit_f32, f32); 131 + delegate!(visit_f64, f64); 132 + 133 + delegate!(visit_char, char); 134 + delegate!(visit_str, &str); 135 + delegate!(visit_borrowed_str, &'de str); 136 + 137 + #[cfg(feature = "std")] 138 + delegate!(visit_byte_buf, Vec<u8>); 139 + 140 + #[cfg(feature = "std")] 141 + delegate!(visit_string, String); 142 + 143 + fn visit_bytes<E: serde::de::Error>(self, value: &[u8]) -> Result<Self::Value, E> { 144 + T::deserialize(BytesDeserializer(value, PhantomData)).map(untagged) 145 + } 146 + 147 + fn visit_borrowed_bytes<E: serde::de::Error>(self, value: &'de [u8]) -> Result<Self::Value, E> { 148 + T::deserialize(serde::de::value::BorrowedBytesDeserializer::new(value)).map(untagged) 149 + } 150 + 151 + fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> { 152 + T::deserialize(().into_deserializer()).map(untagged) 153 + } 154 + 155 + fn visit_none<E: serde::de::Error>(self) -> Result<Self::Value, E> { 156 + T::deserialize(NoneDeserializer(PhantomData)).map(untagged) 157 + } 158 + 159 + fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> { 160 + T::deserialize(deserializer).map(untagged) 161 + } 162 + 163 + fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<Self::Value, A::Error> { 164 + T::deserialize(serde::de::value::SeqAccessDeserializer::new(seq)).map(untagged) 165 + } 166 + 167 + fn visit_map<V: MapAccess<'de>>(self, map: V) -> Result<Self::Value, V::Error> { 168 + T::deserialize(serde::de::value::MapAccessDeserializer::new(map)).map(untagged) 169 + } 170 + 171 + fn visit_enum<A: EnumAccess<'de>>(self, data: A) -> Result<Self::Value, A::Error> { 172 + T::deserialize(EnumDeserializer(data)).map(untagged) 173 + } 174 + 175 + fn visit_newtype_struct<D: serde::Deserializer<'de>>( 176 + self, 177 + deserializer: D, 178 + ) -> Result<Self::Value, D::Error> { 179 + let t = get_tag(); 180 + T::deserialize(deserializer).map(|v| Tagged::new(t, v)) 181 + } 182 + } 183 + 184 + impl<'de, T: serde::de::Deserialize<'de>> serde::de::Deserialize<'de> for Tagged<T> { 185 + fn deserialize<D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { 186 + deserializer.deserialize_any(MaybeTaggedVisitor::<T>(PhantomData)) 187 + } 188 + } 189 + 190 + /// function to get the current cbor tag 191 + /// 192 + /// The only place where it makes sense to call this function is within visit_newtype_struct of a serde visitor. 193 + /// This is a low level API. In most cases it is preferable to use Tagged 194 + pub fn current_cbor_tag() -> Option<u64> { 195 + get_tag() 196 + } 197 + 198 + #[cfg(feature = "tags")] 199 + pub(crate) fn set_tag(value: Option<u64>) { 200 + CBOR_TAG.with(|f| *f.borrow_mut() = value); 201 + } 202 + 203 + #[cfg(feature = "tags")] 204 + pub(crate) fn get_tag() -> Option<u64> { 205 + CBOR_TAG.with(|f| *f.borrow()) 206 + } 207 + 208 + #[cfg(not(feature = "tags"))] 209 + pub(crate) fn set_tag(_value: Option<u64>) {} 210 + 211 + #[cfg(not(feature = "tags"))] 212 + pub(crate) fn get_tag() -> Option<u64> { 213 + None 214 + } 215 + 216 + #[cfg(feature = "tags")] 217 + use std::cell::RefCell; 218 + 219 + #[cfg(feature = "tags")] 220 + thread_local!(static CBOR_TAG: RefCell<Option<u64>> = const { RefCell::new(None) });
+166
vendor/git/cbor/src/value/de.rs
··· 1 + use std::collections::BTreeMap; 2 + use std::fmt; 3 + 4 + use crate::value::Value; 5 + use serde::de; 6 + 7 + impl<'de> de::Deserialize<'de> for Value { 8 + #[inline] 9 + fn deserialize<D>(deserializer: D) -> Result<Value, D::Error> 10 + where 11 + D: de::Deserializer<'de>, 12 + { 13 + struct ValueVisitor; 14 + 15 + impl<'de> de::Visitor<'de> for ValueVisitor { 16 + type Value = Value; 17 + 18 + fn expecting(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { 19 + fmt.write_str("any valid CBOR value") 20 + } 21 + 22 + #[inline] 23 + fn visit_str<E>(self, value: &str) -> Result<Value, E> 24 + where 25 + E: de::Error, 26 + { 27 + self.visit_string(String::from(value)) 28 + } 29 + 30 + #[inline] 31 + fn visit_string<E>(self, value: String) -> Result<Value, E> 32 + where 33 + E: de::Error, 34 + { 35 + Ok(Value::Text(value)) 36 + } 37 + #[inline] 38 + fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> 39 + where 40 + E: de::Error, 41 + { 42 + self.visit_byte_buf(v.to_owned()) 43 + } 44 + 45 + #[inline] 46 + fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> 47 + where 48 + E: de::Error, 49 + { 50 + Ok(Value::Bytes(v)) 51 + } 52 + 53 + #[inline] 54 + fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> 55 + where 56 + E: de::Error, 57 + { 58 + Ok(Value::Integer(v.into())) 59 + } 60 + 61 + #[inline] 62 + fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> 63 + where 64 + E: de::Error, 65 + { 66 + Ok(Value::Integer(v.into())) 67 + } 68 + 69 + #[inline] 70 + fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E> 71 + where 72 + E: de::Error, 73 + { 74 + Ok(Value::Integer(v)) 75 + } 76 + 77 + #[inline] 78 + fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> 79 + where 80 + E: de::Error, 81 + { 82 + Ok(Value::Bool(v)) 83 + } 84 + 85 + #[inline] 86 + fn visit_none<E>(self) -> Result<Self::Value, E> 87 + where 88 + E: de::Error, 89 + { 90 + self.visit_unit() 91 + } 92 + 93 + #[inline] 94 + fn visit_unit<E>(self) -> Result<Self::Value, E> 95 + where 96 + E: de::Error, 97 + { 98 + Ok(Value::Null) 99 + } 100 + 101 + #[inline] 102 + fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> 103 + where 104 + V: de::SeqAccess<'de>, 105 + { 106 + let mut vec = Vec::new(); 107 + 108 + while let Some(elem) = visitor.next_element()? { 109 + vec.push(elem); 110 + } 111 + 112 + Ok(Value::Array(vec)) 113 + } 114 + 115 + #[inline] 116 + fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error> 117 + where 118 + V: de::MapAccess<'de>, 119 + { 120 + let mut values = BTreeMap::new(); 121 + 122 + while let Some((key, value)) = visitor.next_entry()? { 123 + values.insert(key, value); 124 + } 125 + 126 + Ok(Value::Map(values)) 127 + } 128 + 129 + #[inline] 130 + fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E> 131 + where 132 + E: de::Error, 133 + { 134 + Ok(Value::Float(v)) 135 + } 136 + 137 + fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> 138 + where 139 + D: serde::Deserializer<'de>, 140 + { 141 + let tag = crate::tags::get_tag(); 142 + let inner = deserializer.deserialize_any(self); 143 + match tag { 144 + Some(tag) => inner.map(|v| Value::Tag(tag, Box::new(v))), 145 + None => inner, 146 + } 147 + } 148 + } 149 + 150 + deserializer.deserialize_any(ValueVisitor) 151 + } 152 + } 153 + 154 + /// Convert a `serde_cbor::Value` into a type `T` 155 + #[allow(clippy::needless_pass_by_value)] 156 + pub fn from_value<T>(value: Value) -> Result<T, crate::error::Error> 157 + where 158 + T: de::DeserializeOwned, 159 + { 160 + // TODO implement in a way that doesn't require 161 + // roundtrip through buffer (i.e. by implementing 162 + // `serde::de::Deserializer` for `Value` and then doing 163 + // `T::deserialize(value)`). 164 + let buf = crate::to_vec(&value)?; 165 + crate::from_slice(buf.as_slice()) 166 + }
+151
vendor/git/cbor/src/value/mod.rs
··· 1 + //! CBOR values, keys and serialization routines. 2 + 3 + mod de; 4 + mod ser; 5 + 6 + use std::cmp::{Ord, Ordering, PartialOrd}; 7 + use std::collections::BTreeMap; 8 + 9 + #[doc(inline)] 10 + pub use self::de::from_value; 11 + #[doc(inline)] 12 + pub use self::ser::to_value; 13 + 14 + /// The `Value` enum, a loosely typed way of representing any valid CBOR value. 15 + /// 16 + /// Maps are sorted according to the canonical ordering 17 + /// described in [RFC 7049 bis]. 18 + /// Therefore values are unambiguously serialized 19 + /// to a canonical form of CBOR from the same RFC. 20 + /// 21 + /// [RFC 7049 bis]: https://tools.ietf.org/html/draft-ietf-cbor-7049bis-04#section-2 22 + #[derive(Clone, Debug)] 23 + pub enum Value { 24 + /// Represents the absence of a value or the value undefined. 25 + Null, 26 + /// Represents a boolean value. 27 + Bool(bool), 28 + /// Integer CBOR numbers. 29 + /// 30 + /// The biggest value that can be represented is 2^64 - 1. 31 + /// While the smallest value is -2^64. 32 + /// Values outside this range can't be serialized 33 + /// and will cause an error. 34 + Integer(i128), 35 + /// Represents a floating point value. 36 + Float(f64), 37 + /// Represents a byte string. 38 + Bytes(Vec<u8>), 39 + /// Represents an UTF-8 encoded string. 40 + Text(String), 41 + /// Represents an array of values. 42 + Array(Vec<Value>), 43 + /// Represents a map. 44 + /// 45 + /// Maps are also called tables, dictionaries, hashes, or objects (in JSON). 46 + /// While any value can be used as a CBOR key 47 + /// it is better to use only one type of key in a map 48 + /// to avoid ambiguity. 49 + /// If floating point values are used as keys they are compared bit-by-bit for equality. 50 + /// If arrays or maps are used as keys the comparisons 51 + /// to establish canonical order may be slow and therefore insertion 52 + /// and retrieval of values will be slow too. 53 + Map(BTreeMap<Value, Value>), 54 + /// Represents a tagged value 55 + Tag(u64, Box<Value>), 56 + // The hidden variant allows the enum to be extended 57 + // with variants for tags and simple values. 58 + #[doc(hidden)] 59 + __Hidden, 60 + } 61 + 62 + impl PartialEq for Value { 63 + fn eq(&self, other: &Value) -> bool { 64 + self.cmp(other) == Ordering::Equal 65 + } 66 + } 67 + 68 + impl Eq for Value {} 69 + 70 + impl PartialOrd for Value { 71 + fn partial_cmp(&self, other: &Value) -> Option<Ordering> { 72 + Some(self.cmp(other)) 73 + } 74 + } 75 + 76 + impl Ord for Value { 77 + fn cmp(&self, other: &Value) -> Ordering { 78 + // Determine the canonical order of two values: 79 + // 1. Smaller major type sorts first. 80 + // 2. Shorter sequence sorts first. 81 + // 3. Compare integers by magnitude. 82 + // 4. Compare byte and text sequences lexically. 83 + // 5. Compare the serializations of both types. (expensive) 84 + use self::Value::*; 85 + if self.major_type() != other.major_type() { 86 + return self.major_type().cmp(&other.major_type()); 87 + } 88 + match (self, other) { 89 + (Integer(a), Integer(b)) => a.abs().cmp(&b.abs()), 90 + (Bytes(a), Bytes(b)) if a.len() != b.len() => a.len().cmp(&b.len()), 91 + (Text(a), Text(b)) if a.len() != b.len() => a.len().cmp(&b.len()), 92 + (Array(a), Array(b)) if a.len() != b.len() => a.len().cmp(&b.len()), 93 + (Map(a), Map(b)) if a.len() != b.len() => a.len().cmp(&b.len()), 94 + (Bytes(a), Bytes(b)) => a.cmp(b), 95 + (Text(a), Text(b)) => a.cmp(b), 96 + (a, b) => { 97 + let a = crate::to_vec(a).expect("self is serializable"); 98 + let b = crate::to_vec(b).expect("other is serializable"); 99 + a.cmp(&b) 100 + } 101 + } 102 + } 103 + } 104 + 105 + macro_rules! impl_from { 106 + ($variant:path, $for_type:ty) => { 107 + impl From<$for_type> for Value { 108 + fn from(v: $for_type) -> Value { 109 + $variant(v.into()) 110 + } 111 + } 112 + }; 113 + } 114 + 115 + impl_from!(Value::Bool, bool); 116 + impl_from!(Value::Integer, i8); 117 + impl_from!(Value::Integer, i16); 118 + impl_from!(Value::Integer, i32); 119 + impl_from!(Value::Integer, i64); 120 + // i128 omitted because not all numbers fit in CBOR serialization 121 + impl_from!(Value::Integer, u8); 122 + impl_from!(Value::Integer, u16); 123 + impl_from!(Value::Integer, u32); 124 + impl_from!(Value::Integer, u64); 125 + // u128 omitted because not all numbers fit in CBOR serialization 126 + impl_from!(Value::Float, f32); 127 + impl_from!(Value::Float, f64); 128 + impl_from!(Value::Bytes, Vec<u8>); 129 + impl_from!(Value::Text, String); 130 + // TODO: figure out if these impls should be more generic or removed. 131 + impl_from!(Value::Array, Vec<Value>); 132 + impl_from!(Value::Map, BTreeMap<Value, Value>); 133 + 134 + impl Value { 135 + fn major_type(&self) -> u8 { 136 + use self::Value::*; 137 + match self { 138 + Null => 7, 139 + Bool(_) => 7, 140 + Integer(v) if *v < 0 => 1, 141 + Integer(_) => 0, 142 + Tag(_, _) => 6, 143 + Float(_) => 7, 144 + Bytes(_) => 2, 145 + Text(_) => 3, 146 + Array(_) => 4, 147 + Map(_) => 5, 148 + __Hidden => unreachable!(), 149 + } 150 + } 151 + }
+430
vendor/git/cbor/src/value/ser.rs
··· 1 + // Copyright 2017 Serde Developers 2 + // 3 + // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or 4 + // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license 5 + // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your 6 + // option. This file may not be copied, modified, or distributed 7 + // except according to those terms. 8 + 9 + use std::collections::BTreeMap; 10 + 11 + use crate::error::Error; 12 + use serde::{self, Serialize}; 13 + 14 + use crate::tags::Tagged; 15 + use crate::value::Value; 16 + 17 + impl serde::Serialize for Value { 18 + #[inline] 19 + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 20 + where 21 + S: serde::Serializer, 22 + { 23 + match *self { 24 + Value::Integer(v) => serializer.serialize_i128(v), 25 + Value::Bytes(ref v) => serializer.serialize_bytes(v), 26 + Value::Text(ref v) => serializer.serialize_str(v), 27 + Value::Array(ref v) => v.serialize(serializer), 28 + Value::Map(ref v) => v.serialize(serializer), 29 + Value::Tag(tag, ref v) => Tagged::new(Some(tag), v).serialize(serializer), 30 + Value::Float(v) => serializer.serialize_f64(v), 31 + Value::Bool(v) => serializer.serialize_bool(v), 32 + Value::Null => serializer.serialize_unit(), 33 + Value::__Hidden => unreachable!(), 34 + } 35 + } 36 + } 37 + 38 + struct Serializer; 39 + 40 + impl serde::Serializer for Serializer { 41 + type Ok = Value; 42 + type Error = Error; 43 + 44 + type SerializeSeq = SerializeVec; 45 + type SerializeTuple = SerializeVec; 46 + type SerializeTupleStruct = SerializeVec; 47 + type SerializeTupleVariant = SerializeTupleVariant; 48 + type SerializeMap = SerializeMap; 49 + type SerializeStruct = SerializeMap; 50 + type SerializeStructVariant = SerializeStructVariant; 51 + 52 + #[inline] 53 + fn serialize_bool(self, value: bool) -> Result<Value, Error> { 54 + Ok(Value::Bool(value)) 55 + } 56 + 57 + #[inline] 58 + fn serialize_i8(self, value: i8) -> Result<Value, Error> { 59 + self.serialize_i64(i64::from(value)) 60 + } 61 + 62 + #[inline] 63 + fn serialize_i16(self, value: i16) -> Result<Value, Error> { 64 + self.serialize_i64(i64::from(value)) 65 + } 66 + 67 + #[inline] 68 + fn serialize_i32(self, value: i32) -> Result<Value, Error> { 69 + self.serialize_i64(i64::from(value)) 70 + } 71 + 72 + #[inline] 73 + fn serialize_i64(self, value: i64) -> Result<Value, Error> { 74 + self.serialize_i128(i128::from(value)) 75 + } 76 + 77 + fn serialize_i128(self, value: i128) -> Result<Value, Error> { 78 + Ok(Value::Integer(value)) 79 + } 80 + 81 + #[inline] 82 + fn serialize_u8(self, value: u8) -> Result<Value, Error> { 83 + self.serialize_u64(u64::from(value)) 84 + } 85 + 86 + #[inline] 87 + fn serialize_u16(self, value: u16) -> Result<Value, Error> { 88 + self.serialize_u64(u64::from(value)) 89 + } 90 + 91 + #[inline] 92 + fn serialize_u32(self, value: u32) -> Result<Value, Error> { 93 + self.serialize_u64(u64::from(value)) 94 + } 95 + 96 + #[inline] 97 + fn serialize_u64(self, value: u64) -> Result<Value, Error> { 98 + Ok(Value::Integer(value.into())) 99 + } 100 + 101 + #[inline] 102 + fn serialize_f32(self, value: f32) -> Result<Value, Error> { 103 + self.serialize_f64(f64::from(value)) 104 + } 105 + 106 + #[inline] 107 + fn serialize_f64(self, value: f64) -> Result<Value, Error> { 108 + Ok(Value::Float(value)) 109 + } 110 + 111 + #[inline] 112 + fn serialize_char(self, value: char) -> Result<Value, Error> { 113 + let mut s = String::new(); 114 + s.push(value); 115 + self.serialize_str(&s) 116 + } 117 + 118 + #[inline] 119 + fn serialize_str(self, value: &str) -> Result<Value, Error> { 120 + Ok(Value::Text(value.to_owned())) 121 + } 122 + 123 + fn serialize_bytes(self, value: &[u8]) -> Result<Value, Error> { 124 + Ok(Value::Bytes(value.to_vec())) 125 + } 126 + 127 + #[inline] 128 + fn serialize_unit(self) -> Result<Value, Error> { 129 + Ok(Value::Null) 130 + } 131 + 132 + #[inline] 133 + fn serialize_unit_struct(self, _name: &'static str) -> Result<Value, Error> { 134 + self.serialize_unit() 135 + } 136 + 137 + #[inline] 138 + fn serialize_unit_variant( 139 + self, 140 + _name: &'static str, 141 + _variant_index: u32, 142 + variant: &'static str, 143 + ) -> Result<Value, Error> { 144 + self.serialize_str(variant) 145 + } 146 + 147 + #[inline] 148 + fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Value, Error> 149 + where 150 + T: ?Sized + Serialize, 151 + { 152 + value.serialize(self) 153 + } 154 + 155 + fn serialize_newtype_variant<T>( 156 + self, 157 + _name: &'static str, 158 + _variant_index: u32, 159 + variant: &'static str, 160 + value: &T, 161 + ) -> Result<Value, Error> 162 + where 163 + T: ?Sized + Serialize, 164 + { 165 + let mut values = BTreeMap::new(); 166 + values.insert(Value::from(variant.to_owned()), to_value(value)?); 167 + Ok(Value::Map(values)) 168 + } 169 + 170 + #[inline] 171 + fn serialize_none(self) -> Result<Value, Error> { 172 + self.serialize_unit() 173 + } 174 + 175 + #[inline] 176 + fn serialize_some<T>(self, value: &T) -> Result<Value, Error> 177 + where 178 + T: ?Sized + Serialize, 179 + { 180 + value.serialize(self) 181 + } 182 + 183 + fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> { 184 + Ok(SerializeVec { 185 + vec: Vec::with_capacity(len.unwrap_or(0)), 186 + }) 187 + } 188 + 189 + fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Error> { 190 + self.serialize_seq(Some(len)) 191 + } 192 + 193 + fn serialize_tuple_struct( 194 + self, 195 + _name: &'static str, 196 + len: usize, 197 + ) -> Result<Self::SerializeTupleStruct, Error> { 198 + self.serialize_tuple(len) 199 + } 200 + 201 + fn serialize_tuple_variant( 202 + self, 203 + _name: &'static str, 204 + _variant_index: u32, 205 + variant: &'static str, 206 + len: usize, 207 + ) -> Result<Self::SerializeTupleVariant, Error> { 208 + Ok(SerializeTupleVariant { 209 + name: String::from(variant), 210 + vec: Vec::with_capacity(len), 211 + }) 212 + } 213 + 214 + fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Error> { 215 + Ok(SerializeMap { 216 + map: BTreeMap::new(), 217 + next_key: None, 218 + }) 219 + } 220 + 221 + fn serialize_struct( 222 + self, 223 + _name: &'static str, 224 + len: usize, 225 + ) -> Result<Self::SerializeStruct, Error> { 226 + self.serialize_map(Some(len)) 227 + } 228 + 229 + fn serialize_struct_variant( 230 + self, 231 + _name: &'static str, 232 + _variant_index: u32, 233 + variant: &'static str, 234 + _len: usize, 235 + ) -> Result<Self::SerializeStructVariant, Error> { 236 + Ok(SerializeStructVariant { 237 + name: String::from(variant), 238 + map: BTreeMap::new(), 239 + }) 240 + } 241 + 242 + #[inline] 243 + fn is_human_readable(&self) -> bool { 244 + false 245 + } 246 + } 247 + 248 + pub struct SerializeVec { 249 + vec: Vec<Value>, 250 + } 251 + 252 + pub struct SerializeTupleVariant { 253 + name: String, 254 + vec: Vec<Value>, 255 + } 256 + 257 + pub struct SerializeMap { 258 + map: BTreeMap<Value, Value>, 259 + next_key: Option<Value>, 260 + } 261 + 262 + pub struct SerializeStructVariant { 263 + name: String, 264 + map: BTreeMap<Value, Value>, 265 + } 266 + 267 + impl serde::ser::SerializeSeq for SerializeVec { 268 + type Ok = Value; 269 + type Error = Error; 270 + 271 + fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error> 272 + where 273 + T: ?Sized + Serialize, 274 + { 275 + self.vec.push(to_value(value)?); 276 + Ok(()) 277 + } 278 + 279 + fn end(self) -> Result<Value, Error> { 280 + Ok(Value::Array(self.vec)) 281 + } 282 + } 283 + 284 + impl serde::ser::SerializeTuple for SerializeVec { 285 + type Ok = Value; 286 + type Error = Error; 287 + 288 + fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error> 289 + where 290 + T: ?Sized + Serialize, 291 + { 292 + serde::ser::SerializeSeq::serialize_element(self, value) 293 + } 294 + 295 + fn end(self) -> Result<Value, Error> { 296 + serde::ser::SerializeSeq::end(self) 297 + } 298 + } 299 + 300 + impl serde::ser::SerializeTupleStruct for SerializeVec { 301 + type Ok = Value; 302 + type Error = Error; 303 + 304 + fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error> 305 + where 306 + T: ?Sized + Serialize, 307 + { 308 + serde::ser::SerializeSeq::serialize_element(self, value) 309 + } 310 + 311 + fn end(self) -> Result<Value, Error> { 312 + serde::ser::SerializeSeq::end(self) 313 + } 314 + } 315 + 316 + impl serde::ser::SerializeTupleVariant for SerializeTupleVariant { 317 + type Ok = Value; 318 + type Error = Error; 319 + 320 + fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error> 321 + where 322 + T: ?Sized + Serialize, 323 + { 324 + self.vec.push(to_value(value)?); 325 + Ok(()) 326 + } 327 + 328 + fn end(self) -> Result<Value, Error> { 329 + let mut object = BTreeMap::new(); 330 + 331 + object.insert(Value::from(self.name), Value::Array(self.vec)); 332 + 333 + Ok(Value::Map(object)) 334 + } 335 + } 336 + 337 + impl serde::ser::SerializeMap for SerializeMap { 338 + type Ok = Value; 339 + type Error = Error; 340 + 341 + fn serialize_key<T>(&mut self, key: &T) -> Result<(), Error> 342 + where 343 + T: ?Sized + Serialize, 344 + { 345 + self.next_key = Some(to_value(key)?); 346 + Ok(()) 347 + } 348 + 349 + fn serialize_value<T>(&mut self, value: &T) -> Result<(), Error> 350 + where 351 + T: ?Sized + Serialize, 352 + { 353 + let key = self.next_key.take(); 354 + // Panic because this indicates a bug in the program rather than an 355 + // expected failure. 356 + let key = key.expect("serialize_value called before serialize_key"); 357 + self.map.insert(key, to_value(value)?); 358 + Ok(()) 359 + } 360 + 361 + fn end(self) -> Result<Value, Error> { 362 + Ok(Value::Map(self.map)) 363 + } 364 + } 365 + 366 + impl serde::ser::SerializeStruct for SerializeMap { 367 + type Ok = Value; 368 + type Error = Error; 369 + 370 + fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error> 371 + where 372 + T: ?Sized + Serialize, 373 + { 374 + serde::ser::SerializeMap::serialize_key(self, key)?; 375 + serde::ser::SerializeMap::serialize_value(self, value) 376 + } 377 + 378 + fn end(self) -> Result<Value, Error> { 379 + serde::ser::SerializeMap::end(self) 380 + } 381 + } 382 + 383 + impl serde::ser::SerializeStructVariant for SerializeStructVariant { 384 + type Ok = Value; 385 + type Error = Error; 386 + 387 + fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error> 388 + where 389 + T: ?Sized + Serialize, 390 + { 391 + self.map 392 + .insert(Value::from(String::from(key)), to_value(value)?); 393 + Ok(()) 394 + } 395 + 396 + fn end(self) -> Result<Value, Error> { 397 + let mut object = BTreeMap::new(); 398 + 399 + object.insert(Value::from(self.name), Value::Map(self.map)); 400 + 401 + Ok(Value::Map(object)) 402 + } 403 + } 404 + 405 + /// Convert a `T` into `serde_cbor_2::Value` which is an enum that can represent 406 + /// any valid CBOR data. 407 + /// 408 + /// ```rust 409 + /// # use serde::Serialize; 410 + /// #[derive(Serialize)] 411 + /// struct User { 412 + /// fingerprint: String, 413 + /// location: String, 414 + /// } 415 + /// 416 + /// let u = User { 417 + /// fingerprint: "0xF9BA143B95FF6D82".to_owned(), 418 + /// location: "Menlo Park, CA".to_owned(), 419 + /// }; 420 + /// 421 + /// let v = serde_cbor_2::value::to_value(u).unwrap(); 422 + /// ``` 423 + #[allow(clippy::needless_pass_by_value)] 424 + // Taking by value is more friendly to iterator adapters, option and result 425 + pub fn to_value<T>(value: T) -> Result<Value, Error> 426 + where 427 + T: Serialize, 428 + { 429 + value.serialize(Serializer) 430 + }
+175
vendor/git/cbor/src/write.rs
··· 1 + #[cfg(feature = "alloc")] 2 + use alloc::vec::Vec; 3 + #[cfg(not(feature = "std"))] 4 + use core::fmt; 5 + #[cfg(feature = "std")] 6 + use std::io; 7 + 8 + use crate::error; 9 + 10 + #[cfg(not(feature = "unsealed_read_write"))] 11 + /// A sink for serialized CBOR. 12 + /// 13 + /// This trait is similar to the [`Write`]() trait in the standard library, 14 + /// but has a smaller and more general API. 15 + /// 16 + /// Any object implementing `std::io::Write` 17 + /// can be wrapped in an [`IoWrite`](../write/struct.IoWrite.html) that implements 18 + /// this trait for the underlying object. 19 + pub trait Write: private::Sealed { 20 + /// The type of error returned when a write operation fails. 21 + #[doc(hidden)] 22 + type Error: Into<error::Error>; 23 + 24 + /// Attempts to write an entire buffer into this write. 25 + #[doc(hidden)] 26 + fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error>; 27 + } 28 + 29 + #[cfg(feature = "unsealed_read_write")] 30 + /// A sink for serialized CBOR. 31 + /// 32 + /// This trait is similar to the [`Write`]() trait in the standard library, 33 + /// but has a smaller and more general API. 34 + /// 35 + /// Any object implementing `std::io::Write` 36 + /// can be wrapped in an [`IoWrite`](../write/struct.IoWrite.html) that implements 37 + /// this trait for the underlying object. 38 + /// 39 + /// This trait is sealed by default, enabling the `unsealed_read_write` feature removes this bound 40 + /// to allow objects outside of this crate to implement this trait. 41 + pub trait Write { 42 + /// The type of error returned when a write operation fails. 43 + type Error: Into<error::Error>; 44 + 45 + /// Attempts to write an entire buffer into this write. 46 + fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error>; 47 + } 48 + 49 + #[cfg(not(feature = "unsealed_read_write"))] 50 + mod private { 51 + pub trait Sealed {} 52 + } 53 + 54 + impl<W> Write for &mut W 55 + where 56 + W: Write, 57 + { 58 + type Error = W::Error; 59 + 60 + fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> { 61 + (*self).write_all(buf) 62 + } 63 + } 64 + 65 + #[cfg(not(feature = "unsealed_read_write"))] 66 + impl<W> private::Sealed for &mut W where W: Write {} 67 + 68 + #[cfg(feature = "std")] 69 + /// A wrapper for types that implement 70 + /// [`std::io::Write`](https://doc.rust-lang.org/std/io/trait.Write.html) to implement the local 71 + /// [`Write`](trait.Write.html) trait. 72 + #[derive(Debug)] 73 + pub struct IoWrite<W>(W); 74 + 75 + #[cfg(feature = "std")] 76 + impl<W: io::Write> IoWrite<W> { 77 + /// Wraps an `io::Write` writer to make it compatible with [`Write`](trait.Write.html) 78 + pub fn new(w: W) -> IoWrite<W> { 79 + IoWrite(w) 80 + } 81 + } 82 + 83 + #[cfg(feature = "std")] 84 + impl<W: io::Write> Write for IoWrite<W> { 85 + type Error = io::Error; 86 + 87 + fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> { 88 + self.0.write_all(buf) 89 + } 90 + } 91 + 92 + #[cfg(all(feature = "std", not(feature = "unsealed_read_write")))] 93 + impl<W> private::Sealed for IoWrite<W> where W: io::Write {} 94 + 95 + #[cfg(any(feature = "std", feature = "alloc"))] 96 + impl Write for Vec<u8> { 97 + type Error = error::Error; 98 + 99 + fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> { 100 + self.extend_from_slice(buf); 101 + Ok(()) 102 + } 103 + } 104 + 105 + #[cfg(all( 106 + any(feature = "std", feature = "alloc"), 107 + not(feature = "unsealed_read_write") 108 + ))] 109 + impl private::Sealed for Vec<u8> {} 110 + 111 + #[cfg(not(feature = "std"))] 112 + #[derive(Debug)] 113 + pub struct FmtWrite<'a, W: Write>(&'a mut W); 114 + 115 + #[cfg(not(feature = "std"))] 116 + impl<'a, W: Write> FmtWrite<'a, W> { 117 + /// Wraps an `fmt::Write` writer to make it compatible with [`Write`](trait.Write.html) 118 + pub fn new(w: &'a mut W) -> FmtWrite<'a, W> { 119 + FmtWrite(w) 120 + } 121 + } 122 + 123 + #[cfg(not(feature = "std"))] 124 + impl<'a, W: Write> fmt::Write for FmtWrite<'a, W> { 125 + fn write_str(&mut self, s: &str) -> fmt::Result { 126 + self.0.write_all(s.as_bytes()).map_err(|_| fmt::Error) 127 + } 128 + } 129 + 130 + #[cfg(all(not(feature = "std"), not(feature = "unsealed_read_write")))] 131 + impl<'a, W> private::Sealed for FmtWrite<'a, W> where W: Write {} 132 + 133 + /// Implements [`Write`](trait.Write.html) for mutable byte slices (`&mut [u8]`). 134 + /// 135 + /// Returns an error if the value to serialize is too large to fit in the slice. 136 + #[derive(Debug)] 137 + pub struct SliceWrite<'a> { 138 + slice: &'a mut [u8], 139 + index: usize, 140 + } 141 + 142 + impl<'a> SliceWrite<'a> { 143 + /// Wraps a mutable slice so it can be used as a `Write`. 144 + pub fn new(slice: &'a mut [u8]) -> SliceWrite<'a> { 145 + SliceWrite { slice, index: 0 } 146 + } 147 + 148 + /// Returns the number of bytes written to the underlying slice. 149 + pub fn bytes_written(&self) -> usize { 150 + self.index 151 + } 152 + 153 + /// Returns the underlying slice. 154 + pub fn into_inner(self) -> &'a mut [u8] { 155 + self.slice 156 + } 157 + } 158 + 159 + impl Write for SliceWrite<'_> { 160 + type Error = error::Error; 161 + 162 + fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> { 163 + if self.slice.len() - self.index < buf.len() { 164 + // This buffer will not fit in our slice 165 + return Err(error::Error::scratch_too_small(self.index as u64)); 166 + } 167 + let end = self.index + buf.len(); 168 + self.slice[self.index..end].copy_from_slice(buf); 169 + self.index = end; 170 + Ok(()) 171 + } 172 + } 173 + 174 + #[cfg(not(feature = "unsealed_read_write"))] 175 + impl private::Sealed for SliceWrite<'_> {}
+60
vendor/git/cbor/tests/bennofs.rs
··· 1 + #[macro_use] 2 + extern crate serde; 3 + 4 + use serde::Serialize; 5 + use serde_cbor_2::ser::SliceWrite; 6 + use serde_cbor_2::{self, Serializer}; 7 + 8 + #[derive(Debug, PartialEq, Serialize, Deserialize)] 9 + struct Example { 10 + foo: Foo, 11 + payload: u8, 12 + } 13 + 14 + #[derive(Debug, PartialEq, Serialize, Deserialize)] 15 + struct Foo { 16 + x: u8, 17 + color: Color, 18 + } 19 + 20 + #[derive(Debug, PartialEq, Serialize, Deserialize)] 21 + enum Color { 22 + Red, 23 + Blue, 24 + Yellow(u8), 25 + } 26 + 27 + const EXAMPLE: Example = Example { 28 + foo: Foo { 29 + x: 0xAA, 30 + color: Color::Yellow(40), 31 + }, 32 + payload: 0xCC, 33 + }; 34 + 35 + #[cfg(feature = "std")] 36 + mod std_tests { 37 + use super::*; 38 + 39 + #[test] 40 + fn test() { 41 + let serialized = serde_cbor_2::ser::to_vec_packed(&EXAMPLE).expect("bennofs 1"); 42 + println!("{serialized:?}"); 43 + let deserialized: Example = serde_cbor_2::from_slice(&serialized).expect("bennofs 2"); 44 + assert_eq!(EXAMPLE, deserialized); 45 + } 46 + } 47 + 48 + #[test] 49 + fn test() { 50 + let mut slice = [0u8; 64]; 51 + let writer = SliceWrite::new(&mut slice); 52 + let mut serializer = Serializer::new(writer).packed_format(); 53 + EXAMPLE.serialize(&mut serializer).unwrap(); 54 + let writer = serializer.into_inner(); 55 + let end = writer.bytes_written(); 56 + let slice = writer.into_inner(); 57 + let deserialized: Example = 58 + serde_cbor_2::de::from_slice_with_scratch(&slice[..end], &mut []).unwrap(); 59 + assert_eq!(EXAMPLE, deserialized); 60 + }
+104
vendor/git/cbor/tests/canonical.rs
··· 1 + #[cfg(feature = "std")] 2 + mod std_tests { 3 + use serde_cbor_2::value::Value; 4 + 5 + #[test] 6 + fn integer_canonical_sort_order() { 7 + let expected = [ 8 + 0, 9 + 23, 10 + 24, 11 + 255, 12 + 256, 13 + 65535, 14 + 65536, 15 + 4294967295, 16 + -1, 17 + -24, 18 + -25, 19 + -256, 20 + -257, 21 + -65536, 22 + -65537, 23 + -4294967296, 24 + ] 25 + .iter() 26 + .map(|i| Value::Integer(*i)) 27 + .collect::<Vec<_>>(); 28 + 29 + let mut sorted = expected.clone(); 30 + sorted.sort(); 31 + 32 + assert_eq!(expected, sorted); 33 + } 34 + 35 + #[test] 36 + fn string_canonical_sort_order() { 37 + let expected = ["", "a", "b", "aa"] 38 + .iter() 39 + .map(|s| Value::Text(s.to_string())) 40 + .collect::<Vec<_>>(); 41 + 42 + let mut sorted = expected.clone(); 43 + sorted.sort(); 44 + 45 + assert_eq!(expected, sorted); 46 + } 47 + 48 + #[test] 49 + fn bytes_canonical_sort_order() { 50 + let expected = vec![vec![], vec![0u8], vec![1u8], vec![0u8, 0u8]] 51 + .into_iter() 52 + .map(Value::Bytes) 53 + .collect::<Vec<_>>(); 54 + 55 + let mut sorted = expected.clone(); 56 + sorted.sort(); 57 + 58 + assert_eq!(expected, sorted); 59 + } 60 + 61 + #[test] 62 + fn simple_data_canonical_sort_order() { 63 + let expected = vec![Value::Bool(false), Value::Bool(true), Value::Null]; 64 + 65 + let mut sorted = expected.clone(); 66 + sorted.sort(); 67 + 68 + assert_eq!(expected, sorted); 69 + } 70 + 71 + #[test] 72 + fn major_type_canonical_sort_order() { 73 + let expected = vec![ 74 + Value::Integer(0), 75 + Value::Integer(-1), 76 + Value::Bytes(vec![]), 77 + Value::Text("".to_string()), 78 + Value::Null, 79 + ]; 80 + 81 + let mut sorted = expected.clone(); 82 + sorted.sort(); 83 + 84 + assert_eq!(expected, sorted); 85 + } 86 + 87 + #[test] 88 + fn test_rfc_example() { 89 + // See: https://tools.ietf.org/html/draft-ietf-cbor-7049bis-04#section-4.10 90 + let expected = vec![ 91 + Value::Integer(10), 92 + Value::Integer(100), 93 + Value::Integer(-1), 94 + Value::Text("z".to_owned()), 95 + Value::Text("aa".to_owned()), 96 + Value::Array(vec![Value::Integer(100)]), 97 + Value::Array(vec![Value::Integer(-1)]), 98 + Value::Bool(false), 99 + ]; 100 + let mut sorted = expected.clone(); 101 + sorted.sort(); 102 + assert_eq!(expected, sorted); 103 + } 104 + }
vendor/git/cbor/tests/crash.cbor

This is a binary file and will not be displayed.

+754
vendor/git/cbor/tests/de.rs
··· 1 + #[macro_use] 2 + extern crate serde; 3 + 4 + use serde_cbor_2::de; 5 + 6 + #[test] 7 + fn test_str() { 8 + let s: &str = 9 + de::from_slice_with_scratch(&[0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72], &mut []).unwrap(); 10 + assert_eq!(s, "foobar"); 11 + } 12 + 13 + #[test] 14 + fn test_bytes() { 15 + let s: &[u8] = 16 + de::from_slice_with_scratch(&[0x46, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72], &mut []).unwrap(); 17 + assert_eq!(s, b"foobar"); 18 + } 19 + 20 + #[test] 21 + fn test_int() { 22 + let num: i64 = de::from_slice_with_scratch(&[0x39, 0x07, 0xde], &mut []).unwrap(); 23 + assert_eq!(num, -2015); 24 + } 25 + 26 + #[test] 27 + fn test_float() { 28 + let float: f64 = de::from_slice_with_scratch(b"\xfa\x47\xc3\x50\x00", &mut []).unwrap(); 29 + assert_eq!(float, 100000.0); 30 + } 31 + 32 + #[test] 33 + fn test_indefinite_object() { 34 + #[derive(Debug, Deserialize, PartialEq)] 35 + struct Foo { 36 + a: u64, 37 + b: [u64; 2], 38 + } 39 + let expected = Foo { a: 1, b: [2, 3] }; 40 + let actual: Foo = 41 + de::from_slice_with_scratch(b"\xbfaa\x01ab\x9f\x02\x03\xff\xff", &mut []).unwrap(); 42 + assert_eq!(expected, actual); 43 + } 44 + 45 + #[cfg(feature = "std")] 46 + mod std_tests { 47 + use std::collections::BTreeMap; 48 + 49 + use serde::de as serde_de; 50 + use serde_cbor_2::value::Value; 51 + use serde_cbor_2::{de, error, to_vec, Deserializer}; 52 + 53 + #[test] 54 + fn test_string1() { 55 + let value: error::Result<Value> = 56 + de::from_slice(&[0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]); 57 + assert_eq!(value.unwrap(), Value::Text("foobar".to_owned())); 58 + } 59 + 60 + #[test] 61 + fn test_string2() { 62 + let value: error::Result<Value> = de::from_slice(&[ 63 + 0x71, 0x49, 0x20, 0x6d, 0x65, 0x74, 0x20, 0x61, 0x20, 0x74, 0x72, 0x61, 0x76, 0x65, 64 + 0x6c, 0x6c, 0x65, 0x72, 65 + ]); 66 + assert_eq!(value.unwrap(), Value::Text("I met a traveller".to_owned())); 67 + } 68 + 69 + #[test] 70 + fn test_string3() { 71 + let slice = b"\x78\x2fI met a traveller from an antique land who said"; 72 + let value: error::Result<Value> = de::from_slice(slice); 73 + assert_eq!( 74 + value.unwrap(), 75 + Value::Text("I met a traveller from an antique land who said".to_owned()) 76 + ); 77 + } 78 + 79 + #[test] 80 + fn test_byte_string() { 81 + let value: error::Result<Value> = 82 + de::from_slice(&[0x46, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]); 83 + assert_eq!(value.unwrap(), Value::Bytes(b"foobar".to_vec())); 84 + } 85 + 86 + #[test] 87 + fn test_numbers1() { 88 + let value: error::Result<Value> = de::from_slice(&[0x00]); 89 + assert_eq!(value.unwrap(), Value::Integer(0)); 90 + } 91 + 92 + #[test] 93 + fn test_numbers2() { 94 + let value: error::Result<Value> = de::from_slice(&[0x1a, 0x00, 0xbc, 0x61, 0x4e]); 95 + assert_eq!(value.unwrap(), Value::Integer(12345678)); 96 + } 97 + 98 + #[test] 99 + fn test_numbers3() { 100 + let value: error::Result<Value> = de::from_slice(&[0x39, 0x07, 0xde]); 101 + assert_eq!(value.unwrap(), Value::Integer(-2015)); 102 + } 103 + 104 + #[test] 105 + fn test_bool() { 106 + let value: error::Result<Value> = de::from_slice(b"\xf4"); 107 + assert_eq!(value.unwrap(), Value::Bool(false)); 108 + } 109 + 110 + #[test] 111 + fn test_trailing_bytes() { 112 + let value: error::Result<Value> = de::from_slice(b"\xf4trailing"); 113 + assert!(value.is_err()); 114 + } 115 + 116 + #[test] 117 + fn test_list1() { 118 + let value: error::Result<Value> = de::from_slice(b"\x83\x01\x02\x03"); 119 + assert_eq!( 120 + value.unwrap(), 121 + Value::Array(vec![ 122 + Value::Integer(1), 123 + Value::Integer(2), 124 + Value::Integer(3) 125 + ]) 126 + ); 127 + } 128 + 129 + #[test] 130 + fn test_list2() { 131 + let value: error::Result<Value> = de::from_slice(b"\x82\x01\x82\x02\x81\x03"); 132 + assert_eq!( 133 + value.unwrap(), 134 + Value::Array(vec![ 135 + Value::Integer(1), 136 + Value::Array(vec![ 137 + Value::Integer(2), 138 + Value::Array(vec![Value::Integer(3)]) 139 + ]) 140 + ]) 141 + ); 142 + } 143 + 144 + #[test] 145 + fn test_object() { 146 + let value: error::Result<Value> = de::from_slice(b"\xa5aaaAabaBacaCadaDaeaE"); 147 + let mut object = BTreeMap::new(); 148 + object.insert(Value::Text("a".to_owned()), Value::Text("A".to_owned())); 149 + object.insert(Value::Text("b".to_owned()), Value::Text("B".to_owned())); 150 + object.insert(Value::Text("c".to_owned()), Value::Text("C".to_owned())); 151 + object.insert(Value::Text("d".to_owned()), Value::Text("D".to_owned())); 152 + object.insert(Value::Text("e".to_owned()), Value::Text("E".to_owned())); 153 + assert_eq!(value.unwrap(), Value::Map(object)); 154 + } 155 + 156 + #[test] 157 + fn test_indefinite_object() { 158 + let value: error::Result<Value> = de::from_slice(b"\xbfaa\x01ab\x9f\x02\x03\xff\xff"); 159 + let mut object = BTreeMap::new(); 160 + object.insert(Value::Text("a".to_owned()), Value::Integer(1)); 161 + object.insert( 162 + Value::Text("b".to_owned()), 163 + Value::Array(vec![Value::Integer(2), Value::Integer(3)]), 164 + ); 165 + assert_eq!(value.unwrap(), Value::Map(object)); 166 + } 167 + 168 + #[test] 169 + fn test_indefinite_list() { 170 + let value: error::Result<Value> = de::from_slice(b"\x9f\x01\x02\x03\xff"); 171 + assert_eq!( 172 + value.unwrap(), 173 + Value::Array(vec![ 174 + Value::Integer(1), 175 + Value::Integer(2), 176 + Value::Integer(3) 177 + ]) 178 + ); 179 + } 180 + 181 + #[test] 182 + fn test_indefinite_string() { 183 + let value: error::Result<Value> = 184 + de::from_slice(b"\x7f\x65Mary \x64Had \x62a \x67Little \x60\x64Lamb\xff"); 185 + assert_eq!( 186 + value.unwrap(), 187 + Value::Text("Mary Had a Little Lamb".to_owned()) 188 + ); 189 + } 190 + 191 + #[test] 192 + fn test_indefinite_byte_string() { 193 + let value: error::Result<Value> = de::from_slice(b"\x5f\x42\x01\x23\x42\x45\x67\xff"); 194 + assert_eq!(value.unwrap(), Value::Bytes(b"\x01#Eg".to_vec())); 195 + } 196 + 197 + #[test] 198 + fn test_multiple_indefinite_strings() { 199 + let input = b"\x82\x7f\x65Mary \x64Had \x62a \x67Little \x60\x64Lamb\xff\x5f\x42\x01\x23\x42\x45\x67\xff"; 200 + _test_multiple_indefinite_strings(de::from_slice(input)); 201 + _test_multiple_indefinite_strings(de::from_mut_slice(input.to_vec().as_mut())); 202 + let mut buf = [0u8; 64]; 203 + _test_multiple_indefinite_strings(de::from_slice_with_scratch(input, &mut buf)); 204 + } 205 + fn _test_multiple_indefinite_strings(value: error::Result<Value>) { 206 + // This assures that buffer rewinding in infinite buffers works as intended. 207 + assert_eq!( 208 + value.unwrap(), 209 + Value::Array(vec![ 210 + Value::Text("Mary Had a Little Lamb".to_owned()), 211 + Value::Bytes(b"\x01#Eg".to_vec()) 212 + ]) 213 + ); 214 + } 215 + 216 + #[test] 217 + fn test_float() { 218 + let value: error::Result<Value> = de::from_slice(b"\xfa\x47\xc3\x50\x00"); 219 + assert_eq!(value.unwrap(), Value::Float(100000.0)); 220 + } 221 + 222 + #[test] 223 + fn test_self_describing() { 224 + let value: error::Result<Value> = 225 + de::from_slice(&[0xd9, 0xd9, 0xf7, 0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]); 226 + let expected = Value::Text("foobar".to_owned()); 227 + let strip_tags = |x: Value| { 228 + if let Value::Tag(_, inner) = x { 229 + *inner 230 + } else { 231 + x 232 + } 233 + }; 234 + assert_eq!(strip_tags(value.unwrap()), expected); 235 + } 236 + 237 + #[test] 238 + fn test_f16() { 239 + let mut x: Value = de::from_slice(&[0xf9, 0x41, 0x00]).unwrap(); 240 + assert_eq!(x, Value::Float(2.5)); 241 + x = de::from_slice(&[0xf9, 0x41, 0x90]).unwrap(); 242 + assert_eq!(x, Value::Float(2.78125)); 243 + x = de::from_slice(&[0xf9, 0x50, 0x90]).unwrap(); 244 + assert_eq!(x, Value::Float(36.5)); 245 + x = de::from_slice(&[0xf9, 0xd0, 0x90]).unwrap(); 246 + assert_eq!(x, Value::Float(-36.5)); 247 + } 248 + 249 + #[test] 250 + fn test_crazy_list() { 251 + let slice = b"\x88\x1b\x00\x00\x00\x1c\xbe\x99\x1d\xc7\x3b\x00\x7a\xcf\x51\xdc\x51\x70\xdb\x3a\x1b\x3a\x06\xdd\xf5\xf6\xf7\xfb\x41\x76\x5e\xb1\xf8\x00\x00\x00\xf9\x7c\x00"; 252 + let value: Vec<Value> = de::from_slice(slice).unwrap(); 253 + assert_eq!( 254 + value, 255 + vec![ 256 + Value::Integer(123456789959), 257 + Value::Integer(-34567897654325468), 258 + Value::Integer(-456787678), 259 + Value::Bool(true), 260 + Value::Null, 261 + Value::Null, 262 + Value::Float(23456543.5), 263 + Value::Float(f64::INFINITY) 264 + ] 265 + ); 266 + } 267 + 268 + #[test] 269 + fn test_nan() { 270 + let value: f64 = de::from_slice(b"\xf9\x7e\x00").unwrap(); 271 + assert!(value.is_nan()); 272 + } 273 + 274 + #[test] 275 + fn test_32f16() { 276 + let value: f32 = de::from_slice(b"\xf9\x50\x00").unwrap(); 277 + assert_eq!(value, 32.0f32); 278 + } 279 + 280 + #[test] 281 + // The file was reported as not working by user kie0tauB 282 + // but it parses to a cbor value. 283 + fn test_kietaub_file() { 284 + let file = include_bytes!("kietaub.cbor"); 285 + let value_result: error::Result<Value> = de::from_slice(file); 286 + value_result.unwrap(); 287 + } 288 + 289 + #[test] 290 + fn test_option_roundtrip() { 291 + let obj1 = Some(10u32); 292 + 293 + let v = to_vec(&obj1).unwrap(); 294 + let obj2: Result<Option<u32>, _> = serde_cbor_2::de::from_reader(&v[..]); 295 + println!("{obj2:?}"); 296 + 297 + assert_eq!(obj1, obj2.unwrap()); 298 + } 299 + 300 + #[test] 301 + fn test_option_none_roundtrip() { 302 + let obj1 = None; 303 + 304 + let v = to_vec(&obj1).unwrap(); 305 + println!("{v:?}"); 306 + let obj2: Result<Option<u32>, _> = serde_cbor_2::de::from_reader(&v[..]); 307 + 308 + assert_eq!(obj1, obj2.unwrap()); 309 + } 310 + 311 + #[test] 312 + fn test_variable_length_map() { 313 + let slice = b"\xbf\x67\x6d\x65\x73\x73\x61\x67\x65\x64\x70\x6f\x6e\x67\xff"; 314 + let value: Value = de::from_slice(slice).unwrap(); 315 + let mut map = BTreeMap::new(); 316 + map.insert( 317 + Value::Text("message".to_string()), 318 + Value::Text("pong".to_string()), 319 + ); 320 + assert_eq!(value, Value::Map(map)) 321 + } 322 + 323 + #[test] 324 + fn test_object_determinism_roundtrip() { 325 + let expected = b"\xa2aa\x01ab\x82\x02\x03"; 326 + 327 + // 0.1% chance of not catching failure 328 + for _ in 0..10 { 329 + assert_eq!( 330 + &to_vec(&de::from_slice::<Value>(expected).unwrap()).unwrap(), 331 + expected 332 + ); 333 + } 334 + } 335 + 336 + #[test] 337 + fn stream_deserializer() { 338 + let slice = b"\x01\x66foobar"; 339 + let mut it = Deserializer::from_slice(slice).into_iter::<Value>(); 340 + assert_eq!(Value::Integer(1), it.next().unwrap().unwrap()); 341 + assert_eq!( 342 + Value::Text("foobar".to_string()), 343 + it.next().unwrap().unwrap() 344 + ); 345 + assert!(it.next().is_none()); 346 + } 347 + 348 + #[test] 349 + fn stream_deserializer_eof() { 350 + let slice = b"\x01\x66foob"; 351 + let mut it = Deserializer::from_slice(slice).into_iter::<Value>(); 352 + assert_eq!(Value::Integer(1), it.next().unwrap().unwrap()); 353 + assert!(it.next().unwrap().unwrap_err().is_eof()); 354 + } 355 + 356 + #[test] 357 + fn stream_deserializer_eof_in_indefinite() { 358 + let slice = b"\x7f\x65Mary \x64Had \x62a \x60\x67Little \x60\x64Lamb\xff"; 359 + let indices: &[usize] = &[ 360 + 2, // announcement but no data 361 + 10, // mid-buffer EOF 362 + 12, // neither new element nor end marker 363 + ]; 364 + for end_of_slice in indices { 365 + let mut it = Deserializer::from_slice(&slice[..*end_of_slice]).into_iter::<Value>(); 366 + assert!(it.next().unwrap().unwrap_err().is_eof()); 367 + 368 + let mut mutcopy = slice[..*end_of_slice].to_vec(); 369 + let mut it = Deserializer::from_mut_slice(mutcopy.as_mut()).into_iter::<Value>(); 370 + assert!(it.next().unwrap().unwrap_err().is_eof()); 371 + 372 + let mut buf = [0u8; 64]; 373 + let mut it = Deserializer::from_slice_with_scratch(&slice[..*end_of_slice], &mut buf) 374 + .into_iter::<Value>(); 375 + assert!(it.next().unwrap().unwrap_err().is_eof()); 376 + } 377 + } 378 + 379 + #[test] 380 + fn crash() { 381 + let file = include_bytes!("crash.cbor"); 382 + let value_result: error::Result<Value> = de::from_slice(file); 383 + assert_eq!( 384 + value_result.unwrap_err().classify(), 385 + serde_cbor_2::error::Category::Syntax 386 + ); 387 + } 388 + 389 + fn from_slice_stream<'a, T>(slice: &'a [u8]) -> error::Result<(&'a [u8], T)> 390 + where 391 + T: serde_de::Deserialize<'a>, 392 + { 393 + let mut deserializer = Deserializer::from_slice(slice); 394 + let value = serde_de::Deserialize::deserialize(&mut deserializer)?; 395 + let rest = &slice[deserializer.byte_offset()..]; 396 + 397 + Ok((rest, value)) 398 + } 399 + 400 + #[test] 401 + fn test_slice_offset() { 402 + let v: Vec<u8> = vec![ 403 + 0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, 0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, 404 + ]; 405 + let (rest, value): (&[u8], String) = from_slice_stream(&v[..]).unwrap(); 406 + assert_eq!(value, "foobar"); 407 + assert_eq!(rest, &[0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]); 408 + let (rest, value): (&[u8], String) = from_slice_stream(rest).unwrap(); 409 + assert_eq!(value, "foobar"); 410 + assert_eq!(rest, &[]); 411 + } 412 + 413 + #[derive(Debug, Copy, Clone)] 414 + struct Options { 415 + standard: bool, 416 + legacy: bool, 417 + packed: bool, 418 + named: bool, 419 + } 420 + 421 + impl Default for Options { 422 + fn default() -> Self { 423 + Options { 424 + standard: true, 425 + legacy: true, 426 + packed: true, 427 + named: true, 428 + } 429 + } 430 + } 431 + 432 + impl Options { 433 + fn no_standard(self) -> Self { 434 + Options { 435 + standard: false, 436 + ..self 437 + } 438 + } 439 + 440 + fn no_legacy(self) -> Self { 441 + Options { 442 + legacy: false, 443 + ..self 444 + } 445 + } 446 + 447 + fn no_packed(self) -> Self { 448 + Options { 449 + packed: false, 450 + ..self 451 + } 452 + } 453 + 454 + fn no_named(self) -> Self { 455 + Options { 456 + named: false, 457 + ..self 458 + } 459 + } 460 + } 461 + 462 + fn from_slice_stream_options<'a, T>( 463 + slice: &'a [u8], 464 + options: Options, 465 + ) -> error::Result<(&'a [u8], T)> 466 + where 467 + T: serde_de::Deserialize<'a>, 468 + { 469 + let deserializer = Deserializer::from_slice(slice); 470 + let deserializer = if !options.packed { 471 + deserializer.disable_packed_format() 472 + } else { 473 + deserializer 474 + }; 475 + let deserializer = if !options.named { 476 + deserializer.disable_named_format() 477 + } else { 478 + deserializer 479 + }; 480 + let deserializer = if !options.standard { 481 + deserializer.disable_standard_enums() 482 + } else { 483 + deserializer 484 + }; 485 + let mut deserializer = if !options.legacy { 486 + deserializer.disable_legacy_enums() 487 + } else { 488 + deserializer 489 + }; 490 + let value = serde_de::Deserialize::deserialize(&mut deserializer)?; 491 + let rest = &slice[deserializer.byte_offset()..]; 492 + 493 + Ok((rest, value)) 494 + } 495 + 496 + #[test] 497 + fn test_deserializer_enums() { 498 + #[derive(Debug, PartialEq, Deserialize)] 499 + enum Enum { 500 + Unit, 501 + NewType(i32), 502 + Tuple(String, bool), 503 + Struct { x: i32, y: i32 }, 504 + } 505 + 506 + // This is the format used in serde >= 0.10 507 + // 508 + // Serialization of Enum::NewType(10) 509 + let v: Vec<u8> = vec![ 510 + 0xa1, // map 1pair 511 + 0x67, 0x4e, 0x65, 0x77, 0x54, 0x79, 0x70, 0x65, // utf8 string: NewType 512 + 0x1a, // u32 513 + 0x00, 0x00, 0x00, 0x0a, // 10 (dec) 514 + ]; 515 + let (_rest, value): (&[u8], Enum) = from_slice_stream(&v[..]).unwrap(); 516 + assert_eq!(value, Enum::NewType(10)); 517 + let (_rest, value): (&[u8], Enum) = 518 + from_slice_stream_options(&v[..], Options::default().no_legacy()).unwrap(); 519 + assert_eq!(value, Enum::NewType(10)); 520 + let value: error::Result<(&[u8], Enum)> = 521 + from_slice_stream_options(&v[..], Options::default().no_standard()); 522 + assert_eq!( 523 + value.unwrap_err().classify(), 524 + serde_cbor_2::error::Category::Syntax 525 + ); 526 + let value: error::Result<(&[u8], Enum)> = 527 + from_slice_stream_options(&v[..], Options::default().no_standard().no_legacy()); 528 + assert_eq!( 529 + value.unwrap_err().classify(), 530 + serde_cbor_2::error::Category::Syntax 531 + ); 532 + // Serialization of Enum::Unit 533 + let v: Vec<u8> = vec![ 534 + 0x64, 0x55, 0x6e, 0x69, 0x74, // utf8 string: Unit 535 + ]; 536 + let (_rest, value): (&[u8], Enum) = from_slice_stream(&v[..]).unwrap(); 537 + assert_eq!(value, Enum::Unit); 538 + let (_rest, value): (&[u8], Enum) = 539 + from_slice_stream_options(&v[..], Options::default().no_legacy()).unwrap(); 540 + assert_eq!(value, Enum::Unit); 541 + let (_rest, value): (&[u8], Enum) = 542 + from_slice_stream_options(&v[..], Options::default().no_standard()).unwrap(); 543 + assert_eq!(value, Enum::Unit); 544 + let value: error::Result<(&[u8], Enum)> = 545 + from_slice_stream_options(&v[..], Options::default().no_legacy().no_standard()); 546 + assert_eq!( 547 + value.unwrap_err().classify(), 548 + serde_cbor_2::error::Category::Syntax 549 + ); 550 + 551 + // This is the format used in serde <= 0.9 552 + let v: Vec<u8> = vec![ 553 + 0x82, // array 2 items 554 + 0x67, 0x4e, 0x65, 0x77, 0x54, 0x79, 0x70, 0x65, // utf8 string: NewType 555 + 0x1a, // u32 556 + 0x00, 0x00, 0x00, 0x0a, // 10 (dec) 557 + ]; 558 + let (_rest, value): (&[u8], Enum) = from_slice_stream(&v[..]).unwrap(); 559 + assert_eq!(value, Enum::NewType(10)); 560 + let value: error::Result<(&[u8], Enum)> = 561 + from_slice_stream_options(&v[..], Options::default().no_legacy()); 562 + assert_eq!( 563 + value.unwrap_err().classify(), 564 + serde_cbor_2::error::Category::Syntax 565 + ); 566 + let value: error::Result<(&[u8], Enum)> = 567 + from_slice_stream_options(&v[..], Options::default().no_standard()); 568 + assert_eq!(value.unwrap().1, Enum::NewType(10)); 569 + let value: error::Result<(&[u8], Enum)> = 570 + from_slice_stream_options(&v[..], Options::default().no_standard().no_legacy()); 571 + assert_eq!( 572 + value.unwrap_err().classify(), 573 + serde_cbor_2::error::Category::Syntax 574 + ); 575 + } 576 + 577 + #[test] 578 + fn test_packed_deserialization() { 579 + #[derive(Debug, PartialEq, Deserialize)] 580 + struct User { 581 + user_id: u32, 582 + password_hash: [u8; 4], 583 + } 584 + 585 + // unpacked 586 + let v: Vec<u8> = vec![ 587 + 0xa2, // map 2pair 588 + 0x67, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, // utf8 string: user_id 589 + 0x0a, // integer: 10 590 + // utf8 string: password_hash 591 + 0x6d, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x5f, 0x68, 0x61, 0x73, 0x68, 592 + 0x84, 0x01, 0x02, 0x03, 0x04, // 4 byte array [1, 2, 3, 4] 593 + ]; 594 + 595 + let (_rest, value): (&[u8], User) = from_slice_stream(&v[..]).unwrap(); 596 + assert_eq!( 597 + value, 598 + User { 599 + user_id: 10, 600 + password_hash: [1, 2, 3, 4], 601 + } 602 + ); 603 + let (_rest, value): (&[u8], User) = 604 + from_slice_stream_options(&v[..], Options::default().no_packed()).unwrap(); 605 + assert_eq!( 606 + value, 607 + User { 608 + user_id: 10, 609 + password_hash: [1, 2, 3, 4], 610 + } 611 + ); 612 + let value: error::Result<(&[u8], User)> = 613 + from_slice_stream_options(&v[..], Options::default().no_named()); 614 + assert_eq!( 615 + value.unwrap_err().classify(), 616 + serde_cbor_2::error::Category::Syntax 617 + ); 618 + 619 + // unpacked - indefinite length 620 + let v: Vec<u8> = vec![ 621 + 0xbf, // map to be followed by a break 622 + 0x67, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, // utf8 string: user_id 623 + 0x0a, // integer: 10 624 + // utf8 string: password_hash 625 + 0x6d, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x5f, 0x68, 0x61, 0x73, 0x68, 626 + 0x84, 0x01, 0x02, 0x03, 0x04, // 4 byte array [1, 2, 3, 4] 627 + 0xff, // break 628 + ]; 629 + 630 + let (_rest, value): (&[u8], User) = from_slice_stream(&v[..]).unwrap(); 631 + assert_eq!( 632 + value, 633 + User { 634 + user_id: 10, 635 + password_hash: [1, 2, 3, 4], 636 + } 637 + ); 638 + let (_rest, value): (&[u8], User) = 639 + from_slice_stream_options(&v[..], Options::default().no_packed()).unwrap(); 640 + assert_eq!( 641 + value, 642 + User { 643 + user_id: 10, 644 + password_hash: [1, 2, 3, 4], 645 + } 646 + ); 647 + let value: error::Result<(&[u8], User)> = 648 + from_slice_stream_options(&v[..], Options::default().no_named()); 649 + assert_eq!( 650 + value.unwrap_err().classify(), 651 + serde_cbor_2::error::Category::Syntax 652 + ); 653 + 654 + // packed 655 + let v: Vec<u8> = vec![ 656 + 0xa2, // map 2pair 657 + 0x00, // index 0 658 + 0x0a, // integer: 10 659 + 0x01, // index 1 660 + 0x84, 0x01, 0x02, 0x03, 0x04, // 4 byte array [1, 2, 3, 4] 661 + ]; 662 + 663 + let (_rest, value): (&[u8], User) = from_slice_stream(&v[..]).unwrap(); 664 + assert_eq!( 665 + value, 666 + User { 667 + user_id: 10, 668 + password_hash: [1, 2, 3, 4], 669 + } 670 + ); 671 + let (_rest, value): (&[u8], User) = 672 + from_slice_stream_options(&v[..], Options::default().no_named()).unwrap(); 673 + assert_eq!( 674 + value, 675 + User { 676 + user_id: 10, 677 + password_hash: [1, 2, 3, 4], 678 + } 679 + ); 680 + let value: error::Result<(&[u8], User)> = 681 + from_slice_stream_options(&v[..], Options::default().no_packed()); 682 + assert_eq!( 683 + value.unwrap_err().classify(), 684 + serde_cbor_2::error::Category::Syntax 685 + ); 686 + 687 + // packed - indefinite length 688 + let v: Vec<u8> = vec![ 689 + 0xbf, // map, to be followed by a break 690 + 0x00, // index 0 691 + 0x0a, // integer: 10 692 + 0x01, // index 1 693 + 0x84, 0x01, 0x02, 0x03, 0x04, // 4 byte array [1, 2, 3, 4] 694 + 0xff, // break 695 + ]; 696 + 697 + let (_rest, value): (&[u8], User) = from_slice_stream(&v[..]).unwrap(); 698 + assert_eq!( 699 + value, 700 + User { 701 + user_id: 10, 702 + password_hash: [1, 2, 3, 4], 703 + } 704 + ); 705 + let (_rest, value): (&[u8], User) = 706 + from_slice_stream_options(&v[..], Options::default().no_named()).unwrap(); 707 + assert_eq!( 708 + value, 709 + User { 710 + user_id: 10, 711 + password_hash: [1, 2, 3, 4], 712 + } 713 + ); 714 + let value: error::Result<(&[u8], User)> = 715 + from_slice_stream_options(&v[..], Options::default().no_packed()); 716 + assert_eq!( 717 + value.unwrap_err().classify(), 718 + serde_cbor_2::error::Category::Syntax 719 + ); 720 + } 721 + 722 + use serde_cbor_2::{de::from_slice, ser::to_vec_packed}; 723 + use std::net::{IpAddr, Ipv4Addr}; 724 + #[test] 725 + fn test_ipaddr_deserialization() { 726 + let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); 727 + let buf = to_vec_packed(&ip).unwrap(); 728 + let deserialized_ip = from_slice::<IpAddr>(&buf).unwrap(); 729 + assert_eq!(ip, deserialized_ip); 730 + 731 + let buf = to_vec(&ip).unwrap(); 732 + let deserialized_ip = from_slice::<IpAddr>(&buf).unwrap(); 733 + assert_eq!(ip, deserialized_ip); 734 + } 735 + 736 + #[test] 737 + fn attempt_stack_overflow() { 738 + // Create a tag 17, followed by 999 more tag 17: 739 + // 17(17(17(17(17(17(17(17(17(17(17(17(17(17(17(17(17(17(... 740 + // This causes deep recursion in the decoder and may 741 + // exhaust the stack and therfore result in a stack overflow. 742 + let input = vec![0xd1; 1000]; 743 + let err = 744 + serde_cbor_2::from_slice::<serde_cbor_2::Value>(&input).expect_err("recursion limit"); 745 + assert!(err.is_syntax()); 746 + assert!(err.offset() > 0); 747 + 748 + assert!(!err.is_io()); 749 + assert!(!err.is_eof()); 750 + assert!(!err.is_data()); 751 + assert!(!err.is_scratch_too_small()); 752 + assert!(err.is_syntax()); 753 + } 754 + }
+235
vendor/git/cbor/tests/enum.rs
··· 1 + use serde::Serialize; 2 + use serde_cbor_2::ser::{Serializer, SliceWrite}; 3 + 4 + #[macro_use] 5 + extern crate serde; 6 + 7 + #[test] 8 + fn test_simple_data_enum_roundtrip() { 9 + #[derive(Debug, Serialize, Deserialize, PartialEq)] 10 + enum DataEnum { 11 + A(u32), 12 + B(f32), 13 + } 14 + 15 + let a = DataEnum::A(42); 16 + 17 + let mut slice = [0u8; 64]; 18 + let writer = SliceWrite::new(&mut slice); 19 + let mut serializer = Serializer::new(writer); 20 + a.serialize(&mut serializer).unwrap(); 21 + let writer = serializer.into_inner(); 22 + let end = writer.bytes_written(); 23 + let slice = writer.into_inner(); 24 + let deserialized: DataEnum = 25 + serde_cbor_2::de::from_slice_with_scratch(&slice[..end], &mut []).unwrap(); 26 + assert_eq!(a, deserialized); 27 + } 28 + 29 + #[cfg(feature = "std")] 30 + mod std_tests { 31 + use std::collections::BTreeMap; 32 + 33 + use serde_cbor_2::ser::{IoWrite, Serializer}; 34 + use serde_cbor_2::value::Value; 35 + use serde_cbor_2::{from_slice, to_vec}; 36 + 37 + pub fn to_vec_legacy<T>(value: &T) -> serde_cbor_2::Result<Vec<u8>> 38 + where 39 + T: serde::ser::Serialize, 40 + { 41 + let mut vec = Vec::new(); 42 + value.serialize(&mut Serializer::new(&mut IoWrite::new(&mut vec)).legacy_enums())?; 43 + Ok(vec) 44 + } 45 + 46 + #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] 47 + enum Enum { 48 + A, 49 + B, 50 + } 51 + 52 + #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] 53 + struct EnumStruct { 54 + e: Enum, 55 + } 56 + 57 + #[test] 58 + fn test_enum() { 59 + let enum_struct = EnumStruct { e: Enum::B }; 60 + let raw = &to_vec(&enum_struct).unwrap(); 61 + println!("raw enum {raw:?}"); 62 + let re: EnumStruct = from_slice(raw).unwrap(); 63 + assert_eq!(enum_struct, re); 64 + } 65 + 66 + #[repr(u16)] 67 + #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] 68 + enum ReprEnum { 69 + A, 70 + B, 71 + } 72 + 73 + #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] 74 + struct ReprEnumStruct { 75 + e: ReprEnum, 76 + } 77 + 78 + #[test] 79 + fn test_repr_enum() { 80 + let repr_enum_struct = ReprEnumStruct { e: ReprEnum::B }; 81 + let re: ReprEnumStruct = from_slice(&to_vec(&repr_enum_struct).unwrap()).unwrap(); 82 + assert_eq!(repr_enum_struct, re); 83 + } 84 + 85 + #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] 86 + enum DataEnum { 87 + A(u32), 88 + B(bool, u8), 89 + C { x: u8, y: String }, 90 + } 91 + 92 + #[test] 93 + fn test_data_enum() { 94 + let data_enum_a = DataEnum::A(4); 95 + let re_a: DataEnum = from_slice(&to_vec(&data_enum_a).unwrap()).unwrap(); 96 + assert_eq!(data_enum_a, re_a); 97 + let data_enum_b = DataEnum::B(true, 42); 98 + let re_b: DataEnum = from_slice(&to_vec(&data_enum_b).unwrap()).unwrap(); 99 + assert_eq!(data_enum_b, re_b); 100 + let data_enum_c = DataEnum::C { 101 + x: 3, 102 + y: "foo".to_owned(), 103 + }; 104 + println!("{:?}", &to_vec(&data_enum_c).unwrap()); 105 + let re_c: DataEnum = from_slice(&to_vec(&data_enum_c).unwrap()).unwrap(); 106 + assert_eq!(data_enum_c, re_c); 107 + } 108 + 109 + #[test] 110 + fn test_serialize() { 111 + assert_eq!(to_vec_legacy(&Enum::A).unwrap(), &[97, 65]); 112 + assert_eq!(to_vec_legacy(&Enum::B).unwrap(), &[97, 66]); 113 + assert_eq!( 114 + to_vec_legacy(&DataEnum::A(42)).unwrap(), 115 + &[130, 97, 65, 24, 42] 116 + ); 117 + assert_eq!( 118 + to_vec_legacy(&DataEnum::B(true, 9)).unwrap(), 119 + &[131, 97, 66, 245, 9] 120 + ); 121 + } 122 + 123 + #[test] 124 + fn test_newtype_struct() { 125 + #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)] 126 + pub struct Newtype(u8); 127 + assert_eq!(to_vec(&142u8).unwrap(), to_vec(&Newtype(142u8)).unwrap()); 128 + assert_eq!(from_slice::<Newtype>(&[24, 142]).unwrap(), Newtype(142)); 129 + } 130 + 131 + #[derive(Deserialize, PartialEq, Debug)] 132 + enum Foo { 133 + #[serde(rename = "require")] 134 + Require, 135 + } 136 + 137 + #[test] 138 + fn test_variable_length_array() { 139 + let slice = b"\x9F\x67\x72\x65\x71\x75\x69\x72\x65\xFF"; 140 + let value: Vec<Foo> = from_slice(slice).unwrap(); 141 + assert_eq!(value, [Foo::Require]); 142 + } 143 + 144 + #[derive(Serialize, Deserialize, PartialEq, Debug)] 145 + enum Bar { 146 + Empty, 147 + Number(i32), 148 + Flag(String, bool), 149 + Point { x: i32, y: i32 }, 150 + } 151 + 152 + #[test] 153 + fn test_enum_as_map() { 154 + // unit variants serialize like bare strings 155 + let empty_s = to_vec_legacy(&Bar::Empty).unwrap(); 156 + let empty_str_s = to_vec_legacy(&"Empty").unwrap(); 157 + assert_eq!(empty_s, empty_str_s); 158 + 159 + // tuple-variants serialize like ["<variant>", values..] 160 + let number_s = to_vec_legacy(&Bar::Number(42)).unwrap(); 161 + let number_vec = vec![Value::Text("Number".to_string()), Value::Integer(42)]; 162 + let number_vec_s = to_vec_legacy(&number_vec).unwrap(); 163 + assert_eq!(number_s, number_vec_s); 164 + 165 + let flag_s = to_vec_legacy(&Bar::Flag("foo".to_string(), true)).unwrap(); 166 + let flag_vec = vec![ 167 + Value::Text("Flag".to_string()), 168 + Value::Text("foo".to_string()), 169 + Value::Bool(true), 170 + ]; 171 + let flag_vec_s = to_vec_legacy(&flag_vec).unwrap(); 172 + assert_eq!(flag_s, flag_vec_s); 173 + 174 + // struct-variants serialize like ["<variant>", {struct..}] 175 + let point_s = to_vec_legacy(&Bar::Point { x: 5, y: -5 }).unwrap(); 176 + let mut struct_map = BTreeMap::new(); 177 + struct_map.insert(Value::Text("x".to_string()), Value::Integer(5)); 178 + struct_map.insert(Value::Text("y".to_string()), Value::Integer(-5)); 179 + let point_vec = vec![ 180 + Value::Text("Point".to_string()), 181 + Value::Map(struct_map.clone()), 182 + ]; 183 + let point_vec_s = to_vec_legacy(&point_vec).unwrap(); 184 + assert_eq!(point_s, point_vec_s); 185 + 186 + // enum_as_map matches serde_json's default serialization for enums. 187 + 188 + // unit variants still serialize like bare strings 189 + let empty_s = to_vec(&Bar::Empty).unwrap(); 190 + assert_eq!(empty_s, empty_str_s); 191 + 192 + // 1-element tuple variants serialize like {"<variant>": value} 193 + let number_s = to_vec(&Bar::Number(42)).unwrap(); 194 + let mut number_map = BTreeMap::new(); 195 + number_map.insert("Number", 42); 196 + let number_map_s = to_vec(&number_map).unwrap(); 197 + assert_eq!(number_s, number_map_s); 198 + 199 + // multi-element tuple variants serialize like {"<variant>": [values..]} 200 + let flag_s = to_vec(&Bar::Flag("foo".to_string(), true)).unwrap(); 201 + let mut flag_map = BTreeMap::new(); 202 + flag_map.insert( 203 + "Flag", 204 + vec![Value::Text("foo".to_string()), Value::Bool(true)], 205 + ); 206 + let flag_map_s = to_vec(&flag_map).unwrap(); 207 + assert_eq!(flag_s, flag_map_s); 208 + 209 + // struct-variants serialize like {"<variant>", {struct..}} 210 + let point_s = to_vec(&Bar::Point { x: 5, y: -5 }).unwrap(); 211 + let mut point_map = BTreeMap::new(); 212 + point_map.insert("Point", Value::Map(struct_map)); 213 + let point_map_s = to_vec(&point_map).unwrap(); 214 + assert_eq!(point_s, point_map_s); 215 + 216 + // deserialization of all encodings should just work 217 + let empty_str_ds = from_slice(&empty_str_s).unwrap(); 218 + assert_eq!(Bar::Empty, empty_str_ds); 219 + 220 + let number_vec_ds = from_slice(&number_vec_s).unwrap(); 221 + assert_eq!(Bar::Number(42), number_vec_ds); 222 + let number_map_ds = from_slice(&number_map_s).unwrap(); 223 + assert_eq!(Bar::Number(42), number_map_ds); 224 + 225 + let flag_vec_ds = from_slice(&flag_vec_s).unwrap(); 226 + assert_eq!(Bar::Flag("foo".to_string(), true), flag_vec_ds); 227 + let flag_map_ds = from_slice(&flag_map_s).unwrap(); 228 + assert_eq!(Bar::Flag("foo".to_string(), true), flag_map_ds); 229 + 230 + let point_vec_ds = from_slice(&point_vec_s).unwrap(); 231 + assert_eq!(Bar::Point { x: 5, y: -5 }, point_vec_ds); 232 + let point_map_ds = from_slice(&point_map_s).unwrap(); 233 + assert_eq!(Bar::Point { x: 5, y: -5 }, point_map_ds); 234 + } 235 + }
vendor/git/cbor/tests/kietaub.cbor

This is a binary file and will not be displayed.

+254
vendor/git/cbor/tests/ser.rs
··· 1 + use serde::Serialize; 2 + use serde_cbor_2::ser::{Serializer, SliceWrite}; 3 + 4 + #[test] 5 + fn test_str() { 6 + serialize_and_compare("foobar", b"ffoobar"); 7 + } 8 + 9 + #[test] 10 + fn test_list() { 11 + serialize_and_compare([1, 2, 3], b"\x83\x01\x02\x03"); 12 + } 13 + 14 + #[test] 15 + fn test_float() { 16 + serialize_and_compare(12.3f64, b"\xfb@(\x99\x99\x99\x99\x99\x9a"); 17 + } 18 + 19 + #[test] 20 + fn test_integer() { 21 + // u8 22 + serialize_and_compare(24, b"\x18\x18"); 23 + // i8 24 + serialize_and_compare(-5, b"\x24"); 25 + // i16 26 + serialize_and_compare(-300, b"\x39\x01\x2b"); 27 + // i32 28 + serialize_and_compare(-23567997, b"\x3a\x01\x67\x9e\x7c"); 29 + // u64 30 + serialize_and_compare(u64::MAX, b"\x1b\xff\xff\xff\xff\xff\xff\xff\xff"); 31 + } 32 + 33 + fn serialize_and_compare<T: Serialize>(value: T, expected: &[u8]) { 34 + let mut slice = [0u8; 64]; 35 + let writer = SliceWrite::new(&mut slice); 36 + let mut serializer = Serializer::new(writer); 37 + value.serialize(&mut serializer).unwrap(); 38 + let writer = serializer.into_inner(); 39 + let end = writer.bytes_written(); 40 + let slice = writer.into_inner(); 41 + assert_eq!(&slice[..end], expected); 42 + } 43 + 44 + #[cfg(feature = "std")] 45 + mod std_tests { 46 + use serde::Serializer; 47 + use serde_cbor_2::ser; 48 + use serde_cbor_2::{from_slice, to_vec}; 49 + use std::collections::BTreeMap; 50 + 51 + #[test] 52 + fn test_string() { 53 + let value = "foobar".to_owned(); 54 + assert_eq!(&to_vec(&value).unwrap()[..], b"ffoobar"); 55 + } 56 + 57 + #[test] 58 + fn test_list() { 59 + let value = vec![1, 2, 3]; 60 + assert_eq!(&to_vec(&value).unwrap()[..], b"\x83\x01\x02\x03"); 61 + } 62 + 63 + #[test] 64 + fn test_object() { 65 + let mut object = BTreeMap::new(); 66 + object.insert("a".to_owned(), "A".to_owned()); 67 + object.insert("b".to_owned(), "B".to_owned()); 68 + object.insert("c".to_owned(), "C".to_owned()); 69 + object.insert("d".to_owned(), "D".to_owned()); 70 + object.insert("e".to_owned(), "E".to_owned()); 71 + let vec = to_vec(&object).unwrap(); 72 + let test_object = from_slice(&vec[..]).unwrap(); 73 + assert_eq!(object, test_object); 74 + } 75 + 76 + #[test] 77 + fn test_object_list_keys() { 78 + let mut object = BTreeMap::new(); 79 + object.insert(vec![0i64], ()); 80 + object.insert(vec![100i64], ()); 81 + object.insert(vec![-1i64], ()); 82 + object.insert(vec![-2i64], ()); 83 + object.insert(vec![0i64, 0i64], ()); 84 + object.insert(vec![0i64, -1i64], ()); 85 + let vec = to_vec(&serde_cbor_2::value::to_value(object.clone()).unwrap()).unwrap(); 86 + assert_eq!( 87 + vec![ 88 + 166, 129, 0, 246, 129, 24, 100, 246, 129, 32, 246, 129, 33, 246, 130, 0, 0, 246, 89 + 130, 0, 32, 246 90 + ], 91 + vec 92 + ); 93 + let test_object = from_slice(&vec[..]).unwrap(); 94 + assert_eq!(object, test_object); 95 + } 96 + 97 + #[test] 98 + fn test_object_object_keys() { 99 + use std::iter::FromIterator; 100 + let mut object = BTreeMap::new(); 101 + let keys = vec![ 102 + vec!["a"], 103 + vec!["b"], 104 + vec!["c"], 105 + vec!["d"], 106 + vec!["aa"], 107 + vec!["a", "aa"], 108 + ] 109 + .into_iter() 110 + .map(|v| BTreeMap::from_iter(v.into_iter().map(|s| (s.to_owned(), ())))); 111 + 112 + for key in keys { 113 + object.insert(key, ()); 114 + } 115 + let vec = to_vec(&serde_cbor_2::value::to_value(object.clone()).unwrap()).unwrap(); 116 + assert_eq!( 117 + vec![ 118 + 166, 161, 97, 97, 246, 246, 161, 97, 98, 246, 246, 161, 97, 99, 246, 246, 161, 97, 119 + 100, 246, 246, 161, 98, 97, 97, 246, 246, 162, 97, 97, 246, 98, 97, 97, 246, 246 120 + ], 121 + vec 122 + ); 123 + let test_object = from_slice(&vec[..]).unwrap(); 124 + assert_eq!(object, test_object); 125 + } 126 + 127 + #[test] 128 + fn test_float() { 129 + let vec = to_vec(&12.3f64).unwrap(); 130 + assert_eq!(vec, b"\xfb@(\x99\x99\x99\x99\x99\x9a"); 131 + } 132 + 133 + #[test] 134 + fn test_f32() { 135 + let vec = to_vec(&4000.5f32).unwrap(); 136 + assert_eq!(vec, b"\xfa\x45\x7a\x08\x00"); 137 + } 138 + 139 + #[test] 140 + fn test_infinity() { 141 + let vec = to_vec(&f64::INFINITY).unwrap(); 142 + assert_eq!(vec, b"\xf9|\x00"); 143 + } 144 + 145 + #[test] 146 + fn test_neg_infinity() { 147 + let vec = to_vec(&f64::NEG_INFINITY).unwrap(); 148 + assert_eq!(vec, b"\xf9\xfc\x00"); 149 + } 150 + 151 + #[test] 152 + fn test_nan() { 153 + let vec = to_vec(&f32::NAN).unwrap(); 154 + assert_eq!(vec, b"\xf9\x7e\x00"); 155 + } 156 + 157 + #[test] 158 + fn test_integer() { 159 + // u8 160 + let vec = to_vec(&24).unwrap(); 161 + assert_eq!(vec, b"\x18\x18"); 162 + // i8 163 + let vec = to_vec(&-5).unwrap(); 164 + assert_eq!(vec, b"\x24"); 165 + // i16 166 + let vec = to_vec(&-300).unwrap(); 167 + assert_eq!(vec, b"\x39\x01\x2b"); 168 + // i32 169 + let vec = to_vec(&-23567997).unwrap(); 170 + assert_eq!(vec, b"\x3a\x01\x67\x9e\x7c"); 171 + // u64 172 + let vec = to_vec(&u64::MAX).unwrap(); 173 + assert_eq!(vec, b"\x1b\xff\xff\xff\xff\xff\xff\xff\xff"); 174 + } 175 + 176 + #[test] 177 + fn test_self_describing() { 178 + let mut vec = Vec::new(); 179 + { 180 + let mut serializer = ser::Serializer::new(&mut vec); 181 + serializer.self_describe().unwrap(); 182 + serializer.serialize_u64(9).unwrap(); 183 + } 184 + assert_eq!(vec, b"\xd9\xd9\xf7\x09"); 185 + } 186 + 187 + #[test] 188 + fn test_ip_addr() { 189 + use std::net::Ipv4Addr; 190 + 191 + let addr = Ipv4Addr::new(8, 8, 8, 8); 192 + let vec = to_vec(&addr).unwrap(); 193 + println!("{vec:?}"); 194 + assert_eq!(vec.len(), 5); 195 + let test_addr: Ipv4Addr = from_slice(&vec).unwrap(); 196 + assert_eq!(addr, test_addr); 197 + } 198 + 199 + /// Test all of CBOR's fixed-length byte string types 200 + #[test] 201 + fn test_byte_string() { 202 + // Very short byte strings have 1-byte headers 203 + let short = vec![0, 1, 2, 255]; 204 + let mut short_s = Vec::new(); 205 + serde_cbor_2::Serializer::new(&mut short_s) 206 + .serialize_bytes(&short) 207 + .unwrap(); 208 + assert_eq!(&short_s[..], [0x44, 0, 1, 2, 255]); 209 + 210 + // byte strings > 23 bytes have 2-byte headers 211 + let medium = vec![ 212 + 0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 255, 213 + ]; 214 + let mut medium_s = Vec::new(); 215 + serde_cbor_2::Serializer::new(&mut medium_s) 216 + .serialize_bytes(&medium) 217 + .unwrap(); 218 + assert_eq!( 219 + &medium_s[..], 220 + [ 221 + 0x58, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 222 + 21, 22, 255 223 + ] 224 + ); 225 + 226 + // byte strings > 256 bytes have 3-byte headers 227 + let long_vec = (0..256).map(|i| (i & 0xFF) as u8).collect::<Vec<_>>(); 228 + let mut long_s = Vec::new(); 229 + serde_cbor_2::Serializer::new(&mut long_s) 230 + .serialize_bytes(&long_vec) 231 + .unwrap(); 232 + assert_eq!(&long_s[0..3], [0x59, 1, 0]); 233 + assert_eq!(&long_s[3..], &long_vec[..]); 234 + 235 + // byte strings > 2^16 bytes have 5-byte headers 236 + let very_long_vec = (0..65536).map(|i| (i & 0xFF) as u8).collect::<Vec<_>>(); 237 + let mut very_long_s = Vec::new(); 238 + serde_cbor_2::Serializer::new(&mut very_long_s) 239 + .serialize_bytes(&very_long_vec) 240 + .unwrap(); 241 + assert_eq!(&very_long_s[0..5], [0x5a, 0, 1, 0, 0]); 242 + assert_eq!(&very_long_s[5..], &very_long_vec[..]); 243 + 244 + // byte strings > 2^32 bytes have 9-byte headers, but they take too much RAM 245 + // to test in Travis. 246 + } 247 + 248 + #[test] 249 + fn test_half() { 250 + let vec = to_vec(&42.5f32).unwrap(); 251 + assert_eq!(vec, b"\xF9\x51\x50"); 252 + assert_eq!(from_slice::<f32>(&vec[..]).unwrap(), 42.5f32); 253 + } 254 + }
+183
vendor/git/cbor/tests/std_types.rs
··· 1 + #[cfg(feature = "std")] 2 + mod std_tests { 3 + 4 + use serde::{Deserialize, Serialize}; 5 + use serde_cbor_2::de::from_mut_slice; 6 + use serde_cbor_2::ser::{to_vec, to_vec_packed}; 7 + use serde_cbor_2::{from_reader, from_slice}; 8 + 9 + fn to_binary(s: &'static str) -> Vec<u8> { 10 + assert!(s.len() % 2 == 0); 11 + let mut b = Vec::with_capacity(s.len() / 2); 12 + for i in 0..s.len() / 2 { 13 + b.push(u8::from_str_radix(&s[i * 2..(i + 1) * 2], 16).unwrap()); 14 + } 15 + b 16 + } 17 + 18 + macro_rules! testcase { 19 + ($name:ident, f64, $expr:expr, $s:expr) => { 20 + #[test] 21 + fn $name() { 22 + let expr: f64 = $expr; 23 + let mut serialized = to_binary($s); 24 + assert_eq!(to_vec(&expr).unwrap(), serialized); 25 + let parsed: f64 = from_slice(&serialized[..]).unwrap(); 26 + if !expr.is_nan() { 27 + assert_eq!(expr, parsed); 28 + } else { 29 + assert!(parsed.is_nan()) 30 + } 31 + 32 + let parsed: f64 = from_reader(&mut &serialized[..]).unwrap(); 33 + if !expr.is_nan() { 34 + assert_eq!(expr, parsed); 35 + } else { 36 + assert!(parsed.is_nan()) 37 + } 38 + 39 + let parsed: f64 = from_mut_slice(&mut serialized[..]).unwrap(); 40 + if !expr.is_nan() { 41 + assert_eq!(expr, parsed); 42 + } else { 43 + assert!(parsed.is_nan()) 44 + } 45 + } 46 + }; 47 + ($name:ident, $ty:ty, $expr:expr, $s:expr) => { 48 + #[test] 49 + fn $name() { 50 + let expr: $ty = $expr; 51 + let mut serialized = to_binary($s); 52 + assert_eq!( 53 + to_vec(&expr).expect("ser1 works"), 54 + serialized, 55 + "serialization differs" 56 + ); 57 + let parsed: $ty = from_slice(&serialized[..]).expect("de1 works"); 58 + assert_eq!(parsed, expr, "parsed result differs"); 59 + let packed = &to_vec_packed(&expr).expect("serializing packed")[..]; 60 + let parsed_from_packed: $ty = from_slice(packed).expect("parsing packed"); 61 + assert_eq!(parsed_from_packed, expr, "packed roundtrip fail"); 62 + 63 + let parsed: $ty = from_reader(&mut &serialized[..]).unwrap(); 64 + assert_eq!(parsed, expr, "parsed result differs"); 65 + let mut packed = to_vec_packed(&expr).expect("serializing packed"); 66 + let parsed_from_packed: $ty = 67 + from_reader(&mut &packed[..]).expect("parsing packed"); 68 + assert_eq!(parsed_from_packed, expr, "packed roundtrip fail"); 69 + 70 + let parsed: $ty = from_mut_slice(&mut serialized[..]).unwrap(); 71 + assert_eq!(parsed, expr, "parsed result differs"); 72 + let parsed_from_packed: $ty = 73 + from_mut_slice(&mut packed[..]).expect("parsing packed"); 74 + assert_eq!(parsed_from_packed, expr, "packed roundtrip fail"); 75 + } 76 + }; 77 + } 78 + 79 + testcase!(test_bool_false, bool, false, "f4"); 80 + testcase!(test_bool_true, bool, true, "f5"); 81 + testcase!(test_isize_neg_256, isize, -256, "38ff"); 82 + testcase!(test_isize_neg_257, isize, -257, "390100"); 83 + testcase!(test_isize_255, isize, 255, "18ff"); 84 + testcase!(test_i8_5, i8, 5, "05"); 85 + testcase!(test_i8_23, i8, 23, "17"); 86 + testcase!(test_i8_24, i8, 24, "1818"); 87 + testcase!(test_i8_neg_128, i8, -128, "387f"); 88 + testcase!(test_u32_98745874, u32, 98745874, "1a05e2be12"); 89 + testcase!(test_f32_1234_point_5, f32, 1234.5, "fa449a5000"); 90 + testcase!(test_f64_12345_point_6, f64, 12345.6, "fb40c81ccccccccccd"); 91 + testcase!(test_f64_nan, f64, f64::NAN, "f97e00"); 92 + testcase!(test_f64_infinity, f64, f64::INFINITY, "f97c00"); 93 + testcase!(test_f64_neg_infinity, f64, -f64::INFINITY, "f9fc00"); 94 + testcase!(test_char_null, char, '\x00', "6100"); 95 + testcase!(test_char_broken_heart, char, '💔', "64f09f9294"); 96 + testcase!( 97 + test_str_pangram_de, 98 + String, 99 + "aâø↓é".to_owned(), 100 + "6a61c3a2c3b8e28693c3a9" 101 + ); 102 + testcase!(test_unit, (), (), "f6"); 103 + 104 + #[derive(Debug, PartialEq, Deserialize, Serialize)] 105 + struct UnitStruct; 106 + testcase!(test_unit_struct, UnitStruct, UnitStruct, "f6"); 107 + 108 + #[derive(Debug, PartialEq, Deserialize, Serialize)] 109 + struct NewtypeStruct(bool); 110 + testcase!( 111 + test_newtype_struct, 112 + NewtypeStruct, 113 + NewtypeStruct(true), 114 + "f5" 115 + ); 116 + 117 + testcase!(test_option_none, Option<u8>, None, "f6"); 118 + testcase!(test_option_some, Option<u8>, Some(42), "182a"); 119 + 120 + #[derive(Debug, PartialEq, Deserialize, Serialize)] 121 + struct Person { 122 + name: String, 123 + year_of_birth: u16, 124 + profession: Option<String>, 125 + } 126 + 127 + testcase!(test_person_struct, 128 + Person, 129 + Person { 130 + name: "Grace Hopper".to_string(), 131 + year_of_birth: 1906, 132 + profession: Some("computer scientist".to_string()), 133 + }, 134 + "a3646e616d656c477261636520486f707065726d796561725f6f665f62697274681907726a70726f66657373696f6e72636f6d707574657220736369656e74697374"); 135 + 136 + #[derive(Debug, PartialEq, Deserialize, Serialize)] 137 + struct OptionalPerson { 138 + name: String, 139 + #[serde(skip_serializing_if = "Option::is_none")] 140 + year_of_birth: Option<u16>, 141 + profession: Option<String>, 142 + } 143 + 144 + testcase!(test_optional_person_struct, 145 + OptionalPerson, 146 + OptionalPerson { 147 + name: "Grace Hopper".to_string(), 148 + year_of_birth: None, 149 + profession: Some("computer scientist".to_string()), 150 + }, 151 + "a2646e616d656c477261636520486f707065726a70726f66657373696f6e72636f6d707574657220736369656e74697374"); 152 + 153 + #[derive(Debug, PartialEq, Deserialize, Serialize)] 154 + enum Color { 155 + Red, 156 + Blue, 157 + Yellow, 158 + Other(u64), 159 + Alpha(u64, u8), 160 + } 161 + 162 + testcase!(test_color_enum, Color, Color::Blue, "64426c7565"); 163 + testcase!( 164 + test_color_enum_transparent, 165 + Color, 166 + Color::Other(42), 167 + "a1654f74686572182a" 168 + ); 169 + testcase!( 170 + test_color_enum_with_alpha, 171 + Color, 172 + Color::Alpha(234567, 60), 173 + "a165416c706861821a00039447183c" 174 + ); 175 + testcase!(test_i128_a, i128, -1i128, "20"); 176 + testcase!( 177 + test_i128_b, 178 + i128, 179 + -18446744073709551616i128, 180 + "3BFFFFFFFFFFFFFFFF" 181 + ); 182 + testcase!(test_u128, u128, 17, "11"); 183 + }
+48
vendor/git/cbor/tests/tags.rs
··· 1 + #[cfg(feature = "tags")] 2 + mod tagtests { 3 + use serde_cbor_2::value::Value; 4 + use serde_cbor_2::{from_slice, to_vec}; 5 + 6 + fn decode_hex(s: &str) -> std::result::Result<Vec<u8>, std::num::ParseIntError> { 7 + (0..s.len()) 8 + .step_by(2) 9 + .map(|i| u8::from_str_radix(&s[i..i + 2], 16)) 10 + .collect() 11 + } 12 + 13 + // get bytes from http://cbor.me/ trees 14 + fn parse_cbor_me(example: &str) -> std::result::Result<Vec<u8>, std::num::ParseIntError> { 15 + let hex = example 16 + .split('\n') 17 + .flat_map(|line| line.split('#').take(1)) 18 + .collect::<Vec<&str>>() 19 + .join("") 20 + .replace(' ', ""); 21 + decode_hex(&hex) 22 + } 23 + 24 + #[test] 25 + fn tagged_cbor_roundtrip() { 26 + let data = r#" 27 + C1 # tag(1) 28 + 82 # array(2) 29 + C2 # tag(2) 30 + 63 # text(3) 31 + 666F6F # "foo" 32 + C3 # tag(3) 33 + A1 # map(1) 34 + C4 # tag(4) 35 + 61 # text(1) 36 + 61 # "a" 37 + C5 # tag(5) 38 + 61 # text(1) 39 + 62 # "b" 40 + "#; 41 + let bytes1 = parse_cbor_me(data).unwrap(); 42 + let value1: Value = from_slice(&bytes1).unwrap(); 43 + let bytes2 = to_vec(&value1).unwrap(); 44 + let value2: Value = from_slice(&bytes2).unwrap(); 45 + assert_eq!(bytes1, bytes2); 46 + assert_eq!(value1, value2); 47 + } 48 + }
+97
vendor/git/cbor/tests/value.rs
··· 1 + #[cfg(feature = "std")] 2 + mod std_tests { 3 + use std::collections::BTreeMap; 4 + 5 + use serde::{Deserialize, Serialize}; 6 + 7 + #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] 8 + struct TupleStruct(String, i32, u64); 9 + 10 + #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] 11 + struct UnitStruct; 12 + 13 + #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] 14 + struct Struct<'a> { 15 + tuple_struct: TupleStruct, 16 + tuple: (String, f32, f64), 17 + map: BTreeMap<String, String>, 18 + bytes: &'a [u8], 19 + array: Vec<String>, 20 + unit_array: Vec<UnitStruct>, 21 + } 22 + 23 + use serde_cbor_2::value::Value; 24 + use std::iter::FromIterator; 25 + 26 + #[test] 27 + fn serde() { 28 + let tuple_struct = TupleStruct("test".to_owned(), -60, 3000); 29 + 30 + let tuple = ("hello".to_owned(), -50.004_097, -12.094635556478); 31 + 32 + let map = BTreeMap::from_iter( 33 + [ 34 + ("key1".to_owned(), "value1".to_owned()), 35 + ("key2".to_owned(), "value2".to_owned()), 36 + ("key3".to_owned(), "value3".to_owned()), 37 + ("key4".to_owned(), "value4".to_owned()), 38 + ] 39 + .iter() 40 + .cloned(), 41 + ); 42 + 43 + let bytes = b"test byte string"; 44 + 45 + let array = vec![format!("one"), format!("two"), format!("three")]; 46 + let unit_array = vec![UnitStruct, UnitStruct, UnitStruct]; 47 + 48 + let data = Struct { 49 + tuple_struct, 50 + tuple, 51 + map, 52 + bytes, 53 + array, 54 + unit_array, 55 + }; 56 + 57 + let value = serde_cbor_2::value::to_value(data.clone()).unwrap(); 58 + println!("{value:?}"); 59 + 60 + let data_ser = serde_cbor_2::to_vec(&value).unwrap(); 61 + let data_de_value: Value = serde_cbor_2::from_slice(&data_ser).unwrap(); 62 + 63 + fn as_object(value: &Value) -> &BTreeMap<Value, Value> { 64 + if let Value::Map(ref v) = value { 65 + return v; 66 + } 67 + panic!() 68 + } 69 + 70 + for ((k1, v1), (k2, v2)) in as_object(&value) 71 + .iter() 72 + .zip(as_object(&data_de_value).iter()) 73 + { 74 + assert_eq!(k1, k2); 75 + assert_eq!(v1, v2); 76 + } 77 + 78 + assert_eq!(value, data_de_value); 79 + } 80 + 81 + #[derive(Debug, Deserialize, Serialize)] 82 + struct SmallStruct { 83 + spam: u32, 84 + eggs: u32, 85 + } 86 + 87 + #[test] 88 + fn small_struct() { 89 + // Test whether the packed format works. 90 + // Field names should not be serialized, 91 + // instead field indizes are serialized. 92 + let value = SmallStruct { spam: 17, eggs: 42 }; 93 + let data = serde_cbor_2::ser::to_vec_packed(&value).unwrap(); 94 + let reference = b"\xa2\x00\x11\x01\x18\x2a"; 95 + assert_eq!(data, reference); 96 + } 97 + }