Skip to main content

md5_simd/
md5.rs

1//! Streaming MD5 hasher (`Clone` + optional `io::Write`).
2
3use crate::backend;
4use crate::core::Raw;
5use alloc::string::String;
6
7/// Streaming MD5 hasher.
8///
9/// `Clone` supports independent snapshots (`clone().finalize()`); prefer
10/// [`Self::finalize_snapshot`] or [`Self::digest_so_far`] when the hasher
11/// must continue absorbing data.
12#[derive(Clone, Debug)]
13pub struct Md5 {
14    raw: Raw,
15}
16
17impl Default for Md5 {
18    #[inline]
19    fn default() -> Self {
20        Self::new()
21    }
22}
23
24impl Md5 {
25    /// New hasher with the RFC 1321 IV.
26    #[inline]
27    pub const fn new() -> Self {
28        Self { raw: Raw::new() }
29    }
30
31    /// Resume from a block-aligned state that already absorbed `count_bytes`.
32    ///
33    /// The caller must supply the chaining state after exactly that many bytes,
34    /// with `count_bytes` a multiple of 64. No partial block is restored.
35    #[inline]
36    pub const fn from_parts(state: [u32; 4], count_bytes: u64) -> Self {
37        Self {
38            raw: Raw::from_parts(state, count_bytes),
39        }
40    }
41
42    /// Absorb additional bytes.
43    #[inline(always)]
44    pub fn update(&mut self, data: &[u8]) {
45        self.raw.update_opt(data);
46    }
47
48    /// Builder-style update.
49    #[inline]
50    #[must_use]
51    pub fn chain_update(mut self, data: &[u8]) -> Self {
52        self.update(data);
53        self
54    }
55
56    /// Consume and return the 16-byte digest.
57    #[inline]
58    pub fn finalize(self) -> [u8; 16] {
59        self.raw.digest_snapshot(backend::compress_block)
60    }
61
62    /// Non-consuming digest (same as `self.clone().finalize()` without clone).
63    #[inline]
64    pub fn finalize_snapshot(&self) -> [u8; 16] {
65        self.raw.digest_snapshot(backend::compress_block)
66    }
67
68    /// Finalize then reset in place (no full hasher clone).
69    #[inline]
70    pub fn finalize_reset(&mut self) -> [u8; 16] {
71        let d = self.raw.digest_snapshot(backend::compress_block);
72        self.raw.reset();
73        d
74    }
75
76    /// Reset to IV / empty buffer.
77    #[inline]
78    pub fn reset(&mut self) {
79        self.raw.reset();
80    }
81
82    /// Bytes absorbed so far (mod 2^64).
83    #[inline]
84    pub const fn bytes_hashed(&self) -> u64 {
85        self.raw.count
86    }
87
88    /// Clear the native state on a best-effort basis.
89    ///
90    /// Call [`Self::reset`] before hashing another message. This does not erase
91    /// previously made copies or guarantee removal of compiler-generated copies.
92    #[inline]
93    pub fn zeroize(&mut self) {
94        self.raw.zeroize();
95    }
96
97    /// Non-consuming lowercase hex of the current digest (`std`).
98    ///
99    /// Prefer this over `clone().finalize()` when only the snapshot digest is needed.
100    #[cfg(feature = "std")]
101    #[inline]
102    pub fn finalize_hex(&self) -> String {
103        hex_encode(&self.raw.digest_snapshot(backend::compress_block))
104    }
105
106    /// Non-consuming digest bytes (same as [`Self::finalize_snapshot`]).
107    #[inline]
108    pub fn digest_so_far(&self) -> [u8; 16] {
109        self.finalize_snapshot()
110    }
111}
112
113#[cfg(feature = "zeroize")]
114impl Drop for Md5 {
115    #[inline]
116    fn drop(&mut self) {
117        self.raw.zeroize();
118    }
119}
120
121/// One-shot hashing (active backend).
122#[inline(always)]
123pub fn digest(data: &[u8]) -> [u8; 16] {
124    backend::hash(data)
125}
126
127/// Hash a message and return its 32-character lowercase hexadecimal digest.
128pub fn digest_hex(data: &[u8]) -> String {
129    hex_encode(&digest(data))
130}
131
132/// Encode every input byte as two lowercase hexadecimal characters.
133pub fn hex_encode(bytes: &[u8]) -> String {
134    let len = bytes.len().checked_mul(2).expect("hex length overflow");
135    let mut buf = alloc::vec![0u8; len];
136    hex_encode_into(bytes, &mut buf);
137    // SAFETY: hex alphabet is valid ASCII.
138    unsafe { String::from_utf8_unchecked(buf) }
139}
140
141/// Alias for [`digest_hex`] for applications using MD5-shaped ETags.
142///
143/// This does not add HTTP quoting or implement multipart ETag composition.
144#[inline]
145pub fn etag_hex(data: &[u8]) -> String {
146    digest_hex(data)
147}
148
149/// Lowercase hex of a 16-byte digest into a fixed 32-byte array (no alloc).
150#[inline]
151pub fn hex_encode_digest(digest: &[u8; 16]) -> [u8; 32] {
152    let mut out = [0u8; 32];
153    hex_encode_into(digest, &mut out);
154    out
155}
156
157/// Two-byte lowercase hex lookup for every input byte.
158const HEX_PAIRS: [[u8; 2]; 256] = {
159    const HEX: &[u8; 16] = b"0123456789abcdef";
160    let mut table = [[0u8; 2]; 256];
161    let mut i = 0;
162    while i < 256 {
163        table[i] = [HEX[i >> 4], HEX[i & 0x0f]];
164        i += 1;
165    }
166    table
167};
168
169/// Write lowercase hex into `out`; returns bytes written (`2 * bytes.len()`).
170///
171/// `out.len()` must be at least `2 * bytes.len()`.
172///
173/// # Panics
174/// Panics before writing if the output is too short.
175#[inline(always)]
176pub fn hex_encode_into(bytes: &[u8], out: &mut [u8]) -> usize {
177    assert!(bytes.len() <= out.len() / 2, "hex output is too short");
178    for (i, b) in bytes.iter().enumerate() {
179        let pair = HEX_PAIRS[*b as usize];
180        out[i * 2] = pair[0];
181        out[i * 2 + 1] = pair[1];
182    }
183    bytes.len() * 2
184}
185
186/// Hash a reader to lowercase hexadecimal until EOF.
187///
188/// `chunk` is clamped to 4 KiB–1 MiB for the allocated read buffer.
189///
190/// # Errors
191/// Returns reader errors other than [`std::io::ErrorKind::Interrupted`], which
192/// is retried. On error, no partial digest is returned.
193#[cfg(feature = "std")]
194pub fn etag_hex_streaming<R: std::io::Read>(reader: R, chunk: usize) -> std::io::Result<String> {
195    let chunk = chunk.clamp(4096, 1024 * 1024);
196    let mut buf = vec![0u8; chunk];
197    digest_reader_with_buffer(reader, &mut buf).map(|digest| hex_encode(&digest))
198}
199
200/// Hash a reader until EOF using a 64 KiB stack buffer.
201///
202/// # Errors
203/// Returns reader errors other than [`std::io::ErrorKind::Interrupted`], which
204/// is retried. On error, no partial digest is returned.
205#[cfg(feature = "std")]
206pub fn digest_reader<R: std::io::Read>(reader: R) -> std::io::Result<[u8; 16]> {
207    let mut buf = [0u8; 65536];
208    digest_reader_with_buffer(reader, &mut buf)
209}
210
211#[cfg(feature = "std")]
212fn digest_reader_with_buffer<R: std::io::Read>(
213    mut reader: R,
214    buf: &mut [u8],
215) -> std::io::Result<[u8; 16]> {
216    let mut h = Md5::new();
217    loop {
218        match reader.read(buf) {
219            Ok(0) => return Ok(h.finalize()),
220            Ok(n) => h.update(&buf[..n]),
221            Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
222            Err(err) => return Err(err),
223        }
224    }
225}
226
227#[cfg(feature = "std")]
228impl std::io::Write for Md5 {
229    #[inline]
230    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
231        self.update(buf);
232        Ok(buf.len())
233    }
234
235    #[inline]
236    fn flush(&mut self) -> std::io::Result<()> {
237        Ok(())
238    }
239}