odl 3.1.0

flexible download library and CLI intended to be fast, reliable, and easy to use.
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
use base64::{Engine as _, engine::general_purpose};
use digest::Digest;
use md5::Md5;
use sha1::Sha1;
use sha2::{Sha256, Sha384, Sha512};
use std::fmt::Write as _;
use tokio::io::{self as async_io, AsyncRead, AsyncReadExt};

use crate::download_metadata::{ChecksumAlgorithm, ChecksumEncoding, FileChecksum};

fn to_hex(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        let _ = write!(s, "{:02x}", b);
    }
    s
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HashDigest {
    SHA512(String, HashEncoding),
    SHA384(String, HashEncoding),
    SHA256(String, HashEncoding),
    SHA1(String, HashEncoding),
    MD5(String, HashEncoding),
}

/// Bytes read per call while hashing.
///
/// Sized against syscall overhead rather than memory: at 8 KiB a gigabyte
/// costs some 131,000 reads, which dominated the hashing itself. Nothing is
/// held beyond one buffer, so a file of any size is hashed in a few megabytes
/// of resident memory either way.
const HASH_READ_BUFFER: usize = 256 * 1024;

impl HashDigest {
    /// The digest itself, in whatever encoding this value carries.
    pub fn digest(&self) -> &str {
        match self {
            HashDigest::MD5(s, _)
            | HashDigest::SHA1(s, _)
            | HashDigest::SHA256(s, _)
            | HashDigest::SHA384(s, _)
            | HashDigest::SHA512(s, _) => s,
        }
    }

    /// Which algorithm produced this digest.
    pub fn algorithm(&self) -> HashAlgorithm {
        HashAlgorithm::from(self)
    }

    /// How [`Self::digest`] is written.
    pub fn encoding(&self) -> HashEncoding {
        HashEncoding::from(self)
    }

