Skip to main content

runmat_package/identity/
digest.rs

1use crate::IdentityError;
2use serde::{Deserialize, Serialize};
3use sha2::{Digest as _, Sha256};
4use std::fmt::{Display, Formatter};
5use std::str::FromStr;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
8#[serde(rename_all = "lowercase")]
9pub enum DigestAlgorithm {
10    Sha256,
11}
12
13impl DigestAlgorithm {
14    pub const fn label(self) -> &'static str {
15        match self {
16            Self::Sha256 => "sha256",
17        }
18    }
19}
20
21#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
22pub struct ContentDigest {
23    algorithm: DigestAlgorithm,
24    bytes: [u8; 32],
25}
26
27impl ContentDigest {
28    pub fn sha256(bytes: impl AsRef<[u8]>) -> Self {
29        let digest = Sha256::digest(bytes.as_ref());
30        let mut result = [0_u8; 32];
31        result.copy_from_slice(&digest);
32        Self {
33            algorithm: DigestAlgorithm::Sha256,
34            bytes: result,
35        }
36    }
37
38    pub const fn algorithm(&self) -> DigestAlgorithm {
39        self.algorithm
40    }
41
42    pub const fn bytes(&self) -> &[u8; 32] {
43        &self.bytes
44    }
45}
46
47impl Display for ContentDigest {
48    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
49        write!(formatter, "{}:", self.algorithm.label())?;
50        for byte in self.bytes {
51            write!(formatter, "{byte:02x}")?;
52        }
53        Ok(())
54    }
55}
56
57impl FromStr for ContentDigest {
58    type Err = IdentityError;
59
60    fn from_str(value: &str) -> Result<Self, Self::Err> {
61        let Some((algorithm, encoded)) = value.split_once(':') else {
62            return Err(invalid_digest(value, "missing algorithm label"));
63        };
64        if algorithm != DigestAlgorithm::Sha256.label() {
65            return Err(invalid_digest(value, "unsupported digest algorithm"));
66        }
67        if encoded.len() != 64 {
68            return Err(invalid_digest(
69                value,
70                "SHA-256 must contain exactly 64 lowercase hexadecimal digits",
71            ));
72        }
73        if encoded
74            .bytes()
75            .any(|byte| !byte.is_ascii_hexdigit() || byte.is_ascii_uppercase())
76        {
77            return Err(invalid_digest(
78                value,
79                "digest bytes must use lowercase hexadecimal",
80            ));
81        }
82        let mut bytes = [0_u8; 32];
83        for (index, slot) in bytes.iter_mut().enumerate() {
84            *slot = u8::from_str_radix(&encoded[index * 2..index * 2 + 2], 16)
85                .map_err(|_| invalid_digest(value, "invalid hexadecimal digest"))?;
86        }
87        Ok(Self {
88            algorithm: DigestAlgorithm::Sha256,
89            bytes,
90        })
91    }
92}
93
94impl Serialize for ContentDigest {
95    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
96    where
97        S: serde::Serializer,
98    {
99        serializer.serialize_str(&self.to_string())
100    }
101}
102
103impl<'de> Deserialize<'de> for ContentDigest {
104    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
105    where
106        D: serde::Deserializer<'de>,
107    {
108        String::deserialize(deserializer)?
109            .parse()
110            .map_err(serde::de::Error::custom)
111    }
112}
113
114fn invalid_digest(value: &str, reason: &'static str) -> IdentityError {
115    IdentityError::InvalidDigest {
116        value: value.to_string(),
117        reason,
118    }
119}