1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29pub mod cli;
30pub mod fnv;
31pub mod xxhash;
32
33use ctb_formats_utilities::format_info::{FormatInfo, format_help_table};
34use ctb_utilities::FormatId;
35use ctb_utilities::string::{to_hex, to_hex_0x};
36use sha2::{Digest, Sha256 as Sha256Digest};
37use std::sync::LazyLock;
38
39pub type HashAlgorithm = SupportedHashFormat;
41
42#[expect(
43 non_upper_case_globals,
44 reason = "Alias constant matches enum variant naming"
45)]
46pub const Sha256: HashAlgorithm = HashAlgorithm::Sha256;
47
48pub trait HashFormatExt {
50 fn format_info(&self) -> Option<&'static FormatInfo>;
52}
53
54impl HashFormatExt for SupportedHashFormat {
55 fn format_info(&self) -> Option<&'static FormatInfo> {
56 ctb_formats_utilities::get_format_info_by_id(self.to_format_id())
57 }
58}
59
60pub fn csum_help_table() -> String {
62 format_help_table(
63 "Supported hash algorithms:",
64 SupportedHashFormat::ALL_FORMAT_IDS,
65 )
66}
67
68pub static CSUM_AFTER_HELP: LazyLock<String> = LazyLock::new(csum_help_table);
70
71pub fn sha256(data: impl AsRef<[u8]>) -> [u8; 32] {
73 let mut hasher = Sha256Digest::new();
74 hasher.update(data.as_ref());
75 let mut out = [0_u8; 32];
76 out.copy_from_slice(&hasher.finalize());
77 out
78}
79
80pub fn sha256_hex(data: impl AsRef<[u8]>) -> String {
82 to_hex(&sha256(data))
83}
84
85#[derive(Clone, Default)]
87pub struct Sha256Stream {
88 hasher: Sha256Digest,
89}
90
91impl Sha256Stream {
92 #[must_use]
94 pub fn new() -> Self {
95 Self {
96 hasher: Sha256Digest::new(),
97 }
98 }
99
100 pub fn update(&mut self, data: impl AsRef<[u8]>) {
102 self.hasher.update(data.as_ref());
103 }
104
105 #[must_use]
107 pub fn finalize(self) -> [u8; 32] {
108 let mut out = [0_u8; 32];
109 out.copy_from_slice(&self.hasher.finalize());
110 out
111 }
112
113 #[must_use]
115 pub fn finalize_hex(self) -> String {
116 to_hex(&self.finalize())
117 }
118}
119
120impl std::io::Write for Sha256Stream {
121 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
122 self.update(buf);
123 Ok(buf.len())
124 }
125
126 fn flush(&mut self) -> std::io::Result<()> {
127 Ok(())
128 }
129}
130
131#[derive(Clone)]
133pub enum StreamingHasher {
134 Sha256(Sha256Stream),
135 XxHash32(twox_hash::XxHash32),
136 XxHash64(twox_hash::XxHash64),
137 XxHash3_64(twox_hash::XxHash3_64),
138 XxHash3_128(twox_hash::XxHash3_128),
139 Fnv0_32(fnv::FnvStream<4>),
140 Fnv0_64(fnv::FnvStream<8>),
141 Fnv0_128(fnv::FnvStream<16>),
142 Fnv0_256(fnv::FnvStream<32>),
143 Fnv0_512(fnv::FnvStream<64>),
144 Fnv0_1024(fnv::FnvStream<128>),
145 Fnv1_32(fnv::FnvStream<4>),
146 Fnv1_64(fnv::FnvStream<8>),
147 Fnv1_128(fnv::FnvStream<16>),
148 Fnv1_256(fnv::FnvStream<32>),
149 Fnv1_512(fnv::FnvStream<64>),
150 Fnv1_1024(fnv::FnvStream<128>),
151 Fnv1a_32(fnv::FnvStream<4>),
152 Fnv1a_64(fnv::FnvStream<8>),
153 Fnv1a_128(fnv::FnvStream<16>),
154 Fnv1a_256(fnv::FnvStream<32>),
155 Fnv1a_512(fnv::FnvStream<64>),
156 Fnv1a_1024(fnv::FnvStream<128>),
157}
158
159impl StreamingHasher {
160 #[must_use]
162 pub fn new(algo: HashAlgorithm) -> Self {
163 match algo {
164 HashAlgorithm::Sha256 => Self::Sha256(Sha256Stream::new()),
165 HashAlgorithm::XxHash32 => {
166 Self::XxHash32(twox_hash::XxHash32::with_seed(0))
167 }
168 HashAlgorithm::XxHash64 => {
169 Self::XxHash64(twox_hash::XxHash64::with_seed(0))
170 }
171 HashAlgorithm::XxHash3_64 => {
172 Self::XxHash3_64(twox_hash::XxHash3_64::new())
173 }
174 HashAlgorithm::XxHash3_128 => {
175 Self::XxHash3_128(twox_hash::XxHash3_128::new())
176 }
177 HashAlgorithm::Fnv0_32 => Self::Fnv0_32(fnv::FnvStream::new(
178 fnv::FnvVariant::Fnv0,
179 fnv::K_32,
180 fnv::B_32,
181 )),
182 HashAlgorithm::Fnv0_64 => Self::Fnv0_64(fnv::FnvStream::new(
183 fnv::FnvVariant::Fnv0,
184 fnv::K_64,
185 fnv::B_64,
186 )),
187 HashAlgorithm::Fnv0_128 => Self::Fnv0_128(fnv::FnvStream::new(
188 fnv::FnvVariant::Fnv0,
189 fnv::K_128,
190 fnv::B_128,
191 )),
192 HashAlgorithm::Fnv0_256 => Self::Fnv0_256(fnv::FnvStream::new(
193 fnv::FnvVariant::Fnv0,
194 fnv::K_256,
195 fnv::B_256,
196 )),
197 HashAlgorithm::Fnv0_512 => Self::Fnv0_512(fnv::FnvStream::new(
198 fnv::FnvVariant::Fnv0,
199 fnv::K_512,
200 fnv::B_512,
201 )),
202 HashAlgorithm::Fnv0_1024 => Self::Fnv0_1024(fnv::FnvStream::new(
203 fnv::FnvVariant::Fnv0,
204 fnv::K_1024,
205 fnv::B_1024,
206 )),
207 HashAlgorithm::Fnv1_32 => Self::Fnv1_32(fnv::FnvStream::new(
208 fnv::FnvVariant::Fnv1,
209 fnv::K_32,
210 fnv::B_32,
211 )),
212 HashAlgorithm::Fnv1_64 => Self::Fnv1_64(fnv::FnvStream::new(
213 fnv::FnvVariant::Fnv1,
214 fnv::K_64,
215 fnv::B_64,
216 )),
217 HashAlgorithm::Fnv1_128 => Self::Fnv1_128(fnv::FnvStream::new(
218 fnv::FnvVariant::Fnv1,
219 fnv::K_128,
220 fnv::B_128,
221 )),
222 HashAlgorithm::Fnv1_256 => Self::Fnv1_256(fnv::FnvStream::new(
223 fnv::FnvVariant::Fnv1,
224 fnv::K_256,
225 fnv::B_256,
226 )),
227 HashAlgorithm::Fnv1_512 => Self::Fnv1_512(fnv::FnvStream::new(
228 fnv::FnvVariant::Fnv1,
229 fnv::K_512,
230 fnv::B_512,
231 )),
232 HashAlgorithm::Fnv1_1024 => Self::Fnv1_1024(fnv::FnvStream::new(
233 fnv::FnvVariant::Fnv1,
234 fnv::K_1024,
235 fnv::B_1024,
236 )),
237 HashAlgorithm::Fnv1a_32 => Self::Fnv1a_32(fnv::FnvStream::new(
238 fnv::FnvVariant::Fnv1a,
239 fnv::K_32,
240 fnv::B_32,
241 )),
242 HashAlgorithm::Fnv1a_64 => Self::Fnv1a_64(fnv::FnvStream::new(
243 fnv::FnvVariant::Fnv1a,
244 fnv::K_64,
245 fnv::B_64,
246 )),
247 HashAlgorithm::Fnv1a_128 => Self::Fnv1a_128(fnv::FnvStream::new(
248 fnv::FnvVariant::Fnv1a,
249 fnv::K_128,
250 fnv::B_128,
251 )),
252 HashAlgorithm::Fnv1a_256 => Self::Fnv1a_256(fnv::FnvStream::new(
253 fnv::FnvVariant::Fnv1a,
254 fnv::K_256,
255 fnv::B_256,
256 )),
257 HashAlgorithm::Fnv1a_512 => Self::Fnv1a_512(fnv::FnvStream::new(
258 fnv::FnvVariant::Fnv1a,
259 fnv::K_512,
260 fnv::B_512,
261 )),
262 HashAlgorithm::Fnv1a_1024 => Self::Fnv1a_1024(fnv::FnvStream::new(
263 fnv::FnvVariant::Fnv1a,
264 fnv::K_1024,
265 fnv::B_1024,
266 )),
267 }
268 }
269
270 pub fn update(&mut self, data: &[u8]) {
272 use std::hash::Hasher;
273 match self {
274 Self::Sha256(s) => s.update(data),
275 Self::XxHash32(h) => h.write(data),
276 Self::XxHash64(h) => h.write(data),
277 Self::XxHash3_64(h) => h.write(data),
278 Self::XxHash3_128(h) => h.write(data),
279 Self::Fnv0_32(s) | Self::Fnv1_32(s) | Self::Fnv1a_32(s) => {
280 s.update(data);
281 }
282 Self::Fnv0_64(s) | Self::Fnv1_64(s) | Self::Fnv1a_64(s) => {
283 s.update(data);
284 }
285 Self::Fnv0_128(s) | Self::Fnv1_128(s) | Self::Fnv1a_128(s) => {
286 s.update(data);
287 }
288 Self::Fnv0_256(s) | Self::Fnv1_256(s) | Self::Fnv1a_256(s) => {
289 s.update(data);
290 }
291 Self::Fnv0_512(s) | Self::Fnv1_512(s) | Self::Fnv1a_512(s) => {
292 s.update(data);
293 }
294 Self::Fnv0_1024(s) | Self::Fnv1_1024(s) | Self::Fnv1a_1024(s) => {
295 s.update(data);
296 }
297 }
298 }
299
300 #[must_use]
302 pub fn finalize(self) -> Vec<u8> {
303 use std::hash::Hasher;
304 match self {
305 Self::Sha256(s) => s.finalize().to_vec(),
306 Self::XxHash32(h) => h.finish_32().to_be_bytes().to_vec(),
307 Self::XxHash64(h) => h.finish().to_be_bytes().to_vec(),
308 Self::XxHash3_64(h) => h.finish().to_be_bytes().to_vec(),
309 Self::XxHash3_128(h) => h.finish_128().to_be_bytes().to_vec(),
310 Self::Fnv0_32(s) | Self::Fnv1_32(s) | Self::Fnv1a_32(s) => {
311 s.finalize().to_be_bytes().to_vec()
312 }
313 Self::Fnv0_64(s) | Self::Fnv1_64(s) | Self::Fnv1a_64(s) => {
314 s.finalize().to_be_bytes().to_vec()
315 }
316 Self::Fnv0_128(s) | Self::Fnv1_128(s) | Self::Fnv1a_128(s) => {
317 s.finalize().to_be_bytes().to_vec()
318 }
319 Self::Fnv0_256(s) | Self::Fnv1_256(s) | Self::Fnv1a_256(s) => {
320 s.finalize().to_be_bytes().to_vec()
321 }
322 Self::Fnv0_512(s) | Self::Fnv1_512(s) | Self::Fnv1a_512(s) => {
323 s.finalize().to_be_bytes().to_vec()
324 }
325 Self::Fnv0_1024(s) | Self::Fnv1_1024(s) | Self::Fnv1a_1024(s) => {
326 s.finalize().to_be_bytes().to_vec()
327 }
328 }
329 }
330}
331
332impl std::io::Write for StreamingHasher {
333 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
334 self.update(buf);
335 Ok(buf.len())
336 }
337
338 fn flush(&mut self) -> std::io::Result<()> {
339 Ok(())
340 }
341}
342
343pub fn hash(data: &[u8], algo: HashAlgorithm) -> Vec<u8> {
345 let mut hasher = StreamingHasher::new(algo);
346 hasher.update(data);
347 hasher.finalize()
348}
349
350pub fn hash_hex(data: &[u8], algo: HashAlgorithm, prefix_0x: bool) -> String {
353 let bytes = hash(data, algo);
354 if prefix_0x {
355 to_hex_0x(&bytes)
356 } else {
357 to_hex(&bytes)
358 }
359}
360
361#[derive(Debug, Clone, PartialEq, Eq)]
363pub struct ChecksumDetection {
364 pub format_id: FormatId,
367 pub candidate_algorithms: Vec<FormatId>,
369 pub is_manifest: bool,
372 pub digest_len: usize,
374 pub description: String,
376}
377
378fn parse_coreutils_line(line: &str) -> Option<(&str, &str)> {
381 let (digest, rest) = line.split_once(' ')?;
382 let filename = if let Some(bin_file) = rest.strip_prefix('*') {
383 bin_file.trim()
384 } else if let Some(text_file) = rest.strip_prefix(' ') {
385 text_file.trim()
386 } else {
387 return None;
388 };
389 if filename.is_empty() {
390 return None;
391 }
392 if digest.bytes().all(|b| b.is_ascii_hexdigit()) {
393 Some((digest, filename))
394 } else {
395 None
396 }
397}
398
399fn parse_bsd_line(line: &str) -> Option<(&str, &str, &str)> {
401 let (algo_and_file, digest) = line.split_once(" = ")?;
402 let (algo, rest) = algo_and_file.split_once(" (")?;
403 let filename = rest.strip_suffix(')')?;
404 if filename.is_empty() || !digest.bytes().all(|b| b.is_ascii_hexdigit()) {
405 return None;
406 }
407 Some((algo.trim(), filename.trim(), digest.trim()))
408}
409
410#[must_use]
413pub fn detect_checksum(s: &str) -> Option<ChecksumDetection> {
414 let trimmed = s.trim();
415 if trimmed.is_empty() {
416 return None;
417 }
418
419 let lines: Vec<&str> = trimmed
421 .lines()
422 .map(str::trim)
423 .filter(|l| !l.is_empty())
424 .collect();
425
426 if !lines.is_empty() {
427 let manifest_lines: Vec<&str> = lines
428 .iter()
429 .copied()
430 .filter(|l| !l.starts_with('#'))
431 .collect();
432 let comment_header = lines
433 .iter()
434 .find(|l| l.starts_with('#'))
435 .map(|l| l.to_ascii_lowercase());
436
437 let all_coreutils = !manifest_lines.is_empty()
438 && manifest_lines
439 .iter()
440 .all(|l| parse_coreutils_line(l).is_some());
441 if all_coreutils {
442 if let Some((first_digest, _)) =
444 parse_coreutils_line(manifest_lines.first().unwrap_or(&""))
445 {
446 let dlen = first_digest.len();
447 let (mut fmt, candidates, name) = match dlen {
448 8 => (
449 FormatId::Crc32,
450 vec![
451 FormatId::Crc32,
452 FormatId::Adler32,
453 FormatId::XxHash32,
454 FormatId::Fnv1a_32,
455 FormatId::Fnv1_32,
456 FormatId::Fnv0_32,
457 ],
458 "32-bit",
459 ),
460 16 => (
461 FormatId::XxHash64,
462 vec![
463 FormatId::XxHash64,
464 FormatId::XxHash3_64,
465 FormatId::Fnv1a_64,
466 FormatId::Fnv1_64,
467 FormatId::Fnv0_64,
468 ],
469 "64-bit",
470 ),
471 32 => (
472 FormatId::Md5,
473 vec![
474 FormatId::Md5,
475 FormatId::XxHash3_128,
476 FormatId::Fnv1a_128,
477 FormatId::Fnv1_128,
478 FormatId::Fnv0_128,
479 ],
480 "MD5 / 128-bit",
481 ),
482 40 => (FormatId::Sha1, vec![FormatId::Sha1], "SHA-1"),
483 64 => (
484 FormatId::Sha256,
485 vec![
486 FormatId::Sha256,
487 FormatId::Blake3,
488 FormatId::Fnv1a_256,
489 FormatId::Fnv1_256,
490 FormatId::Fnv0_256,
491 ],
492 "SHA-256",
493 ),
494 128 => (
495 FormatId::Sha512,
496 vec![
497 FormatId::Sha512,
498 FormatId::Fnv1a_512,
499 FormatId::Fnv1_512,
500 FormatId::Fnv0_512,
501 ],
502 "SHA-512",
503 ),
504 256 => (
505 FormatId::Fnv1a_1024,
506 vec![
507 FormatId::Fnv1a_1024,
508 FormatId::Fnv1_1024,
509 FormatId::Fnv0_1024,
510 ],
511 "FNV-1a 1024-bit",
512 ),
513 _ => (FormatId::Sha256, vec![FormatId::Sha256], "checksum"),
514 };
515
516 if let Some(comment) = &comment_header {
517 if comment.contains("fnv1a") || comment.contains("fnv-1a") {
518 match dlen {
519 8 => fmt = FormatId::Fnv1a_32,
520 16 => fmt = FormatId::Fnv1a_64,
521 32 => fmt = FormatId::Fnv1a_128,
522 64 => fmt = FormatId::Fnv1a_256,
523 128 => fmt = FormatId::Fnv1a_512,
524 256 => fmt = FormatId::Fnv1a_1024,
525 _ => {}
526 }
527 } else if comment.contains("fnv1")
528 || comment.contains("fnv-1")
529 {
530 match dlen {
531 8 => fmt = FormatId::Fnv1_32,
532 16 => fmt = FormatId::Fnv1_64,
533 32 => fmt = FormatId::Fnv1_128,
534 64 => fmt = FormatId::Fnv1_256,
535 128 => fmt = FormatId::Fnv1_512,
536 256 => fmt = FormatId::Fnv1_1024,
537 _ => {}
538 }
539 } else if comment.contains("fnv0")
540 || comment.contains("fnv-0")
541 {
542 match dlen {
543 8 => fmt = FormatId::Fnv0_32,
544 16 => fmt = FormatId::Fnv0_64,
545 32 => fmt = FormatId::Fnv0_128,
546 64 => fmt = FormatId::Fnv0_256,
547 128 => fmt = FormatId::Fnv0_512,
548 256 => fmt = FormatId::Fnv0_1024,
549 _ => {}
550 }
551 }
552 }
553
554 return Some(ChecksumDetection {
555 format_id: fmt,
556 candidate_algorithms: candidates,
557 is_manifest: true,
558 digest_len: dlen,
559 description: format!("{name} checksum manifest"),
560 });
561 }
562 }
563
564 let all_bsd = lines.iter().all(|l| parse_bsd_line(l).is_some());
565 if all_bsd {
566 if let Some((algo, _, digest)) =
568 parse_bsd_line(lines.first().unwrap_or(&""))
569 {
570 let algo_clean = algo.to_ascii_lowercase();
571 let fmt = match algo_clean.as_str() {
572 "md5" => FormatId::Md5,
573 "sha1" => FormatId::Sha1,
574 "sha256" => FormatId::Sha256,
575 "sha512" => FormatId::Sha512,
576 "fnv0_32" | "fnv0-32" => FormatId::Fnv0_32,
577 "fnv0_64" | "fnv0-64" | "fnv0" => FormatId::Fnv0_64,
578 "fnv1_32" | "fnv1-32" => FormatId::Fnv1_32,
579 "fnv1_64" | "fnv1-64" | "fnv1" => FormatId::Fnv1_64,
580 "fnv1a_32" | "fnv1a-32" => FormatId::Fnv1a_32,
581 "fnv1a_64" | "fnv1a-64" | "fnv1a" => FormatId::Fnv1a_64,
582 _ => FormatId::Sha256,
583 };
584 return Some(ChecksumDetection {
585 format_id: fmt,
586 candidate_algorithms: vec![fmt],
587 is_manifest: true,
588 digest_len: digest.len(),
589 description: format!("BSD {algo} checksum file"),
590 });
591 }
592 }
593 }
594
595 if !trimmed.contains('\n') && !trimmed.contains(' ') {
597 let clean = trimmed
599 .strip_prefix("0x")
600 .or_else(|| trimmed.strip_prefix("0X"))
601 .unwrap_or(trimmed);
602 if !clean.is_empty() && clean.bytes().all(|b| b.is_ascii_hexdigit()) {
603 let len = clean.len();
604 match len {
605 64 => {
606 return Some(ChecksumDetection {
607 format_id: FormatId::Sha256,
608 candidate_algorithms: vec![
609 FormatId::Sha256,
610 FormatId::Blake3,
611 ],
612 is_manifest: false,
613 digest_len: 64,
614 description: "SHA-256 (256-bit hex digest)".to_string(),
615 });
616 }
617 32 => {
618 return Some(ChecksumDetection {
619 format_id: FormatId::Md5,
620 candidate_algorithms: vec![
621 FormatId::Md5,
622 FormatId::XxHash3_128,
623 ],
624 is_manifest: false,
625 digest_len: 32,
626 description: "MD5 (128-bit hex digest)".to_string(),
627 });
628 }
629 40 => {
630 return Some(ChecksumDetection {
631 format_id: FormatId::Sha1,
632 candidate_algorithms: vec![FormatId::Sha1],
633 is_manifest: false,
634 digest_len: 40,
635 description: "SHA-1 (160-bit hex digest)".to_string(),
636 });
637 }
638 128 => {
639 return Some(ChecksumDetection {
640 format_id: FormatId::Sha512,
641 candidate_algorithms: vec![FormatId::Sha512],
642 is_manifest: false,
643 digest_len: 128,
644 description: "SHA-512 (512-bit hex digest)".to_string(),
645 });
646 }
647 8 => {
648 return Some(ChecksumDetection {
649 format_id: FormatId::Crc32,
650 candidate_algorithms: vec![
651 FormatId::Crc32,
652 FormatId::Adler32,
653 FormatId::XxHash32,
654 FormatId::Fnv1a_32,
655 FormatId::Fnv1_32,
656 FormatId::Fnv0_32,
657 ],
658 is_manifest: false,
659 digest_len: 8,
660 description: "CRC-32 / 32-bit hex checksum".to_string(),
661 });
662 }
663 16 => {
664 return Some(ChecksumDetection {
665 format_id: FormatId::XxHash64,
666 candidate_algorithms: vec![
667 FormatId::XxHash64,
668 FormatId::XxHash3_64,
669 FormatId::Fnv1a_64,
670 FormatId::Fnv1_64,
671 FormatId::Fnv0_64,
672 ],
673 is_manifest: false,
674 digest_len: 16,
675 description: "xxHash64 / 64-bit hex checksum"
676 .to_string(),
677 });
678 }
679 _ => {}
680 }
681 }
682 }
683
684 None
685}
686
687#[cfg(test)]
688#[allow(
689 clippy::panic,
690 clippy::expect_used,
691 clippy::unwrap_used,
692 clippy::unwrap_in_result,
693 clippy::panic_in_result_fn,
694 clippy::indexing_slicing,
695 clippy::arithmetic_side_effects,
696 reason = "Standard repository test boilerplate"
697)]
698mod tests {
699 use super::*;
700
701 #[crate::ctb_test]
702 fn test_hash_hex() {
703 let data = b"hello world";
704 assert_eq!(hash_hex(data, HashAlgorithm::XxHash32, false), "cebb6622");
705 assert_eq!(hash_hex(data, HashAlgorithm::XxHash32, true), "0xcebb6622");
706
707 assert_eq!(
708 hash_hex(data, HashAlgorithm::XxHash64, false),
709 "45ab6734b21e6968"
710 );
711 assert_eq!(
712 hash_hex(data, HashAlgorithm::XxHash64, true),
713 "0x45ab6734b21e6968"
714 );
715
716 assert_eq!(
717 hash_hex(data, HashAlgorithm::Sha256, false),
718 "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
719 );
720 assert_eq!(
721 sha256_hex(data),
722 "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
723 );
724
725 assert_eq!(
726 hash_hex(b"foobar", HashAlgorithm::Fnv1a_64, false),
727 "85944171f73967e8"
728 );
729 assert_eq!(
730 hash_hex(b"foobar", HashAlgorithm::Fnv1a_32, false),
731 "bf9cf968"
732 );
733 }
734
735 #[crate::ctb_test]
736 fn test_sha256_stream() {
737 let mut stream = Sha256Stream::new();
738 stream.update(b"hello ");
739 stream.update(b"world");
740 assert_eq!(
741 stream.finalize_hex(),
742 "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
743 );
744
745 use std::io::Write;
746 let mut stream2 = Sha256Stream::default();
747 stream2.write_all(b"hello world").expect("write to stream");
748 assert_eq!(
749 stream2.finalize_hex(),
750 "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
751 );
752 }
753
754 #[crate::ctb_test]
755 fn test_hash_algorithm_parsing_and_metadata() {
756 assert_eq!(
757 HashAlgorithm::try_from("xxh32").unwrap(),
758 HashAlgorithm::XxHash32
759 );
760 assert_eq!(
761 HashAlgorithm::try_from("xxhash32").unwrap(),
762 HashAlgorithm::XxHash32
763 );
764 assert_eq!(
765 HashAlgorithm::try_from("xxh64").unwrap(),
766 HashAlgorithm::XxHash64
767 );
768 assert_eq!(
769 HashAlgorithm::try_from("xxh3").unwrap(),
770 HashAlgorithm::XxHash3_64
771 );
772 assert_eq!(
773 HashAlgorithm::try_from("xxhash3-64").unwrap(),
774 HashAlgorithm::XxHash3_64
775 );
776 assert_eq!(
777 HashAlgorithm::try_from("xxh128").unwrap(),
778 HashAlgorithm::XxHash3_128
779 );
780 assert_eq!(
781 HashAlgorithm::try_from("sha256").unwrap(),
782 HashAlgorithm::Sha256
783 );
784 assert_eq!(
785 HashAlgorithm::try_from("sha-256").unwrap(),
786 HashAlgorithm::Sha256
787 );
788 assert_eq!(
789 HashAlgorithm::try_from("fnv1a").unwrap(),
790 HashAlgorithm::Fnv1a_64
791 );
792 assert_eq!(
793 HashAlgorithm::try_from("fnv1a_32").unwrap(),
794 HashAlgorithm::Fnv1a_32
795 );
796 assert_eq!(
797 HashAlgorithm::try_from("fnv0_64").unwrap(),
798 HashAlgorithm::Fnv0_64
799 );
800 assert_eq!(
801 HashAlgorithm::try_from("fnv1_128").unwrap(),
802 HashAlgorithm::Fnv1_128
803 );
804 HashAlgorithm::try_from("nonexistent_hash").unwrap_err();
805
806 let help = csum_help_table();
807 assert!(help.contains("Supported hash algorithms:"));
808 assert!(help.contains("xxh32, xxhash32: xxHash32"));
809 assert!(help.contains("sha256"));
810 }
811
812 #[crate::ctb_test]
813 fn test_detect_checksum_cases() {
814 let sha256_hex =
816 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
817 let det = detect_checksum(sha256_hex).unwrap();
818 assert_eq!(det.format_id, FormatId::Sha256);
819 assert!(!det.is_manifest);
820 assert_eq!(det.digest_len, 64);
821
822 let md5_hex = "d41d8cd98f00b204e9800998ecf8427e";
824 let det = detect_checksum(md5_hex).unwrap();
825 assert_eq!(det.format_id, FormatId::Md5);
826 assert!(!det.is_manifest);
827
828 let sha1_hex = "da39a3ee5e6b4b0d3255bfef95601890afd80709";
830 let det = detect_checksum(sha1_hex).unwrap();
831 assert_eq!(det.format_id, FormatId::Sha1);
832
833 let crc_hex = "00000000";
835 let det = detect_checksum(crc_hex).unwrap();
836 assert_eq!(det.format_id, FormatId::Crc32);
837 assert!(det.candidate_algorithms.contains(&FormatId::Fnv1a_32));
838
839 let fnv64_hex = "85944171f73967e8";
841 let det64 = detect_checksum(fnv64_hex).unwrap();
842 assert_eq!(det64.format_id, FormatId::XxHash64);
843 assert!(det64.candidate_algorithms.contains(&FormatId::Fnv1a_64));
844
845 let manifest = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 empty.txt\n\
847 ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad *abc.txt";
848 let det = detect_checksum(manifest).unwrap();
849 assert_eq!(det.format_id, FormatId::Sha256);
850 assert!(det.is_manifest);
851
852 let manifest16 = "85944171f73967e8 foobar.txt";
854 let det16 = detect_checksum(manifest16).unwrap();
855 assert_eq!(det16.format_id, FormatId::XxHash64);
856 assert!(det16.candidate_algorithms.contains(&FormatId::Fnv1a_64));
857 assert!(det16.is_manifest);
858
859 let manifest_fnv = "# FNV1A_64 checksum\n85944171f73967e8 foobar.txt";
861 let det_fnv_core = detect_checksum(manifest_fnv).unwrap();
862 assert_eq!(det_fnv_core.format_id, FormatId::Fnv1a_64);
863 assert!(det_fnv_core.is_manifest);
864
865 let bsd = "SHA256 (file.tar.gz) = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
867 let det = detect_checksum(bsd).unwrap();
868 assert_eq!(det.format_id, FormatId::Sha256);
869 assert!(det.is_manifest);
870
871 let bsd_fnv = "FNV1A_64 (file.tar.gz) = 85944171f73967e8";
872 let det_fnv = detect_checksum(bsd_fnv).unwrap();
873 assert_eq!(det_fnv.format_id, FormatId::Fnv1a_64);
874 assert!(det_fnv.is_manifest);
875
876 assert!(detect_checksum("").is_none());
877 assert!(detect_checksum("not-a-hash").is_none());
878 }
879
880 #[crate::ctb_test]
881 fn test_sha256_large_buffer_determinism() {
882 let mut buf = vec![0u8; 2 * 1024 * 1024];
883 for (i, b) in buf.iter_mut().enumerate() {
884 *b = u8::try_from(i.wrapping_mul(13).wrapping_add(7) & 0xff)
885 .unwrap();
886 }
887 let mut streaming = Sha256Digest::new();
888 for blk in buf.chunks_exact(64) {
889 streaming.update(blk);
890 }
891 let expected: [u8; 32] = streaming.finalize().into();
892
893 for trial in 0..3 {
894 let bulk: [u8; 32] = Sha256Digest::digest(&buf).into();
895 assert_eq!(bulk, expected, "bulk digest differed at trial {trial}");
896 }
897 }
898}