Skip to content

Make HashAlgo more idiomatic #19

Description

@rusty1968

https://github.com/AspeedTech-BMC/aspeed-rust/blob/2e04396ebab3db4d7b122cc8296efcf058505b8c/src/hash.rs#L199

Your methods can be const - const fn methods are evaluated at compile time.
#[derive(Copy, Clone)]
pub enum HashAlgo {
SHA1,
SHA224,
SHA256,
SHA384,
SHA512,
SHA512_224,
SHA512_256,
}

impl HashAlgo {
pub const fn digest_size(&self) -> usize {
match self {
HashAlgo::SHA1 => 20,
HashAlgo::SHA224 | HashAlgo::SHA512_224 => 28,
HashAlgo::SHA256 | HashAlgo::SHA512_256 => 32,
HashAlgo::SHA384 => 48,
HashAlgo::SHA512 => 64,
}
}

pub const fn block_size(&self) -> usize {
    match self {
        HashAlgo::SHA1 | HashAlgo::SHA224 | HashAlgo::SHA256 => 64,
        HashAlgo::SHA384 | HashAlgo::SHA512 | HashAlgo::SHA512_224 | HashAlgo::SHA512_256 => 128,
    }
}

pub const fn bitmask(&self) -> u32 {
    match self {
        HashAlgo::SHA1 => HACE_ALGO_SHA1,
        HashAlgo::SHA224 => HACE_ALGO_SHA224,
        HashAlgo::SHA256 => HACE_ALGO_SHA256,
        HashAlgo::SHA512 => HACE_ALGO_SHA512,
        HashAlgo::SHA384 => HACE_ALGO_SHA384,
        HashAlgo::SHA512_224 => HACE_ALGO_SHA512_224,
        HashAlgo::SHA512_256 => HACE_ALGO_SHA512_256,
    }
}

pub const fn iv(&self) -> &'static [u32] {
    match self {
        HashAlgo::SHA1 => &SHA1_IV,
        HashAlgo::SHA224 => &SHA224_IV,
        HashAlgo::SHA256 => &SHA256_IV,
        HashAlgo::SHA384 => &SHA384_IV,
        HashAlgo::SHA512 => &SHA512_IV,
        HashAlgo::SHA512_224 => &SHA512_224_IV,
        HashAlgo::SHA512_256 => &SHA512_256_IV,
    }
}

pub const fn iv_size(&self) -> usize {
    match self {
        HashAlgo::SHA1 => SHA1_IV.len(),
        HashAlgo::SHA224 => SHA224_IV.len(),
        HashAlgo::SHA256 => SHA256_IV.len(),
        HashAlgo::SHA384 => SHA384_IV.len(),
        HashAlgo::SHA512 => SHA512_IV.len(),
        HashAlgo::SHA512_224 => SHA512_224_IV.len(),
        HashAlgo::SHA512_256 => SHA512_256_IV.len(),
    }
}

pub const fn hash_cmd(&self) -> u32 {
    const COMMON_FLAGS: u32 = HACE_CMD_ACC_MODE | HACE_SHA_BE_EN | HACE_SG_EN;
    COMMON_FLAGS | self.bitmask()
}

}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions