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
//! Trait specifying valid [`GitOid`] hash algorithms.

use crate::sealed::Sealed;
#[cfg(doc)]
use crate::GitOid;
use core::fmt::Debug;
use core::hash::Hash;
use core::ops::Deref;
use digest::block_buffer::generic_array::GenericArray;
use digest::Digest;
use digest::OutputSizeUser;

/// Hash algorithms that can be used to make a [`GitOid`].
///
/// This is a sealed trait to ensure it's only used for hash
/// algorithms which are actually supported by Git.
///
/// For more information on sealed traits, read Predrag
/// Gruevski's ["A Definitive Guide to Sealed Traits in Rust"][1].
///
/// [1]: https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/
pub trait HashAlgorithm: Sealed {
    /// The name of the hash algorithm in lowercase ASCII.
    #[doc(hidden)]
    const NAME: &'static str;

    /// The actual digest type used by the algorithm.
    #[doc(hidden)]
    type Alg: Digest;

    /// The array type generated by the hash.
    #[doc(hidden)]
    type Array: Copy + PartialEq + Ord + Hash + Debug + Deref<Target = [u8]>;

    /// Helper function to convert the GenericArray type to Self::Array
    #[doc(hidden)]
    fn array_from_generic(
        arr: GenericArray<u8, <Self::Alg as OutputSizeUser>::OutputSize>,
    ) -> Self::Array;

    /// Get an instance of the digester.
    #[doc(hidden)]
    fn new() -> Self::Alg;
}

#[allow(unused_macros)]
macro_rules! impl_hash_algorithm {
    ( $type:ident, $alg_ty:ty, $name:literal ) => {
        impl Sealed for $type {}

        impl HashAlgorithm for $type {
            const NAME: &'static str = $name;

            type Alg = $alg_ty;

            type Array = GenericArray<u8, <Self::Alg as OutputSizeUser>::OutputSize>;

            fn array_from_generic(
                arr: GenericArray<u8, <Self::Alg as OutputSizeUser>::OutputSize>,
            ) -> Self::Array {
                arr
            }

            fn new() -> Self::Alg {
                Self::Alg::new()
            }
        }
    };
}

#[cfg(feature = "sha1")]
/// SHA-1 algorithm,
pub struct Sha1 {
    #[doc(hidden)]
    _private: (),
}

#[cfg(feature = "sha1")]
impl_hash_algorithm!(Sha1, sha1::Sha1, "sha1");

#[cfg(feature = "sha256")]
/// SHA-256 algorithm.
pub struct Sha256 {
    #[doc(hidden)]
    _private: (),
}

#[cfg(feature = "sha256")]
impl_hash_algorithm!(Sha256, sha2::Sha256, "sha256");

#[cfg(feature = "sha1cd")]
/// SHA-1Cd (collision detection) algorithm.
pub struct Sha1Cd {
    #[doc(hidden)]
    _private: (),
}

#[cfg(feature = "sha1cd")]
impl_hash_algorithm!(Sha1Cd, sha1collisiondetection::Sha1CD, "sha1cd");