    /// The digest as raw bytes, whatever encoding it is written in.
    ///
    /// `None` when the text is not valid for its stated encoding, which is
    /// possible for a value parsed from a server header or a config file.
    pub fn raw_bytes(&self) -> Option<Vec<u8>> {
        match self.encoding() {
            HashEncoding::Hex => {
                let s = self.digest();
                if !s.len().is_multiple_of(2) {
                    return None;
                }
                (0..s.len())
                    .step_by(2)
                    .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok())
                    .collect()
            }
            HashEncoding::Base64 => general_purpose::STANDARD.decode(self.digest()).ok(),
        }
    }

    /// Whether two digests assert the same thing.
    ///
    /// Unlike `==`, this ignores how each is written: the same SHA-256 in hex
    /// and in base64 are equal here and not under `PartialEq`, which compares
    /// the text. Servers and config files disagree about encoding often
    /// enough that comparing them literally is a trap.
    pub fn matches(&self, other: &HashDigest) -> bool {
        if self.algorithm() != other.algorithm() {
            return false;
        }
        if self.encoding() == other.encoding() {
            // Hex casing is not significant, and everything else is exact.
            return self.digest().eq_ignore_ascii_case(other.digest());
        }
        match (self.raw_bytes(), other.raw_bytes()) {
            (Some(a), Some(b)) => a == b,
            // An undecodable digest asserts nothing; treating it as a match
            // would turn a malformed value into a passing check.
            _ => false,
        }
    }

    /// Hash a file, reading it in chunks rather than loading it.
    pub async fn from_path(
        path: impl AsRef<std::path::Path>,
        algo: HashAlgorithm,
        encoding: HashEncoding,
    ) -> async_io::Result<HashDigest> {
        Self::from_path_with_progress(path, algo, encoding, |_| {}).await
    }

    /// As [`Self::from_path`], reporting progress as it goes. See
    /// [`Self::from_reader_with_progress`] for what `on_bytes` receives.
    pub async fn from_path_with_progress(
        path: impl AsRef<std::path::Path>,
        algo: HashAlgorithm,
        encoding: HashEncoding,
        on_bytes: impl FnMut(u64) + Send,
    ) -> async_io::Result<HashDigest> {
        // No `BufReader`: the hashing loop reads in large blocks already, and
        // layering a smaller buffer under it would only add a copy.
        let file = tokio::fs::File::open(path.as_ref()).await?;
        Self::from_reader_with_progress(file, algo, encoding, on_bytes).await
    }

    /// Whether the file at `path` has the digest `expected` claims.
    ///
    /// The file is hashed with `expected`'s own algorithm, so a caller only
    /// needs the value they were given — from a release listing, a header, or
    /// a user — and never has to restate the algorithm separately.
    ///
    /// ```no_run
    /// # async fn example() -> std::io::Result<()> {
    /// use odl::hash::HashDigest;
    /// let expected = HashDigest::parse_cli("sha256:abc…").expect("a valid digest");
    /// if !HashDigest::verify_file("/tmp/thing.bin", &expected).await? {
    ///     eprintln!("that is not the file it claims to be");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn verify_file(
        path: impl AsRef<std::path::Path>,
        expected: &HashDigest,
    ) -> async_io::Result<bool> {
        let actual = Self::from_path(path, expected.algorithm(), expected.encoding()).await?;
        Ok(actual.matches(expected))
    }

    /// Hashes the contents of an async reader using the specified Digest type (async).
    ///
    /// `on_bytes` is called with the size of each block as it is hashed. It is
    /// `&mut dyn` rather than a generic so the one closure can be handed to
    /// whichever algorithm arm runs, and `Send` because the future holding it
    /// is routinely spawned.
    async fn hash_reader<D: Digest + Default + Unpin>(
        mut reader: impl AsyncRead + Unpin,
        on_bytes: &mut (dyn FnMut(u64) + Send),
    ) -> async_io::Result<D> {
        let mut hasher = D::default();
        // Heap rather than the stack: this buffer lives inside the returned
        // future, and a large array there would be copied around with it.
        let mut buf = vec![0u8; HASH_READ_BUFFER];
        loop {
            let n = reader.read(&mut buf).await?;
            if n == 0 {
                break;
            }
            hasher.update(&buf[..n]);
            on_bytes(n as u64);
        }
        Ok(hasher)
    }

    /// Compute a hash from an async reader using the specified algorithm and encoding (async).
    pub async fn from_reader_with_algorithm<R: AsyncRead + Unpin>(
        reader: R,
        algo: HashAlgorithm,
        encoding: HashEncoding,
    ) -> async_io::Result<HashDigest> {
        Self::from_reader_with_progress(reader, algo, encoding, |_| {}).await
    }

    /// As [`Self::from_reader_with_algorithm`], reporting progress as it goes.
    ///
    /// `on_bytes` receives the size of each block as it is hashed — a running
    /// delta, not a total. Hashing a large file takes long enough to look like
    /// a hang, and this is the only way a caller can show otherwise; nothing
    /// here knows about progress events, so the shape of the report stays the
    /// caller's decision.
    ///
    /// ```no_run
    /// # async fn example() -> std::io::Result<()> {
    /// use odl::hash::{HashAlgorithm, HashDigest, HashEncoding};
    /// let file = tokio::fs::File::open("/tmp/big.iso").await?;
    /// let mut hashed = 0u64;
    /// let digest = HashDigest::from_reader_with_progress(
    ///     file,
    ///     HashAlgorithm::SHA256,
    ///     HashEncoding::Hex,
    ///     |n| hashed += n,
    /// )
    /// .await?;
    /// println!("{digest:?} over {hashed} bytes");
    /// # Ok(())
    /// # }
    /// ```
    pub async fn from_reader_with_progress<R: AsyncRead + Unpin>(
        reader: R,
        algo: HashAlgorithm,
        encoding: HashEncoding,
        mut on_bytes: impl FnMut(u64) + Send,
    ) -> async_io::Result<HashDigest> {
        let on_bytes: &mut (dyn FnMut(u64) + Send) = &mut on_bytes;
        match algo {
            HashAlgorithm::MD5 => {
                let hasher = Self::hash_reader::<Md5>(reader, on_bytes).await?;
                let bytes = hasher.finalize();
                let s = match encoding {
                    HashEncoding::Hex => to_hex(&bytes),
                    HashEncoding::Base64 => general_purpose::STANDARD.encode(bytes),
                };
                Ok(HashDigest::MD5(s, encoding))
            }
            HashAlgorithm::SHA1 => {
                let hasher = Self::hash_reader::<Sha1>(reader, on_bytes).await?;
                let bytes = hasher.finalize();
                let s = match encoding {
                    HashEncoding::Hex => to_hex(&bytes),
                    HashEncoding::Base64 => general_purpose::STANDARD.encode(bytes),
                };
                Ok(HashDigest::SHA1(s, encoding))
            }
            HashAlgorithm::SHA256 => {
                let hasher = Self::hash_reader::<Sha256>(reader, on_bytes).await?;
                let bytes = hasher.finalize();
                let s = match encoding {
                    HashEncoding::Hex => to_hex(&bytes),
                    HashEncoding::Base64 => general_purpose::STANDARD.encode(bytes),
                };
                Ok(HashDigest::SHA256(s, encoding))
            }
            HashAlgorithm::SHA384 => {
                let hasher = Self::hash_reader::<Sha384>(reader, on_bytes).await?;
                let bytes = hasher.finalize();
                let s = match encoding {
                    HashEncoding::Hex => to_hex(&bytes),
                    HashEncoding::Base64 => general_purpose::STANDARD.encode(bytes),
                };
                Ok(HashDigest::SHA384(s, encoding))
            }
            HashAlgorithm::SHA512 => {
                let hasher = Self::hash_reader::<Sha512>(reader, on_bytes).await?;
                let bytes = hasher.finalize();
                let s = match encoding {
                    HashEncoding::Hex => to_hex(&bytes),
                    HashEncoding::Base64 => general_purpose::STANDARD.encode(bytes),
                };
                Ok(HashDigest::SHA512(s, encoding))
            }
        }
    }

    /// Parse a user-supplied checksum string into a `HashDigest`.
    ///
    /// Accepts `ALGO:DIGEST` (digest hex-encoded) or
    /// `ALGO:ENCODING:DIGEST`. `ALGO` is one of `md5`, `sha1`, `sha256`,
    /// `sha384`, `sha512`; `ENCODING` is `hex` (default) or `base64`.
    /// Hex digests are validated for length and lowercased so they match
    /// the lowercase hex produced during verification.
    pub fn parse_cli(s: &str) -> Result<HashDigest, String> {
        let parts: Vec<&str> = s.splitn(3, ':').collect();
        let (algo_str, encoding, digest) = match parts.as_slice() {
            [algo, digest] => (*algo, HashEncoding::Hex, (*digest).to_string()),
            [algo, enc, digest] => {
                let encoding = match enc.to_ascii_lowercase().as_str() {
                    "hex" => HashEncoding::Hex,
                    "base64" | "b64" => HashEncoding::Base64,
                    other => return Err(format!("unknown checksum encoding '{other}'")),
                };
                (*algo, encoding, (*digest).to_string())
            }
            _ => {
                return Err(format!(
                    "invalid checksum '{s}': expected ALGO:DIGEST or ALGO:ENCODING:DIGEST"
                ));
            }
        };

        let algo = match algo_str.to_ascii_lowercase().as_str() {
            "md5" => HashAlgorithm::MD5,
            "sha1" => HashAlgorithm::SHA1,
            "sha256" => HashAlgorithm::SHA256,
            "sha384" => HashAlgorithm::SHA384,
            "sha512" => HashAlgorithm::SHA512,
            other => return Err(format!("unknown checksum algorithm '{other}'")),
        };

        if digest.is_empty() {
            return Err(format!("invalid checksum '{s}': empty digest"));
        }

        let digest = match encoding {
            HashEncoding::Hex => {
                let expected_len = match algo {
                    HashAlgorithm::MD5 => 32,
                    HashAlgorithm::SHA1 => 40,
                    HashAlgorithm::SHA256 => 64,
                    HashAlgorithm::SHA384 => 96,
                    HashAlgorithm::SHA512 => 128,
                };
                if digest.len() != expected_len || !digest.bytes().all(|b| b.is_ascii_hexdigit()) {
                    return Err(format!(
                        "invalid {algo:?} hex digest: expected {expected_len} hex characters"
                    ));
                }
                digest.to_ascii_lowercase()
            }
            HashEncoding::Base64 => {
                let decoded = general_purpose::STANDARD
                    .decode(digest.as_bytes())
                    .map_err(|e| format!("invalid base64 digest: {e}"))?;
                let expected_bytes = match algo {
                    HashAlgorithm::MD5 => 16,
                    HashAlgorithm::SHA1 => 20,
                    HashAlgorithm::SHA256 => 32,
                    HashAlgorithm::SHA384 => 48,
                    HashAlgorithm::SHA512 => 64,
                };
                if decoded.len() != expected_bytes {
                    return Err(format!(
                        "invalid {algo:?} base64 digest: expected {expected_bytes} bytes, got {}",
                        decoded.len()
                    ));
                }
                digest
            }
        };

        Ok(match algo {
            HashAlgorithm::MD5 => HashDigest::MD5(digest, encoding),
            HashAlgorithm::SHA1 => HashDigest::SHA1(digest, encoding),
            HashAlgorithm::SHA256 => HashDigest::SHA256(digest, encoding),
            HashAlgorithm::SHA384 => HashDigest::SHA384(digest, encoding),
            HashAlgorithm::SHA512 => HashDigest::SHA512(digest, encoding),
        })
    }

    /// Compute a hash from an async reader using the algorithm implied by the HashDigest variant and encoding (async).
    pub async fn from_reader<R: AsyncRead + Unpin>(
        reader: R,
        hash_type: &HashDigest,
    ) -> async_io::Result<HashDigest> {
        let algo = HashAlgorithm::from(hash_type);
        let encoding = HashEncoding::from(hash_type);
        Self::from_reader_with_algorithm(reader, algo, encoding).await
    }
}

