use serde::{Deserialize, Serialize};
use sha2::Digest;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TypedDigest {
pub algorithm: String,
pub value: String,
}
impl TypedDigest {
#[must_use]
pub fn sha256(data: &[u8]) -> Self {
let hash = sha2::Sha256::digest(data);
Self {
algorithm: "sha256".into(),
value: hex::encode(hash),
}
}
#[must_use]
pub fn iscc(code: &[u8]) -> Self {
Self {
algorithm: "iscc".into(),
value: hex::encode(code),
}
}
#[must_use]
pub fn local_fingerprint(data: &[u8]) -> Self {
Self {
algorithm: "local".into(),
value: hex::encode(data),
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
let (algorithm, value) = s.split_once(':')?;
if algorithm.is_empty() || value.is_empty() {
return None;
}
Some(Self {
algorithm: algorithm.to_string(),
value: value.to_string(),
})
}
#[must_use]
pub fn to_string_value(&self) -> String {
format!("{}:{}", self.algorithm, self.value)
}
}