rs_sha3_512/
sha3_512hasher.rs

1use crate::{Sha3_512State, OUTPUT_SIZE};
2use core::hash::Hasher;
3use rs_hasher_ctx::{ByteArrayWrapper, GenericHasher, HasherContext};
4use rs_internal_hasher::HashAlgorithm;
5use rs_internal_state::ExtendedOutputFunction;
6
7/// `Sha3_512Hasher` is a type that provides the SHA3-512 hashing algorithm in Rust.
8///
9/// In the context of cryptographic hashing, a "Hasher" is the object that manages the process of transforming input
10/// data into a fixed-size sequence of bytes. The Hasher is in charge of maintaining the internal state of the
11/// hashing process and offering methods to append more data and obtain the resultant hash.
12///
13/// The `Sha3_512Hasher` struct conforms to Rust's `Hasher` trait, allowing you to use it interchangeably with other hashers
14/// in Rust. It can be utilized wherever a type implementing `Hasher` is needed.
15///
16/// ## Examples
17///
18/// The following examples illustrate using `Sha3_512Hasher` with both `Hash` and `Hasher`, and explain the differences
19/// between the two:
20///
21///```rust
22/// # use std::hash::{BuildHasher, Hash, Hasher};
23/// # use rs_sha3_512::Sha3_512State;
24/// let data = b"hello";
25///
26/// // Using Hash
27/// let mut sha3_512hasher = Sha3_512State::default().build_hasher();
28/// data.hash(&mut sha3_512hasher);
29/// let result_via_hash = sha3_512hasher.finish();
30///
31/// // Using Hasher
32/// let mut sha3_512hasher = Sha3_512State::default().build_hasher();
33/// sha3_512hasher.write(data);
34/// let result_via_hasher = sha3_512hasher.finish();
35///
36/// // Simulating the Hash inners
37/// let mut sha3_512hasher = Sha3_512State::default().build_hasher();
38/// sha3_512hasher.write_usize(data.len());
39/// sha3_512hasher.write(data);
40/// let simulated_hash_result = sha3_512hasher.finish();
41///
42/// assert_ne!(result_via_hash, result_via_hasher);
43/// assert_eq!(result_via_hash, simulated_hash_result);
44///```
45#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
46pub struct Sha3_512Hasher(GenericHasher<Sha3_512State, OUTPUT_SIZE>);
47
48impl From<Sha3_512Hasher> for Sha3_512State {
49    fn from(value: Sha3_512Hasher) -> Self {
50        value.0.state
51    }
52}
53
54impl From<Sha3_512State> for Sha3_512Hasher {
55    fn from(value: Sha3_512State) -> Self {
56        Self(GenericHasher {
57            padding: <Sha3_512State as HashAlgorithm>::Padding::default(),
58            state: value,
59        })
60    }
61}
62
63impl Hasher for Sha3_512Hasher {
64    fn finish(&self) -> u64 {
65        self.0.finish()
66    }
67
68    fn write(&mut self, bytes: &[u8]) {
69        self.0.write(bytes)
70    }
71}
72
73impl HasherContext<OUTPUT_SIZE> for Sha3_512Hasher {
74    type Output = ByteArrayWrapper<OUTPUT_SIZE>;
75
76    fn finish(&mut self) -> Self::Output {
77        HasherContext::finish(&mut self.0).squeeze().into()
78    }
79}