hashjunkie 0.6.0

Fast multi-algorithm hashing library with file-sharing and cloud hash support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::sync::{Arc, mpsc};
use std::thread;
use std::time::Duration;

use rayon::prelude::*;

use crate::hashes::{self, Hasher};
use crate::{Algorithm, DigestValue};

const PARALLEL_UPDATE_MIN: usize = 128 * 1024;
const PIPELINE_QUEUE_DEPTH: usize = 2;

pub struct MultiHasher {
    pairs: Vec<(Algorithm, Box<dyn Hasher>)>,
}

#[derive(Debug)]
pub enum PipelinedHashError {
    WorkerStopped,
    WorkerPanicked,
}

impl fmt::Display for PipelinedHashError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PipelinedHashError::WorkerStopped => f.write_str("hash worker stopped unexpectedly"),
            PipelinedHashError::WorkerPanicked => f.write_str("hash worker panicked"),
        }
    }
}

impl std::error::Error for PipelinedHashError {}

pub struct PipelinedMultiHasher {
    senders: Option<Vec<mpsc::SyncSender<Arc<[u8]>>>>,
    workers: Vec<thread::JoinHandle<WorkerResult>>,
}

struct WorkerResult {
    algorithm: Algorithm,
    digest: DigestValue,
    elapsed: Duration,
}

impl PipelinedMultiHasher {
    pub fn new(algorithms: &[Algorithm]) -> Self {
        let mut seen = HashSet::new();
        let algorithms = algorithms.iter().copied().filter(|alg| seen.insert(*alg));

        let mut senders = Vec::new();
        let mut workers = Vec::new();

        for algorithm in algorithms {
            let (sender, receiver) = mpsc::sync_channel(PIPELINE_QUEUE_DEPTH);
            senders.push(sender);
            workers.push(thread::spawn(move || {
                hash_one_algorithm(algorithm, receiver)
            }));
        }

        Self {
            senders: Some(senders),
            workers,
        }
    }

    pub fn update(&mut self, data: &[u8]) -> Result<(), PipelinedHashError> {
        let chunk: Arc<[u8]> = Arc::from(data.to_vec().into_boxed_slice());
        let senders = self
            .senders
            .as_ref()
            .ok_or(PipelinedHashError::WorkerStopped)?;

        for sender in senders {
            sender
                .send(Arc::clone(&chunk))
                .map_err(|_| PipelinedHashError::WorkerStopped)?;
        }

        Ok(())
    }

    pub fn finalize_digests(
        mut self,
    ) -> Result<HashMap<Algorithm, DigestValue>, PipelinedHashError> {
        self.senders.take();

        let mut digests = HashMap::new();
        for worker in self.workers {
            let result = worker
                .join()
                .map_err(|_| PipelinedHashError::WorkerPanicked)?;
            if std::env::var_os("HASHJUNKIE_PROFILE_PIPELINE").is_some() {
                eprintln!(
                    "hashjunkie pipeline {:>9}: {:.3}s",
                    result.algorithm,
                    result.elapsed.as_secs_f64()
                );
            }
            digests.insert(result.algorithm, result.digest);
        }

        Ok(digests)
    }

    pub fn finalize(self) -> Result<HashMap<Algorithm, String>, PipelinedHashError> {
        let values = self.finalize_digests()?;
        Ok(values
            .into_iter()
            .map(|(alg, digest)| (alg, digest.standard().to_string()))
            .collect())
    }
}

fn hash_one_algorithm(algorithm: Algorithm, chunks: mpsc::Receiver<Arc<[u8]>>) -> WorkerResult {
    let mut elapsed = Duration::ZERO;
    let mut hasher = MultiHasher::new(&[algorithm]);
    for chunk in chunks {
        let started = std::time::Instant::now();
        hasher.update(&chunk);
        elapsed += started.elapsed();
    }

    let mut digests = hasher.finalize_digests();
    let digest = digests
        .remove(&algorithm)
        .expect("single-algorithm hasher returns its digest");
    WorkerResult {
        algorithm,
        digest,
        elapsed,
    }
}

impl MultiHasher {
    pub fn new(algorithms: &[Algorithm]) -> Self {
        let mut seen = HashSet::new();
        let pairs = algorithms
            .iter()
            .filter(|&&alg| seen.insert(alg))
            .map(|&alg| (alg, make_hasher(alg)))
            .collect();
        Self { pairs }
    }

    pub fn all() -> Self {
        Self::new(Algorithm::all())
    }

    pub fn update(&mut self, data: &[u8]) {
        for (_, hasher) in &mut self.pairs {
            hasher.update(data);
        }
    }

    pub fn update_parallel(&mut self, data: &[u8]) {
        if self.pairs.len() < 2 || data.len() < PARALLEL_UPDATE_MIN {
            self.update(data);
            return;
        }

        self.pairs
            .par_iter_mut()
            .for_each(|(_, hasher)| hasher.update(data));
    }