/// Supported hash algorithms for file/content checksums.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum HashAlgorithm {
    // Ordered from strongest to weakest.
    // We only check the strongest one from the ones available.
    SHA512,
    SHA384,
    SHA256,
    SHA1,
    MD5,
}

impl From<&HashDigest> for HashAlgorithm {
    fn from(hash_type: &HashDigest) -> Self {
        match hash_type {
            HashDigest::MD5(_, _) => HashAlgorithm::MD5,
            HashDigest::SHA1(_, _) => HashAlgorithm::SHA1,
            HashDigest::SHA256(_, _) => HashAlgorithm::SHA256,
            HashDigest::SHA384(_, _) => HashAlgorithm::SHA384,
            HashDigest::SHA512(_, _) => HashAlgorithm::SHA512,
        }
    }
}

impl From<&HashDigest> for HashEncoding {
    fn from(hash_type: &HashDigest) -> Self {
        match hash_type {
            HashDigest::MD5(_, encoding)
            | HashDigest::SHA1(_, encoding)
            | HashDigest::SHA256(_, encoding)
            | HashDigest::SHA384(_, encoding)
            | HashDigest::SHA512(_, encoding) => *encoding,
        }
    }
}
impl TryFrom<&FileChecksum> for HashDigest {
    type Error = &'static str;

