summaryrefslogtreecommitdiffstats
path: root/vendor/base16ct/src
diff options
context:
space:
mode:
Diffstat (limited to 'vendor/base16ct/src')
-rw-r--r--vendor/base16ct/src/display.rs35
-rw-r--r--vendor/base16ct/src/error.rs32
-rw-r--r--vendor/base16ct/src/lib.rs118
-rw-r--r--vendor/base16ct/src/lower.rs80
-rw-r--r--vendor/base16ct/src/mixed.rs38
-rw-r--r--vendor/base16ct/src/upper.rs80
6 files changed, 383 insertions, 0 deletions
diff --git a/vendor/base16ct/src/display.rs b/vendor/base16ct/src/display.rs
new file mode 100644
index 000000000..1397a91dd
--- /dev/null
+++ b/vendor/base16ct/src/display.rs
@@ -0,0 +1,35 @@
+use core::fmt;
+
+/// `core::fmt` presenter for binary data encoded as hexadecimal (Base16).
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+pub struct HexDisplay<'a>(pub &'a [u8]);
+
+impl fmt::Display for HexDisplay<'_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{:X}", self)
+ }
+}
+
+impl fmt::UpperHex for HexDisplay<'_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let mut hex = [0u8; 2];
+
+ for &byte in self.0 {
+ f.write_str(crate::upper::encode_str(&[byte], &mut hex)?)?;
+ }
+
+ Ok(())
+ }
+}
+
+impl fmt::LowerHex for HexDisplay<'_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let mut hex = [0u8; 2];
+
+ for &byte in self.0 {
+ f.write_str(crate::lower::encode_str(&[byte], &mut hex)?)?;
+ }
+
+ Ok(())
+ }
+}
diff --git a/vendor/base16ct/src/error.rs b/vendor/base16ct/src/error.rs
new file mode 100644
index 000000000..a5f99c2ea
--- /dev/null
+++ b/vendor/base16ct/src/error.rs
@@ -0,0 +1,32 @@
+use core::fmt;
+
+/// Result type with the `base16ct` crate's [`Error`] type.
+pub type Result<T> = core::result::Result<T, Error>;
+
+/// Error type
+#[derive(Clone, Eq, PartialEq, Debug)]
+pub enum Error {
+ /// Invalid encoding of provided Base16 string.
+ InvalidEncoding,
+
+ /// Insufficient output buffer length.
+ InvalidLength,
+}
+
+impl fmt::Display for Error {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Error::InvalidEncoding => f.write_str("invalid Base16 encoding"),
+ Error::InvalidLength => f.write_str("invalid Base16 length"),
+ }
+ }
+}
+
+#[cfg(feature = "std")]
+impl std::error::Error for Error {}
+
+impl From<Error> for core::fmt::Error {
+ fn from(_: Error) -> core::fmt::Error {
+ core::fmt::Error::default()
+ }
+}
diff --git a/vendor/base16ct/src/lib.rs b/vendor/base16ct/src/lib.rs
new file mode 100644
index 000000000..413d512d8
--- /dev/null
+++ b/vendor/base16ct/src/lib.rs
@@ -0,0 +1,118 @@
+//! Pure Rust implementation of Base16 ([RFC 4648], a.k.a. hex).
+//!
+//! Implements lower and upper case Base16 variants without data-dependent branches
+//! or lookup tables, thereby providing portable "best effort" constant-time
+//! operation. Not constant-time with respect to message length (only data).
+//!
+//! Supports `no_std` environments and avoids heap allocations in the core API
+//! (but also provides optional `alloc` support for convenience).
+//!
+//! Based on code from: <https://github.com/Sc00bz/ConstTimeEncoding/blob/master/hex.cpp>
+//!
+//! # Examples
+//! ```
+//! let lower_hex_str = "abcd1234";
+//! let upper_hex_str = "ABCD1234";
+//! let mixed_hex_str = "abCD1234";
+//! let raw = b"\xab\xcd\x12\x34";
+//!
+//! let mut buf = [0u8; 16];
+//! // length of return slice can be different from the input buffer!
+//! let res = base16ct::lower::decode(lower_hex_str, &mut buf).unwrap();
+//! assert_eq!(res, raw);
+//! let res = base16ct::lower::encode(raw, &mut buf).unwrap();
+//! assert_eq!(res, lower_hex_str.as_bytes());
+//! // you also can use `encode_str` and `encode_string` to get
+//! // `&str` and `String` respectively
+//! let res: &str = base16ct::lower::encode_str(raw, &mut buf).unwrap();
+//! assert_eq!(res, lower_hex_str);
+//!
+//! let res = base16ct::upper::decode(upper_hex_str, &mut buf).unwrap();
+//! assert_eq!(res, raw);
+//! let res = base16ct::upper::encode(raw, &mut buf).unwrap();
+//! assert_eq!(res, upper_hex_str.as_bytes());
+//!
+//! // In cases when you don't know if input contains upper or lower
+//! // hex-encoded value, then use functions from the `mixed` module
+//! let res = base16ct::mixed::decode(lower_hex_str, &mut buf).unwrap();
+//! assert_eq!(res, raw);
+//! let res = base16ct::mixed::decode(upper_hex_str, &mut buf).unwrap();
+//! assert_eq!(res, raw);
+//! let res = base16ct::mixed::decode(mixed_hex_str, &mut buf).unwrap();
+//! assert_eq!(res, raw);
+//! ```
+//!
+//! [RFC 4648]: https://tools.ietf.org/html/rfc4648
+
+#![no_std]
+#![cfg_attr(docsrs, feature(doc_cfg))]
+#![warn(missing_docs, rust_2018_idioms)]
+#![doc(
+ html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
+ html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
+ html_root_url = "https://docs.rs/base16ct/0.1.1"
+)]
+
+#[cfg(feature = "alloc")]
+#[macro_use]
+extern crate alloc;
+#[cfg(feature = "std")]
+extern crate std;
+
+/// Function for decoding and encoding lower Base16 (hex)
+pub mod lower;
+/// Function for decoding mixed Base16 (hex)
+pub mod mixed;
+/// Function for decoding and encoding upper Base16 (hex)
+pub mod upper;
+
+/// Display formatter for hex.
+mod display;
+/// Error types.
+mod error;
+
+pub use crate::{
+ display::HexDisplay,
+ error::{Error, Result},
+};
+
+#[cfg(feature = "alloc")]
+use alloc::{string::String, vec::Vec};
+
+/// Compute decoded length of the given hex-encoded input.
+#[inline(always)]
+pub fn decoded_len(bytes: &[u8]) -> Result<usize> {
+ if bytes.len() & 1 == 0 {
+ Ok(bytes.len() / 2)
+ } else {
+ Err(Error::InvalidLength)
+ }
+}
+
+/// Get the length of Base16 (hex) produced by encoding the given bytes.
+#[inline(always)]
+pub fn encoded_len(bytes: &[u8]) -> usize {
+ bytes.len() * 2
+}
+
+fn decode_inner<'a>(
+ src: &[u8],
+ dst: &'a mut [u8],
+ decode_nibble: impl Fn(u8) -> u16,
+) -> Result<&'a [u8]> {
+ let dst = dst
+ .get_mut(..decoded_len(src)?)
+ .ok_or(Error::InvalidLength)?;
+
+ let mut err: u16 = 0;
+ for (src, dst) in src.chunks_exact(2).zip(dst.iter_mut()) {
+ let byte = (decode_nibble(src[0]) << 4) | decode_nibble(src[1]);
+ err |= byte >> 8;
+ *dst = byte as u8;
+ }
+
+ match err {
+ 0 => Ok(dst),
+ _ => Err(Error::InvalidEncoding),
+ }
+}
diff --git a/vendor/base16ct/src/lower.rs b/vendor/base16ct/src/lower.rs
new file mode 100644
index 000000000..b6d9f9453
--- /dev/null
+++ b/vendor/base16ct/src/lower.rs
@@ -0,0 +1,80 @@
+use crate::{decode_inner, encoded_len, Error};
+#[cfg(feature = "alloc")]
+use crate::{decoded_len, String, Vec};
+
+/// Decode a lower Base16 (hex) string into the provided destination buffer.
+pub fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], Error> {
+ decode_inner(src.as_ref(), dst, decode_nibble)
+}
+
+/// Decode a lower Base16 (hex) string into a byte vector.
+#[cfg(feature = "alloc")]
+#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
+pub fn decode_vec(input: impl AsRef<[u8]>) -> Result<Vec<u8>, Error> {
+ let mut output = vec![0u8; decoded_len(input.as_ref())?];
+ decode(input, &mut output)?;
+ Ok(output)
+}
+
+/// Encode the input byte slice as lower Base16.
+///
+/// Writes the result into the provided destination slice, returning an
+/// ASCII-encoded lower Base16 (hex) string value.
+pub fn encode<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a [u8], Error> {
+ let dst = dst
+ .get_mut(..encoded_len(src))
+ .ok_or(Error::InvalidLength)?;
+ for (src, dst) in src.iter().zip(dst.chunks_exact_mut(2)) {
+ dst[0] = encode_nibble(src >> 4);
+ dst[1] = encode_nibble(src & 0x0f);
+ }
+ Ok(dst)
+}
+
+/// Encode input byte slice into a [`&str`] containing lower Base16 (hex).
+pub fn encode_str<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a str, Error> {
+ encode(src, dst).map(|r| unsafe { core::str::from_utf8_unchecked(r) })
+}
+
+/// Encode input byte slice into a [`String`] containing lower Base16 (hex).
+///
+/// # Panics
+/// If `input` length is greater than `usize::MAX/2`.
+#[cfg(feature = "alloc")]
+#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
+pub fn encode_string(input: &[u8]) -> String {
+ let elen = encoded_len(input);
+ let mut dst = vec![0u8; elen];
+ let res = encode(input, &mut dst).expect("dst length is correct");
+
+ debug_assert_eq!(elen, res.len());
+ unsafe { String::from_utf8_unchecked(dst) }
+}
+
+/// Decode a single nibble of lower hex
+#[inline(always)]
+fn decode_nibble(src: u8) -> u16 {
+ // 0-9 0x30-0x39
+ // A-F 0x41-0x46 or a-f 0x61-0x66
+ let byte = src as i16;
+ let mut ret: i16 = -1;
+
+ // 0-9 0x30-0x39
+ // if (byte > 0x2f && byte < 0x3a) ret += byte - 0x30 + 1; // -47
+ ret += (((0x2fi16 - byte) & (byte - 0x3a)) >> 8) & (byte - 47);
+ // a-f 0x61-0x66
+ // if (byte > 0x60 && byte < 0x67) ret += byte - 0x61 + 10 + 1; // -86
+ ret += (((0x60i16 - byte) & (byte - 0x67)) >> 8) & (byte - 86);
+
+ ret as u16
+}
+
+/// Encode a single nibble of hex
+#[inline(always)]
+fn encode_nibble(src: u8) -> u8 {
+ let mut ret = src as i16 + 0x30;
+ // 0-9 0x30-0x39
+ // a-f 0x61-0x66
+ ret += ((0x39i16 - ret) >> 8) & (0x61i16 - 0x3a);
+ ret as u8
+}
diff --git a/vendor/base16ct/src/mixed.rs b/vendor/base16ct/src/mixed.rs
new file mode 100644
index 000000000..50f778d80
--- /dev/null
+++ b/vendor/base16ct/src/mixed.rs
@@ -0,0 +1,38 @@
+use crate::{decode_inner, Error};
+#[cfg(feature = "alloc")]
+use crate::{decoded_len, Vec};
+
+/// Decode a mixed Base16 (hex) string into the provided destination buffer.
+pub fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], Error> {
+ decode_inner(src.as_ref(), dst, decode_nibble)
+}
+
+/// Decode a mixed Base16 (hex) string into a byte vector.
+#[cfg(feature = "alloc")]
+#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
+pub fn decode_vec(input: impl AsRef<[u8]>) -> Result<Vec<u8>, Error> {
+ let mut output = vec![0u8; decoded_len(input.as_ref())?];
+ decode(input, &mut output)?;
+ Ok(output)
+}
+
+/// Decode a single nibble of lower hex
+#[inline(always)]
+fn decode_nibble(src: u8) -> u16 {
+ // 0-9 0x30-0x39
+ // A-F 0x41-0x46 or a-f 0x61-0x66
+ let byte = src as i16;
+ let mut ret: i16 = -1;
+
+ // 0-9 0x30-0x39
+ // if (byte > 0x2f && byte < 0x3a) ret += byte - 0x30 + 1; // -47
+ ret += (((0x2fi16 - byte) & (byte - 0x3a)) >> 8) & (byte - 47);
+ // A-F 0x41-0x46
+ // if (byte > 0x40 && byte < 0x47) ret += byte - 0x41 + 10 + 1; // -54
+ ret += (((0x40i16 - byte) & (byte - 0x47)) >> 8) & (byte - 54);
+ // a-f 0x61-0x66
+ // if (byte > 0x60 && byte < 0x67) ret += byte - 0x61 + 10 + 1; // -86
+ ret += (((0x60i16 - byte) & (byte - 0x67)) >> 8) & (byte - 86);
+
+ ret as u16
+}
diff --git a/vendor/base16ct/src/upper.rs b/vendor/base16ct/src/upper.rs
new file mode 100644
index 000000000..679006e21
--- /dev/null
+++ b/vendor/base16ct/src/upper.rs
@@ -0,0 +1,80 @@
+use crate::{decode_inner, encoded_len, Error};
+#[cfg(feature = "alloc")]
+use crate::{decoded_len, String, Vec};
+
+/// Decode an upper Base16 (hex) string into the provided destination buffer.
+pub fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], Error> {
+ decode_inner(src.as_ref(), dst, decode_nibble)
+}
+
+/// Decode an upper Base16 (hex) string into a byte vector.
+#[cfg(feature = "alloc")]
+#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
+pub fn decode_vec(input: impl AsRef<[u8]>) -> Result<Vec<u8>, Error> {
+ let mut output = vec![0u8; decoded_len(input.as_ref())?];
+ decode(input, &mut output)?;
+ Ok(output)
+}
+
+/// Encode the input byte slice as upper Base16.
+///
+/// Writes the result into the provided destination slice, returning an
+/// ASCII-encoded upper Base16 (hex) string value.
+pub fn encode<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a [u8], Error> {
+ let dst = dst
+ .get_mut(..encoded_len(src))
+ .ok_or(Error::InvalidLength)?;
+ for (src, dst) in src.iter().zip(dst.chunks_exact_mut(2)) {
+ dst[0] = encode_nibble(src >> 4);
+ dst[1] = encode_nibble(src & 0x0f);
+ }
+ Ok(dst)
+}
+
+/// Encode input byte slice into a [`&str`] containing upper Base16 (hex).
+pub fn encode_str<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a str, Error> {
+ encode(src, dst).map(|r| unsafe { core::str::from_utf8_unchecked(r) })
+}
+
+/// Encode input byte slice into a [`String`] containing upper Base16 (hex).
+///
+/// # Panics
+/// If `input` length is greater than `usize::MAX/2`.
+#[cfg(feature = "alloc")]
+#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
+pub fn encode_string(input: &[u8]) -> String {
+ let elen = encoded_len(input);
+ let mut dst = vec![0u8; elen];
+ let res = encode(input, &mut dst).expect("dst length is correct");
+
+ debug_assert_eq!(elen, res.len());
+ unsafe { crate::String::from_utf8_unchecked(dst) }
+}
+
+/// Decode a single nibble of upper hex
+#[inline(always)]
+fn decode_nibble(src: u8) -> u16 {
+ // 0-9 0x30-0x39
+ // A-F 0x41-0x46 or a-f 0x61-0x66
+ let byte = src as i16;
+ let mut ret: i16 = -1;
+
+ // 0-9 0x30-0x39
+ // if (byte > 0x2f && byte < 0x3a) ret += byte - 0x30 + 1; // -47
+ ret += (((0x2fi16 - byte) & (byte - 0x3a)) >> 8) & (byte - 47);
+ // A-F 0x41-0x46
+ // if (byte > 0x40 && byte < 0x47) ret += byte - 0x41 + 10 + 1; // -54
+ ret += (((0x40i16 - byte) & (byte - 0x47)) >> 8) & (byte - 54);
+
+ ret as u16
+}
+
+/// Encode a single nibble of hex
+#[inline(always)]
+fn encode_nibble(src: u8) -> u8 {
+ let mut ret = src as i16 + 0x30;
+ // 0-9 0x30-0x39
+ // A-F 0x41-0x46
+ ret += ((0x39i16 - ret) >> 8) & (0x41i16 - 0x3a);
+ ret as u8
+}