Skip to main content

md5_simd/
engine.rs

1//! Batch hashing and scalar incremental multi-stream operations.
2//!
3//! MD5 is for legacy interoperability and non-adversarial checksums only.
4
5use crate::backend;
6use crate::md5::Md5;
7use crate::multibuf;
8use crate::simd;
9use crate::state::Md5State;
10#[cfg(feature = "std")]
11use alloc::string::String;
12#[cfg(feature = "std")]
13use alloc::vec::Vec;
14
15/// Batch MD5 engine. Construct once and reuse.
16#[derive(Clone, Copy, Debug, Default)]
17pub struct Md5Engine;
18
19impl Md5Engine {
20    /// Create an engine using the process-default backend.
21    #[inline]
22    pub const fn new() -> Self {
23        Self
24    }
25
26    /// Active single-stream backend name.
27    #[inline]
28    pub fn backend_name(self) -> &'static str {
29        backend::backend_name()
30    }
31
32    /// Multi-buffer kernel label (`none` unless feature `simd` is on and active).
33    #[inline]
34    pub fn simd_name(self) -> &'static str {
35        simd::simd_name()
36    }
37
38    /// Effective batch width for `hash_many`.
39    ///
40    /// Maximum usable SIMD width, or 2 for the experimental scalar pair
41    /// path, or 1 for sequential hashing. Individual calls may use fewer lanes.
42    #[inline]
43    pub fn lanes(self) -> usize {
44        let s = simd::runtime_lanes();
45        if s > 1 {
46            s
47        } else if multibuf::pair_path_active() {
48            2
49        } else {
50            1
51        }
52    }
53
54    /// Hash independent messages into `outputs`.
55    ///
56    /// Contiguous equal-length runs may use SIMD when enabled and available.
57    /// Other inputs use the active single-stream backend. Order is preserved;
58    /// extra output slots are left unchanged. No allocation or thread spawning.
59    ///
60    /// # Panics
61    /// Panics if `outputs.len() < inputs.len()`.
62    #[inline]
63    pub fn hash_many(self, inputs: &[&[u8]], outputs: &mut [[u8; 16]]) {
64        simd::hash_many_dispatch(inputs, outputs);
65    }
66
67    /// Hash messages after grouping equal lengths while restoring output order.
68    ///
69    /// This is for callers that own an object scheduling queue and can pay one
70    /// allocation plus an index sort to expose non-adjacent equal-length runs.
71    /// The original [`Self::hash_many`] remains allocation-free and preserves
72    /// the input order during dispatch. Grouping is used only when the sorted
73    /// workload contains a SIMD-sized run; otherwise this falls back to
74    /// [`Self::hash_many`].
75    ///
76    /// # Panics
77    /// Panics if `outputs.len() < inputs.len()`.
78    #[cfg(feature = "std")]
79    pub fn hash_many_grouped(self, inputs: &[&[u8]], outputs: &mut [[u8; 16]]) {
80        assert!(
81            outputs.len() >= inputs.len(),
82            "outputs.len() ({}) < inputs.len() ({})",
83            outputs.len(),
84            inputs.len()
85        );
86        if inputs.len() < 4 || has_simd_sized_adjacent_run(inputs) {
87            self.hash_many(inputs, outputs);
88            return;
89        }
90
91        let mut order: Vec<usize> = (0..inputs.len()).collect();
92        order.sort_unstable_by_key(|&index| inputs[index].len());
93        let mut max_run = 1usize;
94        let mut run = 1usize;
95        for pair in order.windows(2) {
96            if inputs[pair[0]].len() == inputs[pair[1]].len() {
97                run += 1;
98                max_run = max_run.max(run);
99            } else {
100                run = 1;
101            }
102        }
103        if max_run < 4 {
104            self.hash_many(inputs, outputs);
105            return;
106        }
107
108        let sorted_inputs: Vec<&[u8]> = order.iter().map(|&index| inputs[index]).collect();
109        let mut sorted_outputs = vec![[0u8; 16]; inputs.len()];
110        self.hash_many(&sorted_inputs, &mut sorted_outputs);
111        for (sorted_index, &original_index) in order.iter().enumerate() {
112            outputs[original_index] = sorted_outputs[sorted_index];
113        }
114    }
115
116    /// Hash independent messages to lowercase hex (ETag-shaped).
117    ///
118    /// # Panics
119    /// Panics if `outputs.len() < inputs.len()`.
120    #[cfg(feature = "std")]
121    pub fn hash_many_hex(self, inputs: &[&[u8]], outputs: &mut [String]) {
122        assert!(
123            outputs.len() >= inputs.len(),
124            "outputs.len() ({}) < inputs.len() ({})",
125            outputs.len(),
126            inputs.len()
127        );
128        let mut digests = std::vec![[0u8; 16]; inputs.len()];
129        self.hash_many(inputs, &mut digests);
130        for (d, output) in digests.iter().zip(outputs.iter_mut()) {
131            *output = crate::md5::hex_encode(d);
132        }
133    }
134
135    /// Hash one message via the active single-stream path.
136    #[inline]
137    pub fn hash_one(self, input: &[u8]) -> [u8; 16] {
138        backend::hash(input)
139    }
140
141    /// Increment several independent streams through the scalar backend.
142    ///
143    /// # Panics
144    /// Panics if `states.len() != inputs.len()`.
145    #[inline]
146    pub fn update_many(self, states: &mut [Md5State], inputs: &[&[u8]]) {
147        assert_eq!(states.len(), inputs.len());
148        for (state, input) in states.iter_mut().zip(inputs.iter()) {
149            state.update(input);
150        }
151    }
152
153    /// Snapshot-finalize several streams sequentially (states are not consumed).
154    ///
155    /// # Panics
156    /// Panics if `outputs.len() < states.len()`.
157    #[inline]
158    pub fn finalize_many(self, states: &[Md5State], outputs: &mut [[u8; 16]]) {
159        assert!(
160            outputs.len() >= states.len(),
161            "outputs.len() ({}) < states.len() ({})",
162            outputs.len(),
163            states.len()
164        );
165        for (state, output) in states.iter().zip(outputs.iter_mut()) {
166            *output = state.finalize();
167        }
168    }
169
170    /// Streaming hasher on the active backend.
171    #[inline]
172    pub fn hasher(self) -> Md5 {
173        Md5::new()
174    }
175}
176
177#[cfg(feature = "std")]
178fn has_simd_sized_adjacent_run(inputs: &[&[u8]]) -> bool {
179    let mut run = 1usize;
180    for pair in inputs.windows(2) {
181        if pair[0].len() == pair[1].len() {
182            run += 1;
183            if run >= 4 {
184                return true;
185            }
186        } else {
187            run = 1;
188        }
189    }
190    false
191}
192
193/// Hash many independent messages with the process-default engine.
194#[inline]
195pub fn md5_many(inputs: &[&[u8]], outputs: &mut [[u8; 16]]) {
196    Md5Engine::new().hash_many(inputs, outputs);
197}