gitoid 0.9.0

Git Object Identifiers in Rust
Documentation
//! Trait specifying valid [`GitOid`] hash algorithms.

use crate::sealed::Sealed;
use core::{fmt::Debug, hash::Hash, ops::Deref};
use digest::{block_buffer::generic_array::GenericArray, Digest, OutputSizeUser};

#[cfg(doc)]
use crate::GitOid;

/// 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;
}

#[doc(hidden)]
#[macro_export]
#[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()
            }
        }
    };
}