    fn try_from(checksum: &FileChecksum) -> Result<Self, Self::Error> {
        let algo = match ChecksumAlgorithm::try_from(checksum.algorithm) {
            Ok(ChecksumAlgorithm::Sha512) => HashAlgorithm::SHA512,
            Ok(ChecksumAlgorithm::Sha384) => HashAlgorithm::SHA384,
            Ok(ChecksumAlgorithm::Sha256) => HashAlgorithm::SHA256,
            Ok(ChecksumAlgorithm::Sha1) => HashAlgorithm::SHA1,
            Ok(ChecksumAlgorithm::Md5) => HashAlgorithm::MD5,
            _ => return Err("Unknown checksum algorithm"),
        };

        let encoding = match ChecksumEncoding::try_from(checksum.encoding) {
            Ok(ChecksumEncoding::Hex) => HashEncoding::Hex,
            Ok(ChecksumEncoding::Base64) => HashEncoding::Base64,
            _ => return Err("Unknown checksum encoding"),
        };

        let digest = checksum.digest.clone();

        let hash_digest = match algo {
            HashAlgorithm::SHA512 => HashDigest::SHA512(digest, encoding),
            HashAlgorithm::SHA384 => HashDigest::SHA384(digest, encoding),
            HashAlgorithm::SHA256 => HashDigest::SHA256(digest, encoding),
            HashAlgorithm::SHA1 => HashDigest::SHA1(digest, encoding),
            HashAlgorithm::MD5 => HashDigest::MD5(digest, encoding),
        };

        Ok(hash_digest)
    }
}

