Skip to main content

cloudillo_types/
hasher.rs

1//! Hasher format for content-addressing. Capable of handling multiple versions and object variants.
2
3use base64::Engine;
4use sha2::{Digest, Sha256};
5
6pub enum Hasher {
7	V1(Sha256),
8}
9
10impl Default for Hasher {
11	fn default() -> Self {
12		Self::new()
13	}
14}
15
16impl Hasher {
17	pub fn new() -> Self {
18		Self::V1(Sha256::new())
19	}
20
21	pub fn new_v1() -> Self {
22		Self::V1(Sha256::new())
23	}
24
25	pub fn update(&mut self, data: &[u8]) {
26		match self {
27			Self::V1(hasher) => hasher.update(data),
28		}
29	}
30
31	pub fn finalize(self, prefix: &str) -> String {
32		match self {
33			//Self::V2(hasher) => "2.".to_string() + &base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(hasher.finalize())
34			Self::V1(hasher) => {
35				prefix.to_string()
36					+ "1~" + &base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(hasher.finalize())
37			}
38		}
39	}
40}
41
42pub fn hash_v1(prefix: &str, data: &[u8]) -> Box<str> {
43	let mut hasher = Hasher::new();
44	hasher.update(data);
45	let result = hasher.finalize(prefix);
46
47	result.into()
48}
49
50pub fn hash(prefix: &str, data: &[u8]) -> Box<str> {
51	hash_v1(prefix, data)
52}
53
54// vim: ts=4