use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ChecksumAlgorithm {
Md5,
Sha256,
}
impl std::fmt::Display for ChecksumAlgorithm {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ChecksumAlgorithm::Md5 => write!(f, "MD5"),
ChecksumAlgorithm::Sha256 => write!(f, "SHA256"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExpectedChecksum {
pub algorithm: ChecksumAlgorithm,
pub value: String,
}
impl ExpectedChecksum {
pub fn md5(hex_value: impl Into<String>) -> Self {
Self {
algorithm: ChecksumAlgorithm::Md5,
value: hex_value.into().to_lowercase(),
}
}
pub fn sha256(hex_value: impl Into<String>) -> Self {
Self {
algorithm: ChecksumAlgorithm::Sha256,
value: hex_value.into().to_lowercase(),
}
}
pub fn parse(s: &str) -> Option<Self> {
let (algo, hash) = s.split_once(':')?;
let algorithm = match algo.to_lowercase().as_str() {
"md5" => ChecksumAlgorithm::Md5,
"sha256" | "sha-256" => ChecksumAlgorithm::Sha256,
_ => return None,
};
Some(Self {
algorithm,
value: hash.to_lowercase(),
})
}
}