impl TryFrom<FileChecksum> for HashDigest {
    type Error = &'static str;
    fn try_from(checksum: FileChecksum) -> Result<Self, Self::Error> {
        HashDigest::try_from(&checksum)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum HashEncoding {
    Hex,
    Base64,
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::io::BufReader as AsyncBufReader;

    async fn hash_hex_async(algo: HashAlgorithm, data: &[u8]) -> String {
        HashDigest::from_reader_with_algorithm(AsyncBufReader::new(data), algo, HashEncoding::Hex)
            .await
            .unwrap()
            .digest()
            .to_owned()
    }

    #[tokio::test]
    async fn test_md5_hex_async() {
        let data = b"hello world";
        let hash = hash_hex_async(HashAlgorithm::MD5, data).await;
        assert_eq!(hash, "5eb63bbbe01eeed093cb22bb8f5acdc3");
    }

    #[tokio::test]
    async fn test_sha1_hex_async() {
        let data = b"hello world";
        let hash = hash_hex_async(HashAlgorithm::SHA1, data).await;
        assert_eq!(hash, "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed");
    }

    #[tokio::test]
    async fn test_sha256_hex_async() {
        let data = b"hello world";
        let hash = hash_hex_async(HashAlgorithm::SHA256, data).await;
        assert_eq!(
            hash,
            "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
        );
    }

    #[tokio::test]
    async fn test_sha384_hex_async() {
        let data = b"hello world";
        let hash = hash_hex_async(HashAlgorithm::SHA384, data).await;
        assert_eq!(
            hash,
            "fdbd8e75a67f29f701a4e040385e2e23986303ea10239211af907fcbb83578b3e417cb71ce646efd0819dd8c088de1bd"
        );
    }

    #[tokio::test]
    async fn test_sha512_hex_async() {
        let data = b"hello world";
        let hash = hash_hex_async(HashAlgorithm::SHA512, data).await;
        assert_eq!(
            hash,
            "309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f"
        );
    }

    #[tokio::test]
    async fn test_md5_empty_async() {
        let data = b"";
        let hash = hash_hex_async(HashAlgorithm::MD5, data).await;
        assert_eq!(hash, "d41d8cd98f00b204e9800998ecf8427e");
    }

    #[test]
    fn parse_cli_hex_sha256_lowercases() {
        let d = HashDigest::parse_cli(
            "sha256:B94D27B9934D3E08A52E52D7DA7DABFAC484EFE37A5380EE9088F7ACE2EFCDE9",
        )
        .unwrap();
        assert_eq!(
            d,
            HashDigest::SHA256(
                "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9".to_string(),
                HashEncoding::Hex,
            )
        );
    }

    #[test]
    fn parse_cli_explicit_encoding_and_algos() {
        assert_eq!(
            HashDigest::parse_cli("md5:hex:5eb63bbbe01eeed093cb22bb8f5acdc3").unwrap(),
            HashDigest::MD5(
                "5eb63bbbe01eeed093cb22bb8f5acdc3".to_string(),
                HashEncoding::Hex
            )
        );
        assert_eq!(
            HashDigest::parse_cli("sha256:base64:uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek=")
                .unwrap(),
            HashDigest::SHA256(
                "uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek=".to_string(),
                HashEncoding::Base64,
            )
        );
    }

    #[test]
    fn parse_cli_rejects_bad_input() {
        assert!(HashDigest::parse_cli("sha256:nothex").is_err());
        assert!(HashDigest::parse_cli("sha256:abcd").is_err()); // wrong length
        assert!(HashDigest::parse_cli("bogus:deadbeef").is_err());
        assert!(HashDigest::parse_cli("sha256").is_err());
        assert!(HashDigest::parse_cli("sha256:").is_err());
        assert!(HashDigest::parse_cli("sha256:rot13:deadbeef").is_err());
    }

    #[tokio::test]
    async fn test_sha256_base64_async() {
        let data = b"hello world";
        let digest = HashDigest::from_reader_with_algorithm(
            AsyncBufReader::new(&data[..]),
            HashAlgorithm::SHA256,
            HashEncoding::Base64,
        )
        .await
        .unwrap();
        match digest {
            HashDigest::SHA256(s, HashEncoding::Base64) => {
                assert_eq!(s, "uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek=");
            }
            _ => panic!("Unexpected digest variant"),
        }
    }

    #[tokio::test]
    async fn a_file_can_be_hashed_by_path() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("payload");
        tokio::fs::write(&path, b"hello world").await.unwrap();

        let digest = HashDigest::from_path(&path, HashAlgorithm::SHA256, HashEncoding::Hex)
            .await
            .unwrap();
        assert_eq!(
            digest.digest(),
            "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
        );
        assert_eq!(digest.algorithm(), HashAlgorithm::SHA256);
        assert_eq!(digest.encoding(), HashEncoding::Hex);
    }

    #[tokio::test]
    async fn verifying_a_file_uses_the_expectation_s_own_algorithm() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("payload");
        tokio::fs::write(&path, b"hello world").await.unwrap();

        let expected = HashDigest::parse_cli(
            "sha256:b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9",
        )
        .unwrap();
        assert!(HashDigest::verify_file(&path, &expected).await.unwrap());

        let wrong = HashDigest::parse_cli(&format!("sha256:{}", "00".repeat(32))).unwrap();
        assert!(!HashDigest::verify_file(&path, &wrong).await.unwrap());
    }

