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
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.

// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Parity Ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Parity Ethereum.  If not, see <http://www.gnu.org/licenses/>.

use super::Error;
use rustc_hex::{FromHex, ToHex};
use serde::{
    de::{Error as SerdeError, Visitor},
    Deserialize, Deserializer, Serialize, Serializer,
};
use std::{cmp::Ordering, fmt, ops, str};

macro_rules! impl_hash {
    ($name:ident, $size:expr) => {
        pub struct $name([u8; $size]);

        impl $name {
            pub fn at(&self, idx: usize) -> u8 {
                assert!(idx < $size);
                self.0[idx]
            }
        }

        impl fmt::Debug for $name {
            fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
                let self_ref: &[u8] = &self.0;
                write!(f, "{:?}", self_ref)
            }
        }

        impl PartialEq for $name {
            fn eq(&self, other: &Self) -> bool {
                let self_ref: &[u8] = &self.0;
                let other_ref: &[u8] = &other.0;
                self_ref == other_ref
            }
        }

        impl ops::Deref for $name {
            type Target = [u8];

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

        impl Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where S: Serializer {
                serializer.serialize_str(&self.0.to_hex::<String>())
            }
        }

        impl<'a> Deserialize<'a> for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where D: Deserializer<'a> {
                struct HashVisitor;

                impl<'b> Visitor<'b> for HashVisitor {
                    type Value = $name;

                    fn expecting(
                        &self, formatter: &mut fmt::Formatter,
                    ) -> fmt::Result {
                        write!(formatter, "a hex-encoded {}", stringify!($name))
                    }

                    fn visit_str<E>(
                        self, value: &str,
                    ) -> Result<Self::Value, E>
                    where E: SerdeError {
                        value.parse().map_err(SerdeError::custom)
                    }

                    fn visit_string<E>(
                        self, value: String,
                    ) -> Result<Self::Value, E>
                    where E: SerdeError {
                        self.visit_str(value.as_ref())
                    }
                }

                deserializer.deserialize_any(HashVisitor)
            }
        }

        impl str::FromStr for $name {
            type Err = Error;

            fn from_str(value: &str) -> Result<Self, Self::Err> {
                match value.from_hex::<Vec<u8>>() {
                    Ok(ref hex) if hex.len() == $size => {
                        let mut hash = [0u8; $size];
                        hash.clone_from_slice(hex);
                        Ok($name(hash))
                    }
                    _ => Err(Error::InvalidH256),
                }
            }
        }

        impl From<&'static str> for $name {
            fn from(s: &'static str) -> Self {
                s.parse().expect(&format!(
                    "invalid string literal for {}: '{}'",
                    stringify!($name),
                    s
                ))
            }
        }

        impl From<[u8; $size]> for $name {
            fn from(bytes: [u8; $size]) -> Self { $name(bytes) }
        }

        impl Into<[u8; $size]> for $name {
            fn into(self) -> [u8; $size] { self.0 }
        }
    };
}

impl_hash!(H128, 16);
impl_hash!(H160, 20);
impl_hash!(H256, 32);

// FIXME: find a better hash type.
impl PartialOrd for H160 {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Eq for H160 {}

impl Ord for H160 {
    fn cmp(&self, other: &Self) -> Ordering { self.0.cmp(&other.0) }
}