forked from Angry-Penguins-Colony/mx-rust-utilities
-
Notifications
You must be signed in to change notification settings - Fork 0
/
u64_utils.rs
97 lines (80 loc) · 2.46 KB
/
u64_utils.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use elrond_wasm::{
api::ManagedTypeApi,
types::{ManagedBuffer, ManagedVec},
};
use crate::sc_panic_self;
pub trait UtilsU64 {
fn to_ascii<M: ManagedTypeApi>(&self) -> ManagedBuffer<M>;
fn to_hex<M: ManagedTypeApi>(&self) -> ManagedBuffer<M>;
}
impl UtilsU64 for u64 {
fn to_hex<M: ManagedTypeApi>(&self) -> ManagedBuffer<M> {
let mut reversed_digits = ManagedVec::<M, u8>::new();
let mut result = self.clone();
while result > 0 {
let digit = result % 16;
result /= 16;
let digit_char = match digit {
0 => b'0',
1 => b'1',
2 => b'2',
3 => b'3',
4 => b'4',
5 => b'5',
6 => b'6',
7 => b'7',
8 => b'8',
9 => b'9',
10 => b'a',
11 => b'b',
12 => b'c',
13 => b'd',
14 => b'e',
15 => b'f',
_ => sc_panic_self!(M, "invalid digit"),
};
reversed_digits.push(digit_char);
}
if &reversed_digits.len() == &0 {
return ManagedBuffer::<M>::new_from_bytes(b"00");
}
let mut o = ManagedBuffer::<M>::new();
if &reversed_digits.len() % 2 != 0 {
o.append_bytes(b"0");
}
for digit in reversed_digits.iter().rev() {
o.append_bytes(&[digit]);
}
return o;
}
fn to_ascii<M: ManagedTypeApi>(&self) -> ManagedBuffer<M> {
let mut reversed_digits = ManagedVec::<M, u8>::new();
let mut result = self.clone();
while result > 0 {
let digit = result % 10;
result /= 10;
let digit_char = match digit {
0 => b'0',
1 => b'1',
2 => b'2',
3 => b'3',
4 => b'4',
5 => b'5',
6 => b'6',
7 => b'7',
8 => b'8',
9 => b'9',
_ => sc_panic_self!(M, "invalid digit"),
};
reversed_digits.push(digit_char);
}
if &reversed_digits.len() == &0 {
return ManagedBuffer::<M>::new_from_bytes(b"0");
}
let mut o = ManagedBuffer::<M>::new();
for digit in reversed_digits.iter().rev() {
o.append_bytes(&[digit]);
}
return o;
}
}