diem_crypto/
compat.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4// Copyright 2021 Conflux Foundation. All rights reserved.
5// Conflux is free software and distributed under GNU General Public License.
6// See http://www.gnu.org/licenses/
7
8//! Wrapper structs for types that need [RustCrypto](https://github.com/RustCrypto)
9//! traits implemented.
10
11use digest::{
12    consts::{U136, U32},
13    generic_array::GenericArray,
14    BlockInput, Digest, FixedOutput, Reset, Update,
15};
16use tiny_keccak::{Hasher, Sha3};
17
18/// A wrapper for [`tiny_keccak::Sha3::v256`] that
19/// implements RustCrypto [`digest`] traits [`BlockInput`], [`Update`],
20/// [`Reset`], and [`FixedOutput`]. Consequently, this wrapper can be used in
21/// RustCrypto APIs that require a hash function (usually something that impls
22/// [`Digest`]).
23#[derive(Clone)]
24pub struct Sha3_256(Sha3);
25
26// ensure that we impl all of the sub-traits required for the Digest trait alias
27static_assertions::assert_impl_all!(Sha3_256: Digest);
28
29impl Default for Sha3_256 {
30    #[inline]
31    fn default() -> Self { Self(Sha3::v256()) }
32}
33
34impl BlockInput for Sha3_256 {
35    type BlockSize = U136;
36}
37
38impl Update for Sha3_256 {
39    #[inline]
40    fn update(&mut self, data: impl AsRef<[u8]>) {
41        self.0.update(data.as_ref());
42    }
43}
44
45impl Reset for Sha3_256 {
46    #[inline]
47    fn reset(&mut self) { *self = Self::default(); }
48}
49
50impl FixedOutput for Sha3_256 {
51    type OutputSize = U32;
52
53    #[inline]
54    fn finalize_into(self, out: &mut GenericArray<u8, Self::OutputSize>) {
55        self.0.finalize(out.as_mut());
56    }
57
58    #[inline]
59    fn finalize_into_reset(
60        &mut self, out: &mut GenericArray<u8, Self::OutputSize>,
61    ) {
62        self.clone().finalize_into(out);
63        Reset::reset(self)
64    }
65}