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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
use digest::generic_array::GenericArray;
use serde::de::{Error, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;

use std::fmt;

use crate::{ByteVisitor, VisitBytes};

use super::{Output, SupportedDigest};

#[derive(Default, PartialOrd, Ord)]
pub struct Hash<D: SupportedDigest> {
    pub(crate) digest: Output<D>,
}

struct HashVisitor<D: SupportedDigest> {
    digest: D,
}

impl<D> HashVisitor<D>
where
    D: SupportedDigest,
{
    fn new() -> Self {
        HashVisitor { digest: D::new() }
    }

    fn finalize(self) -> Hash<D> {
        Hash {
            digest: self.digest.finalize(),
        }
    }
}

impl<D: SupportedDigest> ByteVisitor for HashVisitor<D> {
    fn visit_bytes(&mut self, bytes: impl AsRef<[u8]>) {
        self.digest.update(bytes)
    }
}

impl<D: SupportedDigest> Hash<D> {
    pub fn of(content: impl VisitBytes) -> Self {
        let mut visitor = HashVisitor::new();
        content.visit(&mut visitor);
        visitor.finalize()
    }

    pub fn bytes(&self) -> &[u8] {
        self.digest.as_slice()
    }

    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        self.bytes().len()
    }

    pub fn bit_len(&self) -> usize {
        self.bytes().len() * 8
    }
}

impl<D: SupportedDigest> VisitBytes for Hash<D> {
    fn visit<BV: ?Sized + ByteVisitor>(&self, visitor: &mut BV) {
        visitor.visit_bytes(self.bytes())
    }
}

impl<D: SupportedDigest> std::hash::Hash for Hash<D> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.digest.hash(state);
    }
}

// Derived clone does not have precise enough bounds and type info.
impl<D: SupportedDigest> Clone for Hash<D> {
    fn clone(&self) -> Self {
        Self {
            digest: self.digest.clone(),
        }
    }
}

impl<D: SupportedDigest> Eq for Hash<D> {}
impl<D: SupportedDigest> PartialEq for Hash<D> {
    fn eq(&self, other: &Self) -> bool {
        self.digest == other.digest
    }
}

impl<D: SupportedDigest> fmt::Display for Hash<D> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "{}:{}",
            D::ALGORITHM,
            hex::encode(self.digest.as_slice())
        )
    }
}

impl<D: SupportedDigest> fmt::Debug for Hash<D> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "Hash<{:?}>({})",
            D::ALGORITHM,
            hex::encode(self.digest.as_slice())
        )
    }
}

impl<D: SupportedDigest> From<Output<D>> for Hash<D> {
    fn from(value: Output<D>) -> Self {
        Hash { digest: value }
    }
}

impl<D: SupportedDigest> TryFrom<Vec<u8>> for Hash<D> {
    type Error = IncorrectLengthError;

    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
        let hash = Hash {
            digest: GenericArray::from_exact_iter(value.into_iter()).ok_or(IncorrectLengthError)?,
        };
        Ok(hash)
    }
}

#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[error("the provided vector was not the correct length")]
pub struct IncorrectLengthError;

impl<D: SupportedDigest> Serialize for Hash<D> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_bytes(&self.digest)
    }
}

impl<'de, T: SupportedDigest> Deserialize<'de> for Hash<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct CopyVisitor<T>(T);

        impl<T: AsRef<[u8]> + AsMut<[u8]>> From<T> for CopyVisitor<T> {
            fn from(buffer: T) -> Self {
                Self(buffer)
            }
        }

        impl<'a, T: AsRef<[u8]> + AsMut<[u8]>> Visitor<'a> for CopyVisitor<T> {
            type Value = T;

            fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                formatter.write_fmt(format_args!("{} bytes", self.0.as_ref().len()))
            }

            fn visit_byte_buf<E: Error>(self, v: Vec<u8>) -> Result<Self::Value, E> {
                self.visit_bytes(&v)
            }

            fn visit_borrowed_bytes<E: Error>(self, v: &'a [u8]) -> Result<Self::Value, E> {
                self.visit_bytes(v)
            }

            fn visit_bytes<E: Error>(mut self, v: &[u8]) -> Result<Self::Value, E> {
                if v.len() != self.0.as_mut().len() {
                    return Err(E::custom("invalid length"));
                }

                self.0.as_mut().copy_from_slice(v);
                Ok(self.0)
            }
        }

        let buffer = Output::<T>::default();
        let visitor = CopyVisitor::from(buffer);
        Ok(Self {
            digest: deserializer.deserialize_bytes(visitor)?,
        })
    }
}

#[cfg(test)]
mod tests {
    use sha2::Sha256;

    use super::*;

    #[test]
    fn test_hash_empties_have_no_impact() {
        let empty: &[u8] = &[];

        let h0: Hash<Sha256> = Hash::of((0u8, 1u8));
        let h1: Hash<Sha256> = Hash::of((0u8, 1u8, empty));
        let h2: Hash<Sha256> = Hash::of((0u8, empty, 1u8));
        let h3: Hash<Sha256> = Hash::of((0u8, empty, 1u8, empty));
        let h4: Hash<Sha256> = Hash::of((empty, 0u8, 1u8));
        let h5: Hash<Sha256> = Hash::of((empty, 0u8, 1u8, empty));
        let h6: Hash<Sha256> = Hash::of((empty, 0u8, empty, 1u8));
        let h7: Hash<Sha256> = Hash::of((empty, 0u8, empty, 1u8, empty));

        assert_eq!(h0, h1);
        assert_eq!(h0, h2);
        assert_eq!(h0, h3);
        assert_eq!(h0, h4);
        assert_eq!(h0, h5);
        assert_eq!(h0, h6);
        assert_eq!(h0, h7);
    }
}