ccp_shared/types/
difficulty.rs

1/*
2 * Copyright 2024 Fluence DAO
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use std::str::FromStr;
18
19use hex::FromHex;
20use hex::ToHex;
21use serde_with::DeserializeFromStr;
22use serde_with::SerializeDisplay;
23
24use crate::RANDOMX_RESULT_SIZE;
25
26pub type DifficultyInner = [u8; RANDOMX_RESULT_SIZE];
27
28#[derive(Copy, Clone, Hash, PartialEq, Eq, SerializeDisplay, DeserializeFromStr, Default)]
29#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
30#[repr(transparent)]
31pub struct Difficulty(DifficultyInner);
32
33impl Difficulty {
34    pub const fn new(inner: DifficultyInner) -> Self {
35        Self(inner)
36    }
37}
38
39impl AsRef<DifficultyInner> for Difficulty {
40    fn as_ref(&self) -> &DifficultyInner {
41        &self.0
42    }
43}
44
45impl FromHex for Difficulty {
46    type Error = <DifficultyInner as FromHex>::Error;
47
48    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
49        DifficultyInner::from_hex(hex).map(Self)
50    }
51}
52
53impl PartialEq<Difficulty> for DifficultyInner {
54    fn eq(&self, other: &Difficulty) -> bool {
55        self.eq(&other.0)
56    }
57}
58
59impl PartialOrd<Difficulty> for DifficultyInner {
60    fn partial_cmp(&self, other: &Difficulty) -> Option<std::cmp::Ordering> {
61        self.partial_cmp(&other.0)
62    }
63}
64
65impl ToHex for Difficulty {
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 Difficulty {
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 Difficulty {
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 Difficulty {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        f.debug_tuple("Difficulty")
94            .field(&self.to_string())
95            .finish()
96    }
97}