diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-04 12:47:55 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-04 12:47:55 +0000 |
commit | 2aadc03ef15cb5ca5cc2af8a7c08e070742f0ac4 (patch) | |
tree | 033cc839730fda84ff08db877037977be94e5e3a /vendor/hex | |
parent | Initial commit. (diff) | |
download | cargo-upstream.tar.xz cargo-upstream.zip |
Adding upstream version 0.70.1+ds1.upstream/0.70.1+ds1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vendor/hex')
-rw-r--r-- | vendor/hex/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | vendor/hex/Cargo.toml | 63 | ||||
-rw-r--r-- | vendor/hex/LICENSE-APACHE | 202 | ||||
-rw-r--r-- | vendor/hex/LICENSE-MIT | 20 | ||||
-rw-r--r-- | vendor/hex/README.md | 69 | ||||
-rw-r--r-- | vendor/hex/benches/hex.rs | 61 | ||||
-rw-r--r-- | vendor/hex/src/error.rs | 59 | ||||
-rw-r--r-- | vendor/hex/src/lib.rs | 525 | ||||
-rw-r--r-- | vendor/hex/src/serde.rs | 102 | ||||
-rw-r--r-- | vendor/hex/tests/serde.rs | 59 | ||||
-rw-r--r-- | vendor/hex/tests/version-number.rs | 11 |
11 files changed, 1172 insertions, 0 deletions
diff --git a/vendor/hex/.cargo-checksum.json b/vendor/hex/.cargo-checksum.json new file mode 100644 index 0000000..80c1815 --- /dev/null +++ b/vendor/hex/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{},"package":"7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"}
\ No newline at end of file diff --git a/vendor/hex/Cargo.toml b/vendor/hex/Cargo.toml new file mode 100644 index 0000000..fab04a8 --- /dev/null +++ b/vendor/hex/Cargo.toml @@ -0,0 +1,63 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "hex" +version = "0.4.3" +authors = ["KokaKiwi <kokakiwi@kokakiwi.net>"] +description = "Encoding and decoding data into/from hexadecimal representation." +documentation = "https://docs.rs/hex/" +readme = "README.md" +keywords = ["no_std", "hex"] +categories = ["encoding", "no-std"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/KokaKiwi/rust-hex" +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] + +[[bench]] +name = "hex" +harness = false +[dependencies.serde] +version = "1.0" +optional = true +default-features = false +[dev-dependencies.criterion] +version = "0.3" + +[dev-dependencies.faster-hex] +version = "0.5" + +[dev-dependencies.pretty_assertions] +version = "0.6" + +[dev-dependencies.rustc-hex] +version = "2.1" + +[dev-dependencies.serde] +version = "1.0" +features = ["derive"] + +[dev-dependencies.serde_json] +version = "1.0" + +[dev-dependencies.version-sync] +version = "0.9" + +[features] +alloc = [] +default = ["std"] +std = ["alloc"] +[badges.maintenance] +status = "actively-developed" diff --git a/vendor/hex/LICENSE-APACHE b/vendor/hex/LICENSE-APACHE new file mode 100644 index 0000000..8f71f43 --- /dev/null +++ b/vendor/hex/LICENSE-APACHE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/vendor/hex/LICENSE-MIT b/vendor/hex/LICENSE-MIT new file mode 100644 index 0000000..a7b461f --- /dev/null +++ b/vendor/hex/LICENSE-MIT @@ -0,0 +1,20 @@ +Copyright (c) 2013-2014 The Rust Project Developers. +Copyright (c) 2015-2020 The rust-hex Developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/hex/README.md b/vendor/hex/README.md new file mode 100644 index 0000000..5dfd4b2 --- /dev/null +++ b/vendor/hex/README.md @@ -0,0 +1,69 @@ +# hex + +[![Crates.io: hex](https://img.shields.io/crates/v/hex.svg)](https://crates.io/crates/hex) +[![Documentation](https://docs.rs/hex/badge.svg)](https://docs.rs/hex) +[![Build Status (Github Actions)](https://github.com/KokaKiwi/rust-hex/workflows/Test%20hex/badge.svg?master)](https://github.com/KokaKiwi/rust-hex/actions) + +Encoding and decoding data into/from hexadecimal representation. + +## Examples + +Encoding a `String` + +```rust +let hex_string = hex::encode("Hello world!"); + +println!("{}", hex_string); // Prints "48656c6c6f20776f726c6421" +``` + +Decoding a `String` + +```rust +let decoded_string = hex::decode("48656c6c6f20776f726c6421"); + +println!("{}", decoded_string); // Prints "Hello world!" +``` + +You can find the [documentation](https://docs.rs/hex) here. + +## Installation + +In order to use this crate, you have to add it under `[dependencies]` to your `Cargo.toml` + +```toml +[dependencies] +hex = "0.4" +``` + +By default this will import `std`, if you are working in a +[`no_std`](https://rust-embedded.github.io/book/intro/no-std.html) +environment you can turn this off by adding the following + +```toml +[dependencies] +hex = { version = "0.4", default-features = false } +``` + +## Features + +- `std`: + Enabled by default. Add support for Rust's libstd types. +- `serde`: + Disabled by default. Add support for `serde` de/serializing library. + See the `serde` module documentation for usage. + +## License + +Licensed under either of + +- Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally +submitted for inclusion in the work by you, as defined in the Apache-2.0 +license, shall be dual licensed as above, without any additional terms or +conditions. diff --git a/vendor/hex/benches/hex.rs b/vendor/hex/benches/hex.rs new file mode 100644 index 0000000..6435032 --- /dev/null +++ b/vendor/hex/benches/hex.rs @@ -0,0 +1,61 @@ +use criterion::{criterion_group, criterion_main, Criterion}; +use rustc_hex::{FromHex, ToHex}; + +const DATA: &[u8] = include_bytes!("../src/lib.rs"); + +fn bench_encode(c: &mut Criterion) { + c.bench_function("hex_encode", |b| b.iter(|| hex::encode(DATA))); + + c.bench_function("rustc_hex_encode", |b| b.iter(|| DATA.to_hex::<String>())); + + c.bench_function("faster_hex_encode", |b| { + b.iter(|| faster_hex::hex_string(DATA).unwrap()) + }); + + c.bench_function("faster_hex_encode_fallback", |b| { + b.iter(|| { + let mut dst = vec![0; DATA.len() * 2]; + faster_hex::hex_encode_fallback(DATA, &mut dst); + dst + }) + }); +} + +fn bench_decode(c: &mut Criterion) { + c.bench_function("hex_decode", |b| { + let hex = hex::encode(DATA); + b.iter(|| hex::decode(&hex).unwrap()) + }); + + c.bench_function("rustc_hex_decode", |b| { + let hex = DATA.to_hex::<String>(); + b.iter(|| hex.from_hex::<Vec<u8>>().unwrap()) + }); + + c.bench_function("faster_hex_decode", move |b| { + let hex = faster_hex::hex_string(DATA).unwrap(); + let len = DATA.len(); + let mut dst = vec![0; len]; + + b.iter(|| faster_hex::hex_decode(hex.as_bytes(), &mut dst).unwrap()) + }); + + c.bench_function("faster_hex_decode_unchecked", |b| { + let hex = faster_hex::hex_string(DATA).unwrap(); + let len = DATA.len(); + let mut dst = vec![0; len]; + + b.iter(|| faster_hex::hex_decode_unchecked(hex.as_bytes(), &mut dst)) + }); + + c.bench_function("faster_hex_decode_fallback", |b| { + let hex = faster_hex::hex_string(DATA).unwrap(); + let len = DATA.len(); + let mut dst = vec![0; len]; + + b.iter(|| faster_hex::hex_decode_fallback(hex.as_bytes(), &mut dst)) + }); +} + +criterion_group!(benches, bench_encode, bench_decode); +criterion_main!(benches); diff --git a/vendor/hex/src/error.rs b/vendor/hex/src/error.rs new file mode 100644 index 0000000..ff7a3b5 --- /dev/null +++ b/vendor/hex/src/error.rs @@ -0,0 +1,59 @@ +use core::fmt; + +/// The error type for decoding a hex string into `Vec<u8>` or `[u8; N]`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum FromHexError { + /// An invalid character was found. Valid ones are: `0...9`, `a...f` + /// or `A...F`. + InvalidHexCharacter { c: char, index: usize }, + + /// A hex string's length needs to be even, as two digits correspond to + /// one byte. + OddLength, + + /// If the hex string is decoded into a fixed sized container, such as an + /// array, the hex string's length * 2 has to match the container's + /// length. + InvalidStringLength, +} + +#[cfg(feature = "std")] +impl std::error::Error for FromHexError {} + +impl fmt::Display for FromHexError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + FromHexError::InvalidHexCharacter { c, index } => { + write!(f, "Invalid character {:?} at position {}", c, index) + } + FromHexError::OddLength => write!(f, "Odd number of digits"), + FromHexError::InvalidStringLength => write!(f, "Invalid string length"), + } + } +} + +#[cfg(test)] +// this feature flag is here to suppress unused +// warnings of `super::*` and `pretty_assertions::assert_eq` +#[cfg(feature = "alloc")] +mod tests { + use super::*; + #[cfg(feature = "alloc")] + use alloc::string::ToString; + use pretty_assertions::assert_eq; + + #[test] + #[cfg(feature = "alloc")] + fn test_display() { + assert_eq!( + FromHexError::InvalidHexCharacter { c: '\n', index: 5 }.to_string(), + "Invalid character '\\n' at position 5" + ); + + assert_eq!(FromHexError::OddLength.to_string(), "Odd number of digits"); + assert_eq!( + FromHexError::InvalidStringLength.to_string(), + "Invalid string length" + ); + } +} diff --git a/vendor/hex/src/lib.rs b/vendor/hex/src/lib.rs new file mode 100644 index 0000000..ec48961 --- /dev/null +++ b/vendor/hex/src/lib.rs @@ -0,0 +1,525 @@ +// Copyright (c) 2013-2014 The Rust Project Developers. +// Copyright (c) 2015-2020 The rust-hex Developers. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +//! Encoding and decoding hex strings. +//! +//! For most cases, you can simply use the [`decode`], [`encode`] and +//! [`encode_upper`] functions. If you need a bit more control, use the traits +//! [`ToHex`] and [`FromHex`] instead. +//! +//! # Example +//! +//! ``` +//! # #[cfg(not(feature = "alloc"))] +//! # let mut output = [0; 0x18]; +//! # +//! # #[cfg(not(feature = "alloc"))] +//! # hex::encode_to_slice(b"Hello world!", &mut output).unwrap(); +//! # +//! # #[cfg(not(feature = "alloc"))] +//! # let hex_string = ::core::str::from_utf8(&output).unwrap(); +//! # +//! # #[cfg(feature = "alloc")] +//! let hex_string = hex::encode("Hello world!"); +//! +//! println!("{}", hex_string); // Prints "48656c6c6f20776f726c6421" +//! +//! # assert_eq!(hex_string, "48656c6c6f20776f726c6421"); +//! ``` + +#![doc(html_root_url = "https://docs.rs/hex/0.4.3")] +#![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(docsrs, feature(doc_cfg))] +#![allow(clippy::unreadable_literal)] + +#[cfg(feature = "alloc")] +extern crate alloc; +#[cfg(feature = "alloc")] +use alloc::{string::String, vec::Vec}; + +use core::iter; + +mod error; +pub use crate::error::FromHexError; + +#[cfg(feature = "serde")] +#[cfg_attr(docsrs, doc(cfg(feature = "serde")))] +pub mod serde; +#[cfg(feature = "serde")] +pub use crate::serde::deserialize; +#[cfg(all(feature = "alloc", feature = "serde"))] +pub use crate::serde::{serialize, serialize_upper}; + +/// Encoding values as hex string. +/// +/// This trait is implemented for all `T` which implement `AsRef<[u8]>`. This +/// includes `String`, `str`, `Vec<u8>` and `[u8]`. +/// +/// # Example +/// +/// ``` +/// use hex::ToHex; +/// +/// println!("{}", "Hello world!".encode_hex::<String>()); +/// # assert_eq!("Hello world!".encode_hex::<String>(), "48656c6c6f20776f726c6421".to_string()); +/// ``` +/// +/// *Note*: instead of using this trait, you might want to use [`encode()`]. +pub trait ToHex { + /// Encode the hex strict representing `self` into the result. Lower case + /// letters are used (e.g. `f9b4ca`) + fn encode_hex<T: iter::FromIterator<char>>(&self) -> T; + + /// Encode the hex strict representing `self` into the result. Upper case + /// letters are used (e.g. `F9B4CA`) + fn encode_hex_upper<T: iter::FromIterator<char>>(&self) -> T; +} + +const HEX_CHARS_LOWER: &[u8; 16] = b"0123456789abcdef"; +const HEX_CHARS_UPPER: &[u8; 16] = b"0123456789ABCDEF"; + +struct BytesToHexChars<'a> { + inner: ::core::slice::Iter<'a, u8>, + table: &'static [u8; 16], + next: Option<char>, +} + +impl<'a> BytesToHexChars<'a> { + fn new(inner: &'a [u8], table: &'static [u8; 16]) -> BytesToHexChars<'a> { + BytesToHexChars { + inner: inner.iter(), + table, + next: None, + } + } +} + +impl<'a> Iterator for BytesToHexChars<'a> { + type Item = char; + + fn next(&mut self) -> Option<Self::Item> { + match self.next.take() { + Some(current) => Some(current), + None => self.inner.next().map(|byte| { + let current = self.table[(byte >> 4) as usize] as char; + self.next = Some(self.table[(byte & 0x0F) as usize] as char); + current + }), + } + } + + fn size_hint(&self) -> (usize, Option<usize>) { + let length = self.len(); + (length, Some(length)) + } +} + +impl<'a> iter::ExactSizeIterator for BytesToHexChars<'a> { + fn len(&self) -> usize { + let mut length = self.inner.len() * 2; + if self.next.is_some() { + length += 1; + } + length + } +} + +#[inline] +fn encode_to_iter<T: iter::FromIterator<char>>(table: &'static [u8; 16], source: &[u8]) -> T { + BytesToHexChars::new(source, table).collect() +} + +impl<T: AsRef<[u8]>> ToHex for T { + fn encode_hex<U: iter::FromIterator<char>>(&self) -> U { + encode_to_iter(HEX_CHARS_LOWER, self.as_ref()) + } + + fn encode_hex_upper<U: iter::FromIterator<char>>(&self) -> U { + encode_to_iter(HEX_CHARS_UPPER, self.as_ref()) + } +} + +/// Types that can be decoded from a hex string. +/// +/// This trait is implemented for `Vec<u8>` and small `u8`-arrays. +/// +/// # Example +/// +/// ``` +/// use core::str; +/// use hex::FromHex; +/// +/// let buffer = <[u8; 12]>::from_hex("48656c6c6f20776f726c6421")?; +/// let string = str::from_utf8(&buffer).expect("invalid buffer length"); +/// +/// println!("{}", string); // prints "Hello world!" +/// # assert_eq!("Hello world!", string); +/// # Ok::<(), hex::FromHexError>(()) +/// ``` +pub trait FromHex: Sized { + type Error; + + /// Creates an instance of type `Self` from the given hex string, or fails + /// with a custom error type. + /// + /// Both, upper and lower case characters are valid and can even be + /// mixed (e.g. `f9b4ca`, `F9B4CA` and `f9B4Ca` are all valid strings). + fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error>; +} + +fn val(c: u8, idx: usize) -> Result<u8, FromHexError> { + match c { + b'A'..=b'F' => Ok(c - b'A' + 10), + b'a'..=b'f' => Ok(c - b'a' + 10), + b'0'..=b'9' => Ok(c - b'0'), + _ => Err(FromHexError::InvalidHexCharacter { + c: c as char, + index: idx, + }), + } +} + +#[cfg(feature = "alloc")] +impl FromHex for Vec<u8> { + type Error = FromHexError; + + fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> { + let hex = hex.as_ref(); + if hex.len() % 2 != 0 { + return Err(FromHexError::OddLength); + } + + hex.chunks(2) + .enumerate() + .map(|(i, pair)| Ok(val(pair[0], 2 * i)? << 4 | val(pair[1], 2 * i + 1)?)) + .collect() + } +} + +// Helper macro to implement the trait for a few fixed sized arrays. Once Rust +// has type level integers, this should be removed. +macro_rules! from_hex_array_impl { + ($($len:expr)+) => {$( + impl FromHex for [u8; $len] { + type Error = FromHexError; + + fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> { + let mut out = [0_u8; $len]; + decode_to_slice(hex, &mut out as &mut [u8])?; + Ok(out) + } + } + )+} +} + +from_hex_array_impl! { + 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 + 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 + 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 + 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 + 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 + 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 + 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 + 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 + 160 192 200 224 256 384 512 768 1024 2048 4096 8192 16384 32768 +} + +#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))] +from_hex_array_impl! { + 65536 131072 262144 524288 1048576 2097152 4194304 8388608 + 16777216 33554432 67108864 134217728 268435456 536870912 + 1073741824 2147483648 +} + +#[cfg(target_pointer_width = "64")] +from_hex_array_impl! { + 4294967296 +} + +/// Encodes `data` as hex string using lowercase characters. +/// +/// Lowercase characters are used (e.g. `f9b4ca`). The resulting string's +/// length is always even, each byte in `data` is always encoded using two hex +/// digits. Thus, the resulting string contains exactly twice as many bytes as +/// the input data. +/// +/// # Example +/// +/// ``` +/// assert_eq!(hex::encode("Hello world!"), "48656c6c6f20776f726c6421"); +/// assert_eq!(hex::encode(vec![1, 2, 3, 15, 16]), "0102030f10"); +/// ``` +#[must_use] +#[cfg(feature = "alloc")] +pub fn encode<T: AsRef<[u8]>>(data: T) -> String { + data.encode_hex() +} + +/// Encodes `data` as hex string using uppercase characters. +/// +/// Apart from the characters' casing, this works exactly like `encode()`. +/// +/// # Example +/// +/// ``` +/// assert_eq!(hex::encode_upper("Hello world!"), "48656C6C6F20776F726C6421"); +/// assert_eq!(hex::encode_upper(vec![1, 2, 3, 15, 16]), "0102030F10"); +/// ``` +#[must_use] +#[cfg(feature = "alloc")] +pub fn encode_upper<T: AsRef<[u8]>>(data: T) -> String { + data.encode_hex_upper() +} + +/// Decodes a hex string into raw bytes. +/// +/// Both, upper and lower case characters are valid in the input string and can +/// even be mixed (e.g. `f9b4ca`, `F9B4CA` and `f9B4Ca` are all valid strings). +/// +/// # Example +/// +/// ``` +/// assert_eq!( +/// hex::decode("48656c6c6f20776f726c6421"), +/// Ok("Hello world!".to_owned().into_bytes()) +/// ); +/// +/// assert_eq!(hex::decode("123"), Err(hex::FromHexError::OddLength)); +/// assert!(hex::decode("foo").is_err()); +/// ``` +#[cfg(feature = "alloc")] +pub fn decode<T: AsRef<[u8]>>(data: T) -> Result<Vec<u8>, FromHexError> { + FromHex::from_hex(data) +} + +/// Decode a hex string into a mutable bytes slice. +/// +/// Both, upper and lower case characters are valid in the input string and can +/// even be mixed (e.g. `f9b4ca`, `F9B4CA` and `f9B4Ca` are all valid strings). +/// +/// # Example +/// +/// ``` +/// let mut bytes = [0u8; 4]; +/// assert_eq!(hex::decode_to_slice("6b697769", &mut bytes as &mut [u8]), Ok(())); +/// assert_eq!(&bytes, b"kiwi"); +/// ``` +pub fn decode_to_slice<T: AsRef<[u8]>>(data: T, out: &mut [u8]) -> Result<(), FromHexError> { + let data = data.as_ref(); + + if data.len() % 2 != 0 { + return Err(FromHexError::OddLength); + } + if data.len() / 2 != out.len() { + return Err(FromHexError::InvalidStringLength); + } + + for (i, byte) in out.iter_mut().enumerate() { + *byte = val(data[2 * i], 2 * i)? << 4 | val(data[2 * i + 1], 2 * i + 1)?; + } + + Ok(()) +} + +// generates an iterator like this +// (0, 1) +// (2, 3) +// (4, 5) +// (6, 7) +// ... +#[inline] +fn generate_iter(len: usize) -> impl Iterator<Item = (usize, usize)> { + (0..len).step_by(2).zip((0..len).skip(1).step_by(2)) +} + +// the inverse of `val`. +#[inline] +#[must_use] +fn byte2hex(byte: u8, table: &[u8; 16]) -> (u8, u8) { + let high = table[((byte & 0xf0) >> 4) as usize]; + let low = table[(byte & 0x0f) as usize]; + + (high, low) +} + +/// Encodes some bytes into a mutable slice of bytes. +/// +/// The output buffer, has to be able to hold at least `input.len() * 2` bytes, +/// otherwise this function will return an error. +/// +/// # Example +/// +/// ``` +/// # use hex::FromHexError; +/// # fn main() -> Result<(), FromHexError> { +/// let mut bytes = [0u8; 4 * 2]; +/// +/// hex::encode_to_slice(b"kiwi", &mut bytes)?; +/// assert_eq!(&bytes, b"6b697769"); +/// # Ok(()) +/// # } +/// ``` +pub fn encode_to_slice<T: AsRef<[u8]>>(input: T, output: &mut [u8]) -> Result<(), FromHexError> { + if input.as_ref().len() * 2 != output.len() { + return Err(FromHexError::InvalidStringLength); + } + + for (byte, (i, j)) in input + .as_ref() + .iter() + .zip(generate_iter(input.as_ref().len() * 2)) + { + let (high, low) = byte2hex(*byte, HEX_CHARS_LOWER); + output[i] = high; + output[j] = low; + } + + Ok(()) +} + +#[cfg(test)] +mod test { + use super::*; + #[cfg(feature = "alloc")] + use alloc::string::ToString; + use pretty_assertions::assert_eq; + + #[test] + #[cfg(feature = "alloc")] + fn test_gen_iter() { + let result = vec![(0, 1), (2, 3)]; + + assert_eq!(generate_iter(5).collect::<Vec<_>>(), result); + } + + #[test] + fn test_encode_to_slice() { + let mut output_1 = [0; 4 * 2]; + encode_to_slice(b"kiwi", &mut output_1).unwrap(); + assert_eq!(&output_1, b"6b697769"); + + let mut output_2 = [0; 5 * 2]; + encode_to_slice(b"kiwis", &mut output_2).unwrap(); + assert_eq!(&output_2, b"6b69776973"); + + let mut output_3 = [0; 100]; + + assert_eq!( + encode_to_slice(b"kiwis", &mut output_3), + Err(FromHexError::InvalidStringLength) + ); + } + + #[test] + fn test_decode_to_slice() { + let mut output_1 = [0; 4]; + decode_to_slice(b"6b697769", &mut output_1).unwrap(); + assert_eq!(&output_1, b"kiwi"); + + let mut output_2 = [0; 5]; + decode_to_slice(b"6b69776973", &mut output_2).unwrap(); + assert_eq!(&output_2, b"kiwis"); + + let mut output_3 = [0; 4]; + + assert_eq!( + decode_to_slice(b"6", &mut output_3), + Err(FromHexError::OddLength) + ); + } + + #[test] + #[cfg(feature = "alloc")] + fn test_encode() { + assert_eq!(encode("foobar"), "666f6f626172"); + } + + #[test] + #[cfg(feature = "alloc")] + fn test_decode() { + assert_eq!( + decode("666f6f626172"), + Ok(String::from("foobar").into_bytes()) + ); + } + + #[test] + #[cfg(feature = "alloc")] + pub fn test_from_hex_okay_str() { + assert_eq!(Vec::from_hex("666f6f626172").unwrap(), b"foobar"); + assert_eq!(Vec::from_hex("666F6F626172").unwrap(), b"foobar"); + } + + #[test] + #[cfg(feature = "alloc")] + pub fn test_from_hex_okay_bytes() { + assert_eq!(Vec::from_hex(b"666f6f626172").unwrap(), b"foobar"); + assert_eq!(Vec::from_hex(b"666F6F626172").unwrap(), b"foobar"); + } + + #[test] + #[cfg(feature = "alloc")] + pub fn test_invalid_length() { + assert_eq!(Vec::from_hex("1").unwrap_err(), FromHexError::OddLength); + assert_eq!( + Vec::from_hex("666f6f6261721").unwrap_err(), + FromHexError::OddLength + ); + } + + #[test] + #[cfg(feature = "alloc")] + pub fn test_invalid_char() { + assert_eq!( + Vec::from_hex("66ag").unwrap_err(), + FromHexError::InvalidHexCharacter { c: 'g', index: 3 } + ); + } + + #[test] + #[cfg(feature = "alloc")] + pub fn test_empty() { + assert_eq!(Vec::from_hex("").unwrap(), b""); + } + + #[test] + #[cfg(feature = "alloc")] + pub fn test_from_hex_whitespace() { + assert_eq!( + Vec::from_hex("666f 6f62617").unwrap_err(), + FromHexError::InvalidHexCharacter { c: ' ', index: 4 } + ); + } + + #[test] + pub fn test_from_hex_array() { + assert_eq!( + <[u8; 6] as FromHex>::from_hex("666f6f626172"), + Ok([0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]) + ); + + assert_eq!( + <[u8; 5] as FromHex>::from_hex("666f6f626172"), + Err(FromHexError::InvalidStringLength) + ); + } + + #[test] + #[cfg(feature = "alloc")] + fn test_to_hex() { + assert_eq!( + [0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72].encode_hex::<String>(), + "666f6f626172".to_string(), + ); + + assert_eq!( + [0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72].encode_hex_upper::<String>(), + "666F6F626172".to_string(), + ); + } +} diff --git a/vendor/hex/src/serde.rs b/vendor/hex/src/serde.rs new file mode 100644 index 0000000..335a151 --- /dev/null +++ b/vendor/hex/src/serde.rs @@ -0,0 +1,102 @@ +//! Hex encoding with `serde`. +#[cfg_attr( + all(feature = "alloc", feature = "serde"), + doc = r##" +# Example + +``` +use serde::{Serialize, Deserialize}; + +#[derive(Serialize, Deserialize)] +struct Foo { + #[serde(with = "hex")] + bar: Vec<u8>, +} +``` +"## +)] +use serde::de::{Error, Visitor}; +use serde::Deserializer; +#[cfg(feature = "alloc")] +use serde::Serializer; + +#[cfg(feature = "alloc")] +use alloc::string::String; + +use core::fmt; +use core::marker::PhantomData; + +use crate::FromHex; + +#[cfg(feature = "alloc")] +use crate::ToHex; + +/// Serializes `data` as hex string using uppercase characters. +/// +/// Apart from the characters' casing, this works exactly like `serialize()`. +#[cfg(feature = "alloc")] +pub fn serialize_upper<S, T>(data: T, serializer: S) -> Result<S::Ok, S::Error> +where + S: Serializer, + T: ToHex, +{ + let s = data.encode_hex_upper::<String>(); + serializer.serialize_str(&s) +} + +/// Serializes `data` as hex string using lowercase characters. +/// +/// Lowercase characters are used (e.g. `f9b4ca`). The resulting string's length +/// is always even, each byte in data is always encoded using two hex digits. +/// Thus, the resulting string contains exactly twice as many bytes as the input +/// data. +#[cfg(feature = "alloc")] +pub fn serialize<S, T>(data: T, serializer: S) -> Result<S::Ok, S::Error> +where + S: Serializer, + T: ToHex, +{ + let s = data.encode_hex::<String>(); + serializer.serialize_str(&s) +} + +/// Deserializes a hex string into raw bytes. +/// +/// Both, upper and lower case characters are valid in the input string and can +/// even be mixed (e.g. `f9b4ca`, `F9B4CA` and `f9B4Ca` are all valid strings). +pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error> +where + D: Deserializer<'de>, + T: FromHex, + <T as FromHex>::Error: fmt::Display, +{ + struct HexStrVisitor<T>(PhantomData<T>); + + impl<'de, T> Visitor<'de> for HexStrVisitor<T> + where + T: FromHex, + <T as FromHex>::Error: fmt::Display, + { + type Value = T; + + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "a hex encoded string") + } + + fn visit_str<E>(self, data: &str) -> Result<Self::Value, E> + where + E: Error, + { + FromHex::from_hex(data).map_err(Error::custom) + } + + fn visit_borrowed_str<E>(self, data: &'de str) -> Result<Self::Value, E> + where + E: Error, + { + FromHex::from_hex(data).map_err(Error::custom) + } + } + + deserializer.deserialize_str(HexStrVisitor(PhantomData)) +} diff --git a/vendor/hex/tests/serde.rs b/vendor/hex/tests/serde.rs new file mode 100644 index 0000000..a571d3a --- /dev/null +++ b/vendor/hex/tests/serde.rs @@ -0,0 +1,59 @@ +#![cfg(all(feature = "serde", feature = "alloc"))] +#![allow(clippy::blacklisted_name)] + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] +struct Foo { + #[serde(with = "hex")] + bar: Vec<u8>, +} + +#[test] +fn serialize() { + let foo = Foo { + bar: vec![1, 10, 100], + }; + + let ser = serde_json::to_string(&foo).expect("serialization failed"); + assert_eq!(ser, r#"{"bar":"010a64"}"#); +} + +#[test] +fn deserialize() { + let foo = Foo { + bar: vec![1, 10, 100], + }; + + let de: Foo = serde_json::from_str(r#"{"bar":"010a64"}"#).expect("deserialization failed"); + assert_eq!(de, foo); +} + +#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] +struct Bar { + #[serde( + serialize_with = "hex::serialize_upper", + deserialize_with = "hex::deserialize" + )] + foo: Vec<u8>, +} + +#[test] +fn serialize_upper() { + let bar = Bar { + foo: vec![1, 10, 100], + }; + + let ser = serde_json::to_string(&bar).expect("serialization failed"); + assert_eq!(ser, r#"{"foo":"010A64"}"#); +} + +#[test] +fn deserialize_upper() { + let bar = Bar { + foo: vec![1, 10, 100], + }; + + let de: Bar = serde_json::from_str(r#"{"foo":"010A64"}"#).expect("deserialization failed"); + assert_eq!(de, bar); +} diff --git a/vendor/hex/tests/version-number.rs b/vendor/hex/tests/version-number.rs new file mode 100644 index 0000000..c4f4084 --- /dev/null +++ b/vendor/hex/tests/version-number.rs @@ -0,0 +1,11 @@ +#![allow(non_fmt_panic)] + +#[test] +fn test_readme_deps() { + version_sync::assert_markdown_deps_updated!("README.md"); +} + +#[test] +fn test_html_root_url() { + version_sync::assert_html_root_url_updated!("src/lib.rs"); +} |