use rhash_rs as rhash;
use super::{Result, Error, error};
use std::str::FromStr;
use std::fmt::{self, Display};
#[cfg(feature = "serde")]
use serde::{Serialize, Deserialize};
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Hash
{
Sha256,
Sha512,
Sha3256,
Sha3512,
Blake2b,
Blake2s,
Blake3,
Crc32,
#[default]
Crc32c
}
impl Display for Hash
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
{
write!(f, "{}", match self
{
Self::Sha256 => "sha256",
Self::Sha512 => "sha512",
Self::Sha3256 => "sha3-256",
Self::Sha3512 => "sha3-512",
Self::Blake2b => "blake2b",
Self::Blake2s => "blake2s",
Self::Blake3 => "blake3",
Self::Crc32 => "crc32",
Self::Crc32c => "crc32c"
})
}
}
impl FromStr for Hash
{
type Err = Error;
fn from_str(s: &str) -> Result<Self>
{
match s.to_ascii_lowercase().replace("_", "-").as_str()
{
"sha256"|"sha-256" => Ok(Self::Sha256),
"sha512"|"sha-512" => Ok(Self::Sha512),
"sha3256"|"sha3-256" => Ok(Self::Sha3256),
"sha3512"|"sha3-512" => Ok(Self::Sha3512),
"blake2b"|"blake2"|"b2"|"b2b" => Ok(Self::Blake2b),
"blake2s"|"b2s" => Ok(Self::Blake2s),
"blake3"|"b3" => Ok(Self::Blake3),
"crc32" => Ok(Self::Crc32),
"crc32c" => Ok(Self::Crc32c),
s => error!("unknown hash algorithm '{s}'")
}
}
}
impl From<Hash> for rhash::Hash
{
fn from(h: Hash) -> Self
{
match h
{
Hash::Sha256 => Self::SHA256,
Hash::Sha512 => Self::SHA512,
Hash::Sha3256 => Self::SHA3_256,
Hash::Sha3512 => Self::SHA3_512,
Hash::Blake2b => Self::BLAKE2B,
Hash::Blake2s => Self::BLAKE2S,
Hash::Blake3 => Self::BLAKE3,
Hash::Crc32 => Self::CRC32,
Hash::Crc32c => Self::CRC32C
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(rename_all = "kebab-case"))]
pub struct Checksum
{
pub algo: Hash,
pub hash: String
}
impl Checksum
{
pub fn new<S>(algo: Hash, hash: S) -> Self
where S: Into<String>
{
Self { hash: hash.into(), algo }
}
}
impl FromStr for Checksum
{
type Err = Error;
fn from_str(input: &str) -> Result<Self>
{
if let Some(parts) = input.split_once(':')
{
Ok(Self::new(Hash::from_str(parts.0)?, parts.1))
}
else
{
error!("Missing ':' separator in checksum notation. Got '{input}'")
}
}
}
impl Display for Checksum
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
{
write!(f, "{}={}", &self.algo, &self.hash)
}
}