summaryrefslogtreecommitdiffstats
path: root/crates/rebel-common/src/string_hash.rs
blob: a2b00dbbc15de70be2d9542997dfdc79b16a78e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use std::fmt::Display;

use serde::{Deserialize, Serialize};

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct StringHash(pub [u8; 32]);

impl Display for StringHash {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.write_str(&hex::encode(self.0))
	}
}

impl std::fmt::Debug for StringHash {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "\"{}\"", self)
	}
}

impl Serialize for StringHash {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: serde::Serializer,
	{
		hex::serialize(self.0, serializer)
	}
}
impl<'de> Deserialize<'de> for StringHash {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: serde::Deserializer<'de>,
	{
		Ok(StringHash(hex::deserialize(deserializer)?))
	}
}

macro_rules! stringhash_newtype {
	($id:ident) => {
		#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
		pub struct $id(pub StringHash);

		impl Display for $id {
			fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
				self.0.fmt(f)
			}
		}
	};
}

stringhash_newtype!(InputHash);
stringhash_newtype!(DependencyHash);
stringhash_newtype!(LayerHash);
stringhash_newtype!(ArchiveHash);