rs_sha384/sha384hasher.rs
1use crate::{Sha384State, BYTES_LEN};
2use core::hash::Hasher;
3use rs_hasher_ctx::{ByteArrayWrapper, GenericHasher, HasherContext};
4use rs_internal_hasher::HashAlgorithm;
5
6/// `Sha384Hasher` is a type that provides the SHA-384 hashing algorithm in RustyShield.
7///
8/// A "Hasher" in the context of cryptographic hashing refers to the object that manages the process of converting input
9/// data into a fixed-size sequence of bytes. The Hasher is responsible for maintaining the internal state of the
10/// hashing process and providing methods to add more data and retrieve the resulting hash.
11///
12/// The `Sha384Hasher` struct adheres to Rust's `Hasher` trait, enabling you to use it interchangeably with other hashers
13/// in Rust. It can be used anywhere a type implementing `Hasher` is required.
14///
15/// ## Examples
16///
17/// The following examples demonstrate using `Sha384Hasher` with both `Hash` and `Hasher`, and explain where the difference
18/// comes from:
19///
20///```rust
21/// # use std::hash::{BuildHasher, Hash, Hasher};
22/// # use rs_sha384::Sha384Hasher;
23/// let data = b"hello";
24///
25/// // Using Hash
26/// let mut sha384hasher = Sha384Hasher::default();
27/// data.hash(&mut sha384hasher);
28/// let result_via_hash = sha384hasher.finish();
29///
30/// // Using Hasher
31/// let mut sha384hasher = Sha384Hasher::default();
32/// sha384hasher.write(data);
33/// let result_via_hasher = sha384hasher.finish();
34///
35/// // Simulating the Hash inners
36/// let mut sha384hasher = Sha384Hasher::default();
37/// sha384hasher.write_usize(data.len());
38/// sha384hasher.write(data);
39/// let simulated_hash_result = sha384hasher.finish();
40///
41/// assert_ne!(result_via_hash, result_via_hasher);
42/// assert_eq!(result_via_hash, simulated_hash_result);
43///```
44#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
45pub struct Sha384Hasher(GenericHasher<Sha384State, BYTES_LEN>);
46
47impl From<Sha384Hasher> for Sha384State {
48 fn from(value: Sha384Hasher) -> Self {
49 value.0.state
50 }
51}
52
53impl From<Sha384State> for Sha384Hasher {
54 fn from(value: Sha384State) -> Self {
55 Self(GenericHasher {
56 padding: <Sha384State as HashAlgorithm>::Padding::default(),
57 state: value,
58 })
59 }
60}
61
62impl Hasher for Sha384Hasher {
63 fn finish(&self) -> u64 {
64 self.0.finish()
65 }
66
67 fn write(&mut self, bytes: &[u8]) {
68 self.0.write(bytes)
69 }
70}
71
72impl HasherContext<BYTES_LEN> for Sha384Hasher {
73 type Output = ByteArrayWrapper<BYTES_LEN>;
74
75 fn finish(&mut self) -> Self::Output {
76 ByteArrayWrapper::from(HasherContext::finish(&mut self.0))
77 }
78}