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
// Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0

use serde::{de::Error as _, Deserialize, Deserializer, Serialize, Serializer};
use std::{fmt, str::FromStr};

#[derive(Clone, Debug, PartialEq, Copy)]
pub struct HashValue(aptos_crypto::hash::HashValue);

impl From<aptos_crypto::hash::HashValue> for HashValue {
    fn from(val: aptos_crypto::hash::HashValue) -> Self {
        Self(val)
    }
}

impl From<HashValue> for aptos_crypto::hash::HashValue {
    fn from(val: HashValue) -> Self {
        val.0
    }
}

impl FromStr for HashValue {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> anyhow::Result<Self, anyhow::Error> {
        if let Some(hex) = s.strip_prefix("0x") {
            Ok(hex.parse::<aptos_crypto::hash::HashValue>()?.into())
        } else {
            Ok(s.parse::<aptos_crypto::hash::HashValue>()?.into())
        }
    }
}

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

impl<'de> Deserialize<'de> for HashValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let hash = <String>::deserialize(deserializer)?;
        hash.parse().map_err(D::Error::custom)
    }
}

impl fmt::Display for HashValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:#x}", self.0)
    }
}

#[cfg(test)]
mod tests {
    use crate::hash::HashValue;

    use serde_json::{json, Value};

    #[test]
    fn test_from_and_to_string() {
        let hash = "0xb78e1ba6fa7f7b3a3f3ac2a31e6675d84f2261c711c3b438a252f648b26df3ed";
        assert_eq!(hash.parse::<HashValue>().unwrap().to_string(), hash);

        let hash_without_prefix =
            "b78e1ba6fa7f7b3a3f3ac2a31e6675d84f2261c711c3b438a252f648b26df3ed";
        assert_eq!(
            hash_without_prefix
                .parse::<HashValue>()
                .unwrap()
                .to_string(),
            hash
        );
    }

    #[test]
    fn test_from_and_to_json() {
        let hex = "0xb78e1ba6fa7f7b3a3f3ac2a31e6675d84f2261c711c3b438a252f648b26df3ed";
        let hash: HashValue = serde_json::from_value(json!(hex)).unwrap();
        assert_eq!(hash, hex.parse().unwrap());

        let val: Value = serde_json::to_value(hash).unwrap();
        assert_eq!(val, json!(hex));
    }
}