quichash_core/hash/computer/
mod.rs1use std::fs::File;
2use std::io::IsTerminal;
3use std::io::Read;
4use std::path::{Path, PathBuf};
5
6#[cfg(feature = "mmap")]
7use memmap2::Mmap;
8
9use super::HashResult;
10use super::file::*;
11use super::hasher::{Hasher, bytes_to_hex};
12use super::registry::HashRegistry;
13use crate::error::HashUtilityError;
14
15mod single;
16
17pub struct HashComputer {
19 pub(crate) buffer_size: usize,
20}
21
22impl HashComputer {
23 pub fn new() -> Self {
25 Self {
26 buffer_size: 1024 * 1024,
27 }
28 }
29
30 pub fn with_buffer_size(buffer_size: usize) -> Self {
32 Self { buffer_size }
33 }
34
35 pub fn buffer_size(&self) -> usize {
37 self.buffer_size
38 }
39
40 pub fn compute_hash_text(
42 &self,
43 text: &str,
44 algorithm: &str,
45 ) -> Result<HashResult, HashUtilityError> {
46 let mut hasher = HashRegistry::get_hasher(algorithm)?;
48
49 hasher.update(text.as_bytes());
51
52 let hash_bytes = hasher.finalize();
54 let hash_hex = bytes_to_hex(&hash_bytes);
55
56 Ok(HashResult {
57 algorithm: algorithm.to_string(),
58 hash: hash_hex,
59 file_path: PathBuf::from("<text>"), })
61 }
62
63 pub fn compute_multiple_hashes_text(
65 &self,
66 text: &str,
67 algorithms: &[String],
68 ) -> Result<Vec<HashResult>, HashUtilityError> {
69 let mut hashers: Vec<(String, Box<dyn Hasher>)> = Vec::new();
71 for algorithm in algorithms {
72 let hasher = HashRegistry::get_hasher(algorithm)?;
73 hashers.push((algorithm.clone(), hasher));
74 }
75
76 let text_bytes = text.as_bytes();
78 for (_, hasher) in &mut hashers {
79 hasher.update(text_bytes);
80 }
81
82 let mut results = Vec::new();
84 for (algorithm, hasher) in hashers {
85 let hash_bytes = hasher.finalize();
86 let hash_hex = bytes_to_hex(&hash_bytes);
87
88 results.push(HashResult {
89 algorithm,
90 hash: hash_hex,
91 file_path: PathBuf::from("<text>"), });
93 }
94
95 Ok(results)
96 }
97
98 pub fn compute_hash_stdin(&self, algorithm: &str) -> Result<HashResult, HashUtilityError> {
100 use std::io::{Read, stdin};
101
102 let mut hasher = HashRegistry::get_hasher(algorithm)?;
104
105 let mut stdin = stdin();
107
108 let mut buffer = vec![0u8; self.buffer_size];
110
111 loop {
113 let bytes_read = stdin
114 .read(&mut buffer)
115 .map_err(|e| HashUtilityError::from_io_error(e, "reading from stdin", None))?;
116 if bytes_read == 0 {
117 break;
118 }
119 hasher.update(&buffer[..bytes_read]);
120 }
121
122 let hash_bytes = hasher.finalize();
124 let hash_hex = bytes_to_hex(&hash_bytes);
125
126 Ok(HashResult {
127 algorithm: algorithm.to_string(),
128 hash: hash_hex,
129 file_path: PathBuf::from("-"), })
131 }
132
133 pub fn compute_multiple_hashes_stdin(
135 &self,
136 algorithms: &[String],
137 ) -> Result<Vec<HashResult>, HashUtilityError> {
138 use std::io::{Read, stdin};
139
140 let mut hashers: Vec<(String, Box<dyn Hasher>)> = Vec::new();
142 for algorithm in algorithms {
143 let hasher = HashRegistry::get_hasher(algorithm)?;
144 hashers.push((algorithm.clone(), hasher));
145 }
146
147 let mut stdin = stdin();
149
150 let mut buffer = vec![0u8; self.buffer_size];
152
153 loop {
155 let bytes_read = stdin
156 .read(&mut buffer)
157 .map_err(|e| HashUtilityError::from_io_error(e, "reading from stdin", None))?;
158 if bytes_read == 0 {
159 break;
160 }
161
162 for (_, hasher) in &mut hashers {
164 hasher.update(&buffer[..bytes_read]);
165 }
166 }
167
168 let mut results = Vec::new();
170 for (algorithm, hasher) in hashers {
171 let hash_bytes = hasher.finalize();
172 let hash_hex = bytes_to_hex(&hash_bytes);
173
174 results.push(HashResult {
175 algorithm,
176 hash: hash_hex,
177 file_path: PathBuf::from("-"), });
179 }
180
181 Ok(results)
182 }
183
184 pub fn compute_multiple_hashes(
194 &self,
195 path: &Path,
196 algorithms: &[String],
197 ) -> Result<Vec<HashResult>, HashUtilityError> {
198 self.compute_multiple_hashes_with_progress(path, algorithms, false)
199 }
200
201 #[allow(unsafe_code)]
206 pub fn compute_multiple_hashes_with_progress(
207 &self,
208 path: &Path,
209 algorithms: &[String],
210 show_progress: bool,
211 ) -> Result<Vec<HashResult>, HashUtilityError> {
212 let mut hashers: Vec<(String, Box<dyn Hasher>)> = Vec::new();
214 for algorithm in algorithms {
215 let hasher = HashRegistry::get_hasher(algorithm)?;
216 hashers.push((algorithm.clone(), hasher));
217 }
218
219 let file = super::io_strategy::open(path, super::HashMode::Full)
221 .map_err(|e| HashUtilityError::from_io_error(e, "reading", Some(path.to_path_buf())))?;
222
223 let file_size = file
225 .metadata()
226 .map_err(|e| {
227 HashUtilityError::from_io_error(e, "reading metadata", Some(path.to_path_buf()))
228 })?
229 .len();
230
231 let should_show_progress =
233 show_progress && file_size > PROGRESS_BAR_THRESHOLD && std::io::stdout().is_terminal();
234
235 #[cfg(feature = "mmap")]
237 {
238 if (MMAP_MIN_SIZE..MMAP_THRESHOLD).contains(&file_size) {
239 match unsafe { Mmap::map(&file) } {
241 Ok(mmap) => {
242 for (_, hasher) in &mut hashers {
245 hasher.update(&mmap[..]);
246 }
247 }
248 Err(_) => {
249 if should_show_progress {
251 self.hash_multiple_with_buffered_io_progress(
252 &mut hashers,
253 file,
254 path,
255 file_size,
256 )?;
257 } else {
258 self.hash_multiple_with_buffered_io(&mut hashers, file, path)?;
259 }
260 }
261 }
262 } else {
263 if should_show_progress {
265 self.hash_multiple_with_buffered_io_progress(
266 &mut hashers,
267 file,
268 path,
269 file_size,
270 )?;
271 } else {
272 self.hash_multiple_with_buffered_io(&mut hashers, file, path)?;
273 }
274 }
275 }
276 #[cfg(not(feature = "mmap"))]
277 {
278 if should_show_progress {
279 self.hash_multiple_with_buffered_io_progress(&mut hashers, file, path, file_size)?;
280 } else {
281 self.hash_multiple_with_buffered_io(&mut hashers, file, path)?;
282 }
283 }
284
285 let mut results = Vec::new();
287 for (algorithm, hasher) in hashers {
288 let hash_bytes = hasher.finalize();
289 let hash_hex = bytes_to_hex(&hash_bytes);
290
291 results.push(HashResult {
292 algorithm,
293 hash: hash_hex,
294 file_path: path.to_path_buf(),
295 });
296 }
297
298 Ok(results)
299 }
300
301 fn hash_multiple_with_buffered_io(
303 &self,
304 hashers: &mut [(String, Box<dyn Hasher>)],
305 mut file: File,
306 path: &Path,
307 ) -> Result<(), HashUtilityError> {
308 let mut buffer = vec![0u8; self.buffer_size];
309
310 loop {
311 let bytes_read = file.read(&mut buffer).map_err(|e| {
312 HashUtilityError::from_io_error(e, "reading", Some(path.to_path_buf()))
313 })?;
314 if bytes_read == 0 {
315 break;
316 }
317
318 for (_, hasher) in hashers.iter_mut() {
320 hasher.update(&buffer[..bytes_read]);
321 }
322 }
323
324 Ok(())
325 }
326
327 fn hash_multiple_with_buffered_io_progress(
329 &self,
330 hashers: &mut [(String, Box<dyn Hasher>)],
331 mut file: File,
332 path: &Path,
333 file_size: u64,
334 ) -> Result<(), HashUtilityError> {
335 use crate::operation::{
336 LegacyProgress as ProgressBar, LegacyProgressStyle as ProgressStyle,
337 };
338 use std::time::{Duration, Instant};
339
340 let pb = ProgressBar::new(file_size);
342 pb.set_style(
343 ProgressStyle::default_bar()
344 .template(
345 "{msg}\n[{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})",
346 )
347 .unwrap()
348 .progress_chars("#>-"),
349 );
350 pb.set_message(format!("Hashing: {}", path.display()));
351
352 let mut buffer = vec![0u8; self.buffer_size];
353 let mut bytes_processed = 0u64;
354 let mut last_update = Instant::now();
355 let update_interval = Duration::from_millis(PROGRESS_UPDATE_INTERVAL_MS);
356
357 loop {
358 let bytes_read = file.read(&mut buffer).map_err(|e| {
359 pb.finish_and_clear();
360 HashUtilityError::from_io_error(e, "reading", Some(path.to_path_buf()))
361 })?;
362 if bytes_read == 0 {
363 break;
364 }
365
366 for (_, hasher) in hashers.iter_mut() {
368 hasher.update(&buffer[..bytes_read]);
369 }
370
371 bytes_processed += bytes_read as u64;
372
373 let now = Instant::now();
375 if now.duration_since(last_update) >= update_interval {
376 pb.set_position(bytes_processed);
377 last_update = now;
378 }
379 }
380
381 pb.finish_and_clear();
383
384 Ok(())
385 }
386}
387
388impl Default for HashComputer {
389 fn default() -> Self {
390 Self::new()
391 }
392}