1use std::fmt;
4use std::io::Read;
5use std::path::Path;
6use std::str::FromStr;
7
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9use sha2::{Digest as _, Sha256};
10
11use crate::error::{Result, VisionError};
12
13#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
32pub struct Digest([u8; 32]);
33
34impl Digest {
35 pub fn of(bytes: &[u8]) -> Self {
37 Self(Sha256::digest(bytes).into())
38 }
39
40 pub fn of_json<T: Serialize>(value: &T) -> Self {
45 let value = serde_json::to_value(value).unwrap_or(serde_json::Value::Null);
46 Self::of(canonical_json(&value).as_bytes())
47 }
48
49 pub fn of_file(path: &Path) -> Result<(Self, u64)> {
55 let mut file =
56 std::fs::File::open(path).map_err(|e| VisionError::io("could not open", path, e))?;
57 let mut hasher = Sha256::new();
58 let mut buffer = vec![0u8; 1 << 20];
59 let mut size = 0u64;
60 loop {
61 let read =
62 file.read(&mut buffer).map_err(|e| VisionError::io("could not read", path, e))?;
63 if read == 0 {
64 break;
65 }
66 size += read as u64;
67 hasher.update(&buffer[..read]);
68 }
69 Ok((Self(hasher.finalize().into()), size))
70 }
71
72 pub fn from_hex(hex_digits: &str) -> Result<Self> {
78 let digits = hex_digits.strip_prefix("sha256:").unwrap_or(hex_digits);
79 if digits.len() != 64 || !digits.bytes().all(|b| b.is_ascii_hexdigit()) {
80 return Err(VisionError::InvalidInput(format!(
81 "`{hex_digits}` is not a SHA-256 digest; expected `sha256:` and 64 hex digits"
82 )));
83 }
84 let mut bytes = [0u8; 32];
85 hex::decode_to_slice(digits.to_ascii_lowercase(), &mut bytes)
86 .map_err(|e| VisionError::InvalidInput(format!("`{hex_digits}`: {e}")))?;
87 Ok(Self(bytes))
88 }
89
90 pub fn hex(&self) -> String {
92 hex::encode(self.0)
93 }
94
95 pub fn as_bytes(&self) -> &[u8; 32] {
97 &self.0
98 }
99}
100
101impl fmt::Display for Digest {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 write!(f, "sha256:{}", self.hex())
104 }
105}
106
107impl fmt::Debug for Digest {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 write!(f, "Digest({self})")
110 }
111}
112
113impl FromStr for Digest {
114 type Err = VisionError;
115
116 fn from_str(s: &str) -> Result<Self> {
117 if !s.starts_with("sha256:") {
118 return Err(VisionError::InvalidInput(format!(
119 "`{s}` is not a digest; expected `sha256:` and 64 hex digits"
120 )));
121 }
122 Self::from_hex(s)
123 }
124}
125
126impl Serialize for Digest {
127 fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
128 serializer.collect_str(self)
129 }
130}
131
132impl<'de> Deserialize<'de> for Digest {
133 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
134 let text = String::deserialize(deserializer)?;
135 text.parse().map_err(serde::de::Error::custom)
136 }
137}
138
139pub(crate) fn canonical_json(value: &serde_json::Value) -> String {
141 match value {
142 serde_json::Value::Object(map) => {
143 let mut keys: Vec<&String> = map.keys().collect();
144 keys.sort();
145 let fields: Vec<String> = keys
146 .into_iter()
147 .map(|key| {
148 let name = serde_json::Value::String(key.clone()).to_string();
149 format!("{name}:{}", canonical_json(&map[key]))
150 })
151 .collect();
152 format!("{{{}}}", fields.join(","))
153 }
154 serde_json::Value::Array(items) => {
155 let items: Vec<String> = items.iter().map(canonical_json).collect();
156 format!("[{}]", items.join(","))
157 }
158 other => other.to_string(),
159 }
160}
161
162#[cfg(test)]
163mod tests {
164 use super::*;
165
166 #[test]
167 fn json_digests_ignore_key_order() {
168 let a = serde_json::json!({"b": 1, "a": [1, {"y": 2, "x": 1}]});
169 let b = serde_json::json!({"a": [1, {"x": 1, "y": 2}], "b": 1});
170 assert_eq!(Digest::of_json(&a), Digest::of_json(&b));
171 assert_eq!(canonical_json(&a), r#"{"a":[1,{"x":1,"y":2}],"b":1}"#);
172 }
173
174 #[test]
175 fn upper_case_hex_parses_to_the_same_digest() {
176 let digest = Digest::of(b"x");
177 let upper = format!("sha256:{}", digest.hex().to_uppercase());
178 assert_eq!(upper.parse::<Digest>().unwrap(), digest);
179 assert!(Digest::from_hex("abc").is_err());
180 }
181
182 #[test]
183 fn files_hash_like_bytes() {
184 let dir = tempfile::tempdir().unwrap();
185 let path = dir.path().join("f");
186 std::fs::write(&path, b"hello").unwrap();
187 assert_eq!(Digest::of_file(&path).unwrap(), (Digest::of(b"hello"), 5));
188 }
189}