    #[test]
    fn the_same_hash_written_two_ways_still_matches() {
        // A server may send base64 where a config file holds hex. Comparing
        // the text would call those different and fail a good download.
        let hex = HashDigest::SHA256(
            "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9".to_owned(),
            HashEncoding::Hex,
        );
        let b64 = HashDigest::SHA256(
            "uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek=".to_owned(),
            HashEncoding::Base64,
        );
        assert!(hex.matches(&b64));
        assert!(b64.matches(&hex));
        assert_ne!(hex, b64, "`==` still compares the written form");

        // Hex casing is not meaningful.
        let upper = HashDigest::SHA256(hex.digest().to_uppercase(), HashEncoding::Hex);
        assert!(hex.matches(&upper));
    }

    #[test]
    fn a_different_algorithm_never_matches() {
        let a = HashDigest::SHA256("aa".repeat(32), HashEncoding::Hex);
        let b = HashDigest::SHA512("aa".repeat(32), HashEncoding::Hex);
        assert!(!a.matches(&b));
    }

    #[test]
    fn an_undecodable_digest_asserts_nothing() {
        // Treating garbage as a match would turn a malformed value into a
        // passing check, which is the opposite of what a checksum is for.
        let broken = HashDigest::SHA256("not-hex!!".to_owned(), HashEncoding::Hex);
        let real = HashDigest::SHA256(
            "uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek=".to_owned(),
            HashEncoding::Base64,
        );
        assert!(!broken.matches(&real));
        assert!(broken.raw_bytes().is_none());
    }
}