|
|
|
@ -1,22 +1,21 @@
|
|
|
|
|
use serde::bytes::ByteBuf; |
|
|
|
|
use crypto::sha3; |
|
|
|
|
use crypto::digest::Digest; |
|
|
|
|
|
|
|
|
|
use blake2::blake2b::Blake2b; |
|
|
|
|
|
|
|
|
|
#[derive(Clone, Debug, Copy)] |
|
|
|
|
#[allow(non_camel_case_types)] |
|
|
|
|
pub enum ChecksumType { |
|
|
|
|
Sha3_256 |
|
|
|
|
Blake2_256 |
|
|
|
|
} |
|
|
|
|
serde_impl!(ChecksumType(u64) { |
|
|
|
|
Sha3_256 => 1 |
|
|
|
|
Blake2_256 => 1 |
|
|
|
|
}); |
|
|
|
|
|
|
|
|
|
impl ChecksumType { |
|
|
|
|
#[inline] |
|
|
|
|
pub fn from(name: &str) -> Result<Self, &'static str> { |
|
|
|
|
match name { |
|
|
|
|
"sha3-256" => Ok(ChecksumType::Sha3_256), |
|
|
|
|
"blake2_256" => Ok(ChecksumType::Blake2_256), |
|
|
|
|
_ => Err("Unsupported checksum type") |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
@ -24,7 +23,7 @@ impl ChecksumType {
|
|
|
|
|
#[inline] |
|
|
|
|
pub fn name(&self) -> &'static str { |
|
|
|
|
match *self { |
|
|
|
|
ChecksumType::Sha3_256 => "sha3-256", |
|
|
|
|
ChecksumType::Blake2_256 => "blake2_256", |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
@ -34,32 +33,31 @@ pub type Checksum = (ChecksumType, ByteBuf);
|
|
|
|
|
|
|
|
|
|
#[allow(non_camel_case_types, unknown_lints, large_enum_variant)] |
|
|
|
|
pub enum ChecksumCreator { |
|
|
|
|
Sha3_256(sha3::Sha3) |
|
|
|
|
Blake2_256(Blake2b) |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
impl ChecksumCreator { |
|
|
|
|
#[inline] |
|
|
|
|
pub fn new(type_: ChecksumType) -> Self { |
|
|
|
|
match type_ { |
|
|
|
|
ChecksumType::Sha3_256 => ChecksumCreator::Sha3_256(sha3::Sha3::sha3_256()) |
|
|
|
|
ChecksumType::Blake2_256 => ChecksumCreator::Blake2_256(Blake2b::new(32)) |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
#[inline] |
|
|
|
|
pub fn update(&mut self, data: &[u8]) { |
|
|
|
|
match *self { |
|
|
|
|
ChecksumCreator::Sha3_256(ref mut state) => state.input(data) |
|
|
|
|
ChecksumCreator::Blake2_256(ref mut state) => state.update(data) |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
#[inline] |
|
|
|
|
pub fn finish(self) -> Checksum { |
|
|
|
|
match self { |
|
|
|
|
ChecksumCreator::Sha3_256(mut state) => { |
|
|
|
|
let mut buf = Vec::with_capacity(state.output_bytes()); |
|
|
|
|
buf.resize(state.output_bytes(), 0); |
|
|
|
|
state.result(&mut buf); |
|
|
|
|
(ChecksumType::Sha3_256, buf.into()) |
|
|
|
|
ChecksumCreator::Blake2_256(state) => { |
|
|
|
|
let mut buf = Vec::with_capacity(32); |
|
|
|
|
buf.extend_from_slice(state.finalize().as_bytes()); |
|
|
|
|
(ChecksumType::Blake2_256, buf.into()) |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|