internals: Run formatter

Add one `rustfmt::skip` statement and run `cargo +nightly fmt`.
This commit is contained in:
Tobin C. Harding 2022-09-20 14:24:47 +10:00
parent aeacbe763d
commit ee19a1633d
3 changed files with 53 additions and 106 deletions

View File

@ -56,9 +56,7 @@ mod out_bytes {
/// ///
/// The method panics if `len` is out of bounds. /// The method panics if `len` is out of bounds.
#[cfg_attr(rust_v_1_46, track_caller)] #[cfg_attr(rust_v_1_46, track_caller)]
pub(crate) fn assume_init(&self, len: usize) -> &[u8] { pub(crate) fn assume_init(&self, len: usize) -> &[u8] { &self.0[..len] }
&self.0[..len]
}
/// Writes given bytes into the buffer. /// Writes given bytes into the buffer.
/// ///
@ -71,9 +69,7 @@ mod out_bytes {
} }
/// Returns the length of the buffer. /// Returns the length of the buffer.
pub(crate) fn len(&self) -> usize { pub(crate) fn len(&self) -> usize { self.0.len() }
self.0.len()
}
fn from_bytes(slice: &[u8]) -> &Self { fn from_bytes(slice: &[u8]) -> &Self {
// SAFETY: copied from std // SAFETY: copied from std
@ -83,9 +79,7 @@ mod out_bytes {
// conversion sound. // conversion sound.
// The pointer was just created from a reference that's still alive so dereferencing is // The pointer was just created from a reference that's still alive so dereferencing is
// sound. // sound.
unsafe { unsafe { &*(slice as *const [u8] as *const Self) }
&*(slice as *const [u8] as *const Self)
}
} }
fn from_mut_bytes(slice: &mut [u8]) -> &mut Self { fn from_mut_bytes(slice: &mut [u8]) -> &mut Self {
@ -96,9 +90,7 @@ mod out_bytes {
// conversion sound. // conversion sound.
// The pointer was just created from a reference that's still alive so dereferencing is // The pointer was just created from a reference that's still alive so dereferencing is
// sound. // sound.
unsafe { unsafe { &mut *(slice as *mut [u8] as *mut Self) }
&mut *(slice as *mut [u8] as *mut Self)
}
} }
} }
@ -121,36 +113,30 @@ mod out_bytes {
} }
impl<T: AsOutBytes + ?Sized> AsOutBytes for &'_ mut T { impl<T: AsOutBytes + ?Sized> AsOutBytes for &'_ mut T {
fn as_out_bytes(&self) -> &OutBytes { fn as_out_bytes(&self) -> &OutBytes { (**self).as_out_bytes() }
(**self).as_out_bytes()
}
fn as_mut_out_bytes(&mut self) -> &mut OutBytes { fn as_mut_out_bytes(&mut self) -> &mut OutBytes { (**self).as_mut_out_bytes() }
(**self).as_mut_out_bytes()
}
} }
impl<T: AsOutBytes + ?Sized> Sealed for &'_ mut T {} impl<T: AsOutBytes + ?Sized> Sealed for &'_ mut T {}
impl AsOutBytes for OutBytes { impl AsOutBytes for OutBytes {
fn as_out_bytes(&self) -> &OutBytes { fn as_out_bytes(&self) -> &OutBytes { self }
self
}
fn as_mut_out_bytes(&mut self) -> &mut OutBytes { fn as_mut_out_bytes(&mut self) -> &mut OutBytes { self }
self
}
} }
impl Sealed for OutBytes {} impl Sealed for OutBytes {}
// As a sanity check we only provide conversions for even, non-empty arrays. // As a sanity check we only provide conversions for even, non-empty arrays.
// Weird lengths 66 and 130 are provided for serialized public keys. // Weird lengths 66 and 130 are provided for serialized public keys.
impl_from_array!(2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 64, 66, 128, 130, 256, 512, 1024, 2048, 4096, 8192); impl_from_array!(
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 64, 66, 128, 130, 256, 512,
1024, 2048, 4096, 8192
);
/// Prevents outside crates from implementing the trait /// Prevents outside crates from implementing the trait
pub trait Sealed {} pub trait Sealed {}
} }
/// Hex-encodes bytes into the provided buffer. /// Hex-encodes bytes into the provided buffer.
@ -169,12 +155,7 @@ impl<T: AsOutBytes> BufEncoder<T> {
/// This is usually used with uninitialized (zeroed) byte array allocated on stack. /// This is usually used with uninitialized (zeroed) byte array allocated on stack.
/// This can only be constructed with an even-length, non-empty array. /// This can only be constructed with an even-length, non-empty array.
#[inline] #[inline]
pub fn new(buf: T) -> Self { pub fn new(buf: T) -> Self { BufEncoder { buf, pos: 0 } }
BufEncoder {
buf,
pos: 0,
}
}
/// Encodes `byte` as hex in given `case` and appends it to the buffer. /// Encodes `byte` as hex in given `case` and appends it to the buffer.
/// ///
@ -207,21 +188,18 @@ impl<T: AsOutBytes> BufEncoder<T> {
/// Returns true if no more bytes can be written into the buffer. /// Returns true if no more bytes can be written into the buffer.
#[inline] #[inline]
pub fn is_full(&self) -> bool { pub fn is_full(&self) -> bool { self.pos == self.buf.as_out_bytes().len() }
self.pos == self.buf.as_out_bytes().len()
}
/// Returns the written bytes as a hex `str`. /// Returns the written bytes as a hex `str`.
#[inline] #[inline]
pub fn as_str(&self) -> &str { pub fn as_str(&self) -> &str {
core::str::from_utf8(self.buf.as_out_bytes().assume_init(self.pos)).expect("we only write ASCII") core::str::from_utf8(self.buf.as_out_bytes().assume_init(self.pos))
.expect("we only write ASCII")
} }
/// Resets the buffer to become empty. /// Resets the buffer to become empty.
#[inline] #[inline]
pub fn clear(&mut self) { pub fn clear(&mut self) { self.pos = 0; }
self.pos = 0;
}
} }
#[cfg(test)] #[cfg(test)]
@ -289,9 +267,7 @@ mod tests {
} }
impl Writer { impl Writer {
fn as_str(&self) -> &str { fn as_str(&self) -> &str { core::str::from_utf8(&self.buf[..self.pos]).unwrap() }
core::str::from_utf8(&self.buf[..self.pos]).unwrap()
}
} }
impl Write for Writer { impl Write for Writer {
@ -307,10 +283,7 @@ mod tests {
} }
} }
let mut writer = Writer { let mut writer = Writer { buf: [0u8; 2], pos: 0 };
buf: [0u8; 2],
pos: 0,
};
let mut buf = [0u8; 2]; let mut buf = [0u8; 2];
let mut encoder = BufEncoder::new(&mut buf); let mut encoder = BufEncoder::new(&mut buf);

