finality_grandpa/
weights.rs1use crate::std::{
18 cmp::Ordering,
19 fmt,
20 num::NonZeroU64,
21 ops::{Add, Sub},
22};
23
24#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
26pub struct VoteWeight(pub u64);
27
28impl fmt::Display for VoteWeight {
29 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
30 write!(f, "{}", self.0)
31 }
32}
33
34impl Add for VoteWeight {
35 type Output = Self;
36
37 fn add(self, rhs: Self) -> Self {
38 VoteWeight(self.0.saturating_add(rhs.0))
39 }
40}
41
42impl Add<VoterWeight> for VoteWeight {
43 type Output = Self;
44
45 fn add(self, rhs: VoterWeight) -> Self {
46 VoteWeight(self.0.saturating_add(rhs.0.get()))
47 }
48}
49
50impl Sub for VoteWeight {
51 type Output = Self;
52
53 fn sub(self, rhs: Self) -> Self {
54 VoteWeight(self.0.saturating_sub(rhs.0))
55 }
56}
57
58impl Sub<VoterWeight> for VoteWeight {
59 type Output = Self;
60
61 fn sub(self, rhs: VoterWeight) -> Self {
62 self - VoteWeight(rhs.get())
63 }
64}
65
66impl PartialEq<VoterWeight> for VoteWeight {
67 fn eq(&self, other: &VoterWeight) -> bool {
68 self.0 == other.get()
69 }
70}
71
72impl PartialOrd<VoterWeight> for VoteWeight {
73 fn partial_cmp(&self, other: &VoterWeight) -> Option<Ordering> {
74 Some(self.0.cmp(&other.0.get()))
75 }
76}
77
78impl From<u64> for VoteWeight {
79 fn from(weight: u64) -> Self {
80 VoteWeight(weight)
81 }
82}
83
84#[derive(PartialEq, Eq, Copy, Clone, Debug)]
88pub struct VoterWeight(pub NonZeroU64);
89
90impl fmt::Display for VoterWeight {
91 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92 write!(f, "{}", self.0)
93 }
94}
95
96impl VoterWeight {
97 pub fn new(weight: u64) -> Option<Self> {
98 NonZeroU64::new(weight).map(Self)
99 }
100
101 pub fn get(self) -> u64 {
102 self.0.get()
103 }
104}
105
106impl Sub<VoteWeight> for VoterWeight {
107 type Output = VoteWeight;
108
109 fn sub(self, rhs: VoteWeight) -> VoteWeight {
110 VoteWeight(self.0.get()) - rhs
111 }
112}
113
114impl Sub<VoterWeight> for VoterWeight {
115 type Output = VoteWeight;
116
117 fn sub(self, rhs: VoterWeight) -> VoteWeight {
118 VoteWeight(self.0.get()) - VoteWeight(rhs.get())
119 }
120}
121
122#[cfg(feature = "std")]
123impl std::convert::TryFrom<u64> for VoterWeight {
124 type Error = &'static str;
125
126 fn try_from(weight: u64) -> Result<Self, Self::Error> {
127 VoterWeight::new(weight).ok_or("VoterWeight only takes non-zero values.")
128 }
129}