raiden_primitives/types/
numeric.rs1#![warn(clippy::missing_docs_in_private_items)]
2
3use std::{
4 ops::{
5 Add,
6 Mul,
7 Sub,
8 },
9 str::FromStr,
10};
11
12use derive_more::Display;
13use web3::types::{
14 U256,
15 U64 as PrimitiveU64,
16};
17
18#[derive(
20 Default, Copy, Clone, Display, Debug, derive_more::Deref, Eq, Ord, PartialEq, PartialOrd, Hash,
21)]
22pub struct U64(PrimitiveU64);
23
24impl U64 {
25 pub fn zero() -> Self {
27 Self(PrimitiveU64::zero())
28 }
29
30 pub fn as_bytes(&self) -> Vec<u8> {
32 let mut bytes: [u8; 8] = [0; 8];
33 self.0.to_big_endian(&mut bytes);
34 bytes.to_vec()
35 }
36
37 pub fn to_be_bytes(&self) -> Vec<u8> {
39 let bytes = self.as_bytes();
40 let mut padded_bytes: [u8; 32] = [0; 32];
41 padded_bytes[24..].copy_from_slice(&bytes);
42 padded_bytes.to_vec()
43 }
44}
45
46impl From<PrimitiveU64> for U64 {
47 fn from(n: PrimitiveU64) -> Self {
48 Self(n)
49 }
50}
51
52impl From<U64> for PrimitiveU64 {
53 fn from(n: U64) -> Self {
54 n.0
55 }
56}
57
58impl FromStr for U64 {
59 type Err = ();
60
61 fn from_str(s: &str) -> Result<Self, Self::Err> {
62 if let Ok(num) = PrimitiveU64::from_dec_str(s) {
63 return Ok(U64(num))
64 }
65 let num = PrimitiveU64::from_str(s).map_err(|_| ())?;
66 Ok(U64(num))
67 }
68}
69
70impl Add<U64> for U64 {
71 type Output = U64;
72
73 fn add(self, rhs: U64) -> Self::Output {
74 U64::from(self.0 + rhs.0)
75 }
76}
77
78impl Sub<U64> for U64 {
79 type Output = U64;
80
81 fn sub(self, rhs: U64) -> Self::Output {
82 U64::from(self.0 - rhs.0)
83 }
84}
85
86impl Mul<U64> for U64 {
87 type Output = U64;
88
89 fn mul(self, rhs: U64) -> Self::Output {
90 U64::from(self.0 * rhs.0)
91 }
92}
93
94impl Mul<u64> for U64 {
95 type Output = U64;
96
97 fn mul(self, rhs: u64) -> Self::Output {
98 U64::from(self.0 * rhs)
99 }
100}
101
102impl From<U64> for U256 {
103 fn from(num: U64) -> Self {
104 num.0.low_u64().into()
105 }
106}
107
108impl From<u64> for U64 {
109 fn from(n: u64) -> Self {
110 Self(n.into())
111 }
112}
113
114impl From<u32> for U64 {
115 fn from(n: u32) -> Self {
116 Self((n as u64).into())
117 }
118}
119
120impl From<i32> for U64 {
121 fn from(n: i32) -> Self {
122 Self((n as u64).into())
123 }
124}