stratum_server/types/
difficulty.rs

1#![allow(clippy::cast_sign_loss)]
2#![allow(clippy::cast_precision_loss)]
3#![allow(clippy::cast_possible_truncation)]
4
5use std::ops::Deref;
6
7const MAX_DIFF: u64 = 9_223_372_036_854_775_808;
8
9#[derive(Clone, Debug, Copy)]
10pub struct Difficulty(u64);
11
12impl Difficulty {
13    #[must_use]
14    pub fn zero() -> Self {
15        Difficulty(0)
16    }
17
18    #[must_use]
19    pub fn is_zero(self) -> bool {
20        self.0 == 0
21    }
22
23    #[must_use]
24    pub fn as_u64(self) -> u64 {
25        self.0
26    }
27
28    #[must_use]
29    pub fn log2(&self) -> u8 {
30        self.0.ilog2() as u8
31    }
32}
33
34impl Deref for Difficulty {
35    type Target = u64;
36
37    fn deref(&self) -> &Self::Target {
38        &self.0
39    }
40}
41
42impl From<u64> for Difficulty {
43    fn from(value: u64) -> Self {
44        Difficulty(format_difficulty(value))
45    }
46}
47
48#[must_use]
49fn format_difficulty(diff: u64) -> u64 {
50    if diff >= MAX_DIFF {
51        return MAX_DIFF;
52    }
53
54    let mut new_diff: u64 = 1;
55    let mut i = 0;
56    while new_diff < diff {
57        new_diff <<= 1;
58        i += 1;
59    }
60    assert!(i <= 63);
61    1_u64 << i
62}
63
64#[cfg(test)]
65mod test {
66    use super::*;
67
68    #[test]
69    fn test_difficulty_log2() {
70        for i in 1..64 {
71            assert_eq!(Difficulty::from(2u64.pow(i)).log2(), i as u8);
72        }
73    }
74}