hashes: Run the formatter

Run `cargo +nightly fmt`, no other manual changes.
This commit is contained in:
Tobin C. Harding 2023-02-22 10:25:12 +11:00
parent 52c4579057
commit 913575ac91
No known key found for this signature in database
GPG Key ID: 40BF9E4C269D6607
18 changed files with 268 additions and 399 deletions

View File

@ -22,22 +22,30 @@ pub fn fixed_time_eq(a: &[u8], b: &[u8]) -> bool {
for i in 0..count { for i in 0..count {
let mut rs = unsafe { core::ptr::read_volatile(&r) }; let mut rs = unsafe { core::ptr::read_volatile(&r) };
rs |= lhs[i] ^ rhs[i]; rs |= lhs[i] ^ rhs[i];
unsafe { core::ptr::write_volatile(&mut r, rs); } unsafe {
core::ptr::write_volatile(&mut r, rs);
}
} }
{ {
let mut t = unsafe { core::ptr::read_volatile(&r) }; let mut t = unsafe { core::ptr::read_volatile(&r) };
t |= t >> 4; t |= t >> 4;
unsafe { core::ptr::write_volatile(&mut r, t); } unsafe {
core::ptr::write_volatile(&mut r, t);
}
} }
{ {
let mut t = unsafe { core::ptr::read_volatile(&r) }; let mut t = unsafe { core::ptr::read_volatile(&r) };
t |= t >> 2; t |= t >> 2;
unsafe { core::ptr::write_volatile(&mut r, t); } unsafe {
core::ptr::write_volatile(&mut r, t);
}
} }
{ {
let mut t = unsafe { core::ptr::read_volatile(&r) }; let mut t = unsafe { core::ptr::read_volatile(&r) };
t |= t >> 1; t |= t >> 1;
unsafe { core::ptr::write_volatile(&mut r, t); } unsafe {
core::ptr::write_volatile(&mut r, t);
}
} }
unsafe { (::core::ptr::read_volatile(&r) & 1) == 0 } unsafe { (::core::ptr::read_volatile(&r) & 1) == 0 }
} }
@ -72,7 +80,7 @@ fn eq_test() {
assert!(!fixed_time_eq(&[0b10000000], &[0b00000000])); assert!(!fixed_time_eq(&[0b10000000], &[0b00000000]));
assert!(!fixed_time_eq(&[0b10000000], &[0b11111111])); assert!(!fixed_time_eq(&[0b10000000], &[0b11111111]));
assert!( fixed_time_eq(&[0b00000000, 0b00000000], &[0b00000000, 0b00000000])); assert!(fixed_time_eq(&[0b00000000, 0b00000000], &[0b00000000, 0b00000000]));
assert!(!fixed_time_eq(&[0b00000001, 0b00000000], &[0b00000000, 0b00000000])); assert!(!fixed_time_eq(&[0b00000001, 0b00000000], &[0b00000000, 0b00000000]));
assert!(!fixed_time_eq(&[0b00000000, 0b00000001], &[0b00000000, 0b00000000])); assert!(!fixed_time_eq(&[0b00000000, 0b00000001], &[0b00000000, 0b00000000]));
assert!(!fixed_time_eq(&[0b00000000, 0b00000000], &[0b00000001, 0b00000000])); assert!(!fixed_time_eq(&[0b00000000, 0b00000000], &[0b00000001, 0b00000000]));
@ -83,78 +91,62 @@ fn eq_test() {
mod benches { mod benches {
use test::Bencher; use test::Bencher;
use crate::{Hash, sha256, sha512};
use crate::cmp::fixed_time_eq; use crate::cmp::fixed_time_eq;
use crate::{sha256, sha512, Hash};
#[bench] #[bench]
fn bench_32b_constant_time_cmp_ne(bh: &mut Bencher) { fn bench_32b_constant_time_cmp_ne(bh: &mut Bencher) {
let hash_a = sha256::Hash::hash(&[0; 1]); let hash_a = sha256::Hash::hash(&[0; 1]);
let hash_b = sha256::Hash::hash(&[1; 1]); let hash_b = sha256::Hash::hash(&[1; 1]);
bh.iter(|| { bh.iter(|| fixed_time_eq(&hash_a[..], &hash_b[..]))
fixed_time_eq(&hash_a[..], &hash_b[..])
})
} }
#[bench] #[bench]
fn bench_32b_slice_cmp_ne(bh: &mut Bencher) { fn bench_32b_slice_cmp_ne(bh: &mut Bencher) {
let hash_a = sha256::Hash::hash(&[0; 1]); let hash_a = sha256::Hash::hash(&[0; 1]);
let hash_b = sha256::Hash::hash(&[1; 1]); let hash_b = sha256::Hash::hash(&[1; 1]);
bh.iter(|| { bh.iter(|| &hash_a[..] == &hash_b[..])
&hash_a[..] == &hash_b[..]
})
} }
#[bench] #[bench]
fn bench_32b_constant_time_cmp_eq(bh: &mut Bencher) { fn bench_32b_constant_time_cmp_eq(bh: &mut Bencher) {
let hash_a = sha256::Hash::hash(&[0; 1]); let hash_a = sha256::Hash::hash(&[0; 1]);
let hash_b = sha256::Hash::hash(&[0; 1]); let hash_b = sha256::Hash::hash(&[0; 1]);
bh.iter(|| { bh.iter(|| fixed_time_eq(&hash_a[..], &hash_b[..]))
fixed_time_eq(&hash_a[..], &hash_b[..])
})
} }
#[bench] #[bench]
fn bench_32b_slice_cmp_eq(bh: &mut Bencher) { fn bench_32b_slice_cmp_eq(bh: &mut Bencher) {
let hash_a = sha256::Hash::hash(&[0; 1]); let hash_a = sha256::Hash::hash(&[0; 1]);
let hash_b = sha256::Hash::hash(&[0; 1]); let hash_b = sha256::Hash::hash(&[0; 1]);
bh.iter(|| { bh.iter(|| &hash_a[..] == &hash_b[..])
&hash_a[..] == &hash_b[..]
})
} }
#[bench] #[bench]
fn bench_64b_constant_time_cmp_ne(bh: &mut Bencher) { fn bench_64b_constant_time_cmp_ne(bh: &mut Bencher) {
let hash_a = sha512::Hash::hash(&[0; 1]); let hash_a = sha512::Hash::hash(&[0; 1]);
let hash_b = sha512::Hash::hash(&[1; 1]); let hash_b = sha512::Hash::hash(&[1; 1]);
bh.iter(|| { bh.iter(|| fixed_time_eq(&hash_a[..], &hash_b[..]))
fixed_time_eq(&hash_a[..], &hash_b[..])
})
} }
#[bench] #[bench]
fn bench_64b_slice_cmp_ne(bh: &mut Bencher) { fn bench_64b_slice_cmp_ne(bh: &mut Bencher) {
let hash_a = sha512::Hash::hash(&[0; 1]); let hash_a = sha512::Hash::hash(&[0; 1]);
let hash_b = sha512::Hash::hash(&[1; 1]); let hash_b = sha512::Hash::hash(&[1; 1]);
bh.iter(|| { bh.iter(|| &hash_a[..] == &hash_b[..])
&hash_a[..] == &hash_b[..]
})
} }
#[bench] #[bench]
fn bench_64b_constant_time_cmp_eq(bh: &mut Bencher) { fn bench_64b_constant_time_cmp_eq(bh: &mut Bencher) {
let hash_a = sha512::Hash::hash(&[0; 1]); let hash_a = sha512::Hash::hash(&[0; 1]);
let hash_b = sha512::Hash::hash(&[0; 1]); let hash_b = sha512::Hash::hash(&[0; 1]);
bh.iter(|| { bh.iter(|| fixed_time_eq(&hash_a[..], &hash_b[..]))
fixed_time_eq(&hash_a[..], &hash_b[..])
})
} }
#[bench] #[bench]
fn bench_64b_slice_cmp_eq(bh: &mut Bencher) { fn bench_64b_slice_cmp_eq(bh: &mut Bencher) {
let hash_a = sha512::Hash::hash(&[0; 1]); let hash_a = sha512::Hash::hash(&[0; 1]);
let hash_b = sha512::Hash::hash(&[0; 1]); let hash_b = sha512::Hash::hash(&[0; 1]);
bh.iter(|| { bh.iter(|| &hash_a[..] == &hash_b[..])
&hash_a[..] == &hash_b[..]
})
} }
} }

View File

@ -29,7 +29,8 @@ impl fmt::Display for Error {
use self::Error::*; use self::Error::*;
match self { match self {
InvalidLength(ref ell, ref ell2) => write!(f, "invalid slice length {} (expected {})", ell2, ell), InvalidLength(ref ell, ref ell2) =>
write!(f, "invalid slice length {} (expected {})", ell2, ell),
} }
} }
} }

View File