View File

@ -4,10 +4,11 @@
//! `&[u8]`. //! `&[u8]`.
use core::fmt; use core::fmt;
#[cfg(feature = "alloc")]
use crate::prelude::*;
use super::buf_encoder::{BufEncoder, OutBytes}; use super::buf_encoder::{BufEncoder, OutBytes};
use super::Case; use super::Case;
#[cfg(feature = "alloc")]
use crate::prelude::*;
/// Extension trait for types that can be displayed as hex. /// Extension trait for types that can be displayed as hex.
/// Types that have a single, obvious text representation being hex should **not** implement this /// Types that have a single, obvious text representation being hex should **not** implement this
@ -28,16 +29,12 @@ pub trait DisplayHex: Copy + sealed::IsRef {
/// Shorthand for `display_hex(Case::Lower)`. /// Shorthand for `display_hex(Case::Lower)`.
/// ///
/// Avoids the requirement to import the `Case` type. /// Avoids the requirement to import the `Case` type.
fn display_lower_hex(self) -> Self::Display { fn display_lower_hex(self) -> Self::Display { self.display_hex(Case::Lower) }
self.display_hex(Case::Lower)
}
/// Shorthand for `display_hex(Case::Upper)`. /// Shorthand for `display_hex(Case::Upper)`.
/// ///
/// Avoids the requirement to import the `Case` type. /// Avoids the requirement to import the `Case` type.
fn display_upper_hex(self) -> Self::Display { fn display_upper_hex(self) -> Self::Display { self.display_hex(Case::Upper) }
self.display_hex(Case::Upper)
}
/// Create a lower-hex-encoded string. /// Create a lower-hex-encoded string.
/// ///
@ -46,9 +43,7 @@ pub trait DisplayHex: Copy + sealed::IsRef {
/// This may be faster than `.display_hex().to_string()` because it uses `reserve_suggestion`. /// This may be faster than `.display_hex().to_string()` because it uses `reserve_suggestion`.
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
fn to_lower_hex_string(self) -> String { fn to_lower_hex_string(self) -> String { self.to_hex_string(Case::Lower) }
self.to_hex_string(Case::Lower)
}
/// Create an upper-hex-encoded string. /// Create an upper-hex-encoded string.
/// ///
@ -57,9 +52,7 @@ pub trait DisplayHex: Copy + sealed::IsRef {
/// This may be faster than `.display_hex().to_string()` because it uses `reserve_suggestion`. /// This may be faster than `.display_hex().to_string()` because it uses `reserve_suggestion`.
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
fn to_upper_hex_string(self) -> String { fn to_upper_hex_string(self) -> String { self.to_hex_string(Case::Upper) }
self.to_hex_string(Case::Upper)
}
/// Create a hex-encoded string. /// Create a hex-encoded string.
/// ///
@ -96,30 +89,21 @@ pub trait DisplayHex: Copy + sealed::IsRef {
/// Defaults to 0. /// Defaults to 0.
/// ///
// We prefix the name with `hex_` to avoid potential collision with other methods. // We prefix the name with `hex_` to avoid potential collision with other methods.
fn hex_reserve_suggestion(self) -> usize { fn hex_reserve_suggestion(self) -> usize { 0 }
0
}
} }
mod sealed { mod sealed {
/// Trait marking a shared reference. /// Trait marking a shared reference.
pub trait IsRef: Copy { pub trait IsRef: Copy {}
}
impl<T: ?Sized> IsRef for &'_ T { impl<T: ?Sized> IsRef for &'_ T {}
}
} }
impl<'a> DisplayHex for &'a [u8] { impl<'a> DisplayHex for &'a [u8] {
type Display = DisplayByteSlice<'a>; type Display = DisplayByteSlice<'a>;
#[inline] #[inline]
fn display_hex(self, case: Case) -> Self::Display { fn display_hex(self, case: Case) -> Self::Display { DisplayByteSlice { bytes: self, case } }
DisplayByteSlice {
bytes: self,
case,
}
}
#[inline] #[inline]
fn hex_reserve_suggestion(self) -> usize { fn hex_reserve_suggestion(self) -> usize {
@ -174,23 +158,26 @@ impl<'a> fmt::Display for DisplayByteSlice<'a> {
/// is more than half of `usize::MAX`. /// is more than half of `usize::MAX`.
#[macro_export] #[macro_export]
macro_rules! fmt_hex_exact { macro_rules! fmt_hex_exact {
($formatter:expr, $len:expr, $bytes:expr, $case:expr) => { ($formatter:expr, $len:expr, $bytes:expr, $case:expr) => {{
{ // statically check $len
// statically check $len #[allow(deprecated)]
#[allow(deprecated)] const _: () = [()][($len > usize::max_value() / 2) as usize];
const _: () = [()][($len > usize::max_value() / 2) as usize]; assert_eq!($bytes.len(), $len);
assert_eq!($bytes.len(), $len); let mut buf = [0u8; $len * 2];
let mut buf = [0u8; $len * 2]; let buf = $crate::hex::buf_encoder::AsOutBytes::as_mut_out_bytes(&mut buf);
let buf = $crate::hex::buf_encoder::AsOutBytes::as_mut_out_bytes(&mut buf); $crate::hex::display::fmt_hex_exact_fn($formatter, buf, $bytes, $case)
$crate::hex::display::fmt_hex_exact_fn($formatter, buf, $bytes, $case) }};
}
}
} }
// Implementation detail of `write_hex_exact` macro to de-duplicate the code // Implementation detail of `write_hex_exact` macro to de-duplicate the code
#[doc(hidden)] #[doc(hidden)]
#[inline] #[inline]
pub fn fmt_hex_exact_fn(f: &mut fmt::Formatter, buf: &mut OutBytes, bytes: &[u8], case: Case) -> fmt::Result { pub fn fmt_hex_exact_fn(
f: &mut fmt::Formatter,
buf: &mut OutBytes,
bytes: &[u8],
case: Case,
) -> fmt::Result {
let mut encoder = BufEncoder::new(buf); let mut encoder = BufEncoder::new(buf);
encoder.put_bytes(bytes, case); encoder.put_bytes(bytes, case);
f.pad_integral(true, "0x", encoder.as_str()) f.pad_integral(true, "0x", encoder.as_str())
@ -217,34 +204,22 @@ mod tests {
} }
#[test] #[test]
fn empty() { fn empty() { check_encoding(b""); }
check_encoding(b"");
}
#[test] #[test]
fn single() { fn single() { check_encoding(b"*"); }
check_encoding(b"*");
}
#[test] #[test]
fn two() { fn two() { check_encoding(b"*x"); }
check_encoding(b"*x");
}
#[test] #[test]
fn just_below_boundary() { fn just_below_boundary() { check_encoding(&[42; 512]); }
check_encoding(&[42; 512]);
}
#[test] #[test]
fn just_above_boundary() { fn just_above_boundary() { check_encoding(&[42; 513]); }
check_encoding(&[42; 513]);
}
#[test] #[test]
fn just_above_double_boundary() { fn just_above_double_boundary() { check_encoding(&[42; 1025]); }
check_encoding(&[42; 1025]);
}
#[test] #[test]
fn fmt_exact_macro() { fn fmt_exact_macro() {

View File

@ -23,9 +23,7 @@ pub enum Case {
} }
impl Default for Case { impl Default for Case {
fn default() -> Self { fn default() -> Self { Case::Lower }
Case::Lower
}
} }
impl Case { impl Case {
@ -33,6 +31,7 @@ impl Case {
/// ///
/// The returned table may only contain displayable ASCII chars. /// The returned table may only contain displayable ASCII chars.
#[inline] #[inline]
#[rustfmt::skip]
pub(crate) fn table(self) -> &'static [u8; 16] { pub(crate) fn table(self) -> &'static [u8; 16] {
static LOWER: [u8; 16] = [b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'a', b'b', b'c', b'd', b'e', b'f']; static LOWER: [u8; 16] = [b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'a', b'b', b'c', b'd', b'e', b'f'];
static UPPER: [u8; 16] = [b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'A', b'B', b'C', b'D', b'E', b'F']; static UPPER: [u8; 16] = [b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'A', b'B', b'C', b'D', b'E', b'F'];