-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathhash.rs
More file actions
111 lines (92 loc) · 2.17 KB
/
hash.rs
File metadata and controls
111 lines (92 loc) · 2.17 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
use super::*;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Hash(blake3::Hash);
impl Hash {
pub(crate) const LEN: usize = blake3::OUT_LEN;
pub(crate) fn as_bytes(&self) -> &[u8; Self::LEN] {
self.0.as_bytes()
}
#[cfg(test)]
pub(crate) fn bytes(input: &[u8]) -> Self {
Self(blake3::hash(input))
}
}
impl From<blake3::Hash> for Hash {
fn from(hash: blake3::Hash) -> Self {
Self(hash)
}
}
impl From<Hash> for [u8; Hash::LEN] {
fn from(hash: Hash) -> Self {
hash.0.into()
}
}
impl From<[u8; Hash::LEN]> for Hash {
fn from(bytes: [u8; Hash::LEN]) -> Self {
Self(bytes.into())
}
}
impl FromStr for Hash {
type Err = blake3::HexError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(s.parse()?))
}
}
impl Ord for Hash {
fn cmp(&self, other: &Self) -> Ordering {
self.as_bytes().cmp(other.as_bytes())
}
}
impl PartialOrd for Hash {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Serialize for Hash {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.0.to_string().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Hash {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::{Error, Unexpected};
let s = String::deserialize(deserializer)?;
Ok(Self(s.parse::<blake3::Hash>().map_err(|_| {
D::Error::invalid_value(Unexpected::Str(&s), &"64 hex digits")
})?))
}
}
impl Display for Hash {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serde() {
let input = Hash::bytes(&[]);
let json = serde_json::to_string(&input).unwrap();
assert_eq!(
json,
"\"af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262\""
);
assert_eq!(serde_json::from_str::<Hash>(&json).unwrap(), input);
}
#[test]
fn deserialize_error_format() {
assert_eq!(
serde_json::from_str::<Hash>("\"foo\"")
.unwrap_err()
.to_string(),
r#"invalid value: string "foo", expected 64 hex digits"#,
);
}
}