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
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use hex::{FromHex, FromHexError, ToHex as _};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::ops::Deref;
use std::str;
use thiserror::Error;

mod iter;
pub use iter::*;

/// The size of a hash in bytes.
pub const HASH_SIZE: usize = 32;

/// A 32 byte hash.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Hash([u8; HASH_SIZE]);

impl Hash {
    /// Obtain a slice of the bytes representing the hash.
    pub fn as_bytes(&self) -> &[u8] {
        &self.0[..]
    }

    pub const fn from_array(arr: [u8; HASH_SIZE]) -> Self {
        Self(arr)
    }
}

impl str::FromStr for Hash {
    type Err = ParseHashError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(FromHex::from_hex(s)?))
    }
}

impl<'de> Deserialize<'de> for Hash {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        str::FromStr::from_str(&s).map_err(serde::de::Error::custom)
    }
}

impl From<[u8; HASH_SIZE]> for Hash {
    fn from(bytes: [u8; HASH_SIZE]) -> Self {
        Hash(bytes)
    }
}

impl From<Hash> for [u8; HASH_SIZE] {
    fn from(hash: Hash) -> Self {
        hash.0
    }
}

impl TryFrom<&[u8]> for Hash {
    type Error = std::array::TryFromSliceError;

    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        Ok(Self(bytes.try_into()?))
    }
}

impl TryFrom<&str> for Hash {
    type Error = ParseHashError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        Ok(Self(FromHex::from_hex(s)?))
    }
}

impl TryFrom<String> for Hash {
    type Error = ParseHashError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::try_from(s.as_str())
    }
}

impl From<Hash> for String {
    fn from(h: Hash) -> Self {
        hex::encode(&h.0)
    }
}

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

impl Serialize for Hash {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl fmt::Debug for Hash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Hash").field(&self.to_string()).finish()
    }
}

impl Deref for Hash {
    type Target = [u8; HASH_SIZE];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// An error encountered while parsing a [`Hash`].
#[derive(Copy, Clone, Debug, Error, PartialEq)]
pub struct ParseHashError(FromHexError);

impl fmt::Display for ParseHashError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            FromHexError::InvalidStringLength => {
                write!(f, "{}, expected {} hex encoded bytes", self.0, HASH_SIZE)
            }
            _ => write!(f, "{}", self.0),
        }
    }
}

impl From<FromHexError> for ParseHashError {
    fn from(e: FromHexError) -> Self {
        ParseHashError(e)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;
    use std::str::FromStr;

    proptest! {
        #[test]
        fn test_from_str_display(ref s in "[[:xdigit:]]{64}") {
            let hash = Hash::from_str(s).unwrap();
            let display = format!("{hash}");
            prop_assert_eq!(s.to_ascii_lowercase(), display);
        }

        #[test]
        fn test_rejects_odd_length_strings(ref s in "[[:xdigit:]][[:xdigit:]]{2}{0,128}") {
            prop_assert_eq!(Err(FromHexError::OddLength.into()), Hash::from_str(s));
        }

        #[test]
        fn test_rejects_incorrect_byte_count(ref s in "[[:xdigit:]]{2}{0,128}") {
            prop_assume!(s.len() != HASH_SIZE * 2);
            prop_assert_eq!(Err(FromHexError::InvalidStringLength.into()), Hash::from_str(s));
        }
    }
}