1use core::fmt;
4use core::hash::{Hash, Hasher};
5use core::marker::PhantomData;
6use core::str::FromStr;
7
8use icedwright_types::Frame;
9use serde::{Deserialize, Deserializer, Serialize, Serializer};
10
11use crate::error::TraceError;
12
13#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub struct BlobHash([u8; 32]);
16
17impl BlobHash {
18 #[must_use]
20 pub fn of(bytes: &[u8]) -> Self {
21 Self(*blake3::hash(bytes).as_bytes())
22 }
23}
24
25impl fmt::Display for BlobHash {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
28 }
29}
30
31impl fmt::Debug for BlobHash {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 write!(f, "BlobHash({self})")
34 }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
39#[error("{0:?} is not 64 lowercase hex digits")]
40pub struct BadBlobHash(String);
41
42impl FromStr for BlobHash {
43 type Err = BadBlobHash;
44
45 fn from_str(text: &str) -> Result<Self, BadBlobHash> {
46 let bad = || BadBlobHash(text.to_owned());
47 if text.len() != 64 {
48 return Err(bad());
49 }
50 let mut bytes = [0u8; 32];
51 let (pairs, _) = text.as_bytes().as_chunks::<2>();
52 for (byte, pair) in bytes.iter_mut().zip(pairs) {
53 let digits = core::str::from_utf8(pair).map_err(|_| bad())?;
54 if digits.bytes().any(|d| d.is_ascii_uppercase()) {
55 return Err(bad());
56 }
57 *byte = u8::from_str_radix(digits, 16).map_err(|_| bad())?;
58 }
59 Ok(Self(bytes))
60 }
61}
62
63impl Serialize for BlobHash {
64 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
65 serializer.collect_str(self)
66 }
67}
68
69impl<'de> Deserialize<'de> for BlobHash {
70 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
71 let text = String::deserialize(deserializer)?;
72 text.parse().map_err(serde::de::Error::custom)
73 }
74}
75
76mod sealed {
77 pub trait Sealed {}
78}
79
80pub trait Media: sealed::Sealed {
82 const EXTENSION: &'static str;
84}
85
86#[derive(Debug)]
88pub enum Yaml {}
89
90impl sealed::Sealed for Yaml {}
91impl Media for Yaml {
92 const EXTENSION: &'static str = "yaml";
93}
94
95impl sealed::Sealed for Png {}
96impl Media for Png {
97 const EXTENSION: &'static str = "png";
98}
99
100pub struct BlobRef<M: Media> {
103 pub hash: BlobHash,
105 media: PhantomData<fn() -> M>,
106}
107
108impl<M: Media> BlobRef<M> {
109 pub(crate) fn new(hash: BlobHash) -> Self {
110 Self {
111 hash,
112 media: PhantomData,
113 }
114 }
115
116 #[must_use]
118 pub fn member(&self) -> String {
119 member_name::<M>(self.hash)
120 }
121}
122
123pub(crate) fn member_name<M: Media>(hash: BlobHash) -> String {
124 format!("blobs/{hash}.{}", M::EXTENSION)
125}
126
127impl<M: Media> Clone for BlobRef<M> {
128 fn clone(&self) -> Self {
129 *self
130 }
131}
132
133impl<M: Media> Copy for BlobRef<M> {}
134
135impl<M: Media> PartialEq for BlobRef<M> {
136 fn eq(&self, other: &Self) -> bool {
137 self.hash == other.hash
138 }
139}
140
141impl<M: Media> Eq for BlobRef<M> {}
142
143impl<M: Media> PartialOrd for BlobRef<M> {
144 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
145 Some(self.cmp(other))
146 }
147}
148
149impl<M: Media> Ord for BlobRef<M> {
150 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
151 self.hash.cmp(&other.hash)
152 }
153}
154
155impl<M: Media> Hash for BlobRef<M> {
156 fn hash<H: Hasher>(&self, state: &mut H) {
157 self.hash.hash(state);
158 }
159}
160
161impl<M: Media> fmt::Debug for BlobRef<M> {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 write!(f, "BlobRef({})", self.member())
164 }
165}
166
167impl<M: Media> Serialize for BlobRef<M> {
168 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
169 self.hash.serialize(serializer)
170 }
171}
172
173impl<'de, M: Media> Deserialize<'de> for BlobRef<M> {
174 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
175 BlobHash::deserialize(deserializer).map(Self::new)
176 }
177}
178
179#[derive(Clone, PartialEq, Eq)]
181pub struct Png(Vec<u8>);
182
183const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
184
185impl Png {
186 pub fn encode(frame: &Frame) -> Result<Png, TraceError> {
189 let size = frame.size().get();
190 let mut bytes = Vec::new();
191 let mut encoder = png::Encoder::new(&mut bytes, size.width, size.height);
192 encoder.set_color(png::ColorType::Rgba);
193 encoder.set_depth(png::BitDepth::Eight);
194 encoder.set_compression(png::Compression::Balanced);
195 encoder.set_filter(png::Filter::Adaptive);
196 let mut writer = encoder
197 .write_header()
198 .map_err(|e| TraceError::Png(e.to_string()))?;
199 writer
200 .write_image_data(frame.rgba())
201 .map_err(|e| TraceError::Png(e.to_string()))?;
202 writer
203 .finish()
204 .map_err(|e| TraceError::Png(e.to_string()))?;
205 Ok(Png(bytes))
206 }
207
208 pub fn from_bytes(bytes: Vec<u8>) -> Result<Png, TraceError> {
210 if !bytes.starts_with(PNG_SIGNATURE) {
211 return Err(TraceError::Png("the PNG signature is missing".to_owned()));
212 }
213 Ok(Png(bytes))
214 }
215
216 #[must_use]
218 pub fn as_bytes(&self) -> &[u8] {
219 &self.0
220 }
221
222 #[must_use]
224 pub fn into_bytes(self) -> Vec<u8> {
225 self.0
226 }
227
228 #[must_use]
230 pub fn len(&self) -> usize {
231 self.0.len()
232 }
233
234 #[must_use]
236 pub fn is_empty(&self) -> bool {
237 self.0.is_empty()
238 }
239}
240
241impl fmt::Debug for Png {
243 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244 write!(f, "Png({} bytes)", self.0.len())
245 }
246}
247
248#[cfg(test)]
249mod tests {
250 use super::*;
251 use icedwright_types::{ScaleFactor, Size, units::Physical};
252
253 #[test]
254 fn hashes_print_and_parse_as_hex() -> Result<(), BadBlobHash> {
255 let hash = BlobHash::of(b"tree");
256 let text = hash.to_string();
257 assert_eq!(text.len(), 64);
258 assert_eq!(text.parse::<BlobHash>()?, hash);
259 assert!("abc".parse::<BlobHash>().is_err());
260 assert!(text.to_uppercase().parse::<BlobHash>().is_err());
261 assert!("zz".repeat(32).parse::<BlobHash>().is_err());
262 Ok(())
263 }
264
265 #[test]
266 fn refs_serialise_as_their_hash() -> Result<(), serde_json::Error> {
267 let tree = BlobRef::<Yaml>::new(BlobHash::of(b"a"));
268 let json = serde_json::to_string(&tree)?;
269 assert_eq!(json, format!("\"{}\"", tree.hash));
270 assert_eq!(serde_json::from_str::<BlobRef<Yaml>>(&json)?, tree);
271 assert_eq!(tree.member(), format!("blobs/{}.yaml", tree.hash));
272 let frame = BlobRef::<Png>::new(tree.hash);
273 assert_eq!(frame.member(), format!("blobs/{}.png", tree.hash));
274 Ok(())
275 }
276
277 #[test]
278 fn encoding_is_stable() -> Result<(), Box<dyn std::error::Error>> {
279 let rgba = (0..64u8).flat_map(|i| [i, 255 - i, i / 2, 255]).collect();
280 let frame = Frame::new(rgba, Physical::new(Size::new(8, 8)), ScaleFactor::ONE)?;
281 let first = Png::encode(&frame)?;
282 let second = Png::encode(&frame)?;
283 assert_eq!(first, second);
284 assert!(first.as_bytes().starts_with(PNG_SIGNATURE));
285 assert_eq!(Png::from_bytes(first.clone().into_bytes())?, first);
286 assert!(!first.is_empty());
287 Ok(())
288 }
289
290 #[test]
291 fn non_png_bytes_are_refused() {
292 let error = Png::from_bytes(b"GIF89a".to_vec())
293 .err()
294 .map(|e| e.to_string());
295 assert_eq!(
296 error.as_deref(),
297 Some("not a PNG: the PNG signature is missing")
298 );
299 }
300}