ccp_shared/types/
result_hash.rs1use std::str::FromStr;
18
19use hex::FromHex;
20use hex::ToHex;
21use serde_with::DeserializeFromStr;
22use serde_with::SerializeDisplay;
23
24pub const RANDOMX_RESULT_SIZE: usize = 32;
25
26pub type ResultHashInner = [u8; RANDOMX_RESULT_SIZE];
27
28#[derive(
29 Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, SerializeDisplay, DeserializeFromStr,
30)]
31#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
32#[repr(transparent)]
33pub struct ResultHash(ResultHashInner);
34
35impl ResultHash {
36 pub const fn from_slice(hash: ResultHashInner) -> Self {
37 Self(hash)
38 }
39
40 pub const fn into_slice(self) -> ResultHashInner {
41 self.0
42 }
43}
44
45impl AsRef<ResultHashInner> for ResultHash {
46 fn as_ref(&self) -> &ResultHashInner {
47 &self.0
48 }
49}
50
51impl AsMut<ResultHashInner> for ResultHash {
52 fn as_mut(&mut self) -> &mut ResultHashInner {
53 &mut self.0
54 }
55}
56
57impl FromHex for ResultHash {
58 type Error = <[u8; 32] as FromHex>::Error;
59
60 fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
61 ResultHashInner::from_hex(hex).map(Self)
62 }
63}
64
65impl ToHex for ResultHash {
66 fn encode_hex<T: std::iter::FromIterator<char>>(&self) -> T {
67 ToHex::encode_hex(&self.0)
68 }
69
70 fn encode_hex_upper<T: std::iter::FromIterator<char>>(&self) -> T {
71 ToHex::encode_hex_upper(&self.0)
72 }
73}
74
75impl FromStr for ResultHash {
76 type Err = hex::FromHexError;
77
78 fn from_str(s: &str) -> Result<Self, Self::Err> {
79 FromHex::from_hex(s)
80 }
81}
82
83use std::fmt;
84
85impl fmt::Display for ResultHash {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 f.write_str(&self.encode_hex::<String>())
88 }
89}
90
91impl fmt::Debug for ResultHash {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 f.debug_tuple("ResultHash")
94 .field(&self.to_string())
95 .finish()
96 }
97}