sapphire_framework_sync/
hash.rs1use std::fmt;
4use std::io::Read;
5use std::path::Path;
6use std::str::FromStr;
7
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9use sha2::{Digest, Sha256};
10
11#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
13pub struct ContentHash(pub [u8; 32]);
14
15#[derive(Debug, thiserror::Error)]
17#[error("invalid content hash")]
18pub struct ParseHashError;
19
20impl ContentHash {
21 pub fn of_bytes(bytes: &[u8]) -> Self {
22 Self(Sha256::digest(bytes).into())
23 }
24
25 pub fn of_file(path: &Path) -> std::io::Result<Self> {
26 let mut file = std::fs::File::open(path)?;
27 let mut hasher = ContentHasher::new();
28 let mut buf = vec![0u8; 64 * 1024];
29 loop {
30 let n = file.read(&mut buf)?;
31 if n == 0 {
32 break;
33 }
34 hasher.update(&buf[..n]);
35 }
36 Ok(hasher.finish())
37 }
38
39 pub fn to_hex(&self) -> String {
40 self.0.iter().map(|b| format!("{b:02x}")).collect()
41 }
42}
43
44#[derive(Clone, Default)]
46pub struct ContentHasher(Sha256);
47
48impl ContentHasher {
49 pub fn new() -> Self {
50 Self::default()
51 }
52
53 pub fn update(&mut self, bytes: &[u8]) {
55 self.0.update(bytes);
56 }
57
58 pub fn finish(self) -> ContentHash {
60 ContentHash(self.0.finalize().into())
61 }
62}
63
64impl fmt::Display for ContentHash {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 f.write_str(&self.to_hex())
67 }
68}
69
70impl fmt::Debug for ContentHash {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 write!(f, "ContentHash({})", self.to_hex())
73 }
74}
75
76impl FromStr for ContentHash {
77 type Err = ParseHashError;
78
79 fn from_str(s: &str) -> Result<Self, Self::Err> {
80 if s.len() != 64 {
81 return Err(ParseHashError);
82 }
83 let mut out = [0u8; 32];
84 for (i, byte) in out.iter_mut().enumerate() {
85 let pair = s.get(2 * i..2 * i + 2).ok_or(ParseHashError)?;
86 *byte = u8::from_str_radix(pair, 16).map_err(|_| ParseHashError)?;
87 }
88 Ok(Self(out))
89 }
90}
91
92impl Serialize for ContentHash {
93 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
94 serializer.serialize_str(&self.to_hex())
95 }
96}
97
98impl<'de> Deserialize<'de> for ContentHash {
99 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
100 let s = String::deserialize(deserializer)?;
101 s.parse().map_err(serde::de::Error::custom)
102 }
103}
104
105#[cfg(test)]
106mod tests {
107 use super::*;
108
109 #[test]
110 fn known_sha256() {
111 assert_eq!(
112 ContentHash::of_bytes(b"abc").to_hex(),
113 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
114 );
115 }
116
117 #[test]
118 fn file_hash_matches_bytes_hash() {
119 let dir = tempfile::tempdir().unwrap();
120 let path = dir.path().join("f");
121 let data = vec![7u8; 200_000];
122 std::fs::write(&path, &data).unwrap();
123 assert_eq!(
124 ContentHash::of_file(&path).unwrap(),
125 ContentHash::of_bytes(&data)
126 );
127 }
128
129 #[test]
130 fn hex_round_trips_through_serde() {
131 let h = ContentHash::of_bytes(b"x");
132 let json = serde_json::to_string(&h).unwrap();
133 assert_eq!(json, format!("\"{}\"", h.to_hex()));
134 assert_eq!(serde_json::from_str::<ContentHash>(&json).unwrap(), h);
135 assert!("zz".parse::<ContentHash>().is_err());
136 }
137}