@ -20,11 +20,11 @@
//! HASH160 (SHA256 then RIPEMD160) implementation. //! HASH160 (SHA256 then RIPEMD160) implementation.
//! //!
use core::str;
use core::ops::Index; use core::ops::Index;
use core::slice::SliceIndex; use core::slice::SliceIndex;
use core::str;
use crate::{Error, ripemd160, sha256}; use crate::{ripemd160, sha256, Error};
crate::internal_macros::hash_type! { crate::internal_macros::hash_type! {
160, 160,
@ -105,7 +105,8 @@ mod tests {
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
#[test] #[test]
fn ripemd_serde() { fn ripemd_serde() {
use serde_test::{Configure, Token, assert_tokens}; use serde_test::{assert_tokens, Configure, Token};
use crate::{hash160, Hash}; use crate::{hash160, Hash};
#[rustfmt::skip] #[rustfmt::skip]
@ -127,13 +128,13 @@ mod tests {
mod benches { mod benches {
use test::Bencher; use test::Bencher;
use crate::{Hash, HashEngine, hash160}; use crate::{hash160, Hash, HashEngine};
#[bench] #[bench]
pub fn hash160_10(bh: &mut Bencher) { pub fn hash160_10(bh: &mut Bencher) {
let mut engine = hash160::Hash::engine(); let mut engine = hash160::Hash::engine();
let bytes = [1u8; 10]; let bytes = [1u8; 10];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -143,7 +144,7 @@ mod benches {
pub fn hash160_1k(bh: &mut Bencher) { pub fn hash160_1k(bh: &mut Bencher) {
let mut engine = hash160::Hash::engine(); let mut engine = hash160::Hash::engine();
let bytes = [1u8; 1024]; let bytes = [1u8; 1024];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -153,7 +154,7 @@ mod benches {
pub fn hash160_64k(bh: &mut Bencher) { pub fn hash160_64k(bh: &mut Bencher) {
let mut engine = hash160::Hash::engine(); let mut engine = hash160::Hash::engine();
let bytes = [1u8; 65536]; let bytes = [1u8; 65536];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;

View File

@ -15,16 +15,15 @@
//! Hex encoding and decoding. //! Hex encoding and decoding.
//! //!
use core::{fmt, str};
#[cfg(all(feature = "alloc", not(feature = "std")))]
use crate::alloc::vec::Vec;
#[cfg(feature = "std")] #[cfg(feature = "std")]
use std::io; use std::io;
#[cfg(all(feature = "core2", not(feature = "std")))] #[cfg(all(feature = "core2", not(feature = "std")))]
use core2::io; use core2::io;
use core::{fmt, str}; #[cfg(all(feature = "alloc", not(feature = "std")))]
use crate::alloc::vec::Vec;
/// Hex decoding error. /// Hex decoding error.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
@ -42,7 +41,8 @@ impl fmt::Display for Error {
match *self { match *self {
Error::InvalidChar(ch) => write!(f, "invalid hex character {}", ch), Error::InvalidChar(ch) => write!(f, "invalid hex character {}", ch),
Error::OddLengthString(ell) => write!(f, "odd hex string length {}", ell), Error::OddLengthString(ell) => write!(f, "odd hex string length {}", ell),
Error::InvalidLength(ell, ell2) => write!(f, "bad hex string length {} (expected {})", ell2, ell), Error::InvalidLength(ell, ell2) =>
write!(f, "bad hex string length {} (expected {})", ell2, ell),
} }
} }
} }
@ -67,9 +67,7 @@ pub trait FromHex: Sized {
I: Iterator<Item = Result<u8, Error>> + ExactSizeIterator + DoubleEndedIterator; I: Iterator<Item = Result<u8, Error>> + ExactSizeIterator + DoubleEndedIterator;
/// Produces an object from a hex string. /// Produces an object from a hex string.
fn from_hex(s: &str) -> Result<Self, Error> { fn from_hex(s: &str) -> Result<Self, Error> { Self::from_byte_iter(HexIterator::new(s)?) }
Self::from_byte_iter(HexIterator::new(s)?)
}
} }
/// Iterator over a hex-encoded string slice which decodes hex and yields bytes. /// Iterator over a hex-encoded string slice which decodes hex and yields bytes.
@ -95,12 +93,8 @@ impl<'a> HexIterator<'a> {
} }
fn chars_to_hex(hi: u8, lo: u8) -> Result<u8, Error> { fn chars_to_hex(hi: u8, lo: u8) -> Result<u8, Error> {
let hih = (hi as char) let hih = (hi as char).to_digit(16).ok_or(Error::InvalidChar(hi))?;
.to_digit(16) let loh = (lo as char).to_digit(16).ok_or(Error::InvalidChar(lo))?;
.ok_or(Error::InvalidChar(hi))?;
let loh = (lo as char)
.to_digit(16)
.ok_or(Error::InvalidChar(lo))?;
let ret = (hih << 4) + loh; let ret = (hih << 4) + loh;
Ok(ret as u8) Ok(ret as u8)
@ -131,7 +125,7 @@ impl<'a> io::Read for HexIterator<'a> {
Some(Ok(src)) => { Some(Ok(src)) => {
*dst = src; *dst = src;
bytes_read += 1; bytes_read += 1;
}, }
_ => break, _ => break,
} }
} }
@ -178,7 +172,7 @@ macro_rules! impl_fromhex_array {
} }
} }
} }
} };
} }
impl_fromhex_array!(2); impl_fromhex_array!(2);
@ -204,9 +198,10 @@ impl_fromhex_array!(512);
#[cfg(test)] #[cfg(test)]
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
mod tests { mod tests {
use super::*;
use internals::hex::exts::DisplayHex; use internals::hex::exts::DisplayHex;
use super::*;
#[test] #[test]
fn hex_roundtrip() { fn hex_roundtrip() {
let expected = "0123456789abcdef"; let expected = "0123456789abcdef";
@ -235,29 +230,11 @@ mod tests {
let badchar2 = "012Y456789abcdeb"; let badchar2 = "012Y456789abcdeb";
let badchar3 = "«23456789abcdef"; let badchar3 = "«23456789abcdef";
assert_eq!( assert_eq!(Vec::<u8>::from_hex(oddlen), Err(Error::OddLengthString(17)));
Vec::<u8>::from_hex(oddlen), assert_eq!(<[u8; 4]>::from_hex(oddlen), Err(Error::OddLengthString(17)));
Err(Error::OddLengthString(17)) assert_eq!(<[u8; 8]>::from_hex(oddlen), Err(Error::OddLengthString(17)));
); assert_eq!(Vec::<u8>::from_hex(badchar1), Err(Error::InvalidChar(b'Z')));
assert_eq!( assert_eq!(Vec::<u8>::from_hex(badchar2), Err(Error::InvalidChar(b'Y')));
<[u8; 4]>::from_hex(oddlen), assert_eq!(Vec::<u8>::from_hex(badchar3), Err(Error::InvalidChar(194)));
Err(Error::OddLengthString(17))
);
assert_eq!(
<[u8; 8]>::from_hex(oddlen),
Err(Error::OddLengthString(17))
);
assert_eq!(
Vec::<u8>::from_hex(badchar1),
Err(Error::InvalidChar(b'Z'))
);
assert_eq!(
Vec::<u8>::from_hex(badchar2),
Err(Error::InvalidChar(b'Y'))
);
assert_eq!(
Vec::<u8>::from_hex(badchar3),
Err(Error::InvalidChar(194))
);
} }
} }

View File

@ -21,8 +21,9 @@
//! //!
use core::{borrow, fmt, ops, str}; use core::{borrow, fmt, ops, str};
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use serde::{Serialize, Serializer, Deserialize, Deserializer}; use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::{Error, Hash, HashEngine}; use crate::{Error, Hash, HashEngine};
@ -35,9 +36,7 @@ pub struct Hmac<T: Hash>(T);
impl<T: Hash + str::FromStr> str::FromStr for Hmac<T> { impl<T: Hash + str::FromStr> str::FromStr for Hmac<T> {
type Err = <T as str::FromStr>::Err; type Err = <T as str::FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Hmac(str::FromStr::from_str(s)?)) }
Ok(Hmac(str::FromStr::from_str(s)?))
}
} }
/// Pair of underlying hash midstates which represent the current state of an `HmacEngine`. /// Pair of underlying hash midstates which represent the current state of an `HmacEngine`.
@ -56,9 +55,7 @@ pub struct HmacEngine<T: Hash> {
} }
impl<T: Hash> Default for HmacEngine<T> { impl<T: Hash> Default for HmacEngine<T> {
fn default() -> Self { fn default() -> Self { HmacEngine::new(&[]) }
HmacEngine::new(&[])
}
} }
impl<T: Hash> HmacEngine<T> { impl<T: Hash> HmacEngine<T> {
@ -74,10 +71,7 @@ impl<T: Hash> HmacEngine<T> {
let mut ipad = [0x36u8; 128]; let mut ipad = [0x36u8; 128];
let mut opad = [0x5cu8; 128]; let mut opad = [0x5cu8; 128];
let mut ret = HmacEngine { let mut ret = HmacEngine { iengine: <T as Hash>::engine(), oengine: <T as Hash>::engine() };
iengine: <T as Hash>::engine(),
oengine: <T as Hash>::engine(),
};
if key.len() > T::Engine::BLOCK_SIZE { if key.len() > T::Engine::BLOCK_SIZE {
let hash = <T as Hash>::hash(key); let hash = <T as Hash>::hash(key);
@ -103,10 +97,7 @@ impl<T: Hash> HmacEngine<T> {
/// A special constructor giving direct access to the underlying "inner" and "outer" engines. /// A special constructor giving direct access to the underlying "inner" and "outer" engines.
pub fn from_inner_engines(iengine: T::Engine, oengine: T::Engine) -> HmacEngine<T> { pub fn from_inner_engines(iengine: T::Engine, oengine: T::Engine) -> HmacEngine<T> {
HmacEngine { HmacEngine { iengine, oengine }
iengine,
oengine,
}
} }
} }
@ -114,80 +105,55 @@ impl<T: Hash> HashEngine for HmacEngine<T> {
type MidState = HmacMidState<T>; type MidState = HmacMidState<T>;
fn midstate(&self) -> Self::MidState { fn midstate(&self) -> Self::MidState {
HmacMidState { HmacMidState { inner: self.iengine.midstate(), outer: self.oengine.midstate() }
inner: self.iengine.midstate(),
outer: self.oengine.midstate(),
}
} }
const BLOCK_SIZE: usize = T::Engine::BLOCK_SIZE; const BLOCK_SIZE: usize = T::Engine::BLOCK_SIZE;
fn n_bytes_hashed(&self) -> usize { fn n_bytes_hashed(&self) -> usize { self.iengine.n_bytes_hashed() }
self.iengine.n_bytes_hashed()
}
fn input(&mut self, buf: &[u8]) { fn input(&mut self, buf: &[u8]) { self.iengine.input(buf) }
self.iengine.input(buf)
}
} }
impl<T: Hash> fmt::Debug for Hmac<T> { impl<T: Hash> fmt::Debug for Hmac<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.0, f) }
fmt::Debug::fmt(&self.0, f)
}
} }
impl<T: Hash> fmt::Display for Hmac<T> { impl<T: Hash> fmt::Display for Hmac<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
fmt::Display::fmt(&self.0, f)
}
} }
impl<T: Hash> fmt::LowerHex for Hmac<T> { impl<T: Hash> fmt::LowerHex for Hmac<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(&self.0, f) }
fmt::LowerHex::fmt(&self.0, f)
}
} }
impl<T: Hash> ops::Index<usize> for Hmac<T> { impl<T: Hash> ops::Index<usize> for Hmac<T> {
type Output = u8; type Output = u8;
fn index(&self, index: usize) -> &u8 { fn index(&self, index: usize) -> &u8 { &self.0[index] }
&self.0[index]
}
} }
impl<T: Hash> ops::Index<ops::Range<usize>> for Hmac<T> { impl<T: Hash> ops::Index<ops::Range<usize>> for Hmac<T> {
type Output = [u8]; type Output = [u8];
fn index(&self, index: ops::Range<usize>) -> &[u8] { fn index(&self, index: ops::Range<usize>) -> &[u8] { &self.0[index] }
&self.0[index]
}
} }
impl<T: Hash> ops::Index<ops::RangeFrom<usize>> for Hmac<T> { impl<T: Hash> ops::Index<ops::RangeFrom<usize>> for Hmac<T> {
type Output = [u8]; type Output = [u8];
fn index(&self, index: ops::RangeFrom<usize>) -> &[u8] { fn index(&self, index: ops::RangeFrom<usize>) -> &[u8] { &self.0[index] }
&self.0[index]
}
} }
impl<T: Hash> ops::Index<ops::RangeTo<usize>> for Hmac<T> { impl<T: Hash> ops::Index<ops::RangeTo<usize>> for Hmac<T> {
type Output = [u8]; type Output = [u8];
fn index(&self, index: ops::RangeTo<usize>) -> &[u8] { fn index(&self, index: ops::RangeTo<usize>) -> &[u8] { &self.0[index] }
&self.0[index]
}
} }
impl<T: Hash> ops::Index<ops::RangeFull> for Hmac<T> { impl<T: Hash> ops::Index<ops::RangeFull> for Hmac<T> {
type Output = [u8]; type Output = [u8];
fn index(&self, index: ops::RangeFull) -> &[u8] { fn index(&self, index: ops::RangeFull) -> &[u8] { &self.0[index] }
&self.0[index]
}
} }
impl<T: Hash> borrow::Borrow<[u8]> for Hmac<T> { impl<T: Hash> borrow::Borrow<[u8]> for Hmac<T> {
fn borrow(&self) -> &[u8] { fn borrow(&self) -> &[u8] { &self[..] }
&self[..]
}
} }
impl<T: Hash> Hash for Hmac<T> { impl<T: Hash> Hash for Hmac<T> {
@ -203,21 +169,13 @@ impl<T: Hash> Hash for Hmac<T> {
const LEN: usize = T::LEN; const LEN: usize = T::LEN;
fn from_slice(sl: &[u8]) -> Result<Hmac<T>, Error> { fn from_slice(sl: &[u8]) -> Result<Hmac<T>, Error> { T::from_slice(sl).map(Hmac) }
T::from_slice(sl).map(Hmac)
}
fn to_byte_array(self) -> Self::Bytes { fn to_byte_array(self) -> Self::Bytes { self.0.to_byte_array() }
self.0.to_byte_array()
}
fn as_byte_array(&self) -> &Self::Bytes { fn as_byte_array(&self) -> &Self::Bytes { self.0.as_byte_array() }
self.0.as_byte_array()
}
fn from_byte_array(bytes: T::Bytes) -> Self { fn from_byte_array(bytes: T::Bytes) -> Self { Hmac(T::from_byte_array(bytes)) }
Hmac(T::from_byte_array(bytes))
}
fn all_zeros() -> Self { fn all_zeros() -> Self {
let zeros = T::all_zeros(); let zeros = T::all_zeros();
@ -247,7 +205,7 @@ mod tests {
#[test] #[test]
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
fn test() { fn test() {
use crate::{sha256, HashEngine, HmacEngine, Hash, Hmac}; use crate::{sha256, Hash, HashEngine, Hmac, HmacEngine};
#[derive(Clone)] #[derive(Clone)]
struct Test { struct Test {
@ -373,7 +331,8 @@ mod tests {
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
#[test] #[test]
fn hmac_sha512_serde() { fn hmac_sha512_serde() {
use serde_test::{Configure, Token, assert_tokens}; use serde_test::{assert_tokens, Configure, Token};
use crate::{sha512, Hash, Hmac}; use crate::{sha512, Hash, Hmac};
#[rustfmt::skip] #[rustfmt::skip]
@ -394,7 +353,7 @@ mod tests {
&hash.readable(), &hash.readable(),
&[Token::Str( &[Token::Str(
"8b41e1b78ad11521113c52ff182a1b8e0a195754aa527fcd00a411620b46f20f\ "8b41e1b78ad11521113c52ff182a1b8e0a195754aa527fcd00a411620b46f20f\
fffb8088ccf85497121ad4499e0845b876f6dd6640088a2f0b2d8a600bdf4c0c" fffb8088ccf85497121ad4499e0845b876f6dd6640088a2f0b2d8a600bdf4c0c",
)], )],
); );
} }
@ -404,13 +363,13 @@ mod tests {
mod benches { mod benches {
use test::Bencher; use test::Bencher;
use crate::{Hmac, Hash, HashEngine, sha256}; use crate::{sha256, Hash, HashEngine, Hmac};
#[bench] #[bench]
pub fn hmac_sha256_10(bh: &mut Bencher) { pub fn hmac_sha256_10(bh: &mut Bencher) {
let mut engine = Hmac::<sha256::Hash>::engine(); let mut engine = Hmac::<sha256::Hash>::engine();
let bytes = [1u8; 10]; let bytes = [1u8; 10];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -420,7 +379,7 @@ mod benches {
pub fn hmac_sha256_1k(bh: &mut Bencher) { pub fn hmac_sha256_1k(bh: &mut Bencher) {
let mut engine = Hmac::<sha256::Hash>::engine(); let mut engine = Hmac::<sha256::Hash>::engine();
let bytes = [1u8; 1024]; let bytes = [1u8; 1024];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -430,10 +389,9 @@ mod benches {
pub fn hmac_sha256_64k(bh: &mut Bencher) { pub fn hmac_sha256_64k(bh: &mut Bencher) {
let mut engine = Hmac::<sha256::Hash>::engine(); let mut engine = Hmac::<sha256::Hash>::engine();
let bytes = [1u8; 65536]; let bytes = [1u8; 65536];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
} }
} }

View File

@ -23,7 +23,7 @@ use std::io;
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
use core2::io; use core2::io;
use crate::{HashEngine, sha1, sha256, sha512, ripemd160, siphash24, hmac}; use crate::{hmac, ripemd160, sha1, sha256, sha512, siphash24, HashEngine};
impl io::Write for sha1::HashEngine { impl io::Write for sha1::HashEngine {
fn flush(&mut self) -> io::Result<()> { Ok(()) } fn flush(&mut self) -> io::Result<()> { Ok(()) }
@ -82,8 +82,7 @@ impl<T: crate::Hash> io::Write for hmac::HmacEngine<T> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::io::Write; use super::io::Write;
use crate::{hash160, hmac, ripemd160, sha1, sha256, sha256d, sha512, siphash24, Hash};
use crate::{Hash, sha1, sha256, sha256d, sha512, ripemd160, hash160, siphash24, hmac};
macro_rules! write_test { macro_rules! write_test {
($mod:ident, $exp_empty:expr, $exp_256:expr, $exp_64k:expr,) => { ($mod:ident, $exp_empty:expr, $exp_256:expr, $exp_64k:expr,) => {
@ -91,26 +90,17 @@ mod tests {
fn $mod() { fn $mod() {
let mut engine = $mod::Hash::engine(); let mut engine = $mod::Hash::engine();
engine.write_all(&[]).unwrap(); engine.write_all(&[]).unwrap();
assert_eq!( assert_eq!(format!("{}", $mod::Hash::from_engine(engine)), $exp_empty);
format!("{}", $mod::Hash::from_engine(engine)),
$exp_empty
);
let mut engine = $mod::Hash::engine(); let mut engine = $mod::Hash::engine();
engine.write_all(&[1; 256]).unwrap(); engine.write_all(&[1; 256]).unwrap();
assert_eq!( assert_eq!(format!("{}", $mod::Hash::from_engine(engine)), $exp_256);
format!("{}", $mod::Hash::from_engine(engine)),
$exp_256
);
let mut engine = $mod::Hash::engine(); let mut engine = $mod::Hash::engine();
engine.write_all(&[99; 64000]).unwrap(); engine.write_all(&[99; 64000]).unwrap();
assert_eq!( assert_eq!(format!("{}", $mod::Hash::from_engine(engine)), $exp_64k);
format!("{}", $mod::Hash::from_engine(engine)),
$exp_64k
);
} }
} };
} }
write_test!( write_test!(
@ -158,12 +148,7 @@ mod tests {
"a9608c952c8dbcc20c53803d2ca5ad31d64d9313", "a9608c952c8dbcc20c53803d2ca5ad31d64d9313",
); );
write_test!( write_test!(siphash24, "d70077739d4b921e", "3a3ccefde9b5b1e3", "ce456e4e4ecbc5bf",);
siphash24,
"d70077739d4b921e",
"3a3ccefde9b5b1e3",
"ce456e4e4ecbc5bf",
);
#[test] #[test]
fn hmac() { fn hmac() {

View File

@ -186,21 +186,16 @@ macro_rules! hash_type {
#[cfg_attr(feature = "schemars", derive(crate::schemars::JsonSchema))] #[cfg_attr(feature = "schemars", derive(crate::schemars::JsonSchema))]
#[repr(transparent)] #[repr(transparent)]
pub struct Hash( pub struct Hash(
#[cfg_attr(feature = "schemars", schemars(schema_with = $schemars))] #[cfg_attr(feature = "schemars", schemars(schema_with = $schemars))] [u8; $bits / 8],
[u8; $bits / 8]
); );
impl Hash { impl Hash {
fn internal_new(arr: [u8; $bits / 8]) -> Self { fn internal_new(arr: [u8; $bits / 8]) -> Self { Hash(arr) }
Hash(arr)
}
fn internal_engine() -> HashEngine { fn internal_engine() -> HashEngine { Default::default() }
Default::default()
}
} }
crate::internal_macros::hash_trait_impls!($bits, $reverse); crate::internal_macros::hash_trait_impls!($bits, $reverse);
} };
} }
pub(crate) use hash_type; pub(crate) use hash_type;

View File

@ -79,28 +79,30 @@
// Coding conventions // Coding conventions
#![warn(missing_docs)] #![warn(missing_docs)]
// Experimental features we need. // Experimental features we need.
#![cfg_attr(docsrs, feature(doc_cfg))] #![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(bench, feature(test))] #![cfg_attr(bench, feature(test))]
// In general, rust is absolutely horrid at supporting users doing things like, // In general, rust is absolutely horrid at supporting users doing things like,
// for example, compiling Rust code for real environments. Disable useless lints // for example, compiling Rust code for real environments. Disable useless lints
// that don't do anything but annoy us and cant actually ever be resolved. // that don't do anything but annoy us and cant actually ever be resolved.
#![allow(bare_trait_objects)] #![allow(bare_trait_objects)]
#![allow(ellipsis_inclusive_range_patterns)] #![allow(ellipsis_inclusive_range_patterns)]
#![cfg_attr(all(not(test), not(feature = "std")), no_std)] #![cfg_attr(all(not(test), not(feature = "std")), no_std)]
// Instead of littering the codebase for non-fuzzing code just globally allow. // Instead of littering the codebase for non-fuzzing code just globally allow.
#![cfg_attr(fuzzing, allow(dead_code, unused_imports))] #![cfg_attr(fuzzing, allow(dead_code, unused_imports))]
#[cfg(bench)] extern crate test; #[cfg(all(feature = "alloc", not(feature = "std")))]
#[cfg(any(test, feature = "std"))] extern crate core; extern crate alloc;
#[cfg(feature = "core2")] extern crate core2; #[cfg(any(test, feature = "std"))]
#[cfg(all(feature = "alloc", not(feature = "std")))] extern crate alloc; extern crate core;
#[cfg(feature = "serde")] pub extern crate serde; #[cfg(feature = "core2")]
#[cfg(all(test,feature = "serde"))] extern crate serde_test; extern crate core2;
#[cfg(feature = "serde")]
pub extern crate serde;
#[cfg(all(test, feature = "serde"))]
extern crate serde_test;
#[cfg(bench)]
extern crate test;
#[doc(hidden)] #[doc(hidden)]
pub mod _export { pub mod _export {
@ -114,27 +116,30 @@ pub mod _export {
extern crate actual_schemars as schemars; extern crate actual_schemars as schemars;
mod internal_macros; mod internal_macros;
#[macro_use] mod util; #[macro_use]
#[macro_use] pub mod serde_macros; mod util;
#[cfg(any(feature = "std", feature = "core2"))] mod impls; #[macro_use]
pub mod serde_macros;
pub mod cmp;
pub mod error; pub mod error;
pub mod hex;
pub mod hash160; pub mod hash160;
pub mod hex;
pub mod hmac; pub mod hmac;
#[cfg(any(feature = "std", feature = "core2"))]
mod impls;
pub mod ripemd160; pub mod ripemd160;
pub mod sha1; pub mod sha1;
pub mod sha256; pub mod sha256;
pub mod sha256d; pub mod sha256d;
pub mod sha256t; pub mod sha256t;
pub mod siphash24;
pub mod sha512; pub mod sha512;
pub mod sha512_256; pub mod sha512_256;
pub mod cmp; pub mod siphash24;
use core::{borrow, fmt, hash, ops}; use core::{borrow, fmt, hash, ops};
pub use hmac::{Hmac, HmacEngine};
pub use error::Error; pub use error::Error;
pub use hmac::{Hmac, HmacEngine};
/// A hashing engine which bytes can be serialized into. /// A hashing engine which bytes can be serialized into.
pub trait HashEngine: Clone + Default { pub trait HashEngine: Clone + Default {
@ -156,14 +161,23 @@ pub trait HashEngine: Clone + Default {
} }
/// Trait which applies to hashes of all types. /// Trait which applies to hashes of all types.
pub trait Hash: Copy + Clone + PartialEq + Eq + PartialOrd + Ord + pub trait Hash:
hash::Hash + fmt::Debug + fmt::Display + fmt::LowerHex + Copy
ops::Index<ops::RangeFull, Output = [u8]> + + Clone
ops::Index<ops::RangeFrom<usize>, Output = [u8]> + + PartialEq
ops::Index<ops::RangeTo<usize>, Output = [u8]> + + Eq
ops::Index<ops::Range<usize>, Output = [u8]> + + PartialOrd
ops::Index<usize, Output = u8> + + Ord
borrow::Borrow<[u8]> + hash::Hash
+ fmt::Debug
+ fmt::Display
+ fmt::LowerHex
+ ops::Index<ops::RangeFull, Output = [u8]>
+ ops::Index<ops::RangeFrom<usize>, Output = [u8]>
+ ops::Index<ops::RangeTo<usize>, Output = [u8]>
+ ops::Index<ops::Range<usize>, Output = [u8]>
+ ops::Index<usize, Output = u8>
+ borrow::Borrow<[u8]>
{ {
/// A hashing engine which bytes can be serialized into. It is expected /// A hashing engine which bytes can be serialized into. It is expected
/// to implement the `io::Write` trait, and to never return errors under /// to implement the `io::Write` trait, and to never return errors under
@ -174,9 +188,7 @@ pub trait Hash: Copy + Clone + PartialEq + Eq + PartialOrd + Ord +
type Bytes: hex::FromHex + Copy; type Bytes: hex::FromHex + Copy;
/// Constructs a new engine. /// Constructs a new engine.
fn engine() -> Self::Engine { fn engine() -> Self::Engine { Self::Engine::default() }
Self::Engine::default()
}
/// Produces a hash from the current state of a given engine. /// Produces a hash from the current state of a given engine.
fn from_engine(e: Self::Engine) -> Self; fn from_engine(e: Self::Engine) -> Self;
@ -218,7 +230,7 @@ pub trait Hash: Copy + Clone + PartialEq + Eq + PartialOrd + Ord +
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::{Hash, sha256d}; use crate::{sha256d, Hash};
hash_newtype! { hash_newtype! {
/// A test newtype /// A test newtype

View File

@ -20,10 +20,10 @@
//! RIPEMD160 implementation. //! RIPEMD160 implementation.
//! //!
use core::{cmp, str};
use core::convert::TryInto; use core::convert::TryInto;
use core::ops::Index; use core::ops::Index;
use core::slice::SliceIndex; use core::slice::SliceIndex;
use core::{cmp, str};
use crate::{Error, HashEngine as _}; use crate::{Error, HashEngine as _};
@ -102,9 +102,7 @@ impl crate::HashEngine for HashEngine {
const BLOCK_SIZE: usize = 64; const BLOCK_SIZE: usize = 64;
fn n_bytes_hashed(&self) -> usize { fn n_bytes_hashed(&self) -> usize { self.length }
self.length
}
engine_input_impl!(); engine_input_impl!();
} }
@ -407,7 +405,7 @@ mod tests {
#[test] #[test]
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
fn test() { fn test() {
use crate::{Hash, HashEngine, ripemd160}; use crate::{ripemd160, Hash, HashEngine};
#[derive(Clone)] #[derive(Clone)]
struct Test { struct Test {
@ -488,7 +486,8 @@ mod tests {
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
#[test] #[test]
fn ripemd_serde() { fn ripemd_serde() {
use serde_test::{Configure, Token, assert_tokens}; use serde_test::{assert_tokens, Configure, Token};
use crate::{ripemd160, Hash}; use crate::{ripemd160, Hash};
#[rustfmt::skip] #[rustfmt::skip]
@ -510,13 +509,13 @@ mod tests {
mod benches { mod benches {
use test::Bencher; use test::Bencher;
use crate::{Hash, HashEngine, ripemd160}; use crate::{ripemd160, Hash, HashEngine};
#[bench] #[bench]
pub fn ripemd160_10(bh: &mut Bencher) { pub fn ripemd160_10(bh: &mut Bencher) {
let mut engine = ripemd160::Hash::engine(); let mut engine = ripemd160::Hash::engine();
let bytes = [1u8; 10]; let bytes = [1u8; 10];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -526,7 +525,7 @@ mod benches {
pub fn ripemd160_1k(bh: &mut Bencher) { pub fn ripemd160_1k(bh: &mut Bencher) {
let mut engine = ripemd160::Hash::engine(); let mut engine = ripemd160::Hash::engine();
let bytes = [1u8; 1024]; let bytes = [1u8; 1024];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -536,10 +535,9 @@ mod benches {
pub fn ripemd160_64k(bh: &mut Bencher) { pub fn ripemd160_64k(bh: &mut Bencher) {
let mut engine = ripemd160::Hash::engine(); let mut engine = ripemd160::Hash::engine();
let bytes = [1u8; 65536]; let bytes = [1u8; 65536];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
} }
} }

View File

@ -19,13 +19,13 @@
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))] #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
pub mod serde_details { pub mod serde_details {
use crate::Error;
use core::marker::PhantomData; use core::marker::PhantomData;
use core::{fmt, ops, str};
use core::str::FromStr; use core::str::FromStr;
use core::{fmt, ops, str};
use crate::Error;
struct HexVisitor<ValueT>(PhantomData<ValueT>); struct HexVisitor<ValueT>(PhantomData<ValueT>);
use serde::{de, Serializer, Deserializer}; use serde::{de, Deserializer, Serializer};
impl<'de, ValueT> de::Visitor<'de> for HexVisitor<ValueT> impl<'de, ValueT> de::Visitor<'de> for HexVisitor<ValueT>
where where
@ -45,10 +45,7 @@ pub mod serde_details {
if let Ok(hex) = str::from_utf8(v) { if let Ok(hex) = str::from_utf8(v) {
Self::Value::from_str(hex).map_err(E::custom) Self::Value::from_str(hex).map_err(E::custom)
} else { } else {
return Err(E::invalid_value( return Err(E::invalid_value(de::Unexpected::Bytes(v), &self));
de::Unexpected::Bytes(v),
&self,
));
} }
} }

View File

@ -15,10 +15,10 @@
//! SHA1 implementation. //! SHA1 implementation.
//! //!
use core::{cmp, str};
use core::convert::TryInto; use core::convert::TryInto;
use core::ops::Index; use core::ops::Index;
use core::slice::SliceIndex; use core::slice::SliceIndex;
use core::{cmp, str};
use crate::{Error, HashEngine as _}; use crate::{Error, HashEngine as _};
@ -89,9 +89,7 @@ impl crate::HashEngine for HashEngine {
const BLOCK_SIZE: usize = 64; const BLOCK_SIZE: usize = 64;
fn n_bytes_hashed(&self) -> usize { fn n_bytes_hashed(&self) -> usize { self.length }
self.length
}
engine_input_impl!(); engine_input_impl!();
} }
@ -106,7 +104,7 @@ impl HashEngine {
*w_val = u32::from_be_bytes(buff_bytes.try_into().expect("4 bytes slice")) *w_val = u32::from_be_bytes(buff_bytes.try_into().expect("4 bytes slice"))
} }
for i in 16..80 { for i in 16..80 {
w[i] =(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1); w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
} }
let mut a = self.h[0]; let mut a = self.h[0];
@ -117,14 +115,15 @@ impl HashEngine {
for (i, &wi) in w.iter().enumerate() { for (i, &wi) in w.iter().enumerate() {
let (f, k) = match i { let (f, k) = match i {
0...19 => ((b & c) | (!b & d), 0x5a827999), 0...19 => ((b & c) | (!b & d), 0x5a827999),
20...39 => (b ^ c ^ d, 0x6ed9eba1), 20...39 => (b ^ c ^ d, 0x6ed9eba1),
40...59 => ((b & c) | (b & d) | (c & d), 0x8f1bbcdc), 40...59 => ((b & c) | (b & d) | (c & d), 0x8f1bbcdc),
60...79 => (b ^ c ^ d, 0xca62c1d6), 60...79 => (b ^ c ^ d, 0xca62c1d6),
_ => unreachable!() _ => unreachable!(),
}; };
let new_a = a.rotate_left(5).wrapping_add(f).wrapping_add(e).wrapping_add(k).wrapping_add(wi); let new_a =
a.rotate_left(5).wrapping_add(f).wrapping_add(e).wrapping_add(k).wrapping_add(wi);
e = d; e = d;
d = c; d = c;
c = b.rotate_left(30); c = b.rotate_left(30);
@ -213,7 +212,8 @@ mod tests {
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
#[test] #[test]
fn sha1_serde() { fn sha1_serde() {
use serde_test::{Configure, Token, assert_tokens}; use serde_test::{assert_tokens, Configure, Token};
use crate::{sha1, Hash}; use crate::{sha1, Hash};
#[rustfmt::skip] #[rustfmt::skip]
@ -235,13 +235,13 @@ mod tests {
mod benches { mod benches {
use test::Bencher; use test::Bencher;
use crate::{Hash, HashEngine, sha1}; use crate::{sha1, Hash, HashEngine};
#[bench] #[bench]
pub fn sha1_10(bh: &mut Bencher) { pub fn sha1_10(bh: &mut Bencher) {
let mut engine = sha1::Hash::engine(); let mut engine = sha1::Hash::engine();
let bytes = [1u8; 10]; let bytes = [1u8; 10];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -251,7 +251,7 @@ mod benches {
pub fn sha1_1k(bh: &mut Bencher) { pub fn sha1_1k(bh: &mut Bencher) {
let mut engine = sha1::Hash::engine(); let mut engine = sha1::Hash::engine();
let bytes = [1u8; 1024]; let bytes = [1u8; 1024];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -261,10 +261,9 @@ mod benches {
pub fn sha1_64k(bh: &mut Bencher) { pub fn sha1_64k(bh: &mut Bencher) {
let mut engine = sha1::Hash::engine(); let mut engine = sha1::Hash::engine();
let bytes = [1u8; 65536]; let bytes = [1u8; 65536];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
} }
} }

View File

@ -15,12 +15,12 @@
//! SHA256 implementation. //! SHA256 implementation.
//! //!
use core::{cmp, str};
use core::convert::TryInto; use core::convert::TryInto;
use core::ops::Index; use core::ops::Index;
use core::slice::SliceIndex; use core::slice::SliceIndex;
use core::{cmp, str};
use crate::{Error, HashEngine as _, hex, sha256d}; use crate::{hex, sha256d, Error, HashEngine as _};
crate::internal_macros::hash_type! { crate::internal_macros::hash_type! {
256, 256,
@ -73,7 +73,10 @@ pub struct HashEngine {
impl Default for HashEngine { impl Default for HashEngine {
fn default() -> Self { fn default() -> Self {
HashEngine { HashEngine {
h: [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19], h: [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19,
],
length: 0, length: 0,
buffer: [0; BLOCK_SIZE], buffer: [0; BLOCK_SIZE],
} }
@ -101,9 +104,7 @@ impl crate::HashEngine for HashEngine {
const BLOCK_SIZE: usize = 64; const BLOCK_SIZE: usize = 64;
fn n_bytes_hashed(&self) -> usize { fn n_bytes_hashed(&self) -> usize { self.length }
self.length
}
engine_input_impl!(); engine_input_impl!();
} }
@ -127,16 +128,12 @@ impl<I: SliceIndex<[u8]>> Index<I> for Midstate {
type Output = I::Output; type Output = I::Output;
#[inline] #[inline]
fn index(&self, index: I) -> &Self::Output { fn index(&self, index: I) -> &Self::Output { &self.0[index] }
&self.0[index]
}
} }
impl str::FromStr for Midstate { impl str::FromStr for Midstate {
type Err = hex::Error; type Err = hex::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> { hex::FromHex::from_hex(s) }
hex::FromHex::from_hex(s)
}
} }
impl Midstate { impl Midstate {
@ -149,9 +146,7 @@ impl Midstate {
const DISPLAY_BACKWARD: bool = true; const DISPLAY_BACKWARD: bool = true;
/// Construct a new [`Midstate`] from the inner value. /// Construct a new [`Midstate`] from the inner value.
pub fn from_byte_array(inner: [u8; 32]) -> Self { pub fn from_byte_array(inner: [u8; 32]) -> Self { Midstate(inner) }
Midstate(inner)
}
/// Copies a byte slice into the [`Midstate`] object. /// Copies a byte slice into the [`Midstate`] object.
pub fn from_slice(sl: &[u8]) -> Result<Midstate, Error> { pub fn from_slice(sl: &[u8]) -> Result<Midstate, Error> {
@ -165,9 +160,7 @@ impl Midstate {
} }
/// Unwraps the [`Midstate`] and returns the underlying byte array. /// Unwraps the [`Midstate`] and returns the underlying byte array.
pub fn to_byte_array(self) -> [u8; 32] { pub fn to_byte_array(self) -> [u8; 32] { self.0 }
self.0
}
} }
impl hex::FromHex for Midstate { impl hex::FromHex for Midstate {
@ -182,7 +175,8 @@ impl hex::FromHex for Midstate {
macro_rules! Ch( ($x:expr, $y:expr, $z:expr) => ($z ^ ($x & ($y ^ $z))) ); macro_rules! Ch( ($x:expr, $y:expr, $z:expr) => ($z ^ ($x & ($y ^ $z))) );
macro_rules! Maj( ($x:expr, $y:expr, $z:expr) => (($x & $y) | ($z & ($x | $y))) ); macro_rules! Maj( ($x:expr, $y:expr, $z:expr) => (($x & $y) | ($z & ($x | $y))) );
macro_rules! Sigma0( ($x:expr) => ($x.rotate_left(30) ^ $x.rotate_left(19) ^ $x.rotate_left(10)) ); macro_rules! Sigma1( ($x:expr) => ( $x.rotate_left(26) ^ $x.rotate_left(21) ^ $x.rotate_left(7)) ); macro_rules! Sigma0( ($x:expr) => ($x.rotate_left(30) ^ $x.rotate_left(19) ^ $x.rotate_left(10)) );
macro_rules! Sigma1( ($x:expr) => ( $x.rotate_left(26) ^ $x.rotate_left(21) ^ $x.rotate_left(7)) );
macro_rules! sigma0( ($x:expr) => ($x.rotate_left(25) ^ $x.rotate_left(14) ^ ($x >> 3)) ); macro_rules! sigma0( ($x:expr) => ($x.rotate_left(25) ^ $x.rotate_left(14) ^ ($x >> 3)) );
macro_rules! sigma1( ($x:expr) => ($x.rotate_left(15) ^ $x.rotate_left(13) ^ ($x >> 10)) ); macro_rules! sigma1( ($x:expr) => ($x.rotate_left(15) ^ $x.rotate_left(13) ^ ($x >> 10)) );
@ -215,11 +209,7 @@ impl HashEngine {
*ret_val = u32::from_be_bytes(midstate_bytes.try_into().expect("4 byte slice")); *ret_val = u32::from_be_bytes(midstate_bytes.try_into().expect("4 byte slice"));
} }
HashEngine { HashEngine { buffer: [0; BLOCK_SIZE], h: ret, length }
buffer: [0; BLOCK_SIZE],
h: ret,
length,
}
} }
// Algorithm copied from libsecp256k1 // Algorithm copied from libsecp256k1
@ -321,7 +311,7 @@ impl HashEngine {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::{Hash, HashEngine, sha256}; use crate::{sha256, Hash, HashEngine};
#[test] #[test]
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
@ -469,7 +459,7 @@ mod tests {
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
#[test] #[test]
fn sha256_serde() { fn sha256_serde() {
use serde_test::{Configure, Token, assert_tokens}; use serde_test::{assert_tokens, Configure, Token};
#[rustfmt::skip] #[rustfmt::skip]
static HASH_BYTES: [u8; 32] = [ static HASH_BYTES: [u8; 32] = [
@ -481,14 +471,17 @@ mod tests {
let hash = sha256::Hash::from_slice(&HASH_BYTES).expect("right number of bytes"); let hash = sha256::Hash::from_slice(&HASH_BYTES).expect("right number of bytes");
assert_tokens(&hash.compact(), &[Token::BorrowedBytes(&HASH_BYTES[..])]); assert_tokens(&hash.compact(), &[Token::BorrowedBytes(&HASH_BYTES[..])]);
assert_tokens(&hash.readable(), &[Token::Str("ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c")]); assert_tokens(
&hash.readable(),
&[Token::Str("ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c")],
);
} }
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
mod wasm_tests { mod wasm_tests {
extern crate wasm_bindgen_test; extern crate wasm_bindgen_test;
use super::*;
use self::wasm_bindgen_test::*; use self::wasm_bindgen_test::*;
use super::*;
#[wasm_bindgen_test] #[wasm_bindgen_test]
fn sha256_tests() { fn sha256_tests() {
test(); test();
@ -502,13 +495,13 @@ mod tests {
mod benches { mod benches {
use test::Bencher; use test::Bencher;
use crate::{Hash, HashEngine, sha256}; use crate::{sha256, Hash, HashEngine};
#[bench] #[bench]
pub fn sha256_10(bh: &mut Bencher) { pub fn sha256_10(bh: &mut Bencher) {
let mut engine = sha256::Hash::engine(); let mut engine = sha256::Hash::engine();
let bytes = [1u8; 10]; let bytes = [1u8; 10];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -518,7 +511,7 @@ mod benches {
pub fn sha256_1k(bh: &mut Bencher) { pub fn sha256_1k(bh: &mut Bencher) {
let mut engine = sha256::Hash::engine(); let mut engine = sha256::Hash::engine();
let bytes = [1u8; 1024]; let bytes = [1u8; 1024];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -528,10 +521,9 @@ mod benches {
pub fn sha256_64k(bh: &mut Bencher) { pub fn sha256_64k(bh: &mut Bencher) {
let mut engine = sha256::Hash::engine(); let mut engine = sha256::Hash::engine();
let bytes = [1u8; 65536]; let bytes = [1u8; 65536];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
} }
} }

View File

@ -15,11 +15,11 @@
//! SHA256d implementation (double SHA256). //! SHA256d implementation (double SHA256).
//! //!
use core::str;
use core::ops::Index; use core::ops::Index;
use core::slice::SliceIndex; use core::slice::SliceIndex;
use core::str;
use crate::{Error, sha256}; use crate::{sha256, Error};
crate::internal_macros::hash_type! { crate::internal_macros::hash_type! {
256, 256,
@ -97,7 +97,8 @@ mod tests {
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
#[test] #[test]
fn sha256_serde() { fn sha256_serde() {
use serde_test::{Configure, Token, assert_tokens}; use serde_test::{assert_tokens, Configure, Token};
use crate::{sha256d, Hash}; use crate::{sha256d, Hash};
#[rustfmt::skip] #[rustfmt::skip]
@ -110,7 +111,10 @@ mod tests {
let hash = sha256d::Hash::from_slice(&HASH_BYTES).expect("right number of bytes"); let hash = sha256d::Hash::from_slice(&HASH_BYTES).expect("right number of bytes");
assert_tokens(&hash.compact(), &[Token::BorrowedBytes(&HASH_BYTES[..])]); assert_tokens(&hash.compact(), &[Token::BorrowedBytes(&HASH_BYTES[..])]);
assert_tokens(&hash.readable(), &[Token::Str("6cfb35868c4465b7c289d7d5641563aa973db6a929655282a7bf95c8257f53ef")]); assert_tokens(
&hash.readable(),
&[Token::Str("6cfb35868c4465b7c289d7d5641563aa973db6a929655282a7bf95c8257f53ef")],
);
} }
} }
@ -118,13 +122,13 @@ mod tests {
mod benches { mod benches {
use test::Bencher; use test::Bencher;
use crate::{Hash, HashEngine, sha256d}; use crate::{sha256d, Hash, HashEngine};
#[bench] #[bench]
pub fn sha256d_10(bh: &mut Bencher) { pub fn sha256d_10(bh: &mut Bencher) {
let mut engine = sha256d::Hash::engine(); let mut engine = sha256d::Hash::engine();
let bytes = [1u8; 10]; let bytes = [1u8; 10];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -134,7 +138,7 @@ mod benches {
pub fn sha256d_1k(bh: &mut Bencher) { pub fn sha256d_1k(bh: &mut Bencher) {
let mut engine = sha256d::Hash::engine(); let mut engine = sha256d::Hash::engine();
let bytes = [1u8; 1024]; let bytes = [1u8; 1024];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -144,7 +148,7 @@ mod benches {
pub fn sha256d_64k(bh: &mut Bencher) { pub fn sha256d_64k(bh: &mut Bencher) {
let mut engine = sha256d::Hash::engine(); let mut engine = sha256d::Hash::engine();
let bytes = [1u8; 65536]; let bytes = [1u8; 65536];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;

View File

@ -15,12 +15,12 @@
//! SHA256t implementation (tagged SHA256). //! SHA256t implementation (tagged SHA256).
//! //!
use core::{cmp, str};
use core::marker::PhantomData; use core::marker::PhantomData;
use core::ops::Index; use core::ops::Index;
use core::slice::SliceIndex; use core::slice::SliceIndex;
use core::{cmp, str};
use crate::{Error, sha256}; use crate::{sha256, Error};
type HashEngine = sha256::HashEngine; type HashEngine = sha256::HashEngine;
@ -34,38 +34,30 @@ pub trait Tag {
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[repr(transparent)] #[repr(transparent)]
pub struct Hash<T: Tag>( pub struct Hash<T: Tag>(
#[cfg_attr(feature = "schemars", schemars(schema_with = "crate::util::json_hex_string::len_32"))] #[cfg_attr(
feature = "schemars",
schemars(schema_with = "crate::util::json_hex_string::len_32")
)]
[u8; 32], [u8; 32],
#[cfg_attr(feature = "schemars", schemars(skip))] #[cfg_attr(feature = "schemars", schemars(skip))] PhantomData<T>,
PhantomData<T>
); );
impl<T: Tag> Hash<T> { impl<T: Tag> Hash<T> {
fn internal_new(arr: [u8; 32]) -> Self { fn internal_new(arr: [u8; 32]) -> Self { Hash(arr, Default::default()) }
Hash(arr, Default::default())
}
fn internal_engine() -> HashEngine { fn internal_engine() -> HashEngine { T::engine() }
T::engine()
}
} }
impl<T: Tag> Copy for Hash<T> {} impl<T: Tag> Copy for Hash<T> {}
impl<T: Tag> Clone for Hash<T> { impl<T: Tag> Clone for Hash<T> {
fn clone(&self) -> Self { fn clone(&self) -> Self { Hash(self.0, self.1) }
Hash(self.0, self.1)
}
} }
impl<T: Tag> PartialEq for Hash<T> { impl<T: Tag> PartialEq for Hash<T> {
fn eq(&self, other: &Hash<T>) -> bool { fn eq(&self, other: &Hash<T>) -> bool { self.0 == other.0 }
self.0 == other.0
}
} }
impl<T: Tag> Eq for Hash<T> {} impl<T: Tag> Eq for Hash<T> {}
impl<T: Tag> Default for Hash<T> { impl<T: Tag> Default for Hash<T> {
fn default() -> Self { fn default() -> Self { Hash([0; 32], PhantomData) }
Hash([0; 32], PhantomData)
}
} }
impl<T: Tag> PartialOrd for Hash<T> { impl<T: Tag> PartialOrd for Hash<T> {
fn partial_cmp(&self, other: &Hash<T>) -> Option<cmp::Ordering> { fn partial_cmp(&self, other: &Hash<T>) -> Option<cmp::Ordering> {
@ -73,14 +65,10 @@ impl<T: Tag> PartialOrd for Hash<T> {
} }
} }
impl<T: Tag> Ord for Hash<T> { impl<T: Tag> Ord for Hash<T> {
fn cmp(&self, other: &Hash<T>) -> cmp::Ordering { fn cmp(&self, other: &Hash<T>) -> cmp::Ordering { cmp::Ord::cmp(&self.0, &other.0) }
cmp::Ord::cmp(&self.0, &other.0)
}
} }
impl<T: Tag> core::hash::Hash for Hash<T> { impl<T: Tag> core::hash::Hash for Hash<T> {
fn hash<H: core::hash::Hasher>(&self, h: &mut H) { fn hash<H: core::hash::Hasher>(&self, h: &mut H) { self.0.hash(h) }
self.0.hash(h)
}
} }
crate::internal_macros::hash_trait_impls!(256, true, T: Tag); crate::internal_macros::hash_trait_impls!(256, true, T: Tag);
@ -98,7 +86,15 @@ fn from_engine<T: Tag>(e: sha256::HashEngine) -> Hash<T> {
#[macro_export] #[macro_export]
macro_rules! sha256t_hash_newtype { macro_rules! sha256t_hash_newtype {
($newtype:ident, $tag:ident, $midstate:ident, $midstate_len:expr, $docs:meta, $direction:tt) => { ($newtype:ident, $tag:ident, $midstate:ident, $midstate_len:expr, $docs:meta, $direction:tt) => {
sha256t_hash_newtype!($newtype, $tag, $midstate, $midstate_len, $docs, $direction, stringify!($newtype)); sha256t_hash_newtype!(
$newtype,
$tag,
$midstate,
$midstate_len,
$docs,
$direction,
stringify!($newtype)
);
}; };
($newtype:ident, $tag:ident, $midstate:ident, $midstate_len:expr, $docs:meta, $direction:tt, $sname:expr) => { ($newtype:ident, $tag:ident, $midstate:ident, $midstate_len:expr, $docs:meta, $direction:tt, $sname:expr) => {
@ -125,13 +121,13 @@ macro_rules! sha256t_hash_newtype {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::{sha256, sha256t};
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
use crate::Hash; use crate::Hash;
use crate::{sha256, sha256t};
const TEST_MIDSTATE: [u8; 32] = [ const TEST_MIDSTATE: [u8; 32] = [
156, 224, 228, 230, 124, 17, 108, 57, 56, 179, 202, 242, 195, 15, 80, 137, 211, 243, 156, 224, 228, 230, 124, 17, 108, 57, 56, 179, 202, 242, 195, 15, 80, 137, 211, 243, 147,
147, 108, 71, 99, 110, 96, 125, 179, 62, 234, 221, 198, 240, 201, 108, 71, 99, 110, 96, 125, 179, 62, 234, 221, 198, 240, 201,
]; ];
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Hash)] #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
@ -150,7 +146,7 @@ mod tests {
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
pub type TestHash = sha256t::Hash<TestHashTag>; pub type TestHash = sha256t::Hash<TestHashTag>;
sha256t_hash_newtype!(NewTypeHash, NewTypeTag, TEST_MIDSTATE, 64, doc="test hash", backward); sha256t_hash_newtype!(NewTypeHash, NewTypeTag, TEST_MIDSTATE, 64, doc = "test hash", backward);
#[test] #[test]
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]

View File

@ -20,10 +20,10 @@
//! SHA512 implementation. //! SHA512 implementation.
//! //!
use core::{cmp, hash, str};
use core::convert::TryInto; use core::convert::TryInto;
use core::ops::Index; use core::ops::Index;
use core::slice::SliceIndex; use core::slice::SliceIndex;
use core::{cmp, hash, str};
use crate::{Error, HashEngine as _}; use crate::{Error, HashEngine as _};
@ -74,9 +74,7 @@ impl crate::HashEngine for HashEngine {
const BLOCK_SIZE: usize = 128; const BLOCK_SIZE: usize = 128;
fn n_bytes_hashed(&self) -> usize { fn n_bytes_hashed(&self) -> usize { self.length }
self.length
}
engine_input_impl!(); engine_input_impl!();
} }
@ -85,18 +83,17 @@ impl crate::HashEngine for HashEngine {
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[repr(transparent)] #[repr(transparent)]
pub struct Hash( pub struct Hash(
#[cfg_attr(feature = "schemars", schemars(schema_with = "crate::util::json_hex_string::len_64"))] #[cfg_attr(
[u8; 64] feature = "schemars",
schemars(schema_with = "crate::util::json_hex_string::len_64")
)]
[u8; 64],
); );
impl Hash { impl Hash {
fn internal_new(arr: [u8; 64]) -> Self { fn internal_new(arr: [u8; 64]) -> Self { Hash(arr) }
Hash(arr)
}
fn internal_engine() -> HashEngine { fn internal_engine() -> HashEngine { Default::default() }
Default::default()
}
} }
impl Copy for Hash {} impl Copy for Hash {}
@ -110,35 +107,25 @@ impl Clone for Hash {
} }
impl PartialEq for Hash { impl PartialEq for Hash {
fn eq(&self, other: &Hash) -> bool { fn eq(&self, other: &Hash) -> bool { self.0[..] == other.0[..] }
self.0[..] == other.0[..]
}
} }
impl Eq for Hash {} impl Eq for Hash {}
impl Default for Hash { impl Default for Hash {
fn default() -> Hash { fn default() -> Hash { Hash([0; 64]) }
Hash([0; 64])
}
} }
impl PartialOrd for Hash { impl PartialOrd for Hash {
fn partial_cmp(&self, other: &Hash) -> Option<cmp::Ordering> { fn partial_cmp(&self, other: &Hash) -> Option<cmp::Ordering> { self.0.partial_cmp(&other.0) }
self.0.partial_cmp(&other.0)
}
} }
impl Ord for Hash { impl Ord for Hash {
fn cmp(&self, other: &Hash) -> cmp::Ordering { fn cmp(&self, other: &Hash) -> cmp::Ordering { self.0.cmp(&other.0) }
self.0.cmp(&other.0)
}
} }
impl hash::Hash for Hash { impl hash::Hash for Hash {
fn hash<H: hash::Hasher>(&self, state: &mut H) { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.0.hash(state) }
self.0.hash(state)
}
} }
#[cfg(not(fuzzing))] #[cfg(not(fuzzing))]
@ -388,7 +375,8 @@ mod tests {
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
#[test] #[test]
fn sha512_serde() { fn sha512_serde() {
use serde_test::{Configure, Token, assert_tokens}; use serde_test::{assert_tokens, Configure, Token};
use crate::{sha512, Hash}; use crate::{sha512, Hash};
#[rustfmt::skip] #[rustfmt::skip]
@ -409,7 +397,7 @@ mod tests {
&hash.readable(), &hash.readable(),
&[Token::Str( &[Token::Str(
"8b41e1b78ad11521113c52ff182a1b8e0a195754aa527fcd00a411620b46f20f\ "8b41e1b78ad11521113c52ff182a1b8e0a195754aa527fcd00a411620b46f20f\
fffb8088ccf85497121ad4499e0845b876f6dd6640088a2f0b2d8a600bdf4c0c" fffb8088ccf85497121ad4499e0845b876f6dd6640088a2f0b2d8a600bdf4c0c",
)], )],
); );
} }
@ -419,13 +407,13 @@ mod tests {
mod benches { mod benches {
use test::Bencher; use test::Bencher;
use crate::{Hash, HashEngine, sha512}; use crate::{sha512, Hash, HashEngine};
#[bench] #[bench]
pub fn sha512_10(bh: &mut Bencher) { pub fn sha512_10(bh: &mut Bencher) {
let mut engine = sha512::Hash::engine(); let mut engine = sha512::Hash::engine();
let bytes = [1u8; 10]; let bytes = [1u8; 10];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -435,7 +423,7 @@ mod benches {
pub fn sha512_1k(bh: &mut Bencher) { pub fn sha512_1k(bh: &mut Bencher) {
let mut engine = sha512::Hash::engine(); let mut engine = sha512::Hash::engine();
let bytes = [1u8; 1024]; let bytes = [1u8; 1024];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -445,10 +433,9 @@ mod benches {
pub fn sha512_64k(bh: &mut Bencher) { pub fn sha512_64k(bh: &mut Bencher) {
let mut engine = sha512::Hash::engine(); let mut engine = sha512::Hash::engine();
let bytes = [1u8; 65536]; let bytes = [1u8; 65536];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
} }
} }

View File

@ -24,11 +24,12 @@
//! produces an entirely different hash compared to sha512. More information at //! produces an entirely different hash compared to sha512. More information at
//! <https://eprint.iacr.org/2010/548.pdf>. //! <https://eprint.iacr.org/2010/548.pdf>.
use core::str;
use core::ops::Index; use core::ops::Index;
use core::slice::SliceIndex; use core::slice::SliceIndex;
use core::str;
use crate::{sha512, sha512::BLOCK_SIZE, Error}; use crate::sha512::BLOCK_SIZE;
use crate::{sha512, Error};
/// Engine to compute SHA512/256 hash function. /// Engine to compute SHA512/256 hash function.
/// ///
@ -56,19 +57,13 @@ impl Default for HashEngine {
impl crate::HashEngine for HashEngine { impl crate::HashEngine for HashEngine {
type MidState = [u8; 64]; type MidState = [u8; 64];
fn midstate(&self) -> [u8; 64] { fn midstate(&self) -> [u8; 64] { self.0.midstate() }
self.0.midstate()
}
const BLOCK_SIZE: usize = sha512::BLOCK_SIZE; const BLOCK_SIZE: usize = sha512::BLOCK_SIZE;
fn n_bytes_hashed(&self) -> usize { fn n_bytes_hashed(&self) -> usize { self.0.length }
self.0.length
}
fn input(&mut self, inp: &[u8]) { fn input(&mut self, inp: &[u8]) { self.0.input(inp); }
self.0.input(inp);
}
} }
crate::internal_macros::hash_type! { crate::internal_macros::hash_type! {
@ -176,13 +171,13 @@ mod tests {
mod benches { mod benches {
use test::Bencher; use test::Bencher;
use crate::{Hash, HashEngine, sha512_256}; use crate::{sha512_256, Hash, HashEngine};
#[bench] #[bench]
pub fn sha512_256_10(bh: &mut Bencher) { pub fn sha512_256_10(bh: &mut Bencher) {
let mut engine = sha512_256::Hash::engine(); let mut engine = sha512_256::Hash::engine();
let bytes = [1u8; 10]; let bytes = [1u8; 10];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -192,7 +187,7 @@ mod benches {
pub fn sha512_256_1k(bh: &mut Bencher) { pub fn sha512_256_1k(bh: &mut Bencher) {
let mut engine = sha512_256::Hash::engine(); let mut engine = sha512_256::Hash::engine();
let bytes = [1u8; 1024]; let bytes = [1u8; 1024];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
@ -202,10 +197,9 @@ mod benches {
pub fn sha512_256_64k(bh: &mut Bencher) { pub fn sha512_256_64k(bh: &mut Bencher) {
let mut engine = sha512_256::Hash::engine(); let mut engine = sha512_256::Hash::engine();
let bytes = [1u8; 65536]; let bytes = [1u8; 65536];
bh.iter( || { bh.iter(|| {
engine.input(&bytes); engine.input(&bytes);
}); });
bh.bytes = bytes.len() as u64; bh.bytes = bytes.len() as u64;
} }
} }

View File

@ -20,9 +20,9 @@
//! SipHash 2-4 implementation. //! SipHash 2-4 implementation.
//! //!
use core::{cmp, mem, ptr, str};
use core::ops::Index; use core::ops::Index;
use core::slice::SliceIndex; use core::slice::SliceIndex;
use core::{cmp, mem, ptr, str};
use crate::{Error, Hash as _, HashEngine as _}; use crate::{Error, Hash as _, HashEngine as _};
@ -34,9 +34,7 @@ crate::internal_macros::hash_type! {
} }
#[cfg(not(fuzzing))] #[cfg(not(fuzzing))]
fn from_engine(e: HashEngine) -> Hash { fn from_engine(e: HashEngine) -> Hash { Hash::from_u64(Hash::from_engine_to_u64(e)) }
Hash::from_u64(Hash::from_engine_to_u64(e))
}
#[cfg(fuzzing)] #[cfg(fuzzing)]
fn from_engine(e: HashEngine) -> Hash { fn from_engine(e: HashEngine) -> Hash {
@ -44,7 +42,6 @@ fn from_engine(e: HashEngine) -> Hash {
Hash::from_u64(state.v0 ^ state.v1 ^ state.v2 ^ state.v3) Hash::from_u64(state.v0 ^ state.v1 ^ state.v2 ^ state.v3)
} }
macro_rules! compress { macro_rules! compress {
($state:expr) => {{ ($state:expr) => {{
compress!($state.v0, $state.v1, $state.v2, $state.v3) compress!($state.v0, $state.v1, $state.v2, $state.v3)
@ -128,14 +125,10 @@ impl HashEngine {
} }
/// Creates a new SipHash24 engine. /// Creates a new SipHash24 engine.
pub fn new() -> HashEngine { pub fn new() -> HashEngine { HashEngine::with_keys(0, 0) }
HashEngine::with_keys(0, 0)
}
/// Retrieves the keys of this engine. /// Retrieves the keys of this engine.
pub fn keys(&self) -> (u64, u64) { pub fn keys(&self) -> (u64, u64) { (self.k0, self.k1) }
(self.k0, self.k1)
}
#[inline] #[inline]
fn c_rounds(state: &mut State) { fn c_rounds(state: &mut State) {
@ -153,17 +146,13 @@ impl HashEngine {
} }
impl Default for HashEngine { impl Default for HashEngine {
fn default() -> Self { fn default() -> Self { HashEngine::new() }
HashEngine::new()
}
} }
impl crate::HashEngine for HashEngine { impl crate::HashEngine for HashEngine {
type MidState = State; type MidState = State;
fn midstate(&self) -> State { fn midstate(&self) -> State { self.state.clone() }
self.state.clone()
}
const BLOCK_SIZE: usize = 8; const BLOCK_SIZE: usize = 8;
@ -207,10 +196,7 @@ impl crate::HashEngine for HashEngine {
self.ntail = left; self.ntail = left;
} }
fn n_bytes_hashed(&self) -> usize { fn n_bytes_hashed(&self) -> usize { self.length }
self.length
}
} }
impl Hash { impl Hash {
@ -246,14 +232,10 @@ impl Hash {
} }
/// Returns the (little endian) 64-bit integer representation of the hash value. /// Returns the (little endian) 64-bit integer representation of the hash value.
pub fn as_u64(&self) -> u64 { pub fn as_u64(&self) -> u64 { u64::from_le_bytes(self.0) }
u64::from_le_bytes(self.0)
}
/// Creates a hash from its (little endian) 64-bit integer representation. /// Creates a hash from its (little endian) 64-bit integer representation.
pub fn from_u64(hash: u64) -> Hash { pub fn from_u64(hash: u64) -> Hash { Hash(hash.to_le_bytes()) }
Hash(hash.to_le_bytes())
}
} }
/// Load an u64 using up to 7 bytes of a byte slice. /// Load an u64 using up to 7 bytes of a byte slice.
@ -376,7 +358,7 @@ mod tests {
mod benches { mod benches {
use test::Bencher; use test::Bencher;
use crate::{Hash, HashEngine, siphash24}; use crate::{siphash24, Hash, HashEngine};
#[bench] #[bench]
pub fn siphash24_1ki(bh: &mut Bencher) { pub fn siphash24_1ki(bh: &mut Bencher) {

View File

@ -107,8 +107,6 @@ macro_rules! engine_input_impl(
) )
); );
/// Creates a new newtype around a [`Hash`] type. /// Creates a new newtype around a [`Hash`] type.
/// ///
/// The syntax is similar to the usual tuple struct syntax: /// The syntax is similar to the usual tuple struct syntax:
@ -403,8 +401,9 @@ macro_rules! hash_newtype_known_attrs {
#[cfg(feature = "schemars")] #[cfg(feature = "schemars")]
#[cfg_attr(docsrs, doc(cfg(feature = "schemars")))] #[cfg_attr(docsrs, doc(cfg(feature = "schemars")))]
pub mod json_hex_string { pub mod json_hex_string {
use schemars::gen::SchemaGenerator;
use schemars::schema::{Schema, SchemaObject}; use schemars::schema::{Schema, SchemaObject};
use schemars::{gen::SchemaGenerator, JsonSchema}; use schemars::JsonSchema;
macro_rules! define_custom_hex { macro_rules! define_custom_hex {
($name:ident, $len:expr) => { ($name:ident, $len:expr) => {
pub fn $name(gen: &mut SchemaGenerator) -> Schema { pub fn $name(gen: &mut SchemaGenerator) -> Schema {
@ -426,7 +425,7 @@ pub mod json_hex_string {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use crate::{Hash, sha256}; use crate::{sha256, Hash};
#[test] #[test]
fn hash_as_ref_array() { fn hash_as_ref_array() {