1use crate::error::{OakError, Result};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum HashKind {
9 Blake3,
11 GitSha1,
13 GitSha256,
16 Unknown,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq, Hash)]
24pub struct Hash(pub String);
25
26impl Hash {
27 pub fn from_hex(hex: &str) -> Result<Self> {
32 let len_ok = hex.len() == 40 || hex.len() == 64;
33 let chars_ok = hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
34 if !len_ok || !chars_ok {
35 return Err(OakError::InvalidHash(hex.to_string()));
36 }
37 Ok(Hash(hex.to_string()))
38 }
39
40 pub fn as_str(&self) -> &str {
42 &self.0
43 }
44
45 pub fn short(&self) -> &str {
47 let end = self
48 .0
49 .char_indices()
50 .map(|(idx, _)| idx)
51 .nth(12)
52 .unwrap_or(self.0.len());
53 &self.0[..end]
54 }
55
56 pub fn kind(&self) -> HashKind {
61 match self.0.len() {
62 40 => HashKind::GitSha1,
63 64 => HashKind::Blake3,
64 _ => HashKind::Unknown,
65 }
66 }
67}
68
69impl std::fmt::Display for Hash {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 write!(f, "{}", self.0)
72 }
73}
74
75impl serde::Serialize for Hash {
76 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
77 where
78 S: serde::Serializer,
79 {
80 serializer.serialize_str(&self.0)
81 }
82}
83
84impl<'de> serde::Deserialize<'de> for Hash {
85 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
91 where
92 D: serde::Deserializer<'de>,
93 {
94 let s = String::deserialize(deserializer)?;
95 Hash::from_hex(&s).map_err(serde::de::Error::custom)
96 }
97}
98
99pub fn hash_bytes(data: &[u8]) -> Hash {
101 let hash = blake3::hash(data);
102 Hash(hash.to_hex().to_string())
103}
104
105pub fn hash_string(s: &str) -> Hash {
107 hash_bytes(s.as_bytes())
108}
109
110#[cfg(test)]
111mod tests {
112 use super::*;
113
114 #[test]
115 fn test_hash_determinism() {
116 let data = b"hello world";
117 let hash1 = hash_bytes(data);
118 let hash2 = hash_bytes(data);
119 assert_eq!(hash1, hash2);
120 }
121
122 #[test]
123 fn test_hash_different_inputs() {
124 let hash1 = hash_bytes(b"hello");
125 let hash2 = hash_bytes(b"world");
126 assert_ne!(hash1, hash2);
127 }
128
129 #[test]
130 fn test_hash_length() {
131 let hash = hash_bytes(b"test");
132 assert_eq!(hash.as_str().len(), 64);
133 }
134
135 #[test]
136 fn test_hash_from_hex_blake3() {
137 let valid_hex = "a".repeat(64);
138 let h = Hash::from_hex(&valid_hex).unwrap();
139 assert_eq!(h.kind(), HashKind::Blake3);
140 }
141
142 #[test]
143 fn test_hash_from_hex_git_sha1() {
144 let valid_hex = "a".repeat(40);
145 let h = Hash::from_hex(&valid_hex).unwrap();
146 assert_eq!(h.kind(), HashKind::GitSha1);
147 }
148
149 #[test]
150 fn test_hash_from_hex_invalid_length() {
151 assert!(Hash::from_hex("abc").is_err());
152 assert!(Hash::from_hex(&"a".repeat(50)).is_err());
153 }
154
155 #[test]
156 fn test_hash_from_hex_invalid_chars() {
157 let invalid_hex = "g".repeat(64);
158 assert!(Hash::from_hex(&invalid_hex).is_err());
159 }
160
161 #[test]
162 fn test_hash_short() {
163 let hash = hash_bytes(b"test");
164 assert_eq!(hash.short().len(), 12);
165 }
166
167 #[test]
168 fn test_hash_short_handles_non_ascii_without_panicking() {
169 let hash = Hash("é".repeat(20));
170 assert_eq!(hash.short(), "éééééééééééé");
171 }
172
173 #[test]
174 fn test_hash_kind_reports_unknown_length() {
175 assert_eq!(Hash("abc".to_string()).kind(), HashKind::Unknown);
176 }
177
178 #[test]
179 fn test_hash_from_hex_rejects_uppercase() {
180 assert!(Hash::from_hex(&"A".repeat(64)).is_err());
181 assert!(Hash::from_hex(&format!("{}F", "a".repeat(63))).is_err());
182 }
183
184 #[test]
185 fn test_deserialize_valid_hex() {
186 let blake3 = format!("\"{}\"", "a".repeat(64));
187 let h: Hash = serde_json::from_str(&blake3).unwrap();
188 assert_eq!(h.kind(), HashKind::Blake3);
189
190 let sha1 = format!("\"{}\"", "0123456789abcdef0123".repeat(2));
191 let h: Hash = serde_json::from_str(&sha1).unwrap();
192 assert_eq!(h.kind(), HashKind::GitSha1);
193
194 let original = hash_bytes(b"round trip");
196 let json = serde_json::to_string(&original).unwrap();
197 let back: Hash = serde_json::from_str(&json).unwrap();
198 assert_eq!(original, back);
199 }
200
201 #[test]
202 fn test_deserialize_rejects_junk() {
203 let cases = [
204 "\"\"".to_string(),
205 "\"not a hash\"".to_string(),
206 format!("\"{}\"", "a".repeat(63)), format!("\"{}\"", "a".repeat(65)), format!("\"{}\"", "A".repeat(64)), format!("\"{}\"", "g".repeat(64)), format!("\"{}\\t{}\"", "a".repeat(31), "a".repeat(32)), format!("\"{}\\n{}\"", "a".repeat(31), "a".repeat(32)), ];
213 for json in cases {
214 assert!(
215 serde_json::from_str::<Hash>(&json).is_err(),
216 "should reject {json}"
217 );
218 }
219 }
220}