···11+# Changelog
22+33+## Unreleased
44+55+- Minimum supported Rust version (MSRV) is now 1.81 due to `half` dependency.
66+77+## 0.11.0
88+99+- TODO
+29
vendor/git/cbor/CONTRIBUTING.md
···11+# Contributing to Serde CBOR
22+Thanks for your interest!
33+There are many ways to help:
44+55+* write an issue about a problem you encountered
66+* submit a pull request
77+* add documentation and examples
88+99+## Pull Requests
1010+1111+Code should be easy to understand and documented.
1212+For new features and fixed bugs please add a test to one of the files in `test/`.
1313+The tests are run on Travis CI to catch regressions early.
1414+Format your code with `cargo fmt` before committing.
1515+Currently Serde CBOR does not contain `unsafe` code and I would like to keep it this way.
1616+1717+## Making a Release
1818+1919+* [ ] Make sure the crate compiles and all tests pass.
2020+* [ ] (Optional) Test that the fuzzer works and fuzz the crate for some time.
2121+* [ ] Write a list with all changes made since the last release
2222+* [ ] 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.
2323+* [ ] Check that the file `examples/readme.rs` and the example from the `README.md` match.
2424+* [ ] Commit the changes.
2525+* [ ] Add a git tag with the new version number:
2626+ `git tag "v42.0.2"`
2727+* [ ] Push the changes: `git push --tags`
2828+* [ ] Run `cargo publish`
2929+* [ ] Add a new release to GitHub with a list of changes.
+34
vendor/git/cbor/Cargo.toml
···11+[package]
22+name = "serde_cbor_2"
33+version = "0.13.0"
44+authors = [
55+ "William Brown <william@blackhats.net.au>",
66+ "James Hodgkinson <james@terminaloutcomes.com>",
77+]
88+repository = "https://github.com/kanidm/cbor"
99+license = "MIT OR Apache-2.0"
1010+description = "CBOR support for Serde."
1111+keywords = ["serde", "cbor", "serialization", "no_std"]
1212+categories = ["encoding"]
1313+edition = "2021"
1414+rust-version = "1.81"
1515+1616+1717+[badges]
1818+maintenance = { status = "passively-maintained" }
1919+2020+[features]
2121+default = ["std"]
2222+# Uses `alloc` library and adds support for vector functions with
2323+# `no_std`.
2424+alloc = ["serde/alloc"]
2525+std = ["serde/std"]
2626+unsealed_read_write = []
2727+tags = []
2828+2929+[dependencies]
3030+half = { version = "2", default-features = false }
3131+serde = { version = "1", default-features = false }
3232+3333+[dev-dependencies]
3434+serde = { version = "1", default-features = false, features = ["derive"] }
+201
vendor/git/cbor/LICENSE-APACHE
···11+ Apache License
22+ Version 2.0, January 2004
33+ http://www.apache.org/licenses/
44+55+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
66+77+1. Definitions.
88+99+ "License" shall mean the terms and conditions for use, reproduction,
1010+ and distribution as defined by Sections 1 through 9 of this document.
1111+1212+ "Licensor" shall mean the copyright owner or entity authorized by
1313+ the copyright owner that is granting the License.
1414+1515+ "Legal Entity" shall mean the union of the acting entity and all
1616+ other entities that control, are controlled by, or are under common
1717+ control with that entity. For the purposes of this definition,
1818+ "control" means (i) the power, direct or indirect, to cause the
1919+ direction or management of such entity, whether by contract or
2020+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
2121+ outstanding shares, or (iii) beneficial ownership of such entity.
2222+2323+ "You" (or "Your") shall mean an individual or Legal Entity
2424+ exercising permissions granted by this License.
2525+2626+ "Source" form shall mean the preferred form for making modifications,
2727+ including but not limited to software source code, documentation
2828+ source, and configuration files.
2929+3030+ "Object" form shall mean any form resulting from mechanical
3131+ transformation or translation of a Source form, including but
3232+ not limited to compiled object code, generated documentation,
3333+ and conversions to other media types.
3434+3535+ "Work" shall mean the work of authorship, whether in Source or
3636+ Object form, made available under the License, as indicated by a
3737+ copyright notice that is included in or attached to the work
3838+ (an example is provided in the Appendix below).
3939+4040+ "Derivative Works" shall mean any work, whether in Source or Object
4141+ form, that is based on (or derived from) the Work and for which the
4242+ editorial revisions, annotations, elaborations, or other modifications
4343+ represent, as a whole, an original work of authorship. For the purposes
4444+ of this License, Derivative Works shall not include works that remain
4545+ separable from, or merely link (or bind by name) to the interfaces of,
4646+ the Work and Derivative Works thereof.
4747+4848+ "Contribution" shall mean any work of authorship, including
4949+ the original version of the Work and any modifications or additions
5050+ to that Work or Derivative Works thereof, that is intentionally
5151+ submitted to Licensor for inclusion in the Work by the copyright owner
5252+ or by an individual or Legal Entity authorized to submit on behalf of
5353+ the copyright owner. For the purposes of this definition, "submitted"
5454+ means any form of electronic, verbal, or written communication sent
5555+ to the Licensor or its representatives, including but not limited to
5656+ communication on electronic mailing lists, source code control systems,
5757+ and issue tracking systems that are managed by, or on behalf of, the
5858+ Licensor for the purpose of discussing and improving the Work, but
5959+ excluding communication that is conspicuously marked or otherwise
6060+ designated in writing by the copyright owner as "Not a Contribution."
6161+6262+ "Contributor" shall mean Licensor and any individual or Legal Entity
6363+ on behalf of whom a Contribution has been received by Licensor and
6464+ subsequently incorporated within the Work.
6565+6666+2. Grant of Copyright License. Subject to the terms and conditions of
6767+ this License, each Contributor hereby grants to You a perpetual,
6868+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
6969+ copyright license to reproduce, prepare Derivative Works of,
7070+ publicly display, publicly perform, sublicense, and distribute the
7171+ Work and such Derivative Works in Source or Object form.
7272+7373+3. Grant of Patent License. Subject to the terms and conditions of
7474+ this License, each Contributor hereby grants to You a perpetual,
7575+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
7676+ (except as stated in this section) patent license to make, have made,
7777+ use, offer to sell, sell, import, and otherwise transfer the Work,
7878+ where such license applies only to those patent claims licensable
7979+ by such Contributor that are necessarily infringed by their
8080+ Contribution(s) alone or by combination of their Contribution(s)
8181+ with the Work to which such Contribution(s) was submitted. If You
8282+ institute patent litigation against any entity (including a
8383+ cross-claim or counterclaim in a lawsuit) alleging that the Work
8484+ or a Contribution incorporated within the Work constitutes direct
8585+ or contributory patent infringement, then any patent licenses
8686+ granted to You under this License for that Work shall terminate
8787+ as of the date such litigation is filed.
8888+8989+4. Redistribution. You may reproduce and distribute copies of the
9090+ Work or Derivative Works thereof in any medium, with or without
9191+ modifications, and in Source or Object form, provided that You
9292+ meet the following conditions:
9393+9494+ (a) You must give any other recipients of the Work or
9595+ Derivative Works a copy of this License; and
9696+9797+ (b) You must cause any modified files to carry prominent notices
9898+ stating that You changed the files; and
9999+100100+ (c) You must retain, in the Source form of any Derivative Works
101101+ that You distribute, all copyright, patent, trademark, and
102102+ attribution notices from the Source form of the Work,
103103+ excluding those notices that do not pertain to any part of
104104+ the Derivative Works; and
105105+106106+ (d) If the Work includes a "NOTICE" text file as part of its
107107+ distribution, then any Derivative Works that You distribute must
108108+ include a readable copy of the attribution notices contained
109109+ within such NOTICE file, excluding those notices that do not
110110+ pertain to any part of the Derivative Works, in at least one
111111+ of the following places: within a NOTICE text file distributed
112112+ as part of the Derivative Works; within the Source form or
113113+ documentation, if provided along with the Derivative Works; or,
114114+ within a display generated by the Derivative Works, if and
115115+ wherever such third-party notices normally appear. The contents
116116+ of the NOTICE file are for informational purposes only and
117117+ do not modify the License. You may add Your own attribution
118118+ notices within Derivative Works that You distribute, alongside
119119+ or as an addendum to the NOTICE text from the Work, provided
120120+ that such additional attribution notices cannot be construed
121121+ as modifying the License.
122122+123123+ You may add Your own copyright statement to Your modifications and
124124+ may provide additional or different license terms and conditions
125125+ for use, reproduction, or distribution of Your modifications, or
126126+ for any such Derivative Works as a whole, provided Your use,
127127+ reproduction, and distribution of the Work otherwise complies with
128128+ the conditions stated in this License.
129129+130130+5. Submission of Contributions. Unless You explicitly state otherwise,
131131+ any Contribution intentionally submitted for inclusion in the Work
132132+ by You to the Licensor shall be under the terms and conditions of
133133+ this License, without any additional terms or conditions.
134134+ Notwithstanding the above, nothing herein shall supersede or modify
135135+ the terms of any separate license agreement you may have executed
136136+ with Licensor regarding such Contributions.
137137+138138+6. Trademarks. This License does not grant permission to use the trade
139139+ names, trademarks, service marks, or product names of the Licensor,
140140+ except as required for reasonable and customary use in describing the
141141+ origin of the Work and reproducing the content of the NOTICE file.
142142+143143+7. Disclaimer of Warranty. Unless required by applicable law or
144144+ agreed to in writing, Licensor provides the Work (and each
145145+ Contributor provides its Contributions) on an "AS IS" BASIS,
146146+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147147+ implied, including, without limitation, any warranties or conditions
148148+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149149+ PARTICULAR PURPOSE. You are solely responsible for determining the
150150+ appropriateness of using or redistributing the Work and assume any
151151+ risks associated with Your exercise of permissions under this License.
152152+153153+8. Limitation of Liability. In no event and under no legal theory,
154154+ whether in tort (including negligence), contract, or otherwise,
155155+ unless required by applicable law (such as deliberate and grossly
156156+ negligent acts) or agreed to in writing, shall any Contributor be
157157+ liable to You for damages, including any direct, indirect, special,
158158+ incidental, or consequential damages of any character arising as a
159159+ result of this License or out of the use or inability to use the
160160+ Work (including but not limited to damages for loss of goodwill,
161161+ work stoppage, computer failure or malfunction, or any and all
162162+ other commercial damages or losses), even if such Contributor
163163+ has been advised of the possibility of such damages.
164164+165165+9. Accepting Warranty or Additional Liability. While redistributing
166166+ the Work or Derivative Works thereof, You may choose to offer,
167167+ and charge a fee for, acceptance of support, warranty, indemnity,
168168+ or other liability obligations and/or rights consistent with this
169169+ License. However, in accepting such obligations, You may act only
170170+ on Your own behalf and on Your sole responsibility, not on behalf
171171+ of any other Contributor, and only if You agree to indemnify,
172172+ defend, and hold each Contributor harmless for any liability
173173+ incurred by, or claims asserted against, such Contributor by reason
174174+ of your accepting any such warranty or additional liability.
175175+176176+END OF TERMS AND CONDITIONS
177177+178178+APPENDIX: How to apply the Apache License to your work.
179179+180180+ To apply the Apache License to your work, attach the following
181181+ boilerplate notice, with the fields enclosed by brackets "[]"
182182+ replaced with your own identifying information. (Don't include
183183+ the brackets!) The text should be enclosed in the appropriate
184184+ comment syntax for the file format. We also recommend that a
185185+ file or class name and description of purpose be included on the
186186+ same "printed page" as the copyright notice for easier
187187+ identification within third-party archives.
188188+189189+Copyright [yyyy] [name of copyright owner]
190190+191191+Licensed under the Apache License, Version 2.0 (the "License");
192192+you may not use this file except in compliance with the License.
193193+You may obtain a copy of the License at
194194+195195+ http://www.apache.org/licenses/LICENSE-2.0
196196+197197+Unless required by applicable law or agreed to in writing, software
198198+distributed under the License is distributed on an "AS IS" BASIS,
199199+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200200+See the License for the specific language governing permissions and
201201+limitations under the License.
+19
vendor/git/cbor/LICENSE-MIT
···11+Copyright (c) 2015 Pyfisch
22+33+Permission is hereby granted, free of charge, to any person obtaining a copy
44+of this software and associated documentation files (the "Software"), to deal
55+in the Software without restriction, including without limitation the rights
66+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
77+copies of the Software, and to permit persons to whom the Software is
88+furnished to do so, subject to the following conditions:
99+1010+The above copyright notice and this permission notice shall be included in
1111+all copies or substantial portions of the Software.
1212+1313+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1414+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1515+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1616+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1717+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1818+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
1919+THE SOFTWARE.
+80
vendor/git/cbor/README.md
···11+# Serde CBOR
22+33+[](https://github.com/kanidm/cbor/actions/workflows/ci.yml)
44+[](https://crates.io/crates/serde_cbor_2)
55+[](https://docs.rs/serde_cbor_2)
66+77+This crate implements the Concise Binary Object Representation from [RFC 7049][rfc7049].
88+It builds on [Serde][serde], the generic serialization framework for Rust.
99+CBOR provides a binary encoding for a superset of the JSON data model that is small and very fast to parse.
1010+1111+## Usage
1212+1313+Serde CBOR supports Rust 1.81 and up. Add this to your `Cargo.toml`:
1414+1515+```toml
1616+[dependencies]
1717+serde_cbor_2 = "0.11.2"
1818+```
1919+2020+Storing and loading Rust types is easy and requires only minimal modifications to the program code.
2121+2222+```rust
2323+use std::{error::Error, fs::File};
2424+use serde::{Deserialize, Serialize};
2525+2626+// Types annotated with `Serialize` can be stored as CBOR.
2727+// To be able to load them again add `Deserialize`.
2828+#[derive(Debug, Serialize, Deserialize)]
2929+struct Mascot {
3030+ name: String,
3131+ species: String,
3232+ year_of_birth: u32,
3333+}
3434+3535+fn main() -> Result<(), Box<dyn Error>> {
3636+ let ferris = Mascot {
3737+ name: "Ferris".to_owned(),
3838+ species: "crab".to_owned(),
3939+ year_of_birth: 2015,
4040+ };
4141+4242+ let ferris_file = File::create("examples/ferris.cbor")?;
4343+ // Write Ferris to the given file.
4444+ // Instead of a file you can use any type that implements `io::Write`
4545+ // like a HTTP body, database connection etc.
4646+ serde_cbor_2::to_writer(ferris_file, &ferris)?;
4747+4848+ let tux_file = File::open("examples/tux.cbor")?;
4949+ // Load Tux from a file.
5050+ // Serde CBOR performs roundtrip serialization meaning that
5151+ // the data will not change in any way.
5252+ let tux: Mascot = serde_cbor_2::from_reader(tux_file)?;
5353+5454+ println!("{tux:?}");
5555+ // prints: Mascot { name: "Tux", species: "penguin", year_of_birth: 1996 }
5656+5757+ Ok(())
5858+}
5959+```
6060+6161+There are a lot of options available to customize the format.
6262+To operate on untyped CBOR values have a look at the `Value` type.
6363+6464+## License
6565+6666+Licensed under either of
6767+6868+- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
6969+- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
7070+7171+at your option.
7272+7373+### Contribution
7474+7575+Unless you explicitly state otherwise, any contribution intentionally submitted
7676+for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any
7777+additional terms or conditions.
7878+7979+[rfc7049]: https://tools.ietf.org/html/rfc7049
8080+[serde]: https://github.com/serde-rs/serde
+38
vendor/git/cbor/examples/readme.rs
···11+// NOTE: This file should be kept in sync with README.md
22+33+use serde::{Deserialize, Serialize};
44+use std::{error::Error, fs::File};
55+66+// Types annotated with `Serialize` can be stored as CBOR.
77+// To be able to load them again add `Deserialize`.
88+#[derive(Debug, Serialize, Deserialize)]
99+struct Mascot {
1010+ name: String,
1111+ species: String,
1212+ year_of_birth: u32,
1313+}
1414+1515+fn main() -> Result<(), Box<dyn Error>> {
1616+ let ferris = Mascot {
1717+ name: "Ferris".to_owned(),
1818+ species: "crab".to_owned(),
1919+ year_of_birth: 2015,
2020+ };
2121+2222+ let ferris_file = File::create("examples/ferris.cbor")?;
2323+ // Write Ferris to the given file.
2424+ // Instead of a file you can use any type that implements `io::Write`
2525+ // like a HTTP body, database connection etc.
2626+ serde_cbor_2::to_writer(ferris_file, &ferris)?;
2727+2828+ let tux_file = File::open("examples/tux.cbor")?;
2929+ // Load Tux from a file.
3030+ // Serde CBOR performs roundtrip serialization meaning that
3131+ // the data will not change in any way.
3232+ let tux: Mascot = serde_cbor_2::from_reader(tux_file)?;
3333+3434+ println!("{tux:?}");
3535+ // prints: Mascot { name: "Tux", species: "penguin", year_of_birth: 1996 }
3636+3737+ Ok(())
3838+}
+81
vendor/git/cbor/examples/tags.rs
···11+use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize};
22+use serde_cbor_2::{tags::Tagged, Value};
33+use std::error::Error;
44+55+/// https://tools.ietf.org/html/rfc7049#section-2.4.1
66+#[derive(Debug, PartialEq)]
77+struct Date(String);
88+99+impl Serialize for Date {
1010+ fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1111+ Tagged::new(Some(0), &self.0).serialize(s)
1212+ }
1313+}
1414+1515+impl<'de> Deserialize<'de> for Date {
1616+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1717+ let tagged = Tagged::<String>::deserialize(deserializer)?;
1818+ match tagged.tag {
1919+ Some(0) | None => Ok(Date(tagged.value)),
2020+ Some(_) => Err(serde::de::Error::custom("unexpected tag")),
2121+ }
2222+ }
2323+}
2424+2525+/// https://tools.ietf.org/html/rfc7049#section-2.4.4.3
2626+#[derive(Debug, PartialEq)]
2727+struct Uri(String);
2828+2929+impl Serialize for Uri {
3030+ fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
3131+ Tagged::new(Some(32), &self.0).serialize(s)
3232+ }
3333+}
3434+impl<'de> Deserialize<'de> for Uri {
3535+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3636+ let tagged = Tagged::<String>::deserialize(deserializer)?;
3737+ match tagged.tag {
3838+ // allow deserialization even if there is no tag. Allows roundtrip via other formats such as json
3939+ Some(0) | None => Ok(Uri(tagged.value)),
4040+ Some(_) => Err(serde::de::Error::custom("unexpected tag")),
4141+ }
4242+ }
4343+}
4444+4545+#[derive(Debug, Serialize, Deserialize, PartialEq)]
4646+struct Bookmark {
4747+ title: String,
4848+ link: Uri,
4949+ created: Date,
5050+}
5151+5252+fn main() -> Result<(), Box<dyn Error>> {
5353+ let bookmark = Bookmark {
5454+ title: "The Example Domain".into(),
5555+ link: Uri("http://example.org/".into()),
5656+ created: Date("2003-12-13T18:30:02Z".into()),
5757+ };
5858+5959+ // serialize the struct to bytes
6060+ let bytes1 = serde_cbor_2::to_vec(&bookmark)?;
6161+ // deserialize to a serde_cbor_2::Value
6262+ let value1: Value = serde_cbor_2::from_slice(&bytes1)?;
6363+ println!("{value1:?}");
6464+ // serialize the value to bytes
6565+ let bytes2 = serde_cbor_2::to_vec(&value1)?;
6666+ // deserialize to a serde_cbor_2::Value
6767+ let value2: Value = serde_cbor_2::from_slice(&bytes2)?;
6868+ println!("{value2:?}");
6969+ // deserialize to a Bookmark
7070+ let result: Bookmark = serde_cbor_2::from_slice(&bytes2)?;
7171+7272+ // check that the roundtrip was successful
7373+ assert_eq!(value1, value2);
7474+ assert_eq!(bookmark, result);
7575+7676+ // check that going via a format that does not support tags does work
7777+ // let json = serde_json::to_vec(&bookmark)?;
7878+ // let result: Bookmark = serde_json::from_slice(&json)?;
7979+ // assert_eq!(bookmark, result);
8080+ Ok(())
8181+}
···11+#!/usr/bin/env python
22+33+import base64
44+import json
55+import sys
66+import os.path
77+88+out_dir = sys.argv[1]
99+os.makedirs(out_dir)
1010+1111+with open("appendix_a.json") as f:
1212+ appendix = json.load(f)
1313+1414+for i, entry in enumerate(appendix):
1515+ buf = base64.b64decode(entry["cbor"])
1616+ with open(os.path.join(out_dir, str(i)), 'wb') as f:
1717+ f.write(buf)
+1359
vendor/git/cbor/src/de.rs
···11+//! Deserialization.
22+33+use core::f32;
44+use core::marker::PhantomData;
55+use core::result;
66+use core::str;
77+use half::f16;
88+use serde::de;
99+#[cfg(feature = "std")]
1010+use std::io;
1111+1212+use crate::error::{Error, ErrorCode, Result};
1313+#[cfg(not(feature = "unsealed_read_write"))]
1414+use crate::read::EitherLifetime;
1515+#[cfg(feature = "unsealed_read_write")]
1616+pub use crate::read::EitherLifetime;
1717+#[cfg(feature = "std")]
1818+pub use crate::read::IoRead;
1919+use crate::read::Offset;
2020+#[cfg(any(feature = "std", feature = "alloc"))]
2121+pub use crate::read::SliceRead;
2222+pub use crate::read::{MutSliceRead, Read, SliceReadFixed};
2323+#[cfg(feature = "tags")]
2424+use crate::tags::set_tag;
2525+/// Decodes a value from CBOR data in a slice.
2626+///
2727+/// # Examples
2828+///
2929+/// Deserialize a `String`
3030+///
3131+/// ```
3232+/// # use serde_cbor_2::de;
3333+/// let v: Vec<u8> = vec![0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72];
3434+/// let value: String = de::from_slice(&v[..]).unwrap();
3535+/// assert_eq!(value, "foobar");
3636+/// ```
3737+///
3838+/// Deserialize a borrowed string with zero copies.
3939+///
4040+/// ```
4141+/// # use serde_cbor_2::de;
4242+/// let v: Vec<u8> = vec![0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72];
4343+/// let value: &str = de::from_slice(&v[..]).unwrap();
4444+/// assert_eq!(value, "foobar");
4545+/// ```
4646+#[cfg(any(feature = "std", feature = "alloc"))]
4747+pub fn from_slice<'a, T>(slice: &'a [u8]) -> Result<T>
4848+where
4949+ T: de::Deserialize<'a>,
5050+{
5151+ let mut deserializer = Deserializer::from_slice(slice);
5252+ let value = de::Deserialize::deserialize(&mut deserializer)?;
5353+ deserializer.end()?;
5454+ Ok(value)
5555+}
5656+5757+// When the "std" feature is enabled there should be little to no need to ever use this function,
5858+// as `from_slice` covers all use cases (at the expense of being less efficient).
5959+/// Decode a value from CBOR data in a mutable slice.
6060+///
6161+/// This can be used in analogy to `from_slice`. Unlike `from_slice`, this will use the slice's
6262+/// mutability to rearrange data in it in order to resolve indefinite byte or text strings without
6363+/// resorting to allocations.
6464+pub fn from_mut_slice<'a, T>(slice: &'a mut [u8]) -> Result<T>
6565+where
6666+ T: de::Deserialize<'a>,
6767+{
6868+ let mut deserializer = Deserializer::from_mut_slice(slice);
6969+ let value = de::Deserialize::deserialize(&mut deserializer)?;
7070+ deserializer.end()?;
7171+ Ok(value)
7272+}
7373+7474+// When the "std" feature is enabled there should be little to no need to ever use this function,
7575+// as `from_slice` covers all use cases and is much more reliable (at the expense of being less
7676+// efficient).
7777+/// Decode a value from CBOR data using a scratch buffer.
7878+///
7979+/// Users should generally prefer to use `from_slice` or `from_mut_slice` over this function,
8080+/// as decoding may fail when the scratch buffer turns out to be too small.
8181+///
8282+/// A realistic use case for this method would be decoding in a `no_std` environment from an
8383+/// immutable slice that is too large to copy.
8484+pub fn from_slice_with_scratch<'a, 'b, T>(slice: &'a [u8], scratch: &'b mut [u8]) -> Result<T>
8585+where
8686+ T: de::Deserialize<'a>,
8787+{
8888+ let mut deserializer = Deserializer::from_slice_with_scratch(slice, scratch);
8989+ let value = de::Deserialize::deserialize(&mut deserializer)?;
9090+ deserializer.end()?;
9191+ Ok(value)
9292+}
9393+9494+/// Decodes a value from CBOR data in a reader.
9595+///
9696+/// # Examples
9797+///
9898+/// Deserialize a `String`
9999+///
100100+/// ```
101101+/// # use serde_cbor_2::de;
102102+/// let v: Vec<u8> = vec![0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72];
103103+/// let value: String = de::from_reader(&v[..]).unwrap();
104104+/// assert_eq!(value, "foobar");
105105+/// ```
106106+///
107107+/// Note that `from_reader` cannot borrow data:
108108+///
109109+/// ```compile_fail
110110+/// # use serde_cbor_2::de;
111111+/// let v: Vec<u8> = vec![0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72];
112112+/// let value: &str = de::from_reader(&v[..]).unwrap();
113113+/// assert_eq!(value, "foobar");
114114+/// ```
115115+#[cfg(feature = "std")]
116116+pub fn from_reader<T, R>(reader: R) -> Result<T>
117117+where
118118+ T: de::DeserializeOwned,
119119+ R: io::Read,
120120+{
121121+ let mut deserializer = Deserializer::from_reader(reader);
122122+ let value = de::Deserialize::deserialize(&mut deserializer)?;
123123+ deserializer.end()?;
124124+ Ok(value)
125125+}
126126+127127+/// A Serde `Deserialize`r of CBOR data.
128128+#[derive(Debug)]
129129+pub struct Deserializer<R> {
130130+ read: R,
131131+ remaining_depth: u8,
132132+ accept_named: bool,
133133+ accept_packed: bool,
134134+ accept_standard_enums: bool,
135135+ accept_legacy_enums: bool,
136136+}
137137+138138+#[cfg(feature = "std")]
139139+impl<R> Deserializer<IoRead<R>>
140140+where
141141+ R: io::Read,
142142+{
143143+ /// Constructs a `Deserializer` which reads from a `Read`er.
144144+ pub fn from_reader(reader: R) -> Deserializer<IoRead<R>> {
145145+ Deserializer::new(IoRead::new(reader))
146146+ }
147147+}
148148+149149+#[cfg(any(feature = "std", feature = "alloc"))]
150150+impl<'a> Deserializer<SliceRead<'a>> {
151151+ /// Constructs a `Deserializer` which reads from a slice.
152152+ ///
153153+ /// Borrowed strings and byte slices will be provided when possible.
154154+ pub fn from_slice(bytes: &'a [u8]) -> Deserializer<SliceRead<'a>> {
155155+ Deserializer::new(SliceRead::new(bytes))
156156+ }
157157+}
158158+159159+impl<'a> Deserializer<MutSliceRead<'a>> {
160160+ /// Constructs a `Deserializer` which reads from a mutable slice that doubles as its own
161161+ /// scratch buffer.
162162+ ///
163163+ /// Borrowed strings and byte slices will be provided even for indefinite strings.
164164+ pub fn from_mut_slice(bytes: &'a mut [u8]) -> Deserializer<MutSliceRead<'a>> {
165165+ Deserializer::new(MutSliceRead::new(bytes))
166166+ }
167167+}
168168+169169+impl<'a, 'b> Deserializer<SliceReadFixed<'a, 'b>> {
170170+ #[doc(hidden)]
171171+ pub fn from_slice_with_scratch(
172172+ bytes: &'a [u8],
173173+ scratch: &'b mut [u8],
174174+ ) -> Deserializer<SliceReadFixed<'a, 'b>> {
175175+ Deserializer::new(SliceReadFixed::new(bytes, scratch))
176176+ }
177177+}
178178+179179+impl<'de, R> Deserializer<R>
180180+where
181181+ R: Read<'de>,
182182+{
183183+ /// Constructs a `Deserializer` from one of the possible serde_cbor_2 input sources.
184184+ ///
185185+ /// `from_slice` and `from_reader` should normally be used instead of this method.
186186+ pub fn new(read: R) -> Self {
187187+ Deserializer {
188188+ read,
189189+ remaining_depth: 128,
190190+ accept_named: true,
191191+ accept_packed: true,
192192+ accept_standard_enums: true,
193193+ accept_legacy_enums: true,
194194+ }
195195+ }
196196+197197+ /// Don't accept named variants and fields.
198198+ pub fn disable_named_format(mut self) -> Self {
199199+ self.accept_named = false;
200200+ self
201201+ }
202202+203203+ /// Don't accept numbered variants and fields.
204204+ pub fn disable_packed_format(mut self) -> Self {
205205+ self.accept_packed = false;
206206+ self
207207+ }
208208+209209+ /// Don't accept the new enum format used by `serde_cbor_2` versions >= v0.10.
210210+ pub fn disable_standard_enums(mut self) -> Self {
211211+ self.accept_standard_enums = false;
212212+ self
213213+ }
214214+215215+ /// Don't accept the old enum format used by `serde_cbor_2` versions <= v0.9.
216216+ pub fn disable_legacy_enums(mut self) -> Self {
217217+ self.accept_legacy_enums = false;
218218+ self
219219+ }
220220+221221+ /// This method should be called after a value has been deserialized to ensure there is no
222222+ /// trailing data in the input source.
223223+ pub fn end(&mut self) -> Result<()> {
224224+ match self.next()? {
225225+ Some(_) => Err(self.error(ErrorCode::TrailingData)),
226226+ None => Ok(()),
227227+ }
228228+ }
229229+230230+ /// Turn a CBOR deserializer into an iterator over values of type T.
231231+ #[allow(clippy::should_implement_trait)] // Trait doesn't allow unconstrained T.
232232+ pub fn into_iter<T>(self) -> StreamDeserializer<'de, R, T>
233233+ where
234234+ T: de::Deserialize<'de>,
235235+ {
236236+ StreamDeserializer {
237237+ de: self,
238238+ output: PhantomData,
239239+ lifetime: PhantomData,
240240+ }
241241+ }
242242+243243+ fn next(&mut self) -> Result<Option<u8>> {
244244+ self.read.next()
245245+ }
246246+247247+ fn peek(&mut self) -> Result<Option<u8>> {
248248+ self.read.peek()
249249+ }
250250+251251+ fn consume(&mut self) {
252252+ self.read.discard();
253253+ }
254254+255255+ fn error(&self, reason: ErrorCode) -> Error {
256256+ let offset = self.read.offset();
257257+ Error::syntax(reason, offset)
258258+ }
259259+260260+ fn parse_u8(&mut self) -> Result<u8> {
261261+ match self.next()? {
262262+ Some(byte) => Ok(byte),
263263+ None => Err(self.error(ErrorCode::EofWhileParsingValue)),
264264+ }
265265+ }
266266+267267+ fn parse_u16(&mut self) -> Result<u16> {
268268+ let mut buf = [0; 2];
269269+ self.read
270270+ .read_into(&mut buf)
271271+ .map(|()| u16::from_be_bytes(buf))
272272+ }
273273+274274+ fn parse_u32(&mut self) -> Result<u32> {
275275+ let mut buf = [0; 4];
276276+ self.read
277277+ .read_into(&mut buf)
278278+ .map(|()| u32::from_be_bytes(buf))
279279+ }
280280+281281+ fn parse_u64(&mut self) -> Result<u64> {
282282+ let mut buf = [0; 8];
283283+ self.read
284284+ .read_into(&mut buf)
285285+ .map(|()| u64::from_be_bytes(buf))
286286+ }
287287+288288+ fn parse_bytes<V>(&mut self, len: usize, visitor: V) -> Result<V::Value>
289289+ where
290290+ V: de::Visitor<'de>,
291291+ {
292292+ match self.read.read(len)? {
293293+ EitherLifetime::Long(buf) => visitor.visit_borrowed_bytes(buf),
294294+ EitherLifetime::Short(buf) => visitor.visit_bytes(buf),
295295+ }
296296+ }
297297+298298+ fn parse_indefinite_bytes<V>(&mut self, visitor: V) -> Result<V::Value>
299299+ where
300300+ V: de::Visitor<'de>,
301301+ {
302302+ self.read.clear_buffer();
303303+ loop {
304304+ let byte = self.parse_u8()?;
305305+ let len = match byte {
306306+ 0x40..=0x57 => byte as usize - 0x40,
307307+ 0x58 => self.parse_u8()? as usize,
308308+ 0x59 => self.parse_u16()? as usize,
309309+ 0x5a => self.parse_u32()? as usize,
310310+ 0x5b => {
311311+ let len = self.parse_u64()?;
312312+ if len > usize::MAX as u64 {
313313+ return Err(self.error(ErrorCode::LengthOutOfRange));
314314+ }
315315+ len as usize
316316+ }
317317+ 0xff => break,
318318+ _ => return Err(self.error(ErrorCode::UnexpectedCode)),
319319+ };
320320+321321+ self.read.read_to_buffer(len)?;
322322+ }
323323+324324+ match self.read.take_buffer() {
325325+ EitherLifetime::Long(buf) => visitor.visit_borrowed_bytes(buf),
326326+ EitherLifetime::Short(buf) => visitor.visit_bytes(buf),
327327+ }
328328+ }
329329+330330+ fn convert_str(buf: &[u8], buf_end_offset: u64) -> Result<&str> {
331331+ match str::from_utf8(buf) {
332332+ Ok(s) => Ok(s),
333333+ Err(e) => {
334334+ let shift = buf.len() - e.valid_up_to();
335335+ let offset = buf_end_offset - shift as u64;
336336+ Err(Error::syntax(ErrorCode::InvalidUtf8, offset))
337337+ }
338338+ }
339339+ }
340340+341341+ fn parse_str<V>(&mut self, len: usize, visitor: V) -> Result<V::Value>
342342+ where
343343+ V: de::Visitor<'de>,
344344+ {
345345+ if let Some(offset) = self.read.offset().checked_add(len as u64) {
346346+ match self.read.read(len)? {
347347+ EitherLifetime::Long(buf) => {
348348+ let s = Self::convert_str(buf, offset)?;
349349+ visitor.visit_borrowed_str(s)
350350+ }
351351+ EitherLifetime::Short(buf) => {
352352+ let s = Self::convert_str(buf, offset)?;
353353+ visitor.visit_str(s)
354354+ }
355355+ }
356356+ } else {
357357+ // An overflow would have occured.
358358+ Err(Error::syntax(
359359+ ErrorCode::LengthOutOfRange,
360360+ self.read.offset(),
361361+ ))
362362+ }
363363+ }
364364+365365+ fn parse_indefinite_str<V>(&mut self, visitor: V) -> Result<V::Value>
366366+ where
367367+ V: de::Visitor<'de>,
368368+ {
369369+ self.read.clear_buffer();
370370+ loop {
371371+ let byte = self.parse_u8()?;
372372+ let len = match byte {
373373+ 0x60..=0x77 => byte as usize - 0x60,
374374+ 0x78 => self.parse_u8()? as usize,
375375+ 0x79 => self.parse_u16()? as usize,
376376+ 0x7a => self.parse_u32()? as usize,
377377+ 0x7b => {
378378+ let len = self.parse_u64()?;
379379+ if len > usize::MAX as u64 {
380380+ return Err(self.error(ErrorCode::LengthOutOfRange));
381381+ }
382382+ len as usize
383383+ }
384384+ 0xff => break,
385385+ _ => return Err(self.error(ErrorCode::UnexpectedCode)),
386386+ };
387387+388388+ self.read.read_to_buffer(len)?;
389389+ }
390390+391391+ let offset = self.read.offset();
392392+ match self.read.take_buffer() {
393393+ EitherLifetime::Long(buf) => {
394394+ let s = Self::convert_str(buf, offset)?;
395395+ visitor.visit_borrowed_str(s)
396396+ }
397397+ EitherLifetime::Short(buf) => {
398398+ let s = Self::convert_str(buf, offset)?;
399399+ visitor.visit_str(s)
400400+ }
401401+ }
402402+ }
403403+404404+ #[cfg(feature = "tags")]
405405+ fn handle_tagged_value<V>(&mut self, tag: u64, visitor: V) -> Result<V::Value>
406406+ where
407407+ V: de::Visitor<'de>,
408408+ {
409409+ self.recursion_checked(|d| {
410410+ set_tag(Some(tag));
411411+ let r = visitor.visit_newtype_struct(d);
412412+ set_tag(None);
413413+ r
414414+ })
415415+ }
416416+417417+ #[cfg(not(feature = "tags"))]
418418+ fn handle_tagged_value<V>(&mut self, _tag: u64, visitor: V) -> Result<V::Value>
419419+ where
420420+ V: de::Visitor<'de>,
421421+ {
422422+ self.recursion_checked(|de| de.parse_value(visitor))
423423+ }
424424+425425+ fn recursion_checked<F, T>(&mut self, f: F) -> Result<T>
426426+ where
427427+ F: FnOnce(&mut Deserializer<R>) -> Result<T>,
428428+ {
429429+ self.remaining_depth -= 1;
430430+ if self.remaining_depth == 0 {
431431+ return Err(self.error(ErrorCode::RecursionLimitExceeded));
432432+ }
433433+ let r = f(self);
434434+ self.remaining_depth += 1;
435435+ r
436436+ }
437437+438438+ fn parse_array<V>(&mut self, mut len: usize, visitor: V) -> Result<V::Value>
439439+ where
440440+ V: de::Visitor<'de>,
441441+ {
442442+ self.recursion_checked(|de| {
443443+ let value = visitor.visit_seq(SeqAccess { de, len: &mut len })?;
444444+445445+ if len != 0 {
446446+ Err(de.error(ErrorCode::TrailingData))
447447+ } else {
448448+ Ok(value)
449449+ }
450450+ })
451451+ }
452452+453453+ fn parse_indefinite_array<V>(&mut self, visitor: V) -> Result<V::Value>
454454+ where
455455+ V: de::Visitor<'de>,
456456+ {
457457+ self.recursion_checked(|de| {
458458+ let value = visitor.visit_seq(IndefiniteSeqAccess { de })?;
459459+ match de.next()? {
460460+ Some(0xff) => Ok(value),
461461+ Some(_) => Err(de.error(ErrorCode::TrailingData)),
462462+ None => Err(de.error(ErrorCode::EofWhileParsingArray)),
463463+ }
464464+ })
465465+ }
466466+467467+ fn parse_map<V>(&mut self, mut len: usize, visitor: V) -> Result<V::Value>
468468+ where
469469+ V: de::Visitor<'de>,
470470+ {
471471+ let accept_packed = self.accept_packed;
472472+ let accept_named = self.accept_named;
473473+ self.recursion_checked(|de| {
474474+ let value = visitor.visit_map(MapAccess {
475475+ de,
476476+ len: &mut len,
477477+ accept_named,
478478+ accept_packed,
479479+ })?;
480480+481481+ if len != 0 {
482482+ Err(de.error(ErrorCode::TrailingData))
483483+ } else {
484484+ Ok(value)
485485+ }
486486+ })
487487+ }
488488+489489+ fn parse_indefinite_map<V>(&mut self, visitor: V) -> Result<V::Value>
490490+ where
491491+ V: de::Visitor<'de>,
492492+ {
493493+ let accept_named = self.accept_named;
494494+ let accept_packed = self.accept_packed;
495495+ self.recursion_checked(|de| {
496496+ let value = visitor.visit_map(IndefiniteMapAccess {
497497+ de,
498498+ accept_packed,
499499+ accept_named,
500500+ })?;
501501+ match de.next()? {
502502+ Some(0xff) => Ok(value),
503503+ Some(_) => Err(de.error(ErrorCode::TrailingData)),
504504+ None => Err(de.error(ErrorCode::EofWhileParsingMap)),
505505+ }
506506+ })
507507+ }
508508+509509+ fn parse_enum<V>(&mut self, mut len: usize, visitor: V) -> Result<V::Value>
510510+ where
511511+ V: de::Visitor<'de>,
512512+ {
513513+ self.recursion_checked(|de| {
514514+ let value = visitor.visit_enum(VariantAccess {
515515+ seq: SeqAccess { de, len: &mut len },
516516+ })?;
517517+518518+ if len != 0 {
519519+ Err(de.error(ErrorCode::TrailingData))
520520+ } else {
521521+ Ok(value)
522522+ }
523523+ })
524524+ }
525525+526526+ fn parse_enum_map<V>(&mut self, visitor: V) -> Result<V::Value>
527527+ where
528528+ V: de::Visitor<'de>,
529529+ {
530530+ let accept_named = self.accept_named;
531531+ let accept_packed = self.accept_packed;
532532+ self.recursion_checked(|de| {
533533+ let mut len = 1;
534534+ let value = visitor.visit_enum(VariantAccessMap {
535535+ map: MapAccess {
536536+ de,
537537+ len: &mut len,
538538+ accept_packed,
539539+ accept_named,
540540+ },
541541+ })?;
542542+543543+ if len != 0 {
544544+ Err(de.error(ErrorCode::TrailingData))
545545+ } else {
546546+ Ok(value)
547547+ }
548548+ })
549549+ }
550550+551551+ fn parse_indefinite_enum<V>(&mut self, visitor: V) -> Result<V::Value>
552552+ where
553553+ V: de::Visitor<'de>,
554554+ {
555555+ self.recursion_checked(|de| {
556556+ let value = visitor.visit_enum(VariantAccess {
557557+ seq: IndefiniteSeqAccess { de },
558558+ })?;
559559+ match de.next()? {
560560+ Some(0xff) => Ok(value),
561561+ Some(_) => Err(de.error(ErrorCode::TrailingData)),
562562+ None => Err(de.error(ErrorCode::EofWhileParsingArray)),
563563+ }
564564+ })
565565+ }
566566+567567+ fn parse_f16(&mut self) -> Result<f32> {
568568+ Ok(f32::from(f16::from_bits(self.parse_u16()?)))
569569+ }
570570+571571+ fn parse_f32(&mut self) -> Result<f32> {
572572+ self.parse_u32().map(f32::from_bits)
573573+ }
574574+575575+ fn parse_f64(&mut self) -> Result<f64> {
576576+ self.parse_u64().map(f64::from_bits)
577577+ }
578578+579579+ // Don't warn about the `unreachable!` in case
580580+ // exhaustive integer pattern matching is enabled.
581581+ #[allow(unreachable_patterns)]
582582+ fn parse_value<V>(&mut self, visitor: V) -> Result<V::Value>
583583+ where
584584+ V: de::Visitor<'de>,
585585+ {
586586+ let byte = self.parse_u8()?;
587587+ match byte {
588588+ // Major type 0: an unsigned integer
589589+ 0x00..=0x17 => visitor.visit_u8(byte),
590590+ 0x18 => {
591591+ let value = self.parse_u8()?;
592592+ visitor.visit_u8(value)
593593+ }
594594+ 0x19 => {
595595+ let value = self.parse_u16()?;
596596+ visitor.visit_u16(value)
597597+ }
598598+ 0x1a => {
599599+ let value = self.parse_u32()?;
600600+ visitor.visit_u32(value)
601601+ }
602602+ 0x1b => {
603603+ let value = self.parse_u64()?;
604604+ visitor.visit_u64(value)
605605+ }
606606+ 0x1c..=0x1f => Err(self.error(ErrorCode::UnassignedCode)),
607607+608608+ // Major type 1: a negative integer
609609+ 0x20..=0x37 => visitor.visit_i8(-1 - (byte - 0x20) as i8),
610610+ 0x38 => {
611611+ let value = self.parse_u8()?;
612612+ visitor.visit_i16(-1 - i16::from(value))
613613+ }
614614+ 0x39 => {
615615+ let value = self.parse_u16()?;
616616+ visitor.visit_i32(-1 - i32::from(value))
617617+ }
618618+ 0x3a => {
619619+ let value = self.parse_u32()?;
620620+ visitor.visit_i64(-1 - i64::from(value))
621621+ }
622622+ 0x3b => {
623623+ let value = self.parse_u64()?;
624624+ if value > i64::MAX as u64 {
625625+ return visitor.visit_i128(-1 - i128::from(value));
626626+ }
627627+ visitor.visit_i64(-1 - value as i64)
628628+ }
629629+ 0x3c..=0x3f => Err(self.error(ErrorCode::UnassignedCode)),
630630+631631+ // Major type 2: a byte string
632632+ 0x40..=0x57 => self.parse_bytes(byte as usize - 0x40, visitor),
633633+ 0x58 => {
634634+ let len = self.parse_u8()?;
635635+ self.parse_bytes(len as usize, visitor)
636636+ }
637637+ 0x59 => {
638638+ let len = self.parse_u16()?;
639639+ self.parse_bytes(len as usize, visitor)
640640+ }
641641+ 0x5a => {
642642+ let len = self.parse_u32()?;
643643+ self.parse_bytes(len as usize, visitor)
644644+ }
645645+ 0x5b => {
646646+ let len = self.parse_u64()?;
647647+ if len > usize::MAX as u64 {
648648+ return Err(self.error(ErrorCode::LengthOutOfRange));
649649+ }
650650+ self.parse_bytes(len as usize, visitor)
651651+ }
652652+ 0x5c..=0x5e => Err(self.error(ErrorCode::UnassignedCode)),
653653+ 0x5f => self.parse_indefinite_bytes(visitor),
654654+655655+ // Major type 3: a text string
656656+ 0x60..=0x77 => self.parse_str(byte as usize - 0x60, visitor),
657657+ 0x78 => {
658658+ let len = self.parse_u8()?;
659659+ self.parse_str(len as usize, visitor)
660660+ }
661661+ 0x79 => {
662662+ let len = self.parse_u16()?;
663663+ self.parse_str(len as usize, visitor)
664664+ }
665665+ 0x7a => {
666666+ let len = self.parse_u32()?;
667667+ self.parse_str(len as usize, visitor)
668668+ }
669669+ 0x7b => {
670670+ let len = self.parse_u64()?;
671671+ if len > usize::MAX as u64 {
672672+ return Err(self.error(ErrorCode::LengthOutOfRange));
673673+ }
674674+ self.parse_str(len as usize, visitor)
675675+ }
676676+ 0x7c..=0x7e => Err(self.error(ErrorCode::UnassignedCode)),
677677+ 0x7f => self.parse_indefinite_str(visitor),
678678+679679+ // Major type 4: an array of data items
680680+ 0x80..=0x97 => self.parse_array(byte as usize - 0x80, visitor),
681681+ 0x98 => {
682682+ let len = self.parse_u8()?;
683683+ self.parse_array(len as usize, visitor)
684684+ }
685685+ 0x99 => {
686686+ let len = self.parse_u16()?;
687687+ self.parse_array(len as usize, visitor)
688688+ }
689689+ 0x9a => {
690690+ let len = self.parse_u32()?;
691691+ self.parse_array(len as usize, visitor)
692692+ }
693693+ 0x9b => {
694694+ let len = self.parse_u64()?;
695695+ if len > usize::MAX as u64 {
696696+ return Err(self.error(ErrorCode::LengthOutOfRange));
697697+ }
698698+ self.parse_array(len as usize, visitor)
699699+ }
700700+ 0x9c..=0x9e => Err(self.error(ErrorCode::UnassignedCode)),
701701+ 0x9f => self.parse_indefinite_array(visitor),
702702+703703+ // Major type 5: a map of pairs of data items
704704+ 0xa0..=0xb7 => self.parse_map(byte as usize - 0xa0, visitor),
705705+ 0xb8 => {
706706+ let len = self.parse_u8()?;
707707+ self.parse_map(len as usize, visitor)
708708+ }
709709+ 0xb9 => {
710710+ let len = self.parse_u16()?;
711711+ self.parse_map(len as usize, visitor)
712712+ }
713713+ 0xba => {
714714+ let len = self.parse_u32()?;
715715+ self.parse_map(len as usize, visitor)
716716+ }
717717+ 0xbb => {
718718+ let len = self.parse_u64()?;
719719+ if len > usize::MAX as u64 {
720720+ return Err(self.error(ErrorCode::LengthOutOfRange));
721721+ }
722722+ self.parse_map(len as usize, visitor)
723723+ }
724724+ 0xbc..=0xbe => Err(self.error(ErrorCode::UnassignedCode)),
725725+ 0xbf => self.parse_indefinite_map(visitor),
726726+727727+ // Major type 6: optional semantic tagging of other major types
728728+ 0xc0..=0xd7 => {
729729+ let tag = u64::from(byte) - 0xc0;
730730+ self.handle_tagged_value(tag, visitor)
731731+ }
732732+ 0xd8 => {
733733+ let tag = self.parse_u8()?;
734734+ self.handle_tagged_value(tag.into(), visitor)
735735+ }
736736+ 0xd9 => {
737737+ let tag = self.parse_u16()?;
738738+ self.handle_tagged_value(tag.into(), visitor)
739739+ }
740740+ 0xda => {
741741+ let tag = self.parse_u32()?;
742742+ self.handle_tagged_value(tag.into(), visitor)
743743+ }
744744+ 0xdb => {
745745+ let tag = self.parse_u64()?;
746746+ self.handle_tagged_value(tag, visitor)
747747+ }
748748+ 0xdc..=0xdf => Err(self.error(ErrorCode::UnassignedCode)),
749749+750750+ // Major type 7: floating-point numbers and other simple data types that need no content
751751+ 0xe0..=0xf3 => Err(self.error(ErrorCode::UnassignedCode)),
752752+ 0xf4 => visitor.visit_bool(false),
753753+ 0xf5 => visitor.visit_bool(true),
754754+ 0xf6 => visitor.visit_unit(),
755755+ 0xf7 => visitor.visit_unit(),
756756+ 0xf8 => Err(self.error(ErrorCode::UnassignedCode)),
757757+ 0xf9 => {
758758+ let value = self.parse_f16()?;
759759+ visitor.visit_f32(value)
760760+ }
761761+ 0xfa => {
762762+ let value = self.parse_f32()?;
763763+ visitor.visit_f32(value)
764764+ }
765765+ 0xfb => {
766766+ let value = self.parse_f64()?;
767767+ visitor.visit_f64(value)
768768+ }
769769+ 0xfc..=0xfe => Err(self.error(ErrorCode::UnassignedCode)),
770770+ 0xff => Err(self.error(ErrorCode::UnexpectedCode)),
771771+772772+ _ => unreachable!(),
773773+ }
774774+ }
775775+}
776776+777777+impl<'de, R> de::Deserializer<'de> for &mut Deserializer<R>
778778+where
779779+ R: Read<'de>,
780780+{
781781+ type Error = Error;
782782+783783+ #[inline]
784784+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
785785+ where
786786+ V: de::Visitor<'de>,
787787+ {
788788+ self.parse_value(visitor)
789789+ }
790790+791791+ #[inline]
792792+ fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
793793+ where
794794+ V: de::Visitor<'de>,
795795+ {
796796+ match self.peek()? {
797797+ Some(0xf6) => {
798798+ self.consume();
799799+ visitor.visit_none()
800800+ }
801801+ _ => visitor.visit_some(self),
802802+ }
803803+ }
804804+805805+ #[inline]
806806+ fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value>
807807+ where
808808+ V: de::Visitor<'de>,
809809+ {
810810+ visitor.visit_newtype_struct(self)
811811+ }
812812+813813+ // Unit variants are encoded as just the variant identifier.
814814+ // Tuple variants are encoded as an array of the variant identifier followed by the fields.
815815+ // Struct variants are encoded as an array of the variant identifier followed by the struct.
816816+ #[inline]
817817+ fn deserialize_enum<V>(
818818+ self,
819819+ _name: &str,
820820+ _variants: &'static [&'static str],
821821+ visitor: V,
822822+ ) -> Result<V::Value>
823823+ where
824824+ V: de::Visitor<'de>,
825825+ {
826826+ match self.peek()? {
827827+ Some(byte @ 0x80..=0x9f) => {
828828+ if !self.accept_legacy_enums {
829829+ return Err(self.error(ErrorCode::WrongEnumFormat));
830830+ }
831831+ self.consume();
832832+ match byte {
833833+ 0x80..=0x97 => self.parse_enum(byte as usize - 0x80, visitor),
834834+ 0x98 => {
835835+ let len = self.parse_u8()?;
836836+ self.parse_enum(len as usize, visitor)
837837+ }
838838+ 0x99 => {
839839+ let len = self.parse_u16()?;
840840+ self.parse_enum(len as usize, visitor)
841841+ }
842842+ 0x9a => {
843843+ let len = self.parse_u32()?;
844844+ self.parse_enum(len as usize, visitor)
845845+ }
846846+ 0x9b => {
847847+ let len = self.parse_u64()?;
848848+ if len > usize::MAX as u64 {
849849+ return Err(self.error(ErrorCode::LengthOutOfRange));
850850+ }
851851+ self.parse_enum(len as usize, visitor)
852852+ }
853853+ 0x9c..=0x9e => Err(self.error(ErrorCode::UnassignedCode)),
854854+ 0x9f => self.parse_indefinite_enum(visitor),
855855+856856+ _ => unreachable!(),
857857+ }
858858+ }
859859+ Some(0xa1) => {
860860+ if !self.accept_standard_enums {
861861+ return Err(self.error(ErrorCode::WrongEnumFormat));
862862+ }
863863+ self.consume();
864864+ self.parse_enum_map(visitor)
865865+ }
866866+ None => Err(self.error(ErrorCode::EofWhileParsingValue)),
867867+ _ => {
868868+ if !self.accept_standard_enums && !self.accept_legacy_enums {
869869+ return Err(self.error(ErrorCode::WrongEnumFormat));
870870+ }
871871+ visitor.visit_enum(UnitVariantAccess { de: self })
872872+ }
873873+ }
874874+ }
875875+876876+ #[inline]
877877+ fn is_human_readable(&self) -> bool {
878878+ false
879879+ }
880880+881881+ serde::forward_to_deserialize_any! {
882882+ bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string unit
883883+ unit_struct seq tuple tuple_struct map struct identifier ignored_any
884884+ bytes byte_buf
885885+ }
886886+}
887887+888888+impl<R> Deserializer<R>
889889+where
890890+ R: Offset,
891891+{
892892+ /// Return the current offset in the reader
893893+ #[inline]
894894+ pub fn byte_offset(&self) -> usize {
895895+ self.read.byte_offset()
896896+ }
897897+}
898898+899899+trait MakeError {
900900+ fn error(&self, code: ErrorCode) -> Error;
901901+}
902902+903903+struct SeqAccess<'a, R> {
904904+ de: &'a mut Deserializer<R>,
905905+ len: &'a mut usize,
906906+}
907907+908908+impl<'de, R> de::SeqAccess<'de> for SeqAccess<'_, R>
909909+where
910910+ R: Read<'de>,
911911+{
912912+ type Error = Error;
913913+914914+ fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
915915+ where
916916+ T: de::DeserializeSeed<'de>,
917917+ {
918918+ if *self.len == 0 {
919919+ return Ok(None);
920920+ }
921921+ *self.len -= 1;
922922+923923+ let value = seed.deserialize(&mut *self.de)?;
924924+ Ok(Some(value))
925925+ }
926926+927927+ fn size_hint(&self) -> Option<usize> {
928928+ Some(*self.len)
929929+ }
930930+}
931931+932932+impl<'de, R> MakeError for SeqAccess<'_, R>
933933+where
934934+ R: Read<'de>,
935935+{
936936+ fn error(&self, code: ErrorCode) -> Error {
937937+ self.de.error(code)
938938+ }
939939+}
940940+941941+struct IndefiniteSeqAccess<'a, R> {
942942+ de: &'a mut Deserializer<R>,
943943+}
944944+945945+impl<'de, R> de::SeqAccess<'de> for IndefiniteSeqAccess<'_, R>
946946+where
947947+ R: Read<'de>,
948948+{
949949+ type Error = Error;
950950+951951+ fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
952952+ where
953953+ T: de::DeserializeSeed<'de>,
954954+ {
955955+ match self.de.peek()? {
956956+ Some(0xff) => return Ok(None),
957957+ Some(_) => {}
958958+ None => return Err(self.de.error(ErrorCode::EofWhileParsingArray)),
959959+ }
960960+961961+ let value = seed.deserialize(&mut *self.de)?;
962962+ Ok(Some(value))
963963+ }
964964+}
965965+966966+impl<'de, R> MakeError for IndefiniteSeqAccess<'_, R>
967967+where
968968+ R: Read<'de>,
969969+{
970970+ fn error(&self, code: ErrorCode) -> Error {
971971+ self.de.error(code)
972972+ }
973973+}
974974+975975+struct MapAccess<'a, R> {
976976+ de: &'a mut Deserializer<R>,
977977+ len: &'a mut usize,
978978+ accept_named: bool,
979979+ accept_packed: bool,
980980+}
981981+982982+impl<'de, R> de::MapAccess<'de> for MapAccess<'_, R>
983983+where
984984+ R: Read<'de>,
985985+{
986986+ type Error = Error;
987987+988988+ fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
989989+ where
990990+ K: de::DeserializeSeed<'de>,
991991+ {
992992+ if *self.len == 0 {
993993+ return Ok(None);
994994+ }
995995+ *self.len -= 1;
996996+997997+ match self.de.peek()? {
998998+ Some(_byte @ 0x00..=0x1b) if !self.accept_packed => {
999999+ return Err(self.de.error(ErrorCode::WrongStructFormat));
10001000+ }
10011001+ Some(_byte @ 0x60..=0x7f) if !self.accept_named => {
10021002+ return Err(self.de.error(ErrorCode::WrongStructFormat));
10031003+ }
10041004+ _ => {}
10051005+ };
10061006+10071007+ let value = seed.deserialize(&mut *self.de)?;
10081008+ Ok(Some(value))
10091009+ }
10101010+10111011+ fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
10121012+ where
10131013+ V: de::DeserializeSeed<'de>,
10141014+ {
10151015+ seed.deserialize(&mut *self.de)
10161016+ }
10171017+10181018+ fn size_hint(&self) -> Option<usize> {
10191019+ Some(*self.len)
10201020+ }
10211021+}
10221022+10231023+impl<'de, R> MakeError for MapAccess<'_, R>
10241024+where
10251025+ R: Read<'de>,
10261026+{
10271027+ fn error(&self, code: ErrorCode) -> Error {
10281028+ self.de.error(code)
10291029+ }
10301030+}
10311031+10321032+struct IndefiniteMapAccess<'a, R> {
10331033+ de: &'a mut Deserializer<R>,
10341034+ accept_packed: bool,
10351035+ accept_named: bool,
10361036+}
10371037+10381038+impl<'de, R> de::MapAccess<'de> for IndefiniteMapAccess<'_, R>
10391039+where
10401040+ R: Read<'de>,
10411041+{
10421042+ type Error = Error;
10431043+10441044+ fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
10451045+ where
10461046+ K: de::DeserializeSeed<'de>,
10471047+ {
10481048+ match self.de.peek()? {
10491049+ Some(_byte @ 0x00..=0x1b) if !self.accept_packed => {
10501050+ return Err(self.de.error(ErrorCode::WrongStructFormat))
10511051+ }
10521052+ Some(_byte @ 0x60..=0x7f) if !self.accept_named => {
10531053+ return Err(self.de.error(ErrorCode::WrongStructFormat))
10541054+ }
10551055+ Some(0xff) => return Ok(None),
10561056+ Some(_) => {}
10571057+ None => return Err(self.de.error(ErrorCode::EofWhileParsingMap)),
10581058+ }
10591059+10601060+ let value = seed.deserialize(&mut *self.de)?;
10611061+ Ok(Some(value))
10621062+ }
10631063+10641064+ fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
10651065+ where
10661066+ V: de::DeserializeSeed<'de>,
10671067+ {
10681068+ seed.deserialize(&mut *self.de)
10691069+ }
10701070+}
10711071+10721072+struct UnitVariantAccess<'a, R> {
10731073+ de: &'a mut Deserializer<R>,
10741074+}
10751075+10761076+impl<'de, 'a, R> de::EnumAccess<'de> for UnitVariantAccess<'a, R>
10771077+where
10781078+ R: Read<'de>,
10791079+{
10801080+ type Error = Error;
10811081+ type Variant = UnitVariantAccess<'a, R>;
10821082+10831083+ fn variant_seed<V>(self, seed: V) -> Result<(V::Value, UnitVariantAccess<'a, R>)>
10841084+ where
10851085+ V: de::DeserializeSeed<'de>,
10861086+ {
10871087+ let variant = seed.deserialize(&mut *self.de)?;
10881088+ Ok((variant, self))
10891089+ }
10901090+}
10911091+10921092+impl<'de, R> de::VariantAccess<'de> for UnitVariantAccess<'_, R>
10931093+where
10941094+ R: Read<'de>,
10951095+{
10961096+ type Error = Error;
10971097+10981098+ fn unit_variant(self) -> Result<()> {
10991099+ Ok(())
11001100+ }
11011101+11021102+ fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value>
11031103+ where
11041104+ T: de::DeserializeSeed<'de>,
11051105+ {
11061106+ Err(de::Error::invalid_type(
11071107+ de::Unexpected::UnitVariant,
11081108+ &"newtype variant",
11091109+ ))
11101110+ }
11111111+11121112+ fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value>
11131113+ where
11141114+ V: de::Visitor<'de>,
11151115+ {
11161116+ Err(de::Error::invalid_type(
11171117+ de::Unexpected::UnitVariant,
11181118+ &"tuple variant",
11191119+ ))
11201120+ }
11211121+11221122+ fn struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value>
11231123+ where
11241124+ V: de::Visitor<'de>,
11251125+ {
11261126+ Err(de::Error::invalid_type(
11271127+ de::Unexpected::UnitVariant,
11281128+ &"struct variant",
11291129+ ))
11301130+ }
11311131+}
11321132+11331133+struct VariantAccess<T> {
11341134+ seq: T,
11351135+}
11361136+11371137+impl<'de, T> de::EnumAccess<'de> for VariantAccess<T>
11381138+where
11391139+ T: de::SeqAccess<'de, Error = Error> + MakeError,
11401140+{
11411141+ type Error = Error;
11421142+ type Variant = VariantAccess<T>;
11431143+11441144+ fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, VariantAccess<T>)>
11451145+ where
11461146+ V: de::DeserializeSeed<'de>,
11471147+ {
11481148+ let variant = match self.seq.next_element_seed(seed) {
11491149+ Ok(Some(variant)) => variant,
11501150+ Ok(None) => return Err(self.seq.error(ErrorCode::ArrayTooShort)),
11511151+ Err(e) => return Err(e),
11521152+ };
11531153+ Ok((variant, self))
11541154+ }
11551155+}
11561156+11571157+impl<'de, T> de::VariantAccess<'de> for VariantAccess<T>
11581158+where
11591159+ T: de::SeqAccess<'de, Error = Error> + MakeError,
11601160+{
11611161+ type Error = Error;
11621162+11631163+ fn unit_variant(mut self) -> Result<()> {
11641164+ match self.seq.next_element() {
11651165+ Ok(Some(())) => Ok(()),
11661166+ Ok(None) => Err(self.seq.error(ErrorCode::ArrayTooLong)),
11671167+ Err(e) => Err(e),
11681168+ }
11691169+ }
11701170+11711171+ fn newtype_variant_seed<S>(mut self, seed: S) -> Result<S::Value>
11721172+ where
11731173+ S: de::DeserializeSeed<'de>,
11741174+ {
11751175+ match self.seq.next_element_seed(seed) {
11761176+ Ok(Some(variant)) => Ok(variant),
11771177+ Ok(None) => Err(self.seq.error(ErrorCode::ArrayTooShort)),
11781178+ Err(e) => Err(e),
11791179+ }
11801180+ }
11811181+11821182+ fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value>
11831183+ where
11841184+ V: de::Visitor<'de>,
11851185+ {
11861186+ visitor.visit_seq(self.seq)
11871187+ }
11881188+11891189+ fn struct_variant<V>(mut self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
11901190+ where
11911191+ V: de::Visitor<'de>,
11921192+ {
11931193+ let seed = StructVariantSeed { visitor };
11941194+ match self.seq.next_element_seed(seed) {
11951195+ Ok(Some(variant)) => Ok(variant),
11961196+ Ok(None) => Err(self.seq.error(ErrorCode::ArrayTooShort)),
11971197+ Err(e) => Err(e),
11981198+ }
11991199+ }
12001200+}
12011201+12021202+struct StructVariantSeed<V> {
12031203+ visitor: V,
12041204+}
12051205+12061206+impl<'de, V> de::DeserializeSeed<'de> for StructVariantSeed<V>
12071207+where
12081208+ V: de::Visitor<'de>,
12091209+{
12101210+ type Value = V::Value;
12111211+12121212+ fn deserialize<D>(self, de: D) -> result::Result<V::Value, D::Error>
12131213+ where
12141214+ D: de::Deserializer<'de>,
12151215+ {
12161216+ de.deserialize_any(self.visitor)
12171217+ }
12181218+}
12191219+12201220+/// Iterator that deserializes a stream into multiple CBOR values.
12211221+///
12221222+/// A stream deserializer can be created from any CBOR deserializer using the
12231223+/// `Deserializer::into_iter` method.
12241224+///
12251225+/// ```
12261226+/// use serde_cbor_2::de::Deserializer;
12271227+/// use serde_cbor_2::value::Value;
12281228+///
12291229+/// # fn main() {
12301230+/// let data: Vec<u8> = vec![
12311231+/// 0x01, 0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72,
12321232+/// ];
12331233+/// let mut it = Deserializer::from_slice(&data[..]).into_iter::<Value>();
12341234+/// assert_eq!(
12351235+/// Value::Integer(1),
12361236+/// it.next().unwrap().unwrap()
12371237+/// );
12381238+/// assert_eq!(
12391239+/// Value::Text("foobar".to_string()),
12401240+/// it.next().unwrap().unwrap()
12411241+/// );
12421242+/// # }
12431243+/// ```
12441244+#[derive(Debug)]
12451245+pub struct StreamDeserializer<'de, R, T> {
12461246+ de: Deserializer<R>,
12471247+ output: PhantomData<T>,
12481248+ lifetime: PhantomData<&'de ()>,
12491249+}
12501250+12511251+impl<'de, R, T> StreamDeserializer<'de, R, T>
12521252+where
12531253+ R: Read<'de>,
12541254+ T: de::Deserialize<'de>,
12551255+{
12561256+ /// Create a new CBOR stream deserializer from one of the possible
12571257+ /// serde_cbor_2 input sources.
12581258+ ///
12591259+ /// Typically it is more convenient to use one of these methods instead:
12601260+ ///
12611261+ /// * `Deserializer::from_slice(...).into_iter()`
12621262+ /// * `Deserializer::from_reader(...).into_iter()`
12631263+ pub fn new(read: R) -> StreamDeserializer<'de, R, T> {
12641264+ StreamDeserializer {
12651265+ de: Deserializer::new(read),
12661266+ output: PhantomData,
12671267+ lifetime: PhantomData,
12681268+ }
12691269+ }
12701270+}
12711271+12721272+impl<'de, R, T> StreamDeserializer<'de, R, T>
12731273+where
12741274+ R: Offset,
12751275+ T: de::Deserialize<'de>,
12761276+{
12771277+ /// Return the current offset in the reader
12781278+ #[inline]
12791279+ pub fn byte_offset(&self) -> usize {
12801280+ self.de.byte_offset()
12811281+ }
12821282+}
12831283+12841284+impl<'de, R, T> Iterator for StreamDeserializer<'de, R, T>
12851285+where
12861286+ R: Read<'de>,
12871287+ T: de::Deserialize<'de>,
12881288+{
12891289+ type Item = Result<T>;
12901290+12911291+ fn next(&mut self) -> Option<Result<T>> {
12921292+ match self.de.peek() {
12931293+ Ok(Some(_)) => Some(T::deserialize(&mut self.de)),
12941294+ Ok(None) => None,
12951295+ Err(e) => Some(Err(e)),
12961296+ }
12971297+ }
12981298+}
12991299+13001300+struct VariantAccessMap<T> {
13011301+ map: T,
13021302+}
13031303+13041304+impl<'de, T> de::EnumAccess<'de> for VariantAccessMap<T>
13051305+where
13061306+ T: de::MapAccess<'de, Error = Error> + MakeError,
13071307+{
13081308+ type Error = Error;
13091309+ type Variant = VariantAccessMap<T>;
13101310+13111311+ fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, VariantAccessMap<T>)>
13121312+ where
13131313+ V: de::DeserializeSeed<'de>,
13141314+ {
13151315+ let variant = match self.map.next_key_seed(seed) {
13161316+ Ok(Some(variant)) => variant,
13171317+ Ok(None) => return Err(self.map.error(ErrorCode::ArrayTooShort)),
13181318+ Err(e) => return Err(e),
13191319+ };
13201320+ Ok((variant, self))
13211321+ }
13221322+}
13231323+13241324+impl<'de, T> de::VariantAccess<'de> for VariantAccessMap<T>
13251325+where
13261326+ T: de::MapAccess<'de, Error = Error> + MakeError,
13271327+{
13281328+ type Error = Error;
13291329+13301330+ fn unit_variant(mut self) -> Result<()> {
13311331+ match self.map.next_value() {
13321332+ Ok(()) => Ok(()),
13331333+ Err(e) => Err(e),
13341334+ }
13351335+ }
13361336+13371337+ fn newtype_variant_seed<S>(mut self, seed: S) -> Result<S::Value>
13381338+ where
13391339+ S: de::DeserializeSeed<'de>,
13401340+ {
13411341+ self.map.next_value_seed(seed)
13421342+ }
13431343+13441344+ fn tuple_variant<V>(mut self, _len: usize, visitor: V) -> Result<V::Value>
13451345+ where
13461346+ V: de::Visitor<'de>,
13471347+ {
13481348+ let seed = StructVariantSeed { visitor };
13491349+ self.map.next_value_seed(seed)
13501350+ }
13511351+13521352+ fn struct_variant<V>(mut self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
13531353+ where
13541354+ V: de::Visitor<'de>,
13551355+ {
13561356+ let seed = StructVariantSeed { visitor };
13571357+ self.map.next_value_seed(seed)
13581358+ }
13591359+}
+303
vendor/git/cbor/src/error.rs
···11+//! When serializing or deserializing CBOR goes wrong.
22+use core::fmt;
33+use core::result;
44+use serde::de;
55+use serde::ser;
66+#[cfg(feature = "std")]
77+use std::error;
88+#[cfg(feature = "std")]
99+use std::io;
1010+1111+/// This type represents all possible errors that can occur when serializing or deserializing CBOR
1212+/// data.
1313+pub struct Error(ErrorImpl);
1414+1515+/// Alias for a `Result` with the error type `serde_cbor::Error`.
1616+pub type Result<T> = result::Result<T, Error>;
1717+1818+/// Categorizes the cause of a `serde_cbor::Error`.
1919+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
2020+pub enum Category {
2121+ /// The error was caused by a failure to read or write bytes on an IO stream.
2222+ Io,
2323+ /// The error was caused by input that was not syntactically valid CBOR.
2424+ Syntax,
2525+ /// The error was caused by input data that was semantically incorrect.
2626+ Data,
2727+ /// The error was caused by prematurely reaching the end of the input data.
2828+ Eof,
2929+}
3030+3131+impl Error {
3232+ /// The byte offset at which the error occurred.
3333+ pub fn offset(&self) -> u64 {
3434+ self.0.offset
3535+ }
3636+3737+ pub(crate) fn syntax(code: ErrorCode, offset: u64) -> Error {
3838+ Error(ErrorImpl { code, offset })
3939+ }
4040+4141+ #[cfg(feature = "std")]
4242+ pub(crate) fn io(error: io::Error) -> Error {
4343+ Error(ErrorImpl {
4444+ code: ErrorCode::Io(error),
4545+ offset: 0,
4646+ })
4747+ }
4848+4949+ #[cfg(all(not(feature = "std"), feature = "unsealed_read_write"))]
5050+ /// Creates an error signalling that the underlying `Read` encountered an I/O error.
5151+ pub fn io() -> Error {
5252+ Error(ErrorImpl {
5353+ code: ErrorCode::Io,
5454+ offset: 0,
5555+ })
5656+ }
5757+5858+ #[cfg(feature = "unsealed_read_write")]
5959+ /// Creates an error signalling that the scratch buffer was too small to fit the data.
6060+ pub fn scratch_too_small(offset: u64) -> Error {
6161+ Error(ErrorImpl {
6262+ code: ErrorCode::ScratchTooSmall,
6363+ offset,
6464+ })
6565+ }
6666+6767+ #[cfg(not(feature = "unsealed_read_write"))]
6868+ pub(crate) fn scratch_too_small(offset: u64) -> Error {
6969+ Error(ErrorImpl {
7070+ code: ErrorCode::ScratchTooSmall,
7171+ offset,
7272+ })
7373+ }
7474+7575+ #[cfg(feature = "unsealed_read_write")]
7676+ /// Creates an error with a custom message.
7777+ ///
7878+ /// **Note**: When the "std" feature is disabled, the message will be discarded.
7979+ pub fn message<T: fmt::Display>(_msg: T) -> Error {
8080+ #[cfg(not(feature = "std"))]
8181+ {
8282+ Error(ErrorImpl {
8383+ code: ErrorCode::Message,
8484+ offset: 0,
8585+ })
8686+ }
8787+ #[cfg(feature = "std")]
8888+ {
8989+ Error(ErrorImpl {
9090+ code: ErrorCode::Message(_msg.to_string()),
9191+ offset: 0,
9292+ })
9393+ }
9494+ }
9595+9696+ #[cfg(not(feature = "unsealed_read_write"))]
9797+ pub(crate) fn message<T: fmt::Display>(_msg: T) -> Error {
9898+ #[cfg(not(feature = "std"))]
9999+ {
100100+ Error(ErrorImpl {
101101+ code: ErrorCode::Message,
102102+ offset: 0,
103103+ })
104104+ }
105105+ #[cfg(feature = "std")]
106106+ {
107107+ Error(ErrorImpl {
108108+ code: ErrorCode::Message(_msg.to_string()),
109109+ offset: 0,
110110+ })
111111+ }
112112+ }
113113+114114+ #[cfg(feature = "unsealed_read_write")]
115115+ /// Creates an error signalling that the underlying read
116116+ /// encountered an end of input.
117117+ pub fn eof(offset: u64) -> Error {
118118+ Error(ErrorImpl {
119119+ code: ErrorCode::EofWhileParsingValue,
120120+ offset,
121121+ })
122122+ }
123123+124124+ /// Categorizes the cause of this error.
125125+ pub fn classify(&self) -> Category {
126126+ match self.0.code {
127127+ #[cfg(feature = "std")]
128128+ ErrorCode::Message(_) => Category::Data,
129129+ #[cfg(not(feature = "std"))]
130130+ ErrorCode::Message => Category::Data,
131131+ #[cfg(feature = "std")]
132132+ ErrorCode::Io(_) => Category::Io,
133133+ #[cfg(not(feature = "std"))]
134134+ ErrorCode::Io => Category::Io,
135135+ ErrorCode::ScratchTooSmall => Category::Io,
136136+ ErrorCode::EofWhileParsingValue
137137+ | ErrorCode::EofWhileParsingArray
138138+ | ErrorCode::EofWhileParsingMap => Category::Eof,
139139+ ErrorCode::LengthOutOfRange
140140+ | ErrorCode::InvalidUtf8
141141+ | ErrorCode::UnassignedCode
142142+ | ErrorCode::UnexpectedCode
143143+ | ErrorCode::TrailingData
144144+ | ErrorCode::ArrayTooShort
145145+ | ErrorCode::ArrayTooLong
146146+ | ErrorCode::RecursionLimitExceeded
147147+ | ErrorCode::WrongEnumFormat
148148+ | ErrorCode::WrongStructFormat => Category::Syntax,
149149+ }
150150+ }
151151+152152+ /// Returns true if this error was caused by a failure to read or write bytes on an IO stream.
153153+ pub fn is_io(&self) -> bool {
154154+ matches!(self.classify(), Category::Io)
155155+ }
156156+157157+ /// Returns true if this error was caused by input that was not syntactically valid CBOR.
158158+ pub fn is_syntax(&self) -> bool {
159159+ matches!(self.classify(), Category::Syntax)
160160+ }
161161+162162+ /// Returns true if this error was caused by data that was semantically incorrect.
163163+ pub fn is_data(&self) -> bool {
164164+ matches!(self.classify(), Category::Data)
165165+ }
166166+167167+ /// Returns true if this error was caused by prematurely reaching the end of the input data.
168168+ pub fn is_eof(&self) -> bool {
169169+ matches!(self.classify(), Category::Eof)
170170+ }
171171+172172+ /// Returns true if this error was caused by the scratch buffer being too small.
173173+ ///
174174+ /// Note this being `true` implies that `is_io()` is also `true`.
175175+ pub fn is_scratch_too_small(&self) -> bool {
176176+ matches!(self.0.code, ErrorCode::ScratchTooSmall)
177177+ }
178178+}
179179+180180+#[cfg(feature = "std")]
181181+impl error::Error for Error {
182182+ fn source(&self) -> Option<&(dyn error::Error + 'static)> {
183183+ match self.0.code {
184184+ ErrorCode::Io(ref err) => Some(err),
185185+ _ => None,
186186+ }
187187+ }
188188+}
189189+190190+impl fmt::Display for Error {
191191+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192192+ if self.0.offset == 0 {
193193+ fmt::Display::fmt(&self.0.code, f)
194194+ } else {
195195+ write!(f, "{} at offset {}", self.0.code, self.0.offset)
196196+ }
197197+ }
198198+}
199199+200200+impl fmt::Debug for Error {
201201+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
202202+ fmt::Debug::fmt(&self.0, fmt)
203203+ }
204204+}
205205+206206+impl de::Error for Error {
207207+ fn custom<T: fmt::Display>(msg: T) -> Error {
208208+ Error::message(msg)
209209+ }
210210+211211+ fn invalid_type(unexp: de::Unexpected<'_>, exp: &dyn de::Expected) -> Error {
212212+ if let de::Unexpected::Unit = unexp {
213213+ Error::custom(format_args!("invalid type: null, expected {exp}"))
214214+ } else {
215215+ Error::custom(format_args!("invalid type: {unexp}, expected {exp}"))
216216+ }
217217+ }
218218+}
219219+220220+impl ser::Error for Error {
221221+ fn custom<T: fmt::Display>(msg: T) -> Error {
222222+ Error::message(msg)
223223+ }
224224+}
225225+226226+#[cfg(feature = "std")]
227227+impl From<io::Error> for Error {
228228+ fn from(e: io::Error) -> Error {
229229+ Error::io(e)
230230+ }
231231+}
232232+233233+#[cfg(not(feature = "std"))]
234234+impl From<core::fmt::Error> for Error {
235235+ fn from(_: core::fmt::Error) -> Error {
236236+ Error(ErrorImpl {
237237+ code: ErrorCode::Message,
238238+ offset: 0,
239239+ })
240240+ }
241241+}
242242+243243+#[derive(Debug)]
244244+struct ErrorImpl {
245245+ code: ErrorCode,
246246+ offset: u64,
247247+}
248248+249249+#[derive(Debug)]
250250+pub(crate) enum ErrorCode {
251251+ #[cfg(feature = "std")]
252252+ Message(String),
253253+ #[cfg(not(feature = "std"))]
254254+ Message,
255255+ #[cfg(feature = "std")]
256256+ Io(io::Error),
257257+ #[allow(unused)]
258258+ #[cfg(not(feature = "std"))]
259259+ Io,
260260+ ScratchTooSmall,
261261+ EofWhileParsingValue,
262262+ EofWhileParsingArray,
263263+ EofWhileParsingMap,
264264+ LengthOutOfRange,
265265+ InvalidUtf8,
266266+ UnassignedCode,
267267+ UnexpectedCode,
268268+ TrailingData,
269269+ ArrayTooShort,
270270+ ArrayTooLong,
271271+ RecursionLimitExceeded,
272272+ WrongEnumFormat,
273273+ WrongStructFormat,
274274+}
275275+276276+impl fmt::Display for ErrorCode {
277277+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
278278+ match *self {
279279+ #[cfg(feature = "std")]
280280+ ErrorCode::Message(ref msg) => f.write_str(msg),
281281+ #[cfg(not(feature = "std"))]
282282+ ErrorCode::Message => f.write_str("Unknown error"),
283283+ #[cfg(feature = "std")]
284284+ ErrorCode::Io(ref err) => fmt::Display::fmt(err, f),
285285+ #[cfg(not(feature = "std"))]
286286+ ErrorCode::Io => f.write_str("Unknown I/O error"),
287287+ ErrorCode::ScratchTooSmall => f.write_str("Scratch buffer too small"),
288288+ ErrorCode::EofWhileParsingValue => f.write_str("EOF while parsing a value"),
289289+ ErrorCode::EofWhileParsingArray => f.write_str("EOF while parsing an array"),
290290+ ErrorCode::EofWhileParsingMap => f.write_str("EOF while parsing a map"),
291291+ ErrorCode::LengthOutOfRange => f.write_str("length out of range"),
292292+ ErrorCode::InvalidUtf8 => f.write_str("invalid UTF-8"),
293293+ ErrorCode::UnassignedCode => f.write_str("unassigned type"),
294294+ ErrorCode::UnexpectedCode => f.write_str("unexpected code"),
295295+ ErrorCode::TrailingData => f.write_str("trailing data"),
296296+ ErrorCode::ArrayTooShort => f.write_str("array too short"),
297297+ ErrorCode::ArrayTooLong => f.write_str("array too long"),
298298+ ErrorCode::RecursionLimitExceeded => f.write_str("recursion limit exceeded"),
299299+ ErrorCode::WrongEnumFormat => f.write_str("wrong enum format"),
300300+ ErrorCode::WrongStructFormat => f.write_str("wrong struct format"),
301301+ }
302302+ }
303303+}
+377
vendor/git/cbor/src/lib.rs
···11+//! CBOR and serialization.
22+//!
33+//! # Usage
44+//!
55+//! Serde CBOR 2 supports Rust 1.62 and up. Add this to your `Cargo.toml`:
66+//!
77+//! ```toml
88+//! [dependencies]
99+//! serde_cbor_2 = "0.12"
1010+//! ```
1111+//!
1212+//! Serde CBOR 2 can be used as a 'drop in' replacement of `serde_cbor`
1313+//!
1414+//! ```toml
1515+//! [dependencies]
1616+//! serde_cbor = { version = "0.12", package = "serde_cbor_2" }
1717+//! ```
1818+//!
1919+//! Storing and loading Rust types is easy and requires only
2020+//! minimal modifications to the program code.
2121+//!
2222+//! ```rust
2323+//! # use serde::{Deserialize, Serialize};
2424+//! use std::error::Error;
2525+//! use std::fs::File;
2626+//!
2727+//! // Types annotated with `Serialize` can be stored as CBOR.
2828+//! // To be able to load them again add `Deserialize`.
2929+//! #[derive(Debug, Serialize, Deserialize)]
3030+//! struct Mascot {
3131+//! name: String,
3232+//! species: String,
3333+//! year_of_birth: u32,
3434+//! }
3535+//!
3636+//! fn main() -> Result<(), Box<dyn Error>> {
3737+//! let ferris = Mascot {
3838+//! name: "Ferris".to_owned(),
3939+//! species: "crab".to_owned(),
4040+//! year_of_birth: 2015,
4141+//! };
4242+//!
4343+//! let ferris_file = File::create("examples/ferris.cbor")?;
4444+//! // Write Ferris to the given file.
4545+//! // Instead of a file you can use any type that implements `io::Write`
4646+//! // like a HTTP body, database connection etc.
4747+//! serde_cbor_2::to_writer(ferris_file, &ferris)?;
4848+//!
4949+//! let tux_file = File::open("examples/tux.cbor")?;
5050+//! // Load Tux from a file.
5151+//! // Serde CBOR performs roundtrip serialization meaning that
5252+//! // the data will not change in any way.
5353+//! let tux: Mascot = serde_cbor_2::from_reader(tux_file)?;
5454+//!
5555+//! println!("{:?}", tux);
5656+//! // prints: Mascot { name: "Tux", species: "penguin", year_of_birth: 1996 }
5757+//!
5858+//! Ok(())
5959+//! }
6060+//! ```
6161+//!
6262+//! There are a lot of options available to customize the format.
6363+//! To operate on untyped CBOR values have a look at the `Value` type.
6464+//!
6565+//! # Type-based Serialization and Deserialization
6666+//! Serde provides a mechanism for low boilerplate serialization & deserialization of values to and
6767+//! from CBOR via the serialization API. To be able to serialize a piece of data, it must implement
6868+//! the `serde::Serialize` trait. To be able to deserialize a piece of data, it must implement the
6969+//! `serde::Deserialize` trait. Serde provides an annotation to automatically generate the
7070+//! code for these traits: `#[derive(Serialize, Deserialize)]`.
7171+//!
7272+//! The CBOR API also provides an enum `serde_cbor_2::Value`.
7373+//!
7474+//! # Packed Encoding
7575+//! When serializing structs or enums in CBOR the keys or enum variant names will be serialized
7676+//! as string keys to a map. Especially in embedded environments this can increase the file
7777+//! size too much. In packed encoding all struct keys, as well as any enum variant that has no data,
7878+//! will be serialized as variable sized integers. The first 24 entries in any struct consume only a
7979+//! single byte! Packed encoding uses serde's preferred [externally tagged enum
8080+//! format](https://serde.rs/enum-representations.html) and therefore serializes enum variant names
8181+//! as string keys when that variant contains data. So, in the packed encoding example, `FirstVariant`
8282+//! encodes to a single byte, but encoding `SecondVariant` requires 16 bytes.
8383+//!
8484+//! To serialize a document in this format use `Serializer::new(writer).packed_format()` or
8585+//! the shorthand `ser::to_vec_packed`. The deserialization works without any changes.
8686+//!
8787+//! If you would like to omit the enum variant encoding for all variants, including ones that
8888+//! contain data, you can add `legacy_enums()` in addition to `packed_format()`, as can seen
8989+//! in the Serialize using minimal encoding example.
9090+//!
9191+//! # Self describing documents
9292+//! In some contexts different formats are used but there is no way to declare the format used
9393+//! out of band. For this reason CBOR has a magic number that may be added before any document.
9494+//! Self describing documents are created with `serializer.self_describe()`.
9595+//!
9696+//! # Examples
9797+//! Read a CBOR value that is known to be a map of string keys to string values and print it.
9898+//!
9999+//! ```rust
100100+//! use std::collections::BTreeMap;
101101+//! use serde_cbor_2::from_slice;
102102+//!
103103+//! let slice = b"\xa5aaaAabaBacaCadaDaeaE";
104104+//! let value: BTreeMap<String, String> = from_slice(slice).unwrap();
105105+//! println!("{:?}", value); // {"e": "E", "d": "D", "a": "A", "c": "C", "b": "B"}
106106+//! ```
107107+//!
108108+//! Read a general CBOR value with an unknown content.
109109+//!
110110+//! ```rust
111111+//! use serde_cbor_2::from_slice;
112112+//! use serde_cbor_2::value::Value;
113113+//!
114114+//! let slice = b"\x82\x01\xa1aaab";
115115+//! let value: Value = from_slice(slice).unwrap();
116116+//! println!("{:?}", value); // Array([U64(1), Object({String("a"): String("b")})])
117117+//! ```
118118+//!
119119+//! Serialize an object.
120120+//!
121121+//! ```rust
122122+//! use std::collections::BTreeMap;
123123+//! use serde_cbor_2::to_vec;
124124+//!
125125+//! let mut programming_languages = BTreeMap::new();
126126+//! programming_languages.insert("rust", vec!["safe", "concurrent", "fast"]);
127127+//! programming_languages.insert("python", vec!["powerful", "friendly", "open"]);
128128+//! programming_languages.insert("js", vec!["lightweight", "interpreted", "object-oriented"]);
129129+//! let encoded = to_vec(&programming_languages);
130130+//! assert_eq!(encoded.unwrap().len(), 103);
131131+//! ```
132132+//!
133133+//! Deserializing data in the middle of a slice
134134+//! ```
135135+//! use serde_cbor_2::Deserializer;
136136+//!
137137+//! # fn main() {
138138+//! let data: Vec<u8> = vec![
139139+//! 0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, 0x66, 0x66, 0x6f, 0x6f, 0x62,
140140+//! 0x61, 0x72,
141141+//! ];
142142+//! let mut deserializer = Deserializer::from_slice(&data);
143143+//! let value: &str = serde::de::Deserialize::deserialize(&mut deserializer)
144144+//! .unwrap();
145145+//! let rest = &data[deserializer.byte_offset()..];
146146+//! assert_eq!(value, "foobar");
147147+//! assert_eq!(rest, &[0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]);
148148+//! # }
149149+//! ```
150150+//!
151151+//! Serialize using packed encoding
152152+//!
153153+//! ```rust
154154+//! # use serde::{Deserialize, Serialize};
155155+//! use serde_cbor_2::ser::to_vec_packed;
156156+//!
157157+//! #[derive(Debug, Serialize, Deserialize)]
158158+//! enum WithTwoVariants {
159159+//! FirstVariant,
160160+//! SecondVariant(u8),
161161+//! }
162162+//!
163163+//! use WithTwoVariants::*;
164164+//!
165165+//! let cbor = to_vec_packed(&FirstVariant).unwrap();
166166+//! assert_eq!(cbor.len(), 1);
167167+//!
168168+//! let cbor = to_vec_packed(&SecondVariant(0)).unwrap();
169169+//! assert_eq!(cbor.len(), 16); // Includes 13 bytes of "SecondVariant"
170170+//! ```
171171+//!
172172+//! Serialize using minimal encoding
173173+//!
174174+//! ```rust
175175+//! # use serde::{Deserialize, Serialize};
176176+//! use serde_cbor_2::{Result, Serializer, ser::{self, IoWrite}};
177177+//!
178178+//! fn to_vec_minimal<T>(value: &T) -> Result<Vec<u8>>
179179+//! where
180180+//! T: serde::Serialize,
181181+//! {
182182+//! let mut vec = Vec::new();
183183+//! value.serialize(&mut Serializer::new(&mut IoWrite::new(&mut vec)).packed_format().legacy_enums())?;
184184+//! Ok(vec)
185185+//! }
186186+//!
187187+//! #[derive(Debug, Serialize, Deserialize)]
188188+//! enum WithTwoVariants {
189189+//! FirstVariant,
190190+//! SecondVariant(u8),
191191+//! }
192192+//!
193193+//! use WithTwoVariants::*;
194194+//!
195195+//! let cbor = to_vec_minimal(&FirstVariant).unwrap();
196196+//! assert_eq!(cbor.len(), 1);
197197+//!
198198+//! let cbor = to_vec_minimal(&SecondVariant(0)).unwrap();
199199+//! assert_eq!(cbor.len(), 3);
200200+//! ```
201201+//!
202202+//! # `no-std` support
203203+//!
204204+//! Serde CBOR supports building in a `no_std` context, use the following lines
205205+//! in your `Cargo.toml` dependencies:
206206+//! ``` toml
207207+//! [dependencies]
208208+//! serde = { version = "1.0", default-features = false }
209209+//! serde_cbor = { version = "0.10", default-features = false }
210210+//! ```
211211+//!
212212+//! Without the `std` feature the functions [from_reader], [from_slice], [to_vec], and [to_writer]
213213+//! are not exported. To export [from_slice] and [to_vec] enable the `alloc` feature. The `alloc`
214214+//! feature uses the [`alloc` library][alloc-lib] and requires at least version 1.36.0 of Rust.
215215+//!
216216+//! [alloc-lib]: https://doc.rust-lang.org/alloc/
217217+//!
218218+//! *Note*: to use derive macros in serde you will need to declare `serde`
219219+//! dependency like so:
220220+//! ``` toml
221221+//! serde = { version = "1.0", default-features = false, features = ["derive"] }
222222+//! ```
223223+//!
224224+//! Serialize an object with `no_std` and without `alloc`.
225225+//! ``` rust
226226+//! # fn main() -> Result<(), serde_cbor_2::Error> {
227227+//! # use serde::Serialize;
228228+//! use serde_cbor_2::Serializer;
229229+//! use serde_cbor_2::ser::SliceWrite;
230230+//!
231231+//! #[derive(Serialize)]
232232+//! struct User {
233233+//! user_id: u32,
234234+//! password_hash: [u8; 4],
235235+//! }
236236+//!
237237+//! let mut buf = [0u8; 100];
238238+//! let writer = SliceWrite::new(&mut buf[..]);
239239+//! let mut ser = Serializer::new(writer);
240240+//! let user = User {
241241+//! user_id: 42,
242242+//! password_hash: [1, 2, 3, 4],
243243+//! };
244244+//! user.serialize(&mut ser)?;
245245+//! let writer = ser.into_inner();
246246+//! let size = writer.bytes_written();
247247+//! let expected = [
248248+//! 0xa2, 0x67, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x2a, 0x6d,
249249+//! 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x5f, 0x68, 0x61, 0x73,
250250+//! 0x68, 0x84, 0x1, 0x2, 0x3, 0x4
251251+//! ];
252252+//! assert_eq!(&buf[..size], expected);
253253+//! # Ok(())
254254+//! # }
255255+//! ```
256256+//!
257257+//! Deserialize an object.
258258+//! ``` rust
259259+//! # use serde::Deserialize;
260260+//! # fn main() -> Result<(), serde_cbor_2::Error> {
261261+//! #[derive(Debug, PartialEq, Deserialize)]
262262+//! struct User {
263263+//! user_id: u32,
264264+//! password_hash: [u8; 4],
265265+//! }
266266+//!
267267+//! let value = [
268268+//! 0xa2, 0x67, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x2a, 0x6d,
269269+//! 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x5f, 0x68, 0x61, 0x73,
270270+//! 0x68, 0x84, 0x1, 0x2, 0x3, 0x4
271271+//! ];
272272+//!
273273+//! // from_slice_with_scratch will not alter input data, use it whenever you
274274+//! // borrow from somewhere else.
275275+//! // You will have to size your scratch according to the input data you
276276+//! // expect.
277277+//! use serde_cbor_2::de::from_slice_with_scratch;
278278+//! let mut scratch = [0u8; 32];
279279+//! let user: User = from_slice_with_scratch(&value[..], &mut scratch)?;
280280+//! assert_eq!(user, User {
281281+//! user_id: 42,
282282+//! password_hash: [1, 2, 3, 4],
283283+//! });
284284+//!
285285+//! let mut value = [
286286+//! 0xa2, 0x67, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x2a, 0x6d,
287287+//! 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x5f, 0x68, 0x61, 0x73,
288288+//! 0x68, 0x84, 0x1, 0x2, 0x3, 0x4
289289+//! ];
290290+//!
291291+//! // from_mut_slice will move data around the input slice, you may only use it
292292+//! // on data you may own or can modify.
293293+//! use serde_cbor_2::de::from_mut_slice;
294294+//! let user: User = from_mut_slice(&mut value[..])?;
295295+//! assert_eq!(user, User {
296296+//! user_id: 42,
297297+//! password_hash: [1, 2, 3, 4],
298298+//! });
299299+//! # Ok(())
300300+//! # }
301301+//! ```
302302+//!
303303+//! # Limitations
304304+//!
305305+//! While Serde CBOR strives to support all features of Serde and CBOR
306306+//! there are a few limitations.
307307+//!
308308+//! * [Tags] are ignored during deserialization and can't be emitted during
309309+//! serialization. This is because Serde has no concept of tagged
310310+//! values. See: [#3]
311311+//! * Unknown [simple values] cause an `UnassignedCode` error.
312312+//! The simple values *False* and *True* are recognized and parsed as bool.
313313+//! *Null* and *Undefined* are both deserialized as *unit*.
314314+//! The *unit* type is serialized as *Null*. See: [#86]
315315+//! * [128-bit integers] can't be directly encoded in CBOR. If you need them
316316+//! store them as a byte string. See: [#77]
317317+//!
318318+//! [Tags]: https://tools.ietf.org/html/rfc7049#section-2.4.4
319319+//! [#3]: https://github.com/pyfisch/cbor/issues/3
320320+//! [simple values]: https://tools.ietf.org/html/rfc7049#section-3.5
321321+//! [#86]: https://github.com/pyfisch/cbor/issues/86
322322+//! [128-bit integers]: https://doc.rust-lang.org/std/primitive.u128.html
323323+//! [#77]: https://github.com/pyfisch/cbor/issues/77
324324+325325+#![deny(missing_docs)]
326326+#![cfg_attr(not(feature = "std"), no_std)]
327327+328328+// When we are running tests in no_std mode we need to explicitly link std, because `cargo test`
329329+// will not work without it.
330330+#[cfg(all(not(feature = "std"), test))]
331331+extern crate std;
332332+333333+#[cfg(feature = "alloc")]
334334+extern crate alloc;
335335+336336+pub mod de;
337337+pub mod error;
338338+mod read;
339339+pub mod ser;
340340+pub mod tags;
341341+mod write;
342342+343343+#[cfg(feature = "std")]
344344+pub mod value;
345345+346346+// Re-export the [items recommended by serde](https://serde.rs/conventions.html).
347347+#[doc(inline)]
348348+pub use crate::de::{Deserializer, StreamDeserializer};
349349+350350+#[doc(inline)]
351351+pub use crate::error::{Error, Result};
352352+353353+#[doc(inline)]
354354+pub use crate::ser::Serializer;
355355+356356+// Convenience functions for serialization and deserialization.
357357+// These functions are only available in `std` mode.
358358+#[cfg(feature = "std")]
359359+#[doc(inline)]
360360+pub use crate::de::from_reader;
361361+362362+#[cfg(any(feature = "std", feature = "alloc"))]
363363+#[doc(inline)]
364364+pub use crate::de::from_slice;
365365+366366+#[cfg(any(feature = "std", feature = "alloc"))]
367367+#[doc(inline)]
368368+pub use crate::ser::to_vec;
369369+370370+#[cfg(feature = "std")]
371371+#[doc(inline)]
372372+pub use crate::ser::to_writer;
373373+374374+// Re-export the value type like serde_json
375375+#[cfg(feature = "std")]
376376+#[doc(inline)]
377377+pub use crate::value::Value;
+637
vendor/git/cbor/src/read.rs
···11+#[cfg(feature = "alloc")]
22+use alloc::{vec, vec::Vec};
33+#[cfg(feature = "std")]
44+use core::cmp;
55+use core::mem;
66+77+#[cfg(feature = "std")]
88+use std::io::{self, Read as StdRead};
99+1010+use crate::error::{Error, ErrorCode, Result};
1111+1212+#[cfg(not(feature = "unsealed_read_write"))]
1313+/// Trait used by the deserializer for iterating over input.
1414+///
1515+/// This trait is sealed by default, enabling the `unsealed_read_write` feature removes this bound
1616+/// to allow objects outside of this crate to implement this trait.
1717+pub trait Read<'de>: private::Sealed {
1818+ #[doc(hidden)]
1919+ /// Read n bytes from the input.
2020+ ///
2121+ /// Implementations that can are asked to return a slice with a Long lifetime that outlives the
2222+ /// decoder, but others (eg. ones that need to allocate the data into a temporary buffer) can
2323+ /// return it with a Short lifetime that just lives for the time of read's mutable borrow of
2424+ /// the reader.
2525+ ///
2626+ /// This may, as a side effect, clear the reader's scratch buffer (as the provided
2727+ /// implementation does).
2828+ ///
2929+ /// A more appropriate lifetime setup for this (that would allow the Deserializer::convert_str
3030+ /// to stay a function) would be something like `fn read<'a, 'r: 'a>(&'a mut 'r immut self, ...) -> ...
3131+ /// EitherLifetime<'r, 'de>>`, which borrows self mutably for the duration of the function and
3232+ /// downgrates that reference to an immutable one that outlives the result (protecting the
3333+ /// scratch buffer from changes), but alas, that can't be expressed (yet?).
3434+ fn read<'a>(&'a mut self, n: usize) -> Result<EitherLifetime<'a, 'de>> {
3535+ self.clear_buffer();
3636+ self.read_to_buffer(n)?;
3737+3838+ Ok(self.take_buffer())
3939+ }
4040+4141+ #[doc(hidden)]
4242+ fn next(&mut self) -> Result<Option<u8>>;
4343+4444+ #[doc(hidden)]
4545+ fn peek(&mut self) -> Result<Option<u8>>;
4646+4747+ #[doc(hidden)]
4848+ fn clear_buffer(&mut self);
4949+5050+ #[doc(hidden)]
5151+ fn read_to_buffer(&mut self, n: usize) -> Result<()>;
5252+5353+ #[doc(hidden)]
5454+ fn take_buffer<'a>(&'a mut self) -> EitherLifetime<'a, 'de>;
5555+5656+ #[doc(hidden)]
5757+ fn read_into(&mut self, buf: &mut [u8]) -> Result<()>;
5858+5959+ #[doc(hidden)]
6060+ fn discard(&mut self);
6161+6262+ #[doc(hidden)]
6363+ fn offset(&self) -> u64;
6464+}
6565+6666+#[cfg(feature = "unsealed_read_write")]
6767+/// Trait used by the deserializer for iterating over input.
6868+pub trait Read<'de> {
6969+ /// Read n bytes from the input.
7070+ ///
7171+ /// Implementations that can are asked to return a slice with a Long lifetime that outlives the
7272+ /// decoder, but others (eg. ones that need to allocate the data into a temporary buffer) can
7373+ /// return it with a Short lifetime that just lives for the time of read's mutable borrow of
7474+ /// the reader.
7575+ ///
7676+ /// This may, as a side effect, clear the reader's scratch buffer (as the provided
7777+ /// implementation does).
7878+7979+ // A more appropriate lifetime setup for this (that would allow the Deserializer::convert_str
8080+ // to stay a function) would be something like `fn read<'a, 'r: 'a>(&'a mut 'r immut self, ...) -> ...
8181+ // EitherLifetime<'r, 'de>>`, which borrows self mutably for the duration of the function and
8282+ // downgrates that reference to an immutable one that outlives the result (protecting the
8383+ // scratch buffer from changes), but alas, that can't be expressed (yet?).
8484+ fn read<'a>(&'a mut self, n: usize) -> Result<EitherLifetime<'a, 'de>> {
8585+ self.clear_buffer();
8686+ self.read_to_buffer(n)?;
8787+8888+ Ok(self.take_buffer())
8989+ }
9090+9191+ /// Read the next byte from the input, if any.
9292+ fn next(&mut self) -> Result<Option<u8>>;
9393+9494+ /// Peek at the next byte of the input, if any. This does not advance the reader, so the result
9595+ /// of this function will remain the same until a read or clear occurs.
9696+ fn peek(&mut self) -> Result<Option<u8>>;
9797+9898+ /// Clear the underlying scratch buffer
9999+ fn clear_buffer(&mut self);
100100+101101+ /// Append n bytes from the reader to the reader's scratch buffer (without clearing it)
102102+ fn read_to_buffer(&mut self, n: usize) -> Result<()>;
103103+104104+ /// Read out everything accumulated in the reader's scratch buffer. This may, as a side effect,
105105+ /// clear it.
106106+ fn take_buffer<'a>(&'a mut self) -> EitherLifetime<'a, 'de>;
107107+108108+ /// Read from the input until `buf` is full or end of input is encountered.
109109+ fn read_into(&mut self, buf: &mut [u8]) -> Result<()>;
110110+111111+ /// Discard any data read by `peek`.
112112+ fn discard(&mut self);
113113+114114+ /// Returns the offset from the start of the reader.
115115+ fn offset(&self) -> u64;
116116+}
117117+118118+/// Represents a reader that can return its current position
119119+pub trait Offset {
120120+ fn byte_offset(&self) -> usize;
121121+}
122122+123123+/// Represents a buffer with one of two lifetimes.
124124+pub enum EitherLifetime<'short, 'long> {
125125+ /// The short lifetime
126126+ Short(&'short [u8]),
127127+ /// The long lifetime
128128+ Long(&'long [u8]),
129129+}
130130+131131+#[cfg(not(feature = "unsealed_read_write"))]
132132+mod private {
133133+ pub trait Sealed {}
134134+}
135135+136136+/// CBOR input source that reads from a std::io input stream.
137137+#[cfg(feature = "std")]
138138+#[derive(Debug)]
139139+pub struct IoRead<R>
140140+where
141141+ R: io::Read,
142142+{
143143+ reader: OffsetReader<R>,
144144+ scratch: Vec<u8>,
145145+ ch: Option<u8>,
146146+}
147147+148148+#[cfg(feature = "std")]
149149+impl<R> IoRead<R>
150150+where
151151+ R: io::Read,
152152+{
153153+ /// Creates a new CBOR input source to read from a std::io input stream.
154154+ pub fn new(reader: R) -> IoRead<R> {
155155+ IoRead {
156156+ reader: OffsetReader { reader, offset: 0 },
157157+ scratch: vec![],
158158+ ch: None,
159159+ }
160160+ }
161161+162162+ #[inline]
163163+ fn next_inner(&mut self) -> Result<Option<u8>> {
164164+ let mut buf = [0; 1];
165165+ loop {
166166+ match self.reader.read(&mut buf) {
167167+ Ok(0) => return Ok(None),
168168+ Ok(_) => return Ok(Some(buf[0])),
169169+ Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
170170+ Err(e) => return Err(Error::io(e)),
171171+ }
172172+ }
173173+ }
174174+}
175175+176176+#[cfg(all(feature = "std", not(feature = "unsealed_read_write")))]
177177+impl<R> private::Sealed for IoRead<R> where R: io::Read {}
178178+179179+#[cfg(feature = "std")]
180180+impl<'de, R> Read<'de> for IoRead<R>
181181+where
182182+ R: io::Read,
183183+{
184184+ #[inline]
185185+ fn next(&mut self) -> Result<Option<u8>> {
186186+ match self.ch.take() {
187187+ Some(ch) => Ok(Some(ch)),
188188+ None => self.next_inner(),
189189+ }
190190+ }
191191+192192+ #[inline]
193193+ fn peek(&mut self) -> Result<Option<u8>> {
194194+ match self.ch {
195195+ Some(ch) => Ok(Some(ch)),
196196+ None => {
197197+ self.ch = self.next_inner()?;
198198+ Ok(self.ch)
199199+ }
200200+ }
201201+ }
202202+203203+ fn read_to_buffer(&mut self, mut n: usize) -> Result<()> {
204204+ // defend against malicious input pretending to be huge strings by limiting growth
205205+ self.scratch.reserve(cmp::min(n, 16 * 1024));
206206+207207+ if n == 0 {
208208+ return Ok(());
209209+ }
210210+211211+ if let Some(ch) = self.ch.take() {
212212+ self.scratch.push(ch);
213213+ n -= 1;
214214+ }
215215+216216+ // n == 0 is OK here and needs no further special treatment
217217+218218+ let transfer_result = {
219219+ // Prepare for take() (which consumes its reader) by creating a reference adaptor
220220+ // that'll only live in this block
221221+ let reference = self.reader.by_ref();
222222+ // Append the first n bytes of the reader to the scratch vector (or up to
223223+ // an error or EOF indicated by a shorter read)
224224+ let mut taken = reference.take(n as u64);
225225+ taken.read_to_end(&mut self.scratch)
226226+ };
227227+228228+ match transfer_result {
229229+ Ok(r) if r == n => Ok(()),
230230+ Ok(_) => Err(Error::syntax(
231231+ ErrorCode::EofWhileParsingValue,
232232+ self.offset(),
233233+ )),
234234+ Err(e) => Err(Error::io(e)),
235235+ }
236236+ }
237237+238238+ fn clear_buffer(&mut self) {
239239+ self.scratch.clear();
240240+ }
241241+242242+ fn take_buffer<'a>(&'a mut self) -> EitherLifetime<'a, 'de> {
243243+ EitherLifetime::Short(&self.scratch)
244244+ }
245245+246246+ fn read_into(&mut self, buf: &mut [u8]) -> Result<()> {
247247+ self.reader.read_exact(buf).map_err(|e| {
248248+ if e.kind() == io::ErrorKind::UnexpectedEof {
249249+ Error::syntax(ErrorCode::EofWhileParsingValue, self.offset())
250250+ } else {
251251+ Error::io(e)
252252+ }
253253+ })
254254+ }
255255+256256+ #[inline]
257257+ fn discard(&mut self) {
258258+ self.ch = None;
259259+ }
260260+261261+ fn offset(&self) -> u64 {
262262+ self.reader.offset
263263+ }
264264+}
265265+266266+#[cfg(feature = "std")]
267267+impl<R> Offset for IoRead<R>
268268+where
269269+ R: std::io::Read,
270270+{
271271+ fn byte_offset(&self) -> usize {
272272+ self.offset() as usize
273273+ }
274274+}
275275+276276+#[cfg(feature = "std")]
277277+#[derive(Debug)]
278278+struct OffsetReader<R> {
279279+ reader: R,
280280+ offset: u64,
281281+}
282282+283283+#[cfg(feature = "std")]
284284+impl<R> io::Read for OffsetReader<R>
285285+where
286286+ R: io::Read,
287287+{
288288+ #[inline]
289289+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
290290+ let r = self.reader.read(buf);
291291+ if let Ok(count) = r {
292292+ self.offset += count as u64;
293293+ }
294294+ r
295295+ }
296296+}
297297+298298+/// A CBOR input source that reads from a slice of bytes.
299299+#[cfg(any(feature = "std", feature = "alloc"))]
300300+#[derive(Debug)]
301301+pub struct SliceRead<'a> {
302302+ slice: &'a [u8],
303303+ scratch: Vec<u8>,
304304+ index: usize,
305305+}
306306+307307+#[cfg(any(feature = "std", feature = "alloc"))]
308308+impl<'a> SliceRead<'a> {
309309+ /// Creates a CBOR input source to read from a slice of bytes.
310310+ pub fn new(slice: &'a [u8]) -> SliceRead<'a> {
311311+ SliceRead {
312312+ slice,
313313+ scratch: vec![],
314314+ index: 0,
315315+ }
316316+ }
317317+318318+ fn end(&self, n: usize) -> Result<usize> {
319319+ match self.index.checked_add(n) {
320320+ Some(end) if end <= self.slice.len() => Ok(end),
321321+ _ => Err(Error::syntax(
322322+ ErrorCode::EofWhileParsingValue,
323323+ self.slice.len() as u64,
324324+ )),
325325+ }
326326+ }
327327+}
328328+329329+#[cfg(any(feature = "std", feature = "alloc"))]
330330+impl Offset for SliceRead<'_> {
331331+ #[inline]
332332+ fn byte_offset(&self) -> usize {
333333+ self.index
334334+ }
335335+}
336336+337337+#[cfg(all(
338338+ any(feature = "std", feature = "alloc"),
339339+ not(feature = "unsealed_read_write")
340340+))]
341341+impl private::Sealed for SliceRead<'_> {}
342342+343343+#[cfg(any(feature = "std", feature = "alloc"))]
344344+impl<'a> Read<'a> for SliceRead<'a> {
345345+ #[inline]
346346+ fn next(&mut self) -> Result<Option<u8>> {
347347+ Ok(if self.index < self.slice.len() {
348348+ let ch = self.slice[self.index];
349349+ self.index += 1;
350350+ Some(ch)
351351+ } else {
352352+ None
353353+ })
354354+ }
355355+356356+ #[inline]
357357+ fn peek(&mut self) -> Result<Option<u8>> {
358358+ Ok(if self.index < self.slice.len() {
359359+ Some(self.slice[self.index])
360360+ } else {
361361+ None
362362+ })
363363+ }
364364+365365+ fn clear_buffer(&mut self) {
366366+ self.scratch.clear();
367367+ }
368368+369369+ fn read_to_buffer(&mut self, n: usize) -> Result<()> {
370370+ let end = self.end(n)?;
371371+ let slice = &self.slice[self.index..end];
372372+ self.scratch.extend_from_slice(slice);
373373+ self.index = end;
374374+375375+ Ok(())
376376+ }
377377+378378+ #[inline]
379379+ fn read<'b>(&'b mut self, n: usize) -> Result<EitherLifetime<'b, 'a>> {
380380+ let end = self.end(n)?;
381381+ let slice = &self.slice[self.index..end];
382382+ self.index = end;
383383+ Ok(EitherLifetime::Long(slice))
384384+ }
385385+386386+ fn take_buffer<'b>(&'b mut self) -> EitherLifetime<'b, 'a> {
387387+ EitherLifetime::Short(&self.scratch)
388388+ }
389389+390390+ #[inline]
391391+ fn read_into(&mut self, buf: &mut [u8]) -> Result<()> {
392392+ let end = self.end(buf.len())?;
393393+ buf.copy_from_slice(&self.slice[self.index..end]);
394394+ self.index = end;
395395+ Ok(())
396396+ }
397397+398398+ #[inline]
399399+ fn discard(&mut self) {
400400+ self.index += 1;
401401+ }
402402+403403+ fn offset(&self) -> u64 {
404404+ self.index as u64
405405+ }
406406+}
407407+408408+/// A CBOR input source that reads from a slice of bytes using a fixed size scratch buffer.
409409+///
410410+/// [`SliceRead`](struct.SliceRead.html) and [`MutSliceRead`](struct.MutSliceRead.html) are usually
411411+/// preferred over this, as they can handle indefinite length items.
412412+#[derive(Debug)]
413413+pub struct SliceReadFixed<'a, 'b> {
414414+ slice: &'a [u8],
415415+ scratch: &'b mut [u8],
416416+ index: usize,
417417+ scratch_index: usize,
418418+}
419419+420420+impl<'a, 'b> SliceReadFixed<'a, 'b> {
421421+ /// Creates a CBOR input source to read from a slice of bytes, backed by a scratch buffer.
422422+ pub fn new(slice: &'a [u8], scratch: &'b mut [u8]) -> SliceReadFixed<'a, 'b> {
423423+ SliceReadFixed {
424424+ slice,
425425+ scratch,
426426+ index: 0,
427427+ scratch_index: 0,
428428+ }
429429+ }
430430+431431+ fn end(&self, n: usize) -> Result<usize> {
432432+ match self.index.checked_add(n) {
433433+ Some(end) if end <= self.slice.len() => Ok(end),
434434+ _ => Err(Error::syntax(
435435+ ErrorCode::EofWhileParsingValue,
436436+ self.slice.len() as u64,
437437+ )),
438438+ }
439439+ }
440440+441441+ fn scratch_end(&self, n: usize) -> Result<usize> {
442442+ match self.scratch_index.checked_add(n) {
443443+ Some(end) if end <= self.scratch.len() => Ok(end),
444444+ _ => Err(Error::scratch_too_small(self.index as u64)),
445445+ }
446446+ }
447447+}
448448+449449+#[cfg(not(feature = "unsealed_read_write"))]
450450+impl private::Sealed for SliceReadFixed<'_, '_> {}
451451+452452+impl<'a> Read<'a> for SliceReadFixed<'a, '_> {
453453+ #[inline]
454454+ fn next(&mut self) -> Result<Option<u8>> {
455455+ Ok(if self.index < self.slice.len() {
456456+ let ch = self.slice[self.index];
457457+ self.index += 1;
458458+ Some(ch)
459459+ } else {
460460+ None
461461+ })
462462+ }
463463+464464+ #[inline]
465465+ fn peek(&mut self) -> Result<Option<u8>> {
466466+ Ok(if self.index < self.slice.len() {
467467+ Some(self.slice[self.index])
468468+ } else {
469469+ None
470470+ })
471471+ }
472472+473473+ fn clear_buffer(&mut self) {
474474+ self.scratch_index = 0;
475475+ }
476476+477477+ fn read_to_buffer(&mut self, n: usize) -> Result<()> {
478478+ let end = self.end(n)?;
479479+ let scratch_end = self.scratch_end(n)?;
480480+ let slice = &self.slice[self.index..end];
481481+ self.scratch[self.scratch_index..scratch_end].copy_from_slice(slice);
482482+ self.index = end;
483483+ self.scratch_index = scratch_end;
484484+485485+ Ok(())
486486+ }
487487+488488+ fn read<'c>(&'c mut self, n: usize) -> Result<EitherLifetime<'c, 'a>> {
489489+ let end = self.end(n)?;
490490+ let slice = &self.slice[self.index..end];
491491+ self.index = end;
492492+ Ok(EitherLifetime::Long(slice))
493493+ }
494494+495495+ fn take_buffer<'c>(&'c mut self) -> EitherLifetime<'c, 'a> {
496496+ EitherLifetime::Short(&self.scratch[0..self.scratch_index])
497497+ }
498498+499499+ #[inline]
500500+ fn read_into(&mut self, buf: &mut [u8]) -> Result<()> {
501501+ let end = self.end(buf.len())?;
502502+ buf.copy_from_slice(&self.slice[self.index..end]);
503503+ self.index = end;
504504+ Ok(())
505505+ }
506506+507507+ #[inline]
508508+ fn discard(&mut self) {
509509+ self.index += 1;
510510+ }
511511+512512+ fn offset(&self) -> u64 {
513513+ self.index as u64
514514+ }
515515+}
516516+517517+#[cfg(any(feature = "std", feature = "alloc"))]
518518+impl Offset for SliceReadFixed<'_, '_> {
519519+ #[inline]
520520+ fn byte_offset(&self) -> usize {
521521+ self.index
522522+ }
523523+}
524524+525525+/// A CBOR input source that reads from a slice of bytes, and can move data around internally to
526526+/// reassemble indefinite strings without the need of an allocated scratch buffer.
527527+#[derive(Debug)]
528528+pub struct MutSliceRead<'a> {
529529+ /// A complete view of the reader's data. It is promised that bytes before buffer_end are not
530530+ /// mutated any more.
531531+ slice: &'a mut [u8],
532532+ /// Read cursor position in slice
533533+ index: usize,
534534+ /// Number of bytes already discarded from the slice
535535+ before: usize,
536536+ /// End of the buffer area that contains all bytes read_into_buffer. This is always <= index.
537537+ buffer_end: usize,
538538+}
539539+540540+impl<'a> MutSliceRead<'a> {
541541+ /// Creates a CBOR input source to read from a slice of bytes.
542542+ pub fn new(slice: &'a mut [u8]) -> MutSliceRead<'a> {
543543+ MutSliceRead {
544544+ slice,
545545+ index: 0,
546546+ before: 0,
547547+ buffer_end: 0,
548548+ }
549549+ }
550550+551551+ fn end(&self, n: usize) -> Result<usize> {
552552+ match self.index.checked_add(n) {
553553+ Some(end) if end <= self.slice.len() => Ok(end),
554554+ _ => Err(Error::syntax(
555555+ ErrorCode::EofWhileParsingValue,
556556+ self.slice.len() as u64,
557557+ )),
558558+ }
559559+ }
560560+}
561561+562562+#[cfg(not(feature = "unsealed_read_write"))]
563563+impl private::Sealed for MutSliceRead<'_> {}
564564+565565+impl<'a> Read<'a> for MutSliceRead<'a> {
566566+ #[inline]
567567+ fn next(&mut self) -> Result<Option<u8>> {
568568+ // This is duplicated from SliceRead, can that be eased?
569569+ Ok(if self.index < self.slice.len() {
570570+ let ch = self.slice[self.index];
571571+ self.index += 1;
572572+ Some(ch)
573573+ } else {
574574+ None
575575+ })
576576+ }
577577+578578+ #[inline]
579579+ fn peek(&mut self) -> Result<Option<u8>> {
580580+ // This is duplicated from SliceRead, can that be eased?
581581+ Ok(if self.index < self.slice.len() {
582582+ Some(self.slice[self.index])
583583+ } else {
584584+ None
585585+ })
586586+ }
587587+588588+ fn clear_buffer(&mut self) {
589589+ self.slice = &mut mem::take(&mut self.slice)[self.index..];
590590+ self.before += self.index;
591591+ self.index = 0;
592592+ self.buffer_end = 0;
593593+ }
594594+595595+ fn read_to_buffer(&mut self, n: usize) -> Result<()> {
596596+ let end = self.end(n)?;
597597+ debug_assert!(
598598+ self.buffer_end <= self.index,
599599+ "MutSliceRead invariant violated: scratch buffer exceeds index"
600600+ );
601601+ self.slice[self.buffer_end..end].rotate_left(self.index - self.buffer_end);
602602+ self.buffer_end += n;
603603+ self.index = end;
604604+605605+ Ok(())
606606+ }
607607+608608+ fn take_buffer<'b>(&'b mut self) -> EitherLifetime<'b, 'a> {
609609+ let (left, right) = mem::take(&mut self.slice).split_at_mut(self.index);
610610+ self.slice = right;
611611+ self.before += self.index;
612612+ self.index = 0;
613613+614614+ let left = &left[..self.buffer_end];
615615+ self.buffer_end = 0;
616616+617617+ EitherLifetime::Long(left)
618618+ }
619619+620620+ #[inline]
621621+ fn read_into(&mut self, buf: &mut [u8]) -> Result<()> {
622622+ // This is duplicated from SliceRead, can that be eased?
623623+ let end = self.end(buf.len())?;
624624+ buf.copy_from_slice(&self.slice[self.index..end]);
625625+ self.index = end;
626626+ Ok(())
627627+ }
628628+629629+ #[inline]
630630+ fn discard(&mut self) {
631631+ self.index += 1;
632632+ }
633633+634634+ fn offset(&self) -> u64 {
635635+ (self.before + self.index) as u64
636636+ }
637637+}
+747
vendor/git/cbor/src/ser.rs
···11+//! Serialize a Rust data structure to CBOR data.
22+33+#[cfg(feature = "alloc")]
44+use alloc::vec::Vec;
55+66+#[cfg(feature = "std")]
77+pub use crate::write::IoWrite;
88+pub use crate::write::{SliceWrite, Write};
99+1010+use crate::error::{Error, Result};
1111+use half::f16;
1212+use serde::ser::{self, Serialize};
1313+#[cfg(feature = "std")]
1414+use std::io;
1515+1616+use crate::tags::{get_tag, CBOR_NEWTYPE_NAME};
1717+1818+/// Serializes a value to a vector.
1919+#[cfg(any(feature = "std", feature = "alloc"))]
2020+pub fn to_vec<T>(value: &T) -> Result<Vec<u8>>
2121+where
2222+ T: ser::Serialize,
2323+{
2424+ let mut vec = Vec::new();
2525+ value.serialize(&mut Serializer::new(&mut vec))?;
2626+ Ok(vec)
2727+}
2828+2929+/// Serializes a value to a vector in packed format.
3030+#[cfg(feature = "std")]
3131+pub fn to_vec_packed<T>(value: &T) -> Result<Vec<u8>>
3232+where
3333+ T: ser::Serialize,
3434+{
3535+ let mut vec = Vec::new();
3636+ value.serialize(&mut Serializer::new(&mut IoWrite::new(&mut vec)).packed_format())?;
3737+ Ok(vec)
3838+}
3939+4040+/// Serializes a value to a writer.
4141+#[cfg(feature = "std")]
4242+pub fn to_writer<W, T>(writer: W, value: &T) -> Result<()>
4343+where
4444+ W: io::Write,
4545+ T: ser::Serialize,
4646+{
4747+ value.serialize(&mut Serializer::new(&mut IoWrite::new(writer)))
4848+}
4949+5050+/// A structure for serializing Rust values to CBOR.
5151+#[derive(Debug)]
5252+pub struct Serializer<W> {
5353+ writer: W,
5454+ packed: bool,
5555+ enum_as_map: bool,
5656+}
5757+5858+impl<W> Serializer<W>
5959+where
6060+ W: Write,
6161+{
6262+ /// Creates a new CBOR serializer.
6363+ ///
6464+ /// `to_vec` and `to_writer` should normally be used instead of this method.
6565+ #[inline]
6666+ pub fn new(writer: W) -> Self {
6767+ Serializer {
6868+ writer,
6969+ packed: false,
7070+ enum_as_map: true,
7171+ }
7272+ }
7373+7474+ /// Choose concise/packed format for serializer.
7575+ ///
7676+ /// In the packed format enum variant names and field names
7777+ /// are replaced with numeric indizes to conserve space.
7878+ pub fn packed_format(mut self) -> Self {
7979+ self.packed = true;
8080+ self
8181+ }
8282+8383+ /// Enable old enum format used by `serde_cbor` versions <= v0.9.
8484+ ///
8585+ /// The `legacy_enums` option determines how enums are encoded.
8686+ ///
8787+ /// This makes no difference when encoding and decoding enums using
8888+ /// this crate, but it shows up when decoding to a `Value` or decoding
8989+ /// in other languages.
9090+ ///
9191+ /// # Examples
9292+ ///
9393+ /// Given the following enum
9494+ ///
9595+ /// ```rust
9696+ /// enum Enum {
9797+ /// Unit,
9898+ /// NewType(i32),
9999+ /// Tuple(String, bool),
100100+ /// Struct{ x: i32, y: i32 },
101101+ /// }
102102+ /// ```
103103+ /// we will give the `Value` with the same encoding for each case using
104104+ /// JSON notation.
105105+ ///
106106+ /// ## Default encodings
107107+ ///
108108+ /// * `Enum::Unit` encodes as `"Unit"`
109109+ /// * `Enum::NewType(10)` encodes as `{"NewType": 10}`
110110+ /// * `Enum::Tuple("x", true)` encodes as `{"Tuple": ["x", true]}`
111111+ ///
112112+ /// ## Legacy encodings
113113+ ///
114114+ /// * `Enum::Unit` encodes as `"Unit"`
115115+ /// * `Enum::NewType(10)` encodes as `["NewType", 10]`
116116+ /// * `Enum::Tuple("x", true)` encodes as `["Tuple", "x", true]`
117117+ /// * `Enum::Struct{ x: 5, y: -5 }` encodes as `["Struct", {"x": 5, "y": -5}]`
118118+ pub fn legacy_enums(mut self) -> Self {
119119+ self.enum_as_map = false;
120120+ self
121121+ }
122122+123123+ /// Writes a CBOR self-describe tag to the stream.
124124+ ///
125125+ /// Tagging allows a decoder to distinguish different file formats based on their content
126126+ /// without further information.
127127+ #[inline]
128128+ pub fn self_describe(&mut self) -> Result<()> {
129129+ let mut buf = [(6 << 5) | 25, 0, 0];
130130+ buf[1..].copy_from_slice(&55799u16.to_be_bytes());
131131+ self.writer.write_all(&buf).map_err(|e| e.into())
132132+ }
133133+134134+ /// Unwrap the `Writer` from the `Serializer`.
135135+ #[inline]
136136+ pub fn into_inner(self) -> W {
137137+ self.writer
138138+ }
139139+140140+ #[inline]
141141+ fn write_u8(&mut self, major: u8, value: u8) -> Result<()> {
142142+ if value <= 0x17 {
143143+ self.writer.write_all(&[(major << 5) | value])
144144+ } else {
145145+ let buf = [(major << 5) | 24, value];
146146+ self.writer.write_all(&buf)
147147+ }
148148+ .map_err(|e| e.into())
149149+ }
150150+151151+ #[inline]
152152+ fn write_u16(&mut self, major: u8, value: u16) -> Result<()> {
153153+ if value <= u16::from(u8::MAX) {
154154+ self.write_u8(major, value as u8)
155155+ } else {
156156+ let mut buf = [(major << 5) | 25, 0, 0];
157157+ buf[1..].copy_from_slice(&value.to_be_bytes());
158158+ self.writer.write_all(&buf).map_err(|e| e.into())
159159+ }
160160+ }
161161+162162+ #[inline]
163163+ fn write_u32(&mut self, major: u8, value: u32) -> Result<()> {
164164+ if value <= u32::from(u16::MAX) {
165165+ self.write_u16(major, value as u16)
166166+ } else {
167167+ let mut buf = [(major << 5) | 26, 0, 0, 0, 0];
168168+ buf[1..].copy_from_slice(&value.to_be_bytes());
169169+ self.writer.write_all(&buf).map_err(|e| e.into())
170170+ }
171171+ }
172172+173173+ #[inline]
174174+ fn write_u64(&mut self, major: u8, value: u64) -> Result<()> {
175175+ if value <= u64::from(u32::MAX) {
176176+ self.write_u32(major, value as u32)
177177+ } else {
178178+ let mut buf = [(major << 5) | 27, 0, 0, 0, 0, 0, 0, 0, 0];
179179+ buf[1..].copy_from_slice(&value.to_be_bytes());
180180+ self.writer.write_all(&buf).map_err(|e| e.into())
181181+ }
182182+ }
183183+184184+ #[inline]
185185+ fn serialize_collection(
186186+ &mut self,
187187+ major: u8,
188188+ len: Option<usize>,
189189+ ) -> Result<CollectionSerializer<'_, W>> {
190190+ let needs_eof = match len {
191191+ Some(len) => {
192192+ self.write_u64(major, len as u64)?;
193193+ false
194194+ }
195195+ None => {
196196+ self.writer
197197+ .write_all(&[(major << 5) | 31])
198198+ .map_err(|e| e.into())?;
199199+ true
200200+ }
201201+ };
202202+203203+ Ok(CollectionSerializer {
204204+ ser: self,
205205+ needs_eof,
206206+ })
207207+ }
208208+}
209209+210210+impl<'a, W> ser::Serializer for &'a mut Serializer<W>
211211+where
212212+ W: Write,
213213+{
214214+ type Ok = ();
215215+ type Error = Error;
216216+217217+ type SerializeSeq = CollectionSerializer<'a, W>;
218218+ type SerializeTuple = &'a mut Serializer<W>;
219219+ type SerializeTupleStruct = &'a mut Serializer<W>;
220220+ type SerializeTupleVariant = &'a mut Serializer<W>;
221221+ type SerializeMap = CollectionSerializer<'a, W>;
222222+ type SerializeStruct = StructSerializer<'a, W>;
223223+ type SerializeStructVariant = StructSerializer<'a, W>;
224224+225225+ #[inline]
226226+ fn serialize_bool(self, value: bool) -> Result<()> {
227227+ let value = if value { 0xf5 } else { 0xf4 };
228228+ self.writer.write_all(&[value]).map_err(|e| e.into())
229229+ }
230230+231231+ #[inline]
232232+ fn serialize_i8(self, value: i8) -> Result<()> {
233233+ if value < 0 {
234234+ self.write_u8(1, -(value + 1) as u8)
235235+ } else {
236236+ self.write_u8(0, value as u8)
237237+ }
238238+ }
239239+240240+ #[inline]
241241+ fn serialize_i16(self, value: i16) -> Result<()> {
242242+ if value < 0 {
243243+ self.write_u16(1, -(value + 1) as u16)
244244+ } else {
245245+ self.write_u16(0, value as u16)
246246+ }
247247+ }
248248+249249+ #[inline]
250250+ fn serialize_i32(self, value: i32) -> Result<()> {
251251+ if value < 0 {
252252+ self.write_u32(1, -(value + 1) as u32)
253253+ } else {
254254+ self.write_u32(0, value as u32)
255255+ }
256256+ }
257257+258258+ #[inline]
259259+ fn serialize_i64(self, value: i64) -> Result<()> {
260260+ if value < 0 {
261261+ self.write_u64(1, -(value + 1) as u64)
262262+ } else {
263263+ self.write_u64(0, value as u64)
264264+ }
265265+ }
266266+267267+ #[inline]
268268+ fn serialize_i128(self, value: i128) -> Result<()> {
269269+ if value < 0 {
270270+ if -(value + 1) > i128::from(u64::MAX) {
271271+ return Err(Error::message("The number can't be stored in CBOR"));
272272+ }
273273+ self.write_u64(1, -(value + 1) as u64)
274274+ } else {
275275+ if value > i128::from(u64::MAX) {
276276+ return Err(Error::message("The number can't be stored in CBOR"));
277277+ }
278278+ self.write_u64(0, value as u64)
279279+ }
280280+ }
281281+282282+ #[inline]
283283+ fn serialize_u8(self, value: u8) -> Result<()> {
284284+ self.write_u8(0, value)
285285+ }
286286+287287+ #[inline]
288288+ fn serialize_u16(self, value: u16) -> Result<()> {
289289+ self.write_u16(0, value)
290290+ }
291291+292292+ #[inline]
293293+ fn serialize_u32(self, value: u32) -> Result<()> {
294294+ self.write_u32(0, value)
295295+ }
296296+297297+ #[inline]
298298+ fn serialize_u64(self, value: u64) -> Result<()> {
299299+ self.write_u64(0, value)
300300+ }
301301+302302+ #[inline]
303303+ fn serialize_u128(self, value: u128) -> Result<()> {
304304+ if value > u128::from(u64::MAX) {
305305+ return Err(Error::message("The number can't be stored in CBOR"));
306306+ }
307307+ self.write_u64(0, value as u64)
308308+ }
309309+310310+ #[inline]
311311+ #[allow(clippy::float_cmp)]
312312+ fn serialize_f32(self, value: f32) -> Result<()> {
313313+ if value.is_infinite() {
314314+ if value.is_sign_positive() {
315315+ self.writer.write_all(&[0xf9, 0x7c, 0x00])
316316+ } else {
317317+ self.writer.write_all(&[0xf9, 0xfc, 0x00])
318318+ }
319319+ } else if value.is_nan() {
320320+ self.writer.write_all(&[0xf9, 0x7e, 0x00])
321321+ } else if f32::from(f16::from_f32(value)) == value {
322322+ let mut buf = [0xf9, 0, 0];
323323+ buf[1..].copy_from_slice(&f16::from_f32(value).to_bits().to_be_bytes());
324324+ self.writer.write_all(&buf)
325325+ } else {
326326+ let mut buf = [0xfa, 0, 0, 0, 0];
327327+ buf[1..].copy_from_slice(&value.to_bits().to_be_bytes());
328328+ self.writer.write_all(&buf)
329329+ }
330330+ .map_err(|e| e.into())
331331+ }
332332+333333+ #[inline]
334334+ #[allow(clippy::float_cmp)]
335335+ fn serialize_f64(self, value: f64) -> Result<()> {
336336+ if !value.is_finite() || f64::from(value as f32) == value {
337337+ self.serialize_f32(value as f32)
338338+ } else {
339339+ let mut buf = [0xfb, 0, 0, 0, 0, 0, 0, 0, 0];
340340+ buf[1..].copy_from_slice(&value.to_bits().to_be_bytes());
341341+ self.writer.write_all(&buf).map_err(|e| e.into())
342342+ }
343343+ }
344344+345345+ #[inline]
346346+ fn serialize_char(self, value: char) -> Result<()> {
347347+ // A char encoded as UTF-8 takes 4 bytes at most.
348348+ let mut buf = [0; 4];
349349+ self.serialize_str(value.encode_utf8(&mut buf))
350350+ }
351351+352352+ #[inline]
353353+ fn serialize_str(self, value: &str) -> Result<()> {
354354+ self.write_u64(3, value.len() as u64)?;
355355+ self.writer
356356+ .write_all(value.as_bytes())
357357+ .map_err(|e| e.into())
358358+ }
359359+360360+ #[inline]
361361+ fn serialize_bytes(self, value: &[u8]) -> Result<()> {
362362+ self.write_u64(2, value.len() as u64)?;
363363+ self.writer.write_all(value).map_err(|e| e.into())
364364+ }
365365+366366+ #[inline]
367367+ fn serialize_unit(self) -> Result<()> {
368368+ self.serialize_none()
369369+ }
370370+371371+ #[inline]
372372+ fn serialize_some<T>(self, value: &T) -> Result<()>
373373+ where
374374+ T: ?Sized + ser::Serialize,
375375+ {
376376+ value.serialize(self)
377377+ }
378378+379379+ #[inline]
380380+ fn serialize_none(self) -> Result<()> {
381381+ self.writer.write_all(&[0xf6]).map_err(|e| e.into())
382382+ }
383383+384384+ #[inline]
385385+ fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
386386+ self.serialize_unit()
387387+ }
388388+389389+ #[inline]
390390+ fn serialize_unit_variant(
391391+ self,
392392+ _name: &'static str,
393393+ variant_index: u32,
394394+ variant: &'static str,
395395+ ) -> Result<()> {
396396+ if self.packed {
397397+ self.serialize_u32(variant_index)
398398+ } else {
399399+ self.serialize_str(variant)
400400+ }
401401+ }
402402+403403+ #[inline]
404404+ fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<()>
405405+ where
406406+ T: ?Sized + ser::Serialize,
407407+ {
408408+ if name == CBOR_NEWTYPE_NAME {
409409+ if let Some(tag) = get_tag() {
410410+ self.write_u64(6, tag)?;
411411+ }
412412+ }
413413+ value.serialize(self)
414414+ }
415415+416416+ #[inline]
417417+ fn serialize_newtype_variant<T>(
418418+ self,
419419+ name: &'static str,
420420+ variant_index: u32,
421421+ variant: &'static str,
422422+ value: &T,
423423+ ) -> Result<()>
424424+ where
425425+ T: ?Sized + ser::Serialize,
426426+ {
427427+ if self.enum_as_map {
428428+ self.write_u64(5, 1u64)?;
429429+ variant.serialize(&mut *self)?;
430430+ } else {
431431+ self.writer
432432+ .write_all(&[(4 << 5) | 2])
433433+ .map_err(|e| e.into())?;
434434+ self.serialize_unit_variant(name, variant_index, variant)?;
435435+ }
436436+ value.serialize(self)
437437+ }
438438+439439+ #[inline]
440440+ fn serialize_seq(self, len: Option<usize>) -> Result<CollectionSerializer<'a, W>> {
441441+ self.serialize_collection(4, len)
442442+ }
443443+444444+ #[inline]
445445+ fn serialize_tuple(self, len: usize) -> Result<&'a mut Serializer<W>> {
446446+ self.write_u64(4, len as u64)?;
447447+ Ok(self)
448448+ }
449449+450450+ #[inline]
451451+ fn serialize_tuple_struct(
452452+ self,
453453+ _name: &'static str,
454454+ len: usize,
455455+ ) -> Result<&'a mut Serializer<W>> {
456456+ self.serialize_tuple(len)
457457+ }
458458+459459+ #[inline]
460460+ fn serialize_tuple_variant(
461461+ self,
462462+ name: &'static str,
463463+ variant_index: u32,
464464+ variant: &'static str,
465465+ len: usize,
466466+ ) -> Result<&'a mut Serializer<W>> {
467467+ if self.enum_as_map {
468468+ self.write_u64(5, 1u64)?;
469469+ variant.serialize(&mut *self)?;
470470+ self.serialize_tuple(len)
471471+ } else {
472472+ self.write_u64(4, (len + 1) as u64)?;
473473+ self.serialize_unit_variant(name, variant_index, variant)?;
474474+ Ok(self)
475475+ }
476476+ }
477477+478478+ #[inline]
479479+ fn serialize_map(self, len: Option<usize>) -> Result<CollectionSerializer<'a, W>> {
480480+ self.serialize_collection(5, len)
481481+ }
482482+483483+ #[cfg(not(feature = "std"))]
484484+ fn collect_str<T: ?Sized>(self, value: &T) -> Result<()>
485485+ where
486486+ T: core::fmt::Display,
487487+ {
488488+ use crate::write::FmtWrite;
489489+ use core::fmt::Write;
490490+491491+ let mut w = FmtWrite::new(&mut self.writer);
492492+ write!(w, "{}", value)?;
493493+ Ok(())
494494+ }
495495+496496+ #[inline]
497497+ fn serialize_struct(self, _name: &'static str, len: usize) -> Result<StructSerializer<'a, W>> {
498498+ self.write_u64(5, len as u64)?;
499499+ Ok(StructSerializer { ser: self, idx: 0 })
500500+ }
501501+502502+ #[inline]
503503+ fn serialize_struct_variant(
504504+ self,
505505+ name: &'static str,
506506+ variant_index: u32,
507507+ variant: &'static str,
508508+ len: usize,
509509+ ) -> Result<StructSerializer<'a, W>> {
510510+ if self.enum_as_map {
511511+ self.write_u64(5, 1u64)?;
512512+ } else {
513513+ self.writer
514514+ .write_all(&[(4 << 5) | 2])
515515+ .map_err(|e| e.into())?;
516516+ }
517517+ self.serialize_unit_variant(name, variant_index, variant)?;
518518+ self.serialize_struct(name, len)
519519+ }
520520+521521+ #[inline]
522522+ fn is_human_readable(&self) -> bool {
523523+ false
524524+ }
525525+}
526526+527527+impl<W> ser::SerializeTuple for &mut Serializer<W>
528528+where
529529+ W: Write,
530530+{
531531+ type Ok = ();
532532+ type Error = Error;
533533+534534+ #[inline]
535535+ fn serialize_element<T>(&mut self, value: &T) -> Result<()>
536536+ where
537537+ T: ?Sized + ser::Serialize,
538538+ {
539539+ value.serialize(&mut **self)
540540+ }
541541+542542+ #[inline]
543543+ fn end(self) -> Result<()> {
544544+ Ok(())
545545+ }
546546+}
547547+548548+impl<W> ser::SerializeTupleStruct for &mut Serializer<W>
549549+where
550550+ W: Write,
551551+{
552552+ type Ok = ();
553553+ type Error = Error;
554554+555555+ #[inline]
556556+ fn serialize_field<T>(&mut self, value: &T) -> Result<()>
557557+ where
558558+ T: ?Sized + ser::Serialize,
559559+ {
560560+ value.serialize(&mut **self)
561561+ }
562562+563563+ #[inline]
564564+ fn end(self) -> Result<()> {
565565+ Ok(())
566566+ }
567567+}
568568+569569+impl<W> ser::SerializeTupleVariant for &mut Serializer<W>
570570+where
571571+ W: Write,
572572+{
573573+ type Ok = ();
574574+ type Error = Error;
575575+576576+ #[inline]
577577+ fn serialize_field<T>(&mut self, value: &T) -> Result<()>
578578+ where
579579+ T: ?Sized + ser::Serialize,
580580+ {
581581+ value.serialize(&mut **self)
582582+ }
583583+584584+ #[inline]
585585+ fn end(self) -> Result<()> {
586586+ Ok(())
587587+ }
588588+}
589589+590590+#[doc(hidden)]
591591+pub struct StructSerializer<'a, W> {
592592+ ser: &'a mut Serializer<W>,
593593+ idx: u32,
594594+}
595595+596596+impl<W> StructSerializer<'_, W>
597597+where
598598+ W: Write,
599599+{
600600+ #[inline]
601601+ fn serialize_field_inner<T>(&mut self, key: &'static str, value: &T) -> Result<()>
602602+ where
603603+ T: ?Sized + ser::Serialize,
604604+ {
605605+ if self.ser.packed {
606606+ self.idx.serialize(&mut *self.ser)?;
607607+ } else {
608608+ key.serialize(&mut *self.ser)?;
609609+ }
610610+ value.serialize(&mut *self.ser)?;
611611+ self.idx += 1;
612612+ Ok(())
613613+ }
614614+615615+ #[inline]
616616+ fn skip_field_inner(&mut self, _: &'static str) -> Result<()> {
617617+ self.idx += 1;
618618+ Ok(())
619619+ }
620620+621621+ #[inline]
622622+ fn end_inner(self) -> Result<()> {
623623+ Ok(())
624624+ }
625625+}
626626+627627+impl<W> ser::SerializeStruct for StructSerializer<'_, W>
628628+where
629629+ W: Write,
630630+{
631631+ type Ok = ();
632632+ type Error = Error;
633633+634634+ #[inline]
635635+ fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
636636+ where
637637+ T: ?Sized + ser::Serialize,
638638+ {
639639+ self.serialize_field_inner(key, value)
640640+ }
641641+642642+ #[inline]
643643+ fn skip_field(&mut self, key: &'static str) -> Result<()> {
644644+ self.skip_field_inner(key)
645645+ }
646646+647647+ #[inline]
648648+ fn end(self) -> Result<()> {
649649+ self.end_inner()
650650+ }
651651+}
652652+653653+impl<W> ser::SerializeStructVariant for StructSerializer<'_, W>
654654+where
655655+ W: Write,
656656+{
657657+ type Ok = ();
658658+ type Error = Error;
659659+660660+ #[inline]
661661+ fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
662662+ where
663663+ T: ?Sized + ser::Serialize,
664664+ {
665665+ self.serialize_field_inner(key, value)
666666+ }
667667+668668+ #[inline]
669669+ fn skip_field(&mut self, key: &'static str) -> Result<()> {
670670+ self.skip_field_inner(key)
671671+ }
672672+673673+ #[inline]
674674+ fn end(self) -> Result<()> {
675675+ self.end_inner()
676676+ }
677677+}
678678+679679+#[doc(hidden)]
680680+pub struct CollectionSerializer<'a, W> {
681681+ ser: &'a mut Serializer<W>,
682682+ needs_eof: bool,
683683+}
684684+685685+impl<W> CollectionSerializer<'_, W>
686686+where
687687+ W: Write,
688688+{
689689+ #[inline]
690690+ fn end_inner(self) -> Result<()> {
691691+ if self.needs_eof {
692692+ self.ser.writer.write_all(&[0xff]).map_err(|e| e.into())
693693+ } else {
694694+ Ok(())
695695+ }
696696+ }
697697+}
698698+699699+impl<W> ser::SerializeSeq for CollectionSerializer<'_, W>
700700+where
701701+ W: Write,
702702+{
703703+ type Ok = ();
704704+ type Error = Error;
705705+706706+ #[inline]
707707+ fn serialize_element<T>(&mut self, value: &T) -> Result<()>
708708+ where
709709+ T: ?Sized + ser::Serialize,
710710+ {
711711+ value.serialize(&mut *self.ser)
712712+ }
713713+714714+ #[inline]
715715+ fn end(self) -> Result<()> {
716716+ self.end_inner()
717717+ }
718718+}
719719+720720+impl<W> ser::SerializeMap for CollectionSerializer<'_, W>
721721+where
722722+ W: Write,
723723+{
724724+ type Ok = ();
725725+ type Error = Error;
726726+727727+ #[inline]
728728+ fn serialize_key<T>(&mut self, key: &T) -> Result<()>
729729+ where
730730+ T: ?Sized + ser::Serialize,
731731+ {
732732+ key.serialize(&mut *self.ser)
733733+ }
734734+735735+ #[inline]
736736+ fn serialize_value<T>(&mut self, value: &T) -> Result<()>
737737+ where
738738+ T: ?Sized + ser::Serialize,
739739+ {
740740+ value.serialize(&mut *self.ser)
741741+ }
742742+743743+ #[inline]
744744+ fn end(self) -> Result<()> {
745745+ self.end_inner()
746746+ }
747747+}
+220
vendor/git/cbor/src/tags.rs
···11+//! Support for cbor tags
22+use core::fmt;
33+use core::marker::PhantomData;
44+use serde::de::{
55+ Deserialize, Deserializer, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, Visitor,
66+};
77+use serde::forward_to_deserialize_any;
88+use serde::ser::{Serialize, Serializer};
99+1010+/// signals that a newtype is from a CBOR tag
1111+pub(crate) const CBOR_NEWTYPE_NAME: &str = "\0cbor_tag";
1212+1313+/// A value that is optionally tagged with a cbor tag
1414+///
1515+/// this only serves as an intermediate helper for tag serialization or deserialization
1616+pub struct Tagged<T> {
1717+ /// cbor tag
1818+ pub tag: Option<u64>,
1919+ /// value
2020+ pub value: T,
2121+}
2222+2323+impl<T> Tagged<T> {
2424+ /// Create a new tagged value
2525+ pub fn new(tag: Option<u64>, value: T) -> Self {
2626+ Self { tag, value }
2727+ }
2828+}
2929+3030+impl<T: Serialize> Serialize for Tagged<T> {
3131+ fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
3232+ set_tag(self.tag);
3333+ let r = s.serialize_newtype_struct(CBOR_NEWTYPE_NAME, &self.value);
3434+ set_tag(None);
3535+ r
3636+ }
3737+}
3838+3939+fn untagged<T>(value: T) -> Tagged<T> {
4040+ Tagged::new(None, value)
4141+}
4242+4343+macro_rules! delegate {
4444+ ($name: ident, $type: ty) => {
4545+ fn $name<E: serde::de::Error>(self, v: $type) -> Result<Self::Value, E> {
4646+ T::deserialize(v.into_deserializer()).map(untagged)
4747+ }
4848+ };
4949+}
5050+5151+struct EnumDeserializer<A>(A);
5252+5353+impl<'de, A> Deserializer<'de> for EnumDeserializer<A>
5454+where
5555+ A: EnumAccess<'de>,
5656+{
5757+ type Error = A::Error;
5858+5959+ fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
6060+ visitor.visit_enum(self.0)
6161+ }
6262+6363+ forward_to_deserialize_any! {
6464+ bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
6565+ bytes byte_buf option unit unit_struct newtype_struct seq tuple
6666+ tuple_struct map struct enum identifier ignored_any
6767+ }
6868+}
6969+7070+struct NoneDeserializer<E>(PhantomData<E>);
7171+7272+impl<'de, E> Deserializer<'de> for NoneDeserializer<E>
7373+where
7474+ E: serde::de::Error,
7575+{
7676+ type Error = E;
7777+7878+ fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
7979+ visitor.visit_none()
8080+ }
8181+8282+ forward_to_deserialize_any! {
8383+ bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
8484+ bytes byte_buf option unit unit_struct newtype_struct seq tuple
8585+ tuple_struct map struct enum identifier ignored_any
8686+ }
8787+}
8888+8989+struct BytesDeserializer<'a, E>(&'a [u8], PhantomData<E>);
9090+9191+impl<'de, E> Deserializer<'de> for BytesDeserializer<'_, E>
9292+where
9393+ E: serde::de::Error,
9494+{
9595+ type Error = E;
9696+9797+ fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
9898+ visitor.visit_bytes(self.0)
9999+ }
100100+101101+ forward_to_deserialize_any! {
102102+ bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
103103+ bytes byte_buf option unit unit_struct newtype_struct seq tuple
104104+ tuple_struct map struct enum identifier ignored_any
105105+ }
106106+}
107107+108108+/// A visitor that intercepts *just* visit_newtype_struct and passes through everything else.
109109+struct MaybeTaggedVisitor<T>(PhantomData<T>);
110110+111111+impl<'de, T: Deserialize<'de>> Visitor<'de> for MaybeTaggedVisitor<T> {
112112+ type Value = Tagged<T>;
113113+114114+ fn expecting(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
115115+ fmt.write_str("a cbor tag newtype")
116116+ }
117117+118118+ delegate!(visit_bool, bool);
119119+120120+ delegate!(visit_i8, i8);
121121+ delegate!(visit_i16, i16);
122122+ delegate!(visit_i32, i32);
123123+ delegate!(visit_i64, i64);
124124+125125+ delegate!(visit_u8, u8);
126126+ delegate!(visit_u16, u16);
127127+ delegate!(visit_u32, u32);
128128+ delegate!(visit_u64, u64);
129129+130130+ delegate!(visit_f32, f32);
131131+ delegate!(visit_f64, f64);
132132+133133+ delegate!(visit_char, char);
134134+ delegate!(visit_str, &str);
135135+ delegate!(visit_borrowed_str, &'de str);
136136+137137+ #[cfg(feature = "std")]
138138+ delegate!(visit_byte_buf, Vec<u8>);
139139+140140+ #[cfg(feature = "std")]
141141+ delegate!(visit_string, String);
142142+143143+ fn visit_bytes<E: serde::de::Error>(self, value: &[u8]) -> Result<Self::Value, E> {
144144+ T::deserialize(BytesDeserializer(value, PhantomData)).map(untagged)
145145+ }
146146+147147+ fn visit_borrowed_bytes<E: serde::de::Error>(self, value: &'de [u8]) -> Result<Self::Value, E> {
148148+ T::deserialize(serde::de::value::BorrowedBytesDeserializer::new(value)).map(untagged)
149149+ }
150150+151151+ fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
152152+ T::deserialize(().into_deserializer()).map(untagged)
153153+ }
154154+155155+ fn visit_none<E: serde::de::Error>(self) -> Result<Self::Value, E> {
156156+ T::deserialize(NoneDeserializer(PhantomData)).map(untagged)
157157+ }
158158+159159+ fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
160160+ T::deserialize(deserializer).map(untagged)
161161+ }
162162+163163+ fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<Self::Value, A::Error> {
164164+ T::deserialize(serde::de::value::SeqAccessDeserializer::new(seq)).map(untagged)
165165+ }
166166+167167+ fn visit_map<V: MapAccess<'de>>(self, map: V) -> Result<Self::Value, V::Error> {
168168+ T::deserialize(serde::de::value::MapAccessDeserializer::new(map)).map(untagged)
169169+ }
170170+171171+ fn visit_enum<A: EnumAccess<'de>>(self, data: A) -> Result<Self::Value, A::Error> {
172172+ T::deserialize(EnumDeserializer(data)).map(untagged)
173173+ }
174174+175175+ fn visit_newtype_struct<D: serde::Deserializer<'de>>(
176176+ self,
177177+ deserializer: D,
178178+ ) -> Result<Self::Value, D::Error> {
179179+ let t = get_tag();
180180+ T::deserialize(deserializer).map(|v| Tagged::new(t, v))
181181+ }
182182+}
183183+184184+impl<'de, T: serde::de::Deserialize<'de>> serde::de::Deserialize<'de> for Tagged<T> {
185185+ fn deserialize<D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
186186+ deserializer.deserialize_any(MaybeTaggedVisitor::<T>(PhantomData))
187187+ }
188188+}
189189+190190+/// function to get the current cbor tag
191191+///
192192+/// The only place where it makes sense to call this function is within visit_newtype_struct of a serde visitor.
193193+/// This is a low level API. In most cases it is preferable to use Tagged
194194+pub fn current_cbor_tag() -> Option<u64> {
195195+ get_tag()
196196+}
197197+198198+#[cfg(feature = "tags")]
199199+pub(crate) fn set_tag(value: Option<u64>) {
200200+ CBOR_TAG.with(|f| *f.borrow_mut() = value);
201201+}
202202+203203+#[cfg(feature = "tags")]
204204+pub(crate) fn get_tag() -> Option<u64> {
205205+ CBOR_TAG.with(|f| *f.borrow())
206206+}
207207+208208+#[cfg(not(feature = "tags"))]
209209+pub(crate) fn set_tag(_value: Option<u64>) {}
210210+211211+#[cfg(not(feature = "tags"))]
212212+pub(crate) fn get_tag() -> Option<u64> {
213213+ None
214214+}
215215+216216+#[cfg(feature = "tags")]
217217+use std::cell::RefCell;
218218+219219+#[cfg(feature = "tags")]
220220+thread_local!(static CBOR_TAG: RefCell<Option<u64>> = const { RefCell::new(None) });
···11+//! CBOR values, keys and serialization routines.
22+33+mod de;
44+mod ser;
55+66+use std::cmp::{Ord, Ordering, PartialOrd};
77+use std::collections::BTreeMap;
88+99+#[doc(inline)]
1010+pub use self::de::from_value;
1111+#[doc(inline)]
1212+pub use self::ser::to_value;
1313+1414+/// The `Value` enum, a loosely typed way of representing any valid CBOR value.
1515+///
1616+/// Maps are sorted according to the canonical ordering
1717+/// described in [RFC 7049 bis].
1818+/// Therefore values are unambiguously serialized
1919+/// to a canonical form of CBOR from the same RFC.
2020+///
2121+/// [RFC 7049 bis]: https://tools.ietf.org/html/draft-ietf-cbor-7049bis-04#section-2
2222+#[derive(Clone, Debug)]
2323+pub enum Value {
2424+ /// Represents the absence of a value or the value undefined.
2525+ Null,
2626+ /// Represents a boolean value.
2727+ Bool(bool),
2828+ /// Integer CBOR numbers.
2929+ ///
3030+ /// The biggest value that can be represented is 2^64 - 1.
3131+ /// While the smallest value is -2^64.
3232+ /// Values outside this range can't be serialized
3333+ /// and will cause an error.
3434+ Integer(i128),
3535+ /// Represents a floating point value.
3636+ Float(f64),
3737+ /// Represents a byte string.
3838+ Bytes(Vec<u8>),
3939+ /// Represents an UTF-8 encoded string.
4040+ Text(String),
4141+ /// Represents an array of values.
4242+ Array(Vec<Value>),
4343+ /// Represents a map.
4444+ ///
4545+ /// Maps are also called tables, dictionaries, hashes, or objects (in JSON).
4646+ /// While any value can be used as a CBOR key
4747+ /// it is better to use only one type of key in a map
4848+ /// to avoid ambiguity.
4949+ /// If floating point values are used as keys they are compared bit-by-bit for equality.
5050+ /// If arrays or maps are used as keys the comparisons
5151+ /// to establish canonical order may be slow and therefore insertion
5252+ /// and retrieval of values will be slow too.
5353+ Map(BTreeMap<Value, Value>),
5454+ /// Represents a tagged value
5555+ Tag(u64, Box<Value>),
5656+ // The hidden variant allows the enum to be extended
5757+ // with variants for tags and simple values.
5858+ #[doc(hidden)]
5959+ __Hidden,
6060+}
6161+6262+impl PartialEq for Value {
6363+ fn eq(&self, other: &Value) -> bool {
6464+ self.cmp(other) == Ordering::Equal
6565+ }
6666+}
6767+6868+impl Eq for Value {}
6969+7070+impl PartialOrd for Value {
7171+ fn partial_cmp(&self, other: &Value) -> Option<Ordering> {
7272+ Some(self.cmp(other))
7373+ }
7474+}
7575+7676+impl Ord for Value {
7777+ fn cmp(&self, other: &Value) -> Ordering {
7878+ // Determine the canonical order of two values:
7979+ // 1. Smaller major type sorts first.
8080+ // 2. Shorter sequence sorts first.
8181+ // 3. Compare integers by magnitude.
8282+ // 4. Compare byte and text sequences lexically.
8383+ // 5. Compare the serializations of both types. (expensive)
8484+ use self::Value::*;
8585+ if self.major_type() != other.major_type() {
8686+ return self.major_type().cmp(&other.major_type());
8787+ }
8888+ match (self, other) {
8989+ (Integer(a), Integer(b)) => a.abs().cmp(&b.abs()),
9090+ (Bytes(a), Bytes(b)) if a.len() != b.len() => a.len().cmp(&b.len()),
9191+ (Text(a), Text(b)) if a.len() != b.len() => a.len().cmp(&b.len()),
9292+ (Array(a), Array(b)) if a.len() != b.len() => a.len().cmp(&b.len()),
9393+ (Map(a), Map(b)) if a.len() != b.len() => a.len().cmp(&b.len()),
9494+ (Bytes(a), Bytes(b)) => a.cmp(b),
9595+ (Text(a), Text(b)) => a.cmp(b),
9696+ (a, b) => {
9797+ let a = crate::to_vec(a).expect("self is serializable");
9898+ let b = crate::to_vec(b).expect("other is serializable");
9999+ a.cmp(&b)
100100+ }
101101+ }
102102+ }
103103+}
104104+105105+macro_rules! impl_from {
106106+ ($variant:path, $for_type:ty) => {
107107+ impl From<$for_type> for Value {
108108+ fn from(v: $for_type) -> Value {
109109+ $variant(v.into())
110110+ }
111111+ }
112112+ };
113113+}
114114+115115+impl_from!(Value::Bool, bool);
116116+impl_from!(Value::Integer, i8);
117117+impl_from!(Value::Integer, i16);
118118+impl_from!(Value::Integer, i32);
119119+impl_from!(Value::Integer, i64);
120120+// i128 omitted because not all numbers fit in CBOR serialization
121121+impl_from!(Value::Integer, u8);
122122+impl_from!(Value::Integer, u16);
123123+impl_from!(Value::Integer, u32);
124124+impl_from!(Value::Integer, u64);
125125+// u128 omitted because not all numbers fit in CBOR serialization
126126+impl_from!(Value::Float, f32);
127127+impl_from!(Value::Float, f64);
128128+impl_from!(Value::Bytes, Vec<u8>);
129129+impl_from!(Value::Text, String);
130130+// TODO: figure out if these impls should be more generic or removed.
131131+impl_from!(Value::Array, Vec<Value>);
132132+impl_from!(Value::Map, BTreeMap<Value, Value>);
133133+134134+impl Value {
135135+ fn major_type(&self) -> u8 {
136136+ use self::Value::*;
137137+ match self {
138138+ Null => 7,
139139+ Bool(_) => 7,
140140+ Integer(v) if *v < 0 => 1,
141141+ Integer(_) => 0,
142142+ Tag(_, _) => 6,
143143+ Float(_) => 7,
144144+ Bytes(_) => 2,
145145+ Text(_) => 3,
146146+ Array(_) => 4,
147147+ Map(_) => 5,
148148+ __Hidden => unreachable!(),
149149+ }
150150+ }
151151+}
···11+#[cfg(feature = "alloc")]
22+use alloc::vec::Vec;
33+#[cfg(not(feature = "std"))]
44+use core::fmt;
55+#[cfg(feature = "std")]
66+use std::io;
77+88+use crate::error;
99+1010+#[cfg(not(feature = "unsealed_read_write"))]
1111+/// A sink for serialized CBOR.
1212+///
1313+/// This trait is similar to the [`Write`]() trait in the standard library,
1414+/// but has a smaller and more general API.
1515+///
1616+/// Any object implementing `std::io::Write`
1717+/// can be wrapped in an [`IoWrite`](../write/struct.IoWrite.html) that implements
1818+/// this trait for the underlying object.
1919+pub trait Write: private::Sealed {
2020+ /// The type of error returned when a write operation fails.
2121+ #[doc(hidden)]
2222+ type Error: Into<error::Error>;
2323+2424+ /// Attempts to write an entire buffer into this write.
2525+ #[doc(hidden)]
2626+ fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error>;
2727+}
2828+2929+#[cfg(feature = "unsealed_read_write")]
3030+/// A sink for serialized CBOR.
3131+///
3232+/// This trait is similar to the [`Write`]() trait in the standard library,
3333+/// but has a smaller and more general API.
3434+///
3535+/// Any object implementing `std::io::Write`
3636+/// can be wrapped in an [`IoWrite`](../write/struct.IoWrite.html) that implements
3737+/// this trait for the underlying object.
3838+///
3939+/// This trait is sealed by default, enabling the `unsealed_read_write` feature removes this bound
4040+/// to allow objects outside of this crate to implement this trait.
4141+pub trait Write {
4242+ /// The type of error returned when a write operation fails.
4343+ type Error: Into<error::Error>;
4444+4545+ /// Attempts to write an entire buffer into this write.
4646+ fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error>;
4747+}
4848+4949+#[cfg(not(feature = "unsealed_read_write"))]
5050+mod private {
5151+ pub trait Sealed {}
5252+}
5353+5454+impl<W> Write for &mut W
5555+where
5656+ W: Write,
5757+{
5858+ type Error = W::Error;
5959+6060+ fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
6161+ (*self).write_all(buf)
6262+ }
6363+}
6464+6565+#[cfg(not(feature = "unsealed_read_write"))]
6666+impl<W> private::Sealed for &mut W where W: Write {}
6767+6868+#[cfg(feature = "std")]
6969+/// A wrapper for types that implement
7070+/// [`std::io::Write`](https://doc.rust-lang.org/std/io/trait.Write.html) to implement the local
7171+/// [`Write`](trait.Write.html) trait.
7272+#[derive(Debug)]
7373+pub struct IoWrite<W>(W);
7474+7575+#[cfg(feature = "std")]
7676+impl<W: io::Write> IoWrite<W> {
7777+ /// Wraps an `io::Write` writer to make it compatible with [`Write`](trait.Write.html)
7878+ pub fn new(w: W) -> IoWrite<W> {
7979+ IoWrite(w)
8080+ }
8181+}
8282+8383+#[cfg(feature = "std")]
8484+impl<W: io::Write> Write for IoWrite<W> {
8585+ type Error = io::Error;
8686+8787+ fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
8888+ self.0.write_all(buf)
8989+ }
9090+}
9191+9292+#[cfg(all(feature = "std", not(feature = "unsealed_read_write")))]
9393+impl<W> private::Sealed for IoWrite<W> where W: io::Write {}
9494+9595+#[cfg(any(feature = "std", feature = "alloc"))]
9696+impl Write for Vec<u8> {
9797+ type Error = error::Error;
9898+9999+ fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
100100+ self.extend_from_slice(buf);
101101+ Ok(())
102102+ }
103103+}
104104+105105+#[cfg(all(
106106+ any(feature = "std", feature = "alloc"),
107107+ not(feature = "unsealed_read_write")
108108+))]
109109+impl private::Sealed for Vec<u8> {}
110110+111111+#[cfg(not(feature = "std"))]
112112+#[derive(Debug)]
113113+pub struct FmtWrite<'a, W: Write>(&'a mut W);
114114+115115+#[cfg(not(feature = "std"))]
116116+impl<'a, W: Write> FmtWrite<'a, W> {
117117+ /// Wraps an `fmt::Write` writer to make it compatible with [`Write`](trait.Write.html)
118118+ pub fn new(w: &'a mut W) -> FmtWrite<'a, W> {
119119+ FmtWrite(w)
120120+ }
121121+}
122122+123123+#[cfg(not(feature = "std"))]
124124+impl<'a, W: Write> fmt::Write for FmtWrite<'a, W> {
125125+ fn write_str(&mut self, s: &str) -> fmt::Result {
126126+ self.0.write_all(s.as_bytes()).map_err(|_| fmt::Error)
127127+ }
128128+}
129129+130130+#[cfg(all(not(feature = "std"), not(feature = "unsealed_read_write")))]
131131+impl<'a, W> private::Sealed for FmtWrite<'a, W> where W: Write {}
132132+133133+/// Implements [`Write`](trait.Write.html) for mutable byte slices (`&mut [u8]`).
134134+///
135135+/// Returns an error if the value to serialize is too large to fit in the slice.
136136+#[derive(Debug)]
137137+pub struct SliceWrite<'a> {
138138+ slice: &'a mut [u8],
139139+ index: usize,
140140+}
141141+142142+impl<'a> SliceWrite<'a> {
143143+ /// Wraps a mutable slice so it can be used as a `Write`.
144144+ pub fn new(slice: &'a mut [u8]) -> SliceWrite<'a> {
145145+ SliceWrite { slice, index: 0 }
146146+ }
147147+148148+ /// Returns the number of bytes written to the underlying slice.
149149+ pub fn bytes_written(&self) -> usize {
150150+ self.index
151151+ }
152152+153153+ /// Returns the underlying slice.
154154+ pub fn into_inner(self) -> &'a mut [u8] {
155155+ self.slice
156156+ }
157157+}
158158+159159+impl Write for SliceWrite<'_> {
160160+ type Error = error::Error;
161161+162162+ fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
163163+ if self.slice.len() - self.index < buf.len() {
164164+ // This buffer will not fit in our slice
165165+ return Err(error::Error::scratch_too_small(self.index as u64));
166166+ }
167167+ let end = self.index + buf.len();
168168+ self.slice[self.index..end].copy_from_slice(buf);
169169+ self.index = end;
170170+ Ok(())
171171+ }
172172+}
173173+174174+#[cfg(not(feature = "unsealed_read_write"))]
175175+impl private::Sealed for SliceWrite<'_> {}
+60
vendor/git/cbor/tests/bennofs.rs
···11+#[macro_use]
22+extern crate serde;
33+44+use serde::Serialize;
55+use serde_cbor_2::ser::SliceWrite;
66+use serde_cbor_2::{self, Serializer};
77+88+#[derive(Debug, PartialEq, Serialize, Deserialize)]
99+struct Example {
1010+ foo: Foo,
1111+ payload: u8,
1212+}
1313+1414+#[derive(Debug, PartialEq, Serialize, Deserialize)]
1515+struct Foo {
1616+ x: u8,
1717+ color: Color,
1818+}
1919+2020+#[derive(Debug, PartialEq, Serialize, Deserialize)]
2121+enum Color {
2222+ Red,
2323+ Blue,
2424+ Yellow(u8),
2525+}
2626+2727+const EXAMPLE: Example = Example {
2828+ foo: Foo {
2929+ x: 0xAA,
3030+ color: Color::Yellow(40),
3131+ },
3232+ payload: 0xCC,
3333+};
3434+3535+#[cfg(feature = "std")]
3636+mod std_tests {
3737+ use super::*;
3838+3939+ #[test]
4040+ fn test() {
4141+ let serialized = serde_cbor_2::ser::to_vec_packed(&EXAMPLE).expect("bennofs 1");
4242+ println!("{serialized:?}");
4343+ let deserialized: Example = serde_cbor_2::from_slice(&serialized).expect("bennofs 2");
4444+ assert_eq!(EXAMPLE, deserialized);
4545+ }
4646+}
4747+4848+#[test]
4949+fn test() {
5050+ let mut slice = [0u8; 64];
5151+ let writer = SliceWrite::new(&mut slice);
5252+ let mut serializer = Serializer::new(writer).packed_format();
5353+ EXAMPLE.serialize(&mut serializer).unwrap();
5454+ let writer = serializer.into_inner();
5555+ let end = writer.bytes_written();
5656+ let slice = writer.into_inner();
5757+ let deserialized: Example =
5858+ serde_cbor_2::de::from_slice_with_scratch(&slice[..end], &mut []).unwrap();
5959+ assert_eq!(EXAMPLE, deserialized);
6060+}