    pub fn finalize(self) -> HashMap<Algorithm, String> {
        self.finalize_digests()
            .into_iter()
            .map(|(alg, digest)| (alg, digest.standard().to_string()))
            .collect()
    }

    pub fn finalize_digests(self) -> HashMap<Algorithm, DigestValue> {
        self.pairs
            .into_iter()
            .map(|(alg, hasher)| (alg, hasher.finalize_digest()))
            .collect()
    }
}

fn make_hasher(alg: Algorithm) -> Box<dyn Hasher> {
    use hashes::*;
    match alg {
        Algorithm::Aich => Box::new(AichHasher::new()),
        Algorithm::Blake3 => Box::new(Blake3Hasher::new()),
        Algorithm::Btv2 => Box::new(Btv2Hasher::new()),
        Algorithm::CidV0 => Box::new(CidHasher::v0()),
        Algorithm::CidV1 => Box::new(CidHasher::v1()),
        Algorithm::Crc32 => Box::new(Crc32Hasher::new()),
        Algorithm::Dropbox => Box::new(DropboxHasher::new()),
        Algorithm::Ed2k => Box::new(Ed2kHasher::new()),
        Algorithm::Hidrive => Box::new(HidriveHasher::new()),
        Algorithm::Mailru => Box::new(MailruHasher::new()),
        Algorithm::Md5 => Box::new(RustCryptoHasher::<md5::Md5>::new()),
        Algorithm::QuickXor => Box::new(QuickXorHasher::new()),
        Algorithm::Sha1 => Box::new(RustCryptoHasher::<sha1::Sha1>::new()),
        Algorithm::Sha256 => Box::new(RustCryptoHasher::<sha2::Sha256>::new()),
        Algorithm::Sha512 => Box::new(RustCryptoHasher::<sha2::Sha512>::new()),
        Algorithm::Tiger => Box::new(TigerTreeHasher::new()),
        Algorithm::Whirlpool => Box::new(RustCryptoHasher::<whirlpool::Whirlpool>::new()),
        Algorithm::Xxh128 => Box::new(Xxh128Hasher::new()),
        Algorithm::Xxh3 => Box::new(Xxh3Hasher::new()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_with_subset_produces_only_requested_algorithms() {
        let algs = &[Algorithm::Md5, Algorithm::Sha256];
        let mut h = MultiHasher::new(algs);
        h.update(b"abc");
        let digests = h.finalize();
        assert_eq!(digests.len(), 2);
        assert!(digests.contains_key(&Algorithm::Md5));
        assert!(digests.contains_key(&Algorithm::Sha256));
    }

    #[test]
    fn all_produces_default_algorithms_without_whirlpool() {
        let mut h = MultiHasher::all();
        h.update(b"");
        let digests = h.finalize();
        assert_eq!(digests.len(), 18);
        assert!(digests.contains_key(&Algorithm::Aich));
        assert!(digests.contains_key(&Algorithm::Ed2k));
        assert!(digests.contains_key(&Algorithm::Tiger));
        assert!(!digests.contains_key(&Algorithm::Whirlpool));
    }

    #[test]
    fn explicit_whirlpool_is_still_supported() {
        let mut h = MultiHasher::new(&[Algorithm::Whirlpool]);
        h.update(b"abc");
        let digests = h.finalize();
        assert_eq!(
            digests[&Algorithm::Whirlpool],
            "4e2448a4c6f486bb16b6562c73b4020bf3043e3a731bce721ae1b303d97e6d4c7181eebdb6c57e277d0e34957114cbd6c797fc9d95d8b582d225292076d4eef5"
        );
    }

    #[test]
    fn md5_result_matches_standalone_hasher() {
        let mut h = MultiHasher::new(&[Algorithm::Md5]);
        h.update(b"abc");
        let digests = h.finalize();
        assert_eq!(digests[&Algorithm::Md5], "900150983cd24fb0d6963f7d28e17f72");
    }

    #[test]
    fn sha256_result_matches_standalone_hasher() {
        let mut h = MultiHasher::new(&[Algorithm::Sha256]);
        h.update(b"abc");
        let digests = h.finalize();
        assert_eq!(
            digests[&Algorithm::Sha256],
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }

    #[test]
    fn finalize_digests_exposes_raw_hex_and_standard_text() {
        let mut h = MultiHasher::new(&[Algorithm::Sha256, Algorithm::Aich, Algorithm::CidV1]);
        h.update(b"abc");
        let digests = h.finalize_digests();

        assert_eq!(
            digests[&Algorithm::Sha256].raw(),
            &hex::decode("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
                .unwrap()
        );
        assert_eq!(
            digests[&Algorithm::Aich].standard(),
            "VGMT4NSHA2AWVOR6EVYXQUGCNSONBWE5"
        );
        assert_eq!(
            digests[&Algorithm::Aich].hex(),
            "a9993e364706816aba3e25717850c26c9cd0d89d"
        );
        assert_eq!(
            digests[&Algorithm::CidV1].standard(),
            "bafkreif2pall7dybz7vecqka3zo24irdwabwdi4wc55jznaq75q7eaavvu"
        );
        assert_eq!(
            digests[&Algorithm::CidV1].hex(),
            "01551220ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }

    #[test]
    fn multi_update_in_chunks_matches_single_update() {
        let data = b"the quick brown fox jumps over the lazy dog";
        let algs = &[Algorithm::Blake3, Algorithm::Sha256, Algorithm::Xxh3];

        let mut h1 = MultiHasher::new(algs);
        h1.update(data);
        let single = h1.finalize();

        let mut h2 = MultiHasher::new(algs);
        for chunk in data.chunks(11) {
            h2.update(chunk);
        }
        let chunked = h2.finalize();

        assert_eq!(single, chunked);
    }

    #[test]
    fn parallel_update_matches_single_update() {
        let data = vec![7; PARALLEL_UPDATE_MIN * 2 + 13];
        let algs = &[
            Algorithm::Aich,
            Algorithm::Blake3,
            Algorithm::Btv2,
            Algorithm::Sha256,
            Algorithm::Md5,
            Algorithm::Xxh3,
            Algorithm::Dropbox,
        ];

        let mut sequential = MultiHasher::new(algs);
        sequential.update(&data);

        let mut parallel = MultiHasher::new(algs);
        parallel.update_parallel(&data);

        assert_eq!(parallel.finalize(), sequential.finalize());
    }

    #[test]
    fn parallel_update_falls_back_for_small_chunks_and_single_algorithm() {
        let small = vec![5; PARALLEL_UPDATE_MIN - 1];
        let algs = &[Algorithm::Blake3, Algorithm::Sha256];

        let mut sequential = MultiHasher::new(algs);
        sequential.update(&small);

        let mut fallback_small = MultiHasher::new(algs);
        fallback_small.update_parallel(&small);

        assert_eq!(fallback_small.finalize(), sequential.finalize());

        let large = vec![9; PARALLEL_UPDATE_MIN + 1];
        let mut sequential_single = MultiHasher::new(&[Algorithm::Sha256]);
        sequential_single.update(&large);

        let mut fallback_single = MultiHasher::new(&[Algorithm::Sha256]);
        fallback_single.update_parallel(&large);

        assert_eq!(fallback_single.finalize(), sequential_single.finalize());
    }

    #[test]
    fn pipelined_multi_hasher_matches_sequential_across_chunks() {
        let data = vec![19; 1024 * 1024 + 13];
        let algs = &[
            Algorithm::Blake3,
            Algorithm::Sha256,
            Algorithm::Sha512,
            Algorithm::CidV0,
            Algorithm::CidV1,
            Algorithm::Dropbox,
        ];

        let mut sequential = MultiHasher::new(algs);
        for chunk in data.chunks(123_457) {
            sequential.update(chunk);
        }

        let mut pipelined = PipelinedMultiHasher::new(algs);
        for chunk in data.chunks(123_457) {
            pipelined.update(chunk).unwrap();
        }

        assert_eq!(pipelined.finalize().unwrap(), sequential.finalize());
    }

    #[test]
    fn pipelined_multi_hasher_profile_branch_still_finalizes() {
        // SAFETY: this test restores the process-wide environment variable before
        // returning; the variable is read only after worker threads have joined.
        unsafe {
            std::env::set_var("HASHJUNKIE_PROFILE_PIPELINE", "1");
        }

        let mut pipelined = PipelinedMultiHasher::new(&[Algorithm::Sha256]);
        pipelined.update(b"abc").unwrap();
        let result = pipelined.finalize();

        // SAFETY: remove the test-only environment variable before returning.
        unsafe {
            std::env::remove_var("HASHJUNKIE_PROFILE_PIPELINE");
        }

        assert_eq!(
            result.unwrap()[&Algorithm::Sha256],
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }

    #[test]
    fn pipelined_error_display_messages_are_stable() {
        assert_eq!(
            PipelinedHashError::WorkerStopped.to_string(),
            "hash worker stopped unexpectedly"
        );
        assert_eq!(
            PipelinedHashError::WorkerPanicked.to_string(),
            "hash worker panicked"
        );
    }

    #[test]
    fn empty_algorithms_slice_produces_empty_result() {
        let mut h = MultiHasher::new(&[]);
        h.update(b"data");
        assert_eq!(h.finalize().len(), 0);
    }

    #[test]
    fn duplicate_algorithms_are_deduplicated() {
        let algs = &[Algorithm::Md5, Algorithm::Md5, Algorithm::Md5];
        let mut h = MultiHasher::new(algs);
        h.update(b"abc");
        assert_eq!(h.finalize().len(), 1